path
stringlengths
4
297
contentHash
stringlengths
1
10
content
stringlengths
0
13M
lab10/app/src/main/java/com/topic3/android/reddit/domain/model/PostType.kt
4180988263
package com.topic3.android.reddit.domain.model enum class PostType(val type: Int) { TEXT(0), IMAGE(1); companion object { fun fromType(type: Int): PostType { return if (type == TEXT.type) { TEXT } else { IMAGE } } } }
lab10/app/src/main/java/com/topic3/android/reddit/dependencyinjection/DependencyInjector.kt
1317812683
package com.topic3.android.reddit.dependencyinjection import android.content.Context import androidx.room.Room import com.topic3.android.reddit.data.database.AppDatabase import com.topic3.android.reddit.data.database.dbmapper.DbMapper import com.topic3.android.reddit.data.database.dbmapper.DbMapperImpl import com.topic3.android.reddit.data.repository.Repository import com.topic3.android.reddit.data.repository.RepositoryImpl import kotlinx.coroutines.DelicateCoroutinesApi /** * Обеспечивает зависимости через приложение. */ class DependencyInjector(applicationContext: Context) { val repository: Repository by lazy { provideRepository(database) } private val database: AppDatabase by lazy { provideDatabase(applicationContext) } private val dbMapper: DbMapper = DbMapperImpl() private fun provideDatabase(applicationContext: Context): AppDatabase = Room.databaseBuilder( applicationContext, AppDatabase::class.java, AppDatabase.DATABASE_NAME ).build() @OptIn(DelicateCoroutinesApi::class) private fun provideRepository(database: AppDatabase): Repository { val postDao = database.postDao() return RepositoryImpl(postDao, dbMapper) } }
SensorApp/app/src/androidTest/java/com/example/ass3/ExampleInstrumentedTest.kt
4242128321
package com.example.ass3 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.ass3", appContext.packageName) } }
SensorApp/app/src/test/java/com/example/ass3/ExampleUnitTest.kt
387910805
package com.example.ass3 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) } }
SensorApp/app/src/main/java/com/example/ass3/ui/theme/Color.kt
1249147131
package com.example.ass3.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
SensorApp/app/src/main/java/com/example/ass3/ui/theme/Theme.kt
1398499533
package com.example.ass3.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun Ass3Theme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
SensorApp/app/src/main/java/com/example/ass3/ui/theme/Type.kt
3779992505
package com.example.ass3.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
SensorApp/app/src/main/java/com/example/ass3/MainActivity.kt
1887902447
package com.example.ass3 import android.content.Context import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.hardware.SensorManager import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.width import androidx.compose.material3.Button import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.collectAsState 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 androidx.compose.ui.graphics.Color import androidx.compose.ui.text.style.LineHeightStyle import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.room.Room import com.example.ass3.ui.theme.Ass3Theme import kotlin.math.atan2 import kotlin.math.log import kotlin.math.sqrt class MainActivity : ComponentActivity() , SensorEventListener { private lateinit var sensorManager: SensorManager private lateinit var accelerometer: Sensor private val _realTimeSensorData = mutableStateOf<FloatArray?>(null) val realTimeSensorData get() = _realTimeSensorData private val _saveInterval = mutableStateOf(5L) // Default interval of 5 seconds private val _isSavingData = mutableStateOf(false) private val intervalOptions = listOf(1L, 5L, 10L, 30L, 60L) private val _isRealTimeScreen = mutableStateOf(true) private val db by lazy{ Room.databaseBuilder( applicationContext, InventoryDatabase::class.java, "WeatherDb" ).build() } private val viewModel by viewModels<OrientationViewModel> ( factoryProducer={ object : ViewModelProvider.Factory{ override fun <T : ViewModel> create(modelClass: Class<T>): T { return OrientationViewModel(db.Dao) as T } } } ) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)!! setContent { Ass3Theme { // A surface container using the 'background' color from the theme Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { val state by viewModel.data.collectAsState() Column(modifier = Modifier ,horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.SpaceAround) { if (_isRealTimeScreen.value) { // Log.d("main",realTimeSensorData.value.toString()) RealTimeDataScreen(realTimeSensorData.value) } else { GraphScreen(viewModel) } var isIntervalDropdownExpanded by remember { mutableStateOf(false) } Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ) { Text("Save Interval: ${_saveInterval.value} seconds") Spacer(modifier = Modifier.width(8.dp)) Button(onClick = { isIntervalDropdownExpanded = true }) { Text("Select Interval") } DropdownMenu( expanded = isIntervalDropdownExpanded, onDismissRequest = { isIntervalDropdownExpanded = false }, modifier = Modifier.fillMaxWidth() ) { intervalOptions.forEach { interval -> DropdownMenuItem(text = {"igigg s" }, onClick = { _saveInterval.value = interval isIntervalDropdownExpanded = false },modifier=Modifier ) } } } Button( onClick = { _isRealTimeScreen.value = !_isRealTimeScreen.value }, modifier = Modifier ) { Text(if (_isRealTimeScreen.value) "Show Graph" else "Show Real-time Data") } } } } } } override fun onResume() { super.onResume() sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL) } override fun onPause() { super.onPause() sensorManager.unregisterListener(this) } override fun onSensorChanged(event: SensorEvent?) { if (event?.sensor?.type == Sensor.TYPE_ACCELEROMETER) { val x = event.values[0] val y = event.values[1] val z = event.values[2] val pitch = atan2(-x, sqrt(y * y + z * z)) * (180 / Math.PI) val roll = atan2(y, sqrt(x * x + z * z)) * (180 / Math.PI) val yaw = atan2(sqrt(x * x + y * y), z) * (180 / Math.PI) val sensorData = SensorData( pitch = pitch, roll = roll, yaw = yaw ) val temp = floatArrayOf(pitch.toFloat(), roll.toFloat(), yaw.toFloat()) if(_realTimeSensorData.value==null || !temp.contentEquals(_realTimeSensorData.value)){ _realTimeSensorData.value = temp viewModel.onSensorChanged(sensorData) } } } override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {} } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Text( text = "Hello $name!", modifier = modifier ) } @Preview(showBackground = true) @Composable fun GreetingPreview() { Ass3Theme { Greeting("Android") } }
SensorApp/app/src/main/java/com/example/ass3/Schema.kt
368039925
package com.example.ass3 import androidx.room.Dao import androidx.room.Entity import androidx.room.Insert import androidx.room.PrimaryKey import androidx.room.Query import kotlinx.coroutines.flow.Flow @Entity data class OrientationData( @PrimaryKey(autoGenerate = true) val id: Int = 0, val pitch: Double, val roll: Double, val yaw: Double, val timestamp: Long = System.currentTimeMillis() ) @Dao interface OrientationDao { @Insert suspend fun insert(orientationData: OrientationData) @Query("DELETE FROM OrientationData") suspend fun deleteAll() @Query("SELECT * FROM OrientationData") fun getAll(): Flow<List<OrientationData>> }
SensorApp/app/src/main/java/com/example/ass3/repository.kt
3678087264
package com.example.ass3 sealed interface DataEvents{ data class addData(val data: OrientationData) : DataEvents }
SensorApp/app/src/main/java/com/example/ass3/RealTimeDataScreen.kt
3756018783
package com.example.ass3 import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import kotlin.math.roundToInt @Composable fun RealTimeDataScreen(sensorData: FloatArray?) { Column( modifier = Modifier .fillMaxWidth() .fillMaxHeight(0.6f) .padding(16.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.SpaceAround ) { if(sensorData==null){ Text("error in fetching data") }else{ SensorAngle("Pitch", sensorData?.get(1) ?: 0f) SensorAngle("Roll", sensorData?.get(0) ?: 0f) SensorAngle("Yaw", sensorData?.get(2) ?: 0f) } } } @Composable fun SensorAngle(name: String, value: Float) { Text( text = "$name: ${value.roundToInt()}°", fontSize = 20.sp, fontWeight = FontWeight.Bold ) }
SensorApp/app/src/main/java/com/example/ass3/SensorData.kt
3379681991
package com.example.ass3 data class SensorData( val pitch: Double, val roll: Double, val yaw: Double, val timestamp: Long = System.currentTimeMillis() )
SensorApp/app/src/main/java/com/example/ass3/OrientationViewModel.kt
1970166696
package com.example.ass3 import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.launch import kotlinx.coroutines.flow.stateIn class OrientationViewModel(private val dao: OrientationDao) : ViewModel() { val data = dao.getAll().stateIn(viewModelScope, SharingStarted.WhileSubscribed(), emptyList()) // val delete=dao.deleteAll() fun onSensorChanged(sensorData: SensorData) { val orientationData = OrientationData( pitch = sensorData.pitch, roll = sensorData.roll, yaw = sensorData.yaw ) viewModelScope.launch { //dao.deleteAll() dao.insert(orientationData) } } fun onEvent(event: DataEvents) { when (event) { is DataEvents.addData -> { viewModelScope.launch { dao.insert(event.data) } } // Handle other events as needed } } }
SensorApp/app/src/main/java/com/example/ass3/Database.kt
483357133
package com.example.ass3 import androidx.room.Database import androidx.room.RoomDatabase @Database(entities = [OrientationData::class], version = 1, exportSchema = false) abstract class InventoryDatabase : RoomDatabase() { abstract val Dao: OrientationDao }
SensorApp/app/src/main/java/com/example/ass3/Graph.kt
4102925157
package com.example.ass3 import android.graphics.Typeface import android.util.Log import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import co.yml.charts.axis.AxisData import co.yml.charts.common.model.Point import co.yml.charts.ui.linechart.LineChart import co.yml.charts.ui.linechart.model.IntersectionPoint import co.yml.charts.ui.linechart.model.Line import co.yml.charts.ui.linechart.model.LineChartData import co.yml.charts.ui.linechart.model.LinePlotData import co.yml.charts.ui.linechart.model.LineStyle import co.yml.charts.ui.linechart.model.LineType import co.yml.charts.ui.linechart.model.SelectionHighlightPopUp @Composable fun GraphScreen(viewModel: OrientationViewModel) { val orientationData by viewModel.data.collectAsState() //Log.d("main",orientationData.toString()) val rollData = orientationData.mapIndexed { index, data -> // Log.d("main",data.toString()) Point(x = index.toFloat(), y = data.roll.toFloat()) } val pitchData = orientationData.mapIndexed { index, data -> Point(x = index.toFloat(), y = data.pitch.toFloat()) } val yawData = orientationData.mapIndexed { index, data -> Point(x = index.toFloat(), y = data.yaw.toFloat()) } Column( modifier = Modifier .fillMaxSize() .padding(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp) ) { StraightLinechart(rollData, "Year", "Roll") StraightLinechart(pitchData, "Year", "Pitch") StraightLinechart(yawData, "Year", "Yaw") } } @Composable private fun StraightLinechart(pointsData: List<Point>, xAxisLabel: String, yAxisLabel: String) { // Ensure at least 2 points for a line chart if (pointsData.size < 2) { // Handle this case, maybe show an error message or return return } // Calculate min and max values for dynamic axis labels val minX = pointsData.minOfOrNull { it.x }?.toFloat() ?: 0f val maxX = pointsData.maxOfOrNull { it.x }?.toFloat() ?: 1f val minY = pointsData.minOfOrNull { it.y }?.toFloat() ?: 0f val maxY = pointsData.maxOfOrNull { it.y }?.toFloat() ?: 100f val xAxisData = AxisData.Builder() .axisStepSize(((maxX - minX) / 5).dp) // Increased step size for wider x-axis .steps(5) // Reduced number of steps for xAxis to spread out labels .labelData { i -> val step = ((maxX - minX) / 5) (minX + i * step).toInt().toString() } .axisLabelAngle(20f) .labelAndAxisLinePadding(15.dp) .axisLabelColor(Color.Blue) .axisLineColor(Color.DarkGray) .typeFace(Typeface.DEFAULT_BOLD) .build() val yAxisData = AxisData.Builder() .steps(10) .labelData { i -> val step = ((maxY - minY) / 10) "${(minY + i * step)}" } .labelAndAxisLinePadding(30.dp) .axisLabelColor(Color.Blue) .axisLineColor(Color.DarkGray) .typeFace(Typeface.DEFAULT_BOLD) .build() val data = LineChartData( linePlotData = LinePlotData( lines = listOf( Line( dataPoints = pointsData, lineStyle = LineStyle(lineType = LineType.Straight(), color = Color.Blue), intersectionPoint = IntersectionPoint(color = Color.Red), selectionHighlightPopUp = SelectionHighlightPopUp(popUpLabel = { x, y -> val xLabel = "Timestamp : ${x.toLong()}" val yLabel = "Value : ${String.format("%.2f", y)}" "$xLabel\n$yLabel" }) ) ) ), xAxisData = xAxisData, yAxisData = yAxisData ) LineChart( modifier = Modifier .fillMaxWidth() .height(300.dp), lineChartData = data ) }
Speaker-Trainer/app/src/androidTest/java/com/app/speakertrainer/ExampleInstrumentedTest.kt
2268051502
package com.app.speakertrainer 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.app.speakertrainer", appContext.packageName) } }
Speaker-Trainer/app/src/test/java/com/app/speakertrainer/ExampleUnitTest.kt
4172038078
package com.app.speakertrainer 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) } }
Speaker-Trainer/app/src/test/java/com/app/speakertrainer/ClientTest.kt
51704763
package com.app.speakertrainer import org.junit.Test import org.junit.Assert.* import android.content.Context import android.graphics.Bitmap import com.app.speakertrainer.modules.Client class ClientTest { @Test fun testResetData() { Client.token = "testToken" Client.resetData() assertEquals("", Client.token) assertTrue(Client.recordList.isEmpty()) } }
Speaker-Trainer/app/src/main/java/com/app/speakertrainer/constance/Constance.kt
4251426676
package com.app.speakertrainer.constance object Constance { const val REQUEST_VIDEO_CAPTURE = 1 const val CORRECT_AUTH_STATUS = "User is successfully logged in." const val EMAIL_ERROR = "Email is not registered." const val PASSWORD_ERROR = "Incorrect password." const val REGISTRATION_SUCCESS = "User is successfully registered." const val ACCOUNT_EXIST_STATUS = "Authentication with this Email already exists." const val UNKNOWN_ERROR = "Server error. Please contact support." const val LOGOUT_SUCCESS = "User is successfully logged out." const val EMAIL_REGISTERED = "Email is registered." const val PASSWORD_CHANGED = "Password is successfully changed." const val FILES_FOUND = "User's files are successfully found." }
Speaker-Trainer/app/src/main/java/com/app/speakertrainer/activities/CheckListActivity.kt
2121492576
package com.app.speakertrainer.activities import android.content.Intent import android.net.Uri import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.app.speakertrainer.R import com.app.speakertrainer.data.Record import com.app.speakertrainer.databinding.ActivityCheckListBinding import com.app.speakertrainer.modules.ApiManager import com.app.speakertrainer.modules.Client.recordList import java.io.File /** * Activity for choosing components for analysing. */ class CheckListActivity : AppCompatActivity() { lateinit var binding: ActivityCheckListBinding private lateinit var videoUri: Uri private val apiManager = ApiManager(this) /** * Method called when the activity is created. * Initializes the binding to the layout and displays it on the screen. * Set actions for menu buttons. * Call function for setting up check boxes. * * @param savedInstanceState a Bundle object containing the previous state of the activity (if saved) */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityCheckListBinding.inflate(layoutInflater) setContentView(binding.root) videoUri = Uri.parse(intent.getStringExtra("uri")) setCheckListeners() binding.bNav.setOnItemSelectedListener { when (it.itemId) { R.id.back -> { returnHome() } R.id.home -> { returnHome() } R.id.forward -> { if (!isFieldEmpty()) { postData() } } } true } } /** * Set up check boxes. */ private fun setCheckListeners() { binding.apply { checkBoxAll.setOnCheckedChangeListener { _, isChecked -> checkBoxVisual.isChecked = isChecked checkBoxAllAudio.isChecked = isChecked checkBoxEmotions.isChecked = isChecked } checkBoxVisual.setOnCheckedChangeListener { _, isChecked -> checkBoxClothes.isChecked = isChecked checkBoxGesture.isChecked = isChecked checkBoxAngle.isChecked = isChecked checkBoxEye.isChecked = isChecked } checkBoxAllAudio.setOnCheckedChangeListener { _, isChecked -> checkBoxIntelligibility.isChecked = isChecked checkBoxPauses.isChecked = isChecked checkBoxParasites.isChecked = isChecked checkBoxNoise.isChecked = isChecked } } } /** * Start home activity. * Finish this activity. */ private fun returnHome() { val intent = Intent(this, Home::class.java) startActivity(intent) finish() } /** * Send request to server for analysing loaded video record. */ private fun postData() { val file = File(videoUri.path) binding.apply { apiManager.postData(file,checkBoxEmotions.isChecked, checkBoxParasites.isChecked, checkBoxPauses.isChecked, checkBoxNoise.isChecked, checkBoxIntelligibility.isChecked, checkBoxGesture.isChecked, checkBoxClothes.isChecked, checkBoxAngle.isChecked, checkBoxEye.isChecked, videoName.text.toString()) { responseResults -> saveData(responseResults) } } } /** * Save record instance with id [id]. */ private fun saveData(id: String) { apiManager.getImg(id) { image -> apiManager.getInfo(id) {info -> val record = Record( image, info.filename, info.datetime, id.toInt() ) recordList.add(record) val intent = Intent(this@CheckListActivity, AnalysisResults::class.java) intent.putExtra("index", (recordList.size - 1).toString()) startActivity(intent) finish() } } } /** * Check if field with video name is empty. * * @return if video name field is empty. */ private fun isFieldEmpty(): Boolean { binding.apply { if (videoName.text.isNullOrEmpty()) videoName.error = resources.getString(R.string.mustFillField) return videoName.text.isNullOrEmpty() } } }
Speaker-Trainer/app/src/main/java/com/app/speakertrainer/activities/EmailEnterActivity.kt
2501037275
package com.app.speakertrainer.activities import android.content.Intent import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import com.app.speakertrainer.R import com.app.speakertrainer.databinding.ActivityEmailEnterBinding import com.app.speakertrainer.modules.ApiManager /** * Activity for entering email to change password. */ class EmailEnterActivity : AppCompatActivity() { private lateinit var bindingClass: ActivityEmailEnterBinding private var numbers: String? = null private var email: String? = null private val apiManager = ApiManager(this) /** * Method called when the activity is created. * Initializes the binding to the layout and displays it on the screen. * * @param savedInstanceState a Bundle object containing the previous state of the activity (if saved) */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) bindingClass = ActivityEmailEnterBinding.inflate(layoutInflater) setContentView(bindingClass.root) } /** * Method starts authorization activity. */ fun onClickAuthorization(view: View) { val intent = Intent(this, MainActivity::class.java) startActivity(intent) finish() } /** * Method post request for getting numbers to check email. */ fun onClickSendCode(view: View) { if (!isFieldEmpty()) { email = bindingClass.emailInput.text.toString() apiManager.getEmailCheckNumbers(email!!) { num -> numbers = num } } } /** * Method opens activity for inputting new password if all data is correct. */ fun onClickNext(view: View) { if (!isNumEmpty() && numbers != null) { if (bindingClass.numInput.text.toString() == numbers) { val intent = Intent(this, PasswordEnterActivity::class.java) intent.putExtra("email", email) startActivity(intent) finish() } else bindingClass.numInput.error = "Неверный код" } } /** * Method checks if email input text is not empty. * If field is empty method set error. * * @return is email input field is empty. */ private fun isFieldEmpty(): Boolean { bindingClass.apply { if (emailInput.text.isNullOrEmpty()) emailInput.error = resources.getString(R.string.mustFillField) return emailInput.text.isNullOrEmpty() } } /** * Method checks if field for numbers is empty. * If field is empty method set error. * * @return is number input field is empty. */ private fun isNumEmpty(): Boolean { bindingClass.apply { if (numInput.text.isNullOrEmpty()) numInput.error = resources.getString(R.string.mustFillField) return numInput.text.isNullOrEmpty() } } }
Speaker-Trainer/app/src/main/java/com/app/speakertrainer/activities/MainActivity.kt
859764917
package com.app.speakertrainer.activities import android.content.Intent import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import com.app.speakertrainer.R import com.app.speakertrainer.data.FilesNumbers import com.app.speakertrainer.data.Record import com.app.speakertrainer.databinding.ActivityMainBinding import com.app.speakertrainer.modules.ApiManager import com.app.speakertrainer.modules.Client /** * Activity for entering data for authorization. */ class MainActivity : AppCompatActivity() { private lateinit var bindingClass: ActivityMainBinding private val apiManager = ApiManager(this) /** * Method called when the activity is created. * Initializes the binding to the layout and displays it on the screen. * * @param savedInstanceState a Bundle object containing the previous state of the activity (if saved) */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) bindingClass = ActivityMainBinding.inflate(layoutInflater) setContentView(bindingClass.root) } /** * Method post data to server and authorize user if everything is correct. * Get info about user from server. */ fun onClickAuthorization(view: View) { if (!isFieldEmpty()) { val username = bindingClass.emailET.text.toString() val password = bindingClass.passwordET.text.toString() apiManager.auth(username, password) { apiManager.getNumberOfFiles { filesInfo -> loadFiles(filesInfo) } val intent = Intent(this@MainActivity, Home::class.java) startActivity(intent) finish() } } } /** * Open registration activity. */ fun onClickRegistration(view: View) { val intent = Intent(this, RegistrationActivity::class.java) startActivity(intent) finish() } /** * Open email enter activity for changing password. */ fun onClickChangePassword(view: View) { val intent = Intent(this, EmailEnterActivity::class.java) startActivity(intent) finish() } /** * @return if any of fields is empty */ private fun isFieldEmpty(): Boolean { bindingClass.apply { if (emailET.text.isNullOrEmpty()) emailET.error = resources.getString(R.string.mustFillField) if (passwordET.text.isNullOrEmpty()) passwordET.error = resources.getString(R.string.mustFillField) return emailET.text.isNullOrEmpty() || passwordET.text.isNullOrEmpty() } } /** * Load users info from server. * * @param members a FilesNumbers object that contains users loaded records. */ private fun loadFiles(members: FilesNumbers) { if (members.num_of_files > 0) { for (id in members.file_ids) { apiManager.getImg(id.toString()) { image -> apiManager.getInfo(id.toString()) {info -> val record = Record( image, info.filename, info.datetime, id ) Client.recordList.add(record) } } } } } }
Speaker-Trainer/app/src/main/java/com/app/speakertrainer/activities/PreviewVideoActivity.kt
1749811165
package com.app.speakertrainer.activities import android.content.Intent import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import com.app.speakertrainer.databinding.ActivityPreviewVideoBinding import com.app.speakertrainer.modules.Client import com.app.speakertrainer.modules.RecordAdapter /** * Activity for displaying archive. */ class PreviewVideoActivity : AppCompatActivity() { lateinit var binding: ActivityPreviewVideoBinding private val adapter = RecordAdapter() /** * Method called when the activity is created. * Initializes the binding to the layout and displays it on the screen. * * @param savedInstanceState a Bundle object containing the previous state of the activity (if saved) */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityPreviewVideoBinding.inflate(layoutInflater) setContentView(binding.root) init() } /** * Method fills adapter for displaying record list. */ private fun init() { binding.apply { rcView.layoutManager = LinearLayoutManager(this@PreviewVideoActivity) rcView.adapter = adapter adapter.setOnItemClickListener(object : RecordAdapter.onItemClickListener { override fun onItemClick(position: Int) { val intent = Intent(this@PreviewVideoActivity, AnalysisResults::class.java) intent.putExtra("index", position.toString()) startActivity(intent) finish() } }) for (item in Client.recordList) { adapter.addRecord(item) } } } /** * Open home screen activity. */ fun onClickHome(view: View) { val intent = Intent(this, Home::class.java) startActivity(intent) finish() } }
Speaker-Trainer/app/src/main/java/com/app/speakertrainer/activities/AnalysisResults.kt
3704991230
package com.app.speakertrainer.activities import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.app.speakertrainer.databinding.ActivityAnalysisResultsBinding import android.net.Uri import android.view.View import android.widget.MediaController import com.app.speakertrainer.modules.Client import com.app.speakertrainer.modules.Client.recordList import com.app.speakertrainer.R import com.app.speakertrainer.data.ResponseResults import com.app.speakertrainer.modules.ApiManager /** * Activity for demonstrating analysis results for chosen video record. */ class AnalysisResults : AppCompatActivity() { private lateinit var binding: ActivityAnalysisResultsBinding private var index: Int = -1 private lateinit var videoUri: Uri private val apiManager = ApiManager(this) /** * Method called when the activity is created. * Initializes the binding to the layout and displays it on the screen. * Set actions for menu buttons. * Call function for setting analysis results. * * @param savedInstanceState a Bundle object containing the previous state of the activity (if saved) */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityAnalysisResultsBinding.inflate(layoutInflater) setContentView(binding.root) binding.frameLayout.visibility = View.VISIBLE index = intent.getStringExtra("index")?.toInt() ?: -1 // Set menu actions. binding.bNav.setOnItemSelectedListener { when (it.itemId) { R.id.back -> { val intent = Intent(this, PreviewVideoActivity::class.java) startActivity(intent) finish() } R.id.home -> { val intent = Intent(this, Home::class.java) startActivity(intent) finish() } } true } setResults(index) } /** * Get the results of analysis of the video recording in the list under [index]. */ private fun setResults(index: Int) { if (index != -1) { val id = recordList[index].index apiManager.getAnalysisInfo(id) { responseResults -> setInfo(responseResults) } apiManager.getVideo(id) {responseResults -> videoUri = responseResults setVideo() } } else apiManager.toastResponse("Ошибка. Повторите позднее") } /** * Set the fields of the [info] to the corresponding text views * and make corresponding text views visible. */ private fun setInfo(info: ResponseResults) { runOnUiThread { binding.apply { if (info.clean_speech != null) { textViewClean.visibility = View.VISIBLE textViewClean.text = Client.setCustomString( "Чистота речи", info.clean_speech.toString(), this@AnalysisResults ) } if (info.speech_rate != null) { textViewRate.visibility = View.VISIBLE textViewRate.text = Client.setCustomString( "Доля плохого темпа речи", info.speech_rate.toString(), this@AnalysisResults ) } if (info.background_noise != null) { textViewNoise.visibility = View.VISIBLE textViewNoise.text = Client.setCustomString( "Доля времени с высоким шумом", info.background_noise.toString(), this@AnalysisResults ) } if (info.intelligibility != null) { textViewIntelligibility.visibility = View.VISIBLE textViewIntelligibility.text = Client.setCustomString( "Разборчивость речи", info.intelligibility.toString(), this@AnalysisResults ) } if (info.clothes != null) { textViewClothes.visibility = View.VISIBLE textViewClothes.text = Client.setCustomString( "Образ", info.clothes.toString(), this@AnalysisResults ) } if (info.gestures != null) { textViewGestures.visibility = View.VISIBLE textViewGestures.text = Client.setCustomString( "Жестикуляция", info.gestures.toString(), this@AnalysisResults ) } if (info.angle != null) { textViewAngle.visibility = View.VISIBLE textViewAngle.text = Client.setCustomString( "Доля времени неверного ракурса", info.angle.toString(), this@AnalysisResults ) } if (info.glances != null) { textViewGlances.visibility = View.VISIBLE textViewGlances.text = Client.setCustomString( "Доля времени некорректного направления взгляда", info.glances.toString(), this@AnalysisResults ) } if (info.emotionality != null) { textViewEmotionality.visibility = View.VISIBLE textViewEmotionality.text = Client.setCustomString( "Эмоциональность", info.emotionality.toString(), this@AnalysisResults ) } } } } /** * Set obtained footage to the video view. * Set media controller to the video view. * Start displaying the video record. */ private fun setVideo() { runOnUiThread { binding.videoView.setVideoURI(videoUri) val mediaController = MediaController(this) // Attach mediaController to the bottom of the video recording. mediaController.setAnchorView(binding.videoView) binding.videoView.setMediaController(mediaController) binding.videoView.start() } } }
Speaker-Trainer/app/src/main/java/com/app/speakertrainer/activities/Home.kt
2527553485
package com.app.speakertrainer.activities import android.app.Activity import android.app.AlertDialog import android.content.ContentValues.TAG import android.content.Intent import android.graphics.Color import android.net.Uri import android.os.Bundle import android.provider.MediaStore import android.util.Log import android.view.View import android.widget.Button import androidx.activity.result.ActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import com.app.speakertrainer.data.Statistics import com.app.speakertrainer.databinding.ActivityHomeBinding import com.app.speakertrainer.modules.ApiManager import com.app.speakertrainer.modules.Client import com.app.speakertrainer.modules.Client.graphEntries import com.app.speakertrainer.modules.Client.lineGraphEntries import com.app.speakertrainer.modules.Client.pieEntries import com.github.mikephil.charting.data.Entry import com.github.mikephil.charting.data.LineData import com.github.mikephil.charting.data.LineDataSet import com.github.mikephil.charting.data.PieData import com.github.mikephil.charting.data.PieDataSet import com.github.mikephil.charting.data.PieEntry import com.gowtham.library.utils.LogMessage import com.gowtham.library.utils.TrimVideo /** * Activity that represents home screen. */ class Home : AppCompatActivity() { private lateinit var selectBtn: Button private lateinit var binding: ActivityHomeBinding private var videoUri: Uri? = null private val apiManager = ApiManager(this) val startForResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult -> if (result.resultCode == Activity.RESULT_OK && result.data != null ) { val uri = Uri.parse(TrimVideo.getTrimmedVideoPath(result.data)) Log.d(TAG, "Trimmed path:: " + videoUri + "\n") val intent = Intent(this@Home, CheckListActivity::class.java) intent.putExtra("uri", uri.toString()) startActivity(intent) finish() } else LogMessage.v("videoTrimResultLauncher data is null") } val startLoadVideo = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult -> if (result.resultCode == Activity.RESULT_OK) { if (result.data != null) { val selectVideo = result.data!!.data videoUri = selectVideo trimVideo(selectVideo.toString()) } } } val startVideoRecord = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult -> if (result.resultCode == Activity.RESULT_OK) { if (result.data != null) { val selectVideo = result.data!!.data videoUri = selectVideo trimVideo(selectVideo.toString()) } } } /** * Method called when the activity is created. * Initializes the binding to the layout and displays it on the screen. * Call method that sets statistics. * * @param savedInstanceState a Bundle object containing the previous state of the activity (if saved) */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityHomeBinding.inflate(layoutInflater) setContentView(binding.root) selectBtn = binding.loadBtn getStatistics() } /** * Post request to get arrays with values for graphs. * Call methods for drawing charts. */ private fun getStatistics() { if (Client.recordList.size > 0) { apiManager.getGraphStatistics { statistics-> setGraphs(statistics) drawLineChart() drawPieChart() } } else { drawLineChart() drawPieChart() } } /** * Method set entries values with data got from server. * * @param statistics a Statistics object which contains arrays of entries for drawing charts. */ private fun setGraphs(statistics: Statistics) { if (statistics.speech_rate != null) { graphEntries = ArrayList<Entry>() for (i in statistics.speech_rate.indices) { graphEntries.add(Entry(i.toFloat(), statistics.speech_rate[i])) } Client.lineText = "Ваш прогресс" } if (statistics.angle != null) { lineGraphEntries = ArrayList<Entry>() for (i in statistics.angle.indices) { lineGraphEntries.add(Entry(i.toFloat(), statistics.angle[i])) } Client.lineText = "Ваш прогресс" } if (statistics.filler_words != null && statistics.filler_words_percentage != null) { pieEntries = ArrayList<PieEntry>() for (i in statistics.filler_words.indices) { pieEntries.add( PieEntry( statistics.filler_words_percentage[i], statistics.filler_words[i] ) ) } Client.pieText = "Ваш прогресс" } } /** * Method set pie charts settings. * Method draw pie chart. */ private fun drawPieChart() { runOnUiThread { val pieChart = binding.pieChart pieChart.setHoleColor(Color.parseColor("#13232C")) val entries = pieEntries val colors = mutableListOf<Int>() // Set colors for drawing pie chart. for (i in entries.indices) { colors.add(Client.colors[i]) } val pieDataSet = PieDataSet(entries, "Слова паразиты") pieDataSet.colors = colors val pieData = PieData(pieDataSet) pieChart.data = pieData pieChart.description.text = Client.pieText pieChart.setEntryLabelColor(Color.WHITE) pieChart.description.textColor = Color.WHITE pieChart.legend.textColor = Color.WHITE pieChart.invalidate() } } /** * Method set line charts settings. * Method draw line chart. */ private fun drawLineChart() { runOnUiThread { val lineChart = binding.lineChart val lineDataSetRate = LineDataSet(graphEntries, "Темп речи") lineDataSetRate.color = Color.BLUE lineDataSetRate.valueTextSize = 12f val lineDataSetAngle = LineDataSet(lineGraphEntries, "Неверный ракурс") lineDataSetAngle.color = Color.RED lineDataSetAngle.valueTextSize = 12f lineDataSetRate.setDrawValues(false) lineDataSetAngle.setDrawValues(false) val lineData = LineData(lineDataSetRate, lineDataSetAngle) lineChart.data = lineData lineChart.description.text = Client.lineText lineChart.description.textColor = Color.WHITE lineChart.legend.textColor = Color.WHITE lineChart.xAxis.textColor = Color.WHITE lineChart.axisLeft.textColor = Color.WHITE lineChart.axisRight.textColor = Color.WHITE lineChart.invalidate() } } /** * Method opens your phone files to choose video for analysing. */ fun onClickLoadVideo(view: View) { val intent = Intent() intent.action = Intent.ACTION_PICK intent.type = "video/*" startLoadVideo.launch(intent) } /** * Method opens video camera for recording video. */ fun onClickStartRecording(view: View) { val takeVideoIntent = Intent(MediaStore.ACTION_VIDEO_CAPTURE) startVideoRecord.launch(takeVideoIntent) } /** * Method creates alert dialog to ensure in users actions. */ fun onClickExit(view: View) { val alertDialog = AlertDialog.Builder(this) .setTitle("Выход из аккаунта") .setMessage("Вы действительно хотите выйти из аккаунта?") .setPositiveButton("Да") { dialog, _ -> logoutUser() dialog.dismiss() } .setNegativeButton("Отмена") { dialog, _ -> dialog.dismiss() } .create() alertDialog.show() } /** * Method post request to logout and reset data. * Return to authorization activity. */ private fun logoutUser() { apiManager.logoutUser() {loggedOut -> if (loggedOut) { val intent = Intent(this@Home, MainActivity::class.java) startActivity(intent) finish() } } } /** * Method starts trim video activity. */ private fun trimVideo(videoUri: String?) { TrimVideo.activity(videoUri) .setHideSeekBar(true) .start(this, startForResult) } /** * Method open archieve and finish home activity. */ fun onClickArchieve(view: View) { val intent = Intent(this, PreviewVideoActivity::class.java) startActivity(intent) finish() } /** * Method open recommendations and finish home activity. */ fun onClickRecommendations(view: View) { val intent = Intent(this, Recommendations::class.java) startActivity(intent) finish() } }
Speaker-Trainer/app/src/main/java/com/app/speakertrainer/activities/PasswordEnterActivity.kt
2691104600
package com.app.speakertrainer.activities import android.content.Intent import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import com.app.speakertrainer.R import com.app.speakertrainer.data.FilesNumbers import com.app.speakertrainer.data.Record import com.app.speakertrainer.databinding.ActivityPasswordEnterBinding import com.app.speakertrainer.modules.ApiManager import com.app.speakertrainer.modules.Client /** * Activity for entering email for futher password change. */ class PasswordEnterActivity : AppCompatActivity() { private lateinit var bindingClass: ActivityPasswordEnterBinding private var email = "" private val apiManager = ApiManager(this) /** * Method called when the activity is created. * Initializes the binding to the layout and displays it on the screen. * Call method that sets statistics. * * @param savedInstanceState a Bundle object containing the previous state of the activity (if saved) */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) bindingClass = ActivityPasswordEnterBinding.inflate(layoutInflater) setContentView(bindingClass.root) email = intent.getStringExtra("email").toString() } /** * Open authorization activity. */ fun onClickAuthorizationScreen(view: View) { val intent = Intent(this, MainActivity::class.java) startActivity(intent) finish() } /** * Post request for checking email validation. * Open password enter activity if email is correct. */ fun onClickRestorePassword(view: View) { if (!isFieldEmpty()) { if (isPasswordCorrect()) { val password = bindingClass.passwordInputLayout.text.toString() apiManager.changePassword(email, password) { apiManager.getNumberOfFiles { filesInfo -> loadFiles(filesInfo) } val intent = Intent(this@PasswordEnterActivity, Home::class.java) startActivity(intent) finish() } } } } /** * @return if any of fields is empty */ private fun isFieldEmpty(): Boolean { bindingClass.apply { if (passwordInputLayout.text.isNullOrEmpty()) passwordInputLayout.error = resources.getString(R.string.mustFillField) if (pasAgainInputLayout.text.isNullOrEmpty()) pasAgainInputLayout.error = resources.getString(R.string.mustFillField) return pasAgainInputLayout.text.isNullOrEmpty() || passwordInputLayout.text.isNullOrEmpty() } } /** * @return if texts in fields for entering password and for checking password are the same. */ private fun isPasswordCorrect(): Boolean { bindingClass.apply { if (passwordInputLayout.text.toString() != pasAgainInputLayout.text.toString()) pasAgainInputLayout.error = "Пароли не совпадают" return passwordInputLayout.text.toString() == pasAgainInputLayout.text.toString() } } /** * Load users info from server. * * @param members a FilesNumbers object that contains users loaded records. */ private fun loadFiles(members: FilesNumbers) { if (members.num_of_files > 0) { for (id in members.file_ids) { apiManager.getImg(id.toString()) { image -> apiManager.getInfo(id.toString()) {info -> val record = Record( image, info.filename, info.datetime, id ) Client.recordList.add(record) } } } } } }
Speaker-Trainer/app/src/main/java/com/app/speakertrainer/activities/RegistrationActivity.kt
3847203789
package com.app.speakertrainer.activities import android.content.Intent import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import com.app.speakertrainer.R import com.app.speakertrainer.databinding.ActivityRegistrationBinding import com.app.speakertrainer.modules.ApiManager /** * Activity for registration user. */ class RegistrationActivity : AppCompatActivity() { private lateinit var bindingClass: ActivityRegistrationBinding private val apiManager = ApiManager(this) /** * Method called when the activity is created. * Initializes the binding to the layout and displays it on the screen. * Call method that sets statistics. * * @param savedInstanceState a Bundle object containing the previous state of the activity (if saved) */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) bindingClass = ActivityRegistrationBinding.inflate(layoutInflater) setContentView(bindingClass.root) } /** * Open authorization activity. */ fun onClickAuthorization(view: View) { val intent = Intent(this, MainActivity::class.java) startActivity(intent) finish() } /** * Post user data to server to registrate user. */ fun onClickRegistration(view: View) { if (!isFieldEmpty()) { if (isPasswordCorrect()) { val username = bindingClass.emailInputLayout.text.toString() val password = bindingClass.passwordInputLayout.text.toString() apiManager.register(username, password) { val intent = Intent( this@RegistrationActivity, Home::class.java ) startActivity(intent) finish() } } } } /** * @return if any of fields is empty */ private fun isFieldEmpty(): Boolean { bindingClass.apply { if (emailInputLayout.text.isNullOrEmpty()) emailInputLayout.error = resources.getString(R.string.mustFillField) if (passwordInputLayout.text.isNullOrEmpty()) passwordInputLayout.error = resources.getString(R.string.mustFillField) if (pasAgainInputLayout.text.isNullOrEmpty()) pasAgainInputLayout.error = resources.getString(R.string.mustFillField) return emailInputLayout.text.isNullOrEmpty() || passwordInputLayout.text.isNullOrEmpty() || pasAgainInputLayout.text.isNullOrEmpty() } } /** * @return if texts in fields for entering password and for checking password are the same. */ private fun isPasswordCorrect(): Boolean { bindingClass.apply { if (passwordInputLayout.text.toString() != pasAgainInputLayout.text.toString()) pasAgainInputLayout.error = "Пароли не совпадают" return passwordInputLayout.text.toString() == pasAgainInputLayout.text.toString() } } }
Speaker-Trainer/app/src/main/java/com/app/speakertrainer/activities/Recommendations.kt
3867853625
package com.app.speakertrainer.activities import android.content.Intent import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import com.app.speakertrainer.R import com.app.speakertrainer.data.RecommendationsInfo import com.app.speakertrainer.databinding.ActivityRecomendationsBinding import com.app.speakertrainer.modules.ApiManager import com.app.speakertrainer.modules.Client /** * Activity for representing recommendations. */ class Recommendations : AppCompatActivity() { private lateinit var binding: ActivityRecomendationsBinding private val apiManager = ApiManager(this) /** * Method called when the activity is created. * Initializes the binding to the layout and displays it on the screen. * Call method that sets statistics. * * @param savedInstanceState a Bundle object containing the previous state of the activity (if saved) */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityRecomendationsBinding.inflate(layoutInflater) setContentView(binding.root) binding.bNav.setOnItemSelectedListener { when (it.itemId) { R.id.home -> { val intent = Intent(this, Home::class.java) startActivity(intent) finish() } } true } getRecommendationsInfo() } /** * Post request to get recommendations from server. */ private fun getRecommendationsInfo() { apiManager.getRecommendations { info -> setInfo(info) } } /** * Set the fields of the [info] to the corresponding text views * and make corresponding text views visible. */ private fun setInfo(info: RecommendationsInfo) { runOnUiThread { binding.apply { if (info.clean_speech != null) { textViewClean.visibility = View.VISIBLE textViewClean.text = Client.setCustomString( "Чистота речи", info.clean_speech.toString(), this@Recommendations ) } if (info.speech_rate != null) { textViewRate.visibility = View.VISIBLE textViewRate.text = Client.setCustomString( "Доля плохого темпа речи", info.speech_rate.toString(), this@Recommendations ) } if (info.background_noise != null) { textViewNoise.visibility = View.VISIBLE textViewNoise.text = Client.setCustomString( "Доля времени с высоким шумом", info.background_noise.toString(), this@Recommendations ) } if (info.intelligibility != null) { textViewIntelligibility.visibility = View.VISIBLE textViewIntelligibility.text = Client.setCustomString( "Разборчивость речи", info.intelligibility.toString(), this@Recommendations ) } if (info.clothes != null) { textViewClothes.visibility = View.VISIBLE textViewClothes.text = Client.setCustomString( "Образ", info.clothes.toString(), this@Recommendations ) } if (info.gestures != null) { textViewGestures.visibility = View.VISIBLE textViewGestures.text = Client.setCustomString( "Жестикуляция", info.gestures.toString(), this@Recommendations ) } if (info.angle != null) { textViewAngle.visibility = View.VISIBLE textViewAngle.text = Client.setCustomString( "Доля времени неверного ракурса", info.angle.toString(), this@Recommendations ) } if (info.glances != null) { textViewGlances.visibility = View.VISIBLE textViewGlances.text = Client.setCustomString( "Доля времени некорректного направления взгляда", info.glances.toString(), this@Recommendations ) } if (info.emotionality != null) { textViewEmotionality.visibility = View.VISIBLE textViewEmotionality.text = Client.setCustomString( "Эмоциональность", info.emotionality.toString(), this@Recommendations ) } } } } }
Speaker-Trainer/app/src/main/java/com/app/speakertrainer/modules/ApiManager.kt
4292543840
package com.app.speakertrainer.modules import android.app.Activity import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri import android.util.Log import android.widget.Toast import com.app.speakertrainer.constance.Constance import com.app.speakertrainer.data.FileInfo import com.app.speakertrainer.data.FilesNumbers import com.app.speakertrainer.data.RecommendationsInfo import com.app.speakertrainer.data.ResponseResults import com.app.speakertrainer.data.Statistics import com.google.gson.Gson import okhttp3.* import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.RequestBody.Companion.asRequestBody import java.io.File import java.io.IOException /** * Class containing all requests to server. * * @param context is an activity for representing requests results to user. */ class ApiManager(private val context: Context) { val gson = Gson() /** * Method gets analysis results from server. * * @param id is an id of video which was analysed. */ fun getAnalysisInfo(id: Int, onResponse: (ResponseResults) -> Unit) { val requestBody = FormBody.Builder() .add("token", Client.token) .add("file_id", id.toString()) .build() Client.client.postRequest("file_statistics/", requestBody, object : Callback { override fun onFailure(call: Call, e: IOException) { toastResponse("Ошибка соединения") } override fun onResponse(call: Call, response: Response) { if (response.isSuccessful) { if (response.header("status") == Constance.UNKNOWN_ERROR) { toastResponse("Ошибка загрузки файла. Пользователь не найден") } else { val info = gson.fromJson(response.body?.string(), ResponseResults::class.java) onResponse.invoke(info) } } else { toastResponse("Ошибка загрузки информации") } } }) } /** * Method gets changed video from server. * * @param id is an id of video which was analysed. */ fun getVideo(id: Int, onVideoReceived: (Uri) -> Unit) { val requestBody = FormBody.Builder() .add("token", Client.token) .add("file_id", id.toString()) .build() Client.client.postRequest("modified_file/", requestBody, object : Callback { override fun onFailure(call: Call, e: IOException) { toastResponse("Ошибка соединения") } override fun onResponse(call: Call, response: Response) { if (response.isSuccessful) { if (response.header("status") == Constance.UNKNOWN_ERROR) { toastResponse("Ошибка загрузки видео. Обратитесь в поддержку") } else { val inputStream = response.body?.byteStream() val videoFile = File(context.cacheDir, "temp_video.mp4") videoFile.outputStream().use { fileOut -> inputStream?.copyTo(fileOut) } val videoUri = Uri.fromFile(videoFile) onVideoReceived.invoke(videoUri) } } else { toastResponse("Ошибка загрузки видео") } } }) } /** * Method send video and options for analysing. * * @param file a video file for analysing. */ fun postData(file: File, emotionality: Boolean, parasites: Boolean, pauses: Boolean, noise: Boolean, intellig: Boolean, gesture: Boolean, clothes: Boolean, angle: Boolean, glance: Boolean, filename: String, onSaveData: (String) -> Unit) { val requestBody: RequestBody = MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart( "file", file.name, file.asRequestBody("video/*".toMediaTypeOrNull()) ) .addFormDataPart("token", Client.token) .addFormDataPart("emotionality", emotionality.toString()) .addFormDataPart("clean_speech", parasites.toString()) .addFormDataPart("speech_rate", pauses.toString()) .addFormDataPart("background_noise", noise.toString()) .addFormDataPart("intelligibility", intellig.toString()) .addFormDataPart("gestures", gesture.toString()) .addFormDataPart("clothing", clothes.toString()) .addFormDataPart("angle", angle.toString()) .addFormDataPart("glances", glance.toString()) .addFormDataPart("filename", filename) .build() Client.client.postRequest("upload_file/", requestBody, object : Callback { override fun onFailure(call: Call, e: IOException) { toastResponse("Ошибка соединения" + e.message) } override fun onResponse(call: Call, response: Response) { if (response.isSuccessful) { when (val responseBodyString = response.body?.string()) { "token_not_found_error" -> toastResponse("Неверный аккаунт") "filename_error" -> toastResponse("Неверное имя файла") "parsing_error" -> toastResponse("Ошибка передачи данных") else -> { if (response.header("status") == "File is successfully uploaded.") { if (responseBodyString != null) { onSaveData.invoke(responseBodyString) } } } } } else toastResponse("Ошибка передачи видео") } }) } /** * Method gets preview of the video from server. * * @param id is an id of video which was analysed. */ fun getImg(id: String, onImageReceived: (Bitmap) -> Unit){ val client = Client.client.getClient() val requestBody = FormBody.Builder() .add("token", Client.token) .add("file_id", id) .build() val request = Client.client.getRequest("archive/file_image/", requestBody) try { client.newCall(request).execute().use { response -> if (response.isSuccessful) { if (response.header("status") == Constance.UNKNOWN_ERROR) { toastResponse("Ошибка загрузки. Пользователь не найден") } else { val inputStream = response.body?.byteStream() val bitmap = BitmapFactory.decodeStream(inputStream) onImageReceived.invoke(bitmap) } } else toastResponse("Ошибка загрузки фото") } } catch (ex: IOException) { toastResponse("Ошибка соединения") } } /** * Method gets information about video file from server. * * @param id is an id of video which was analysed. */ fun getInfo(id: String, onInfoReceived: (FileInfo) -> Unit){ val requestBody = FormBody.Builder() .add("token", Client.token) .add("file_id", id) .build() val client = Client.client.getClient() val request = Client.client.getRequest("archive/file_info/", requestBody) try { client.newCall(request).execute().use { response -> if (response.isSuccessful) { if (response.header("status") == Constance.UNKNOWN_ERROR) { toastResponse("Ошибка загрузки. Пользователь не найден") } else { val info = gson.fromJson( response.body?.string(), FileInfo::class.java ) onInfoReceived.invoke(info) } } else toastResponse("Ошибка загрузки информации") } } catch (ex: IOException) { toastResponse("Ошибка соединения") } } /** * Method gets numbers that were send to users email. * * @param email is an email for sending numbers. */ fun getEmailCheckNumbers(email: String, onNumbersReceived: (String) -> Unit) { val requestBody = FormBody.Builder() .add("email", email) .build() Client.client.postRequest("password_recovery/", requestBody, object : Callback { override fun onFailure(call: Call, e: IOException) { toastResponse("Ошибка соединения" + e.message) } override fun onResponse(call: Call, response: Response) { val responseBody = response.body if (response.isSuccessful) { if (response.header("status") == Constance.EMAIL_REGISTERED) { val numbers = responseBody?.string() toastResponse("Письмо отправлено на почту") if (numbers != null) { onNumbersReceived.invoke(numbers) } else toastResponse("Неизвестная ошибка. Попробуйте позже") } else { toastResponse("Неверная почта") } } else toastResponse("Неизвестная ошибка. Попробуйте позже") } }) } /** * Post request to logout to delete token. */ fun logoutUser(onStatusReceived: (Boolean) -> Unit) { val requestBody = FormBody.Builder() .add("token", Client.token) .build() Client.client.postRequest("logout/", requestBody, object : Callback { override fun onFailure(call: Call, e: IOException) { toastResponse("Ошибка соединения") } override fun onResponse(call: Call, response: Response) { if (response.isSuccessful) { if (response.header("status") == Constance.LOGOUT_SUCCESS) { Client.resetData() onStatusReceived.invoke(true) } else { toastResponse("Неизвестная ошибка. Свяжитесь с тех. поддержкой") } } else toastResponse("Неизвестная ошибка. Повторите позже") } }) } /** * Method gets arrays of entries to draw charts. */ fun getGraphStatistics(onStatisticsReceived: (Statistics) -> Unit) { val requestBody = FormBody.Builder() .add("token", Client.token) .build() Client.client.postRequest("statistics/", requestBody, object : Callback { override fun onFailure(call: Call, e: IOException) { toastResponse("Ошибка соединения") } override fun onResponse(call: Call, response: Response) { if (response.isSuccessful) { if (response.header("status") != Constance.UNKNOWN_ERROR) { val statistics = gson.fromJson( response.body?.string(), Statistics::class.java ) onStatisticsReceived.invoke(statistics) } else toastResponse("Ошибка загрузки статистики. Обратитесь в поддержку") } else toastResponse("Ошибка загрузки статистики") } }) } /** * Method post request to authorize user. * * @param username is users email. * @param password is users password. */ fun auth(username: String, password: String, onTokenReceived: () -> Unit) { val requestBody = FormBody.Builder() .add("email", username) .add("password", password) .build() Client.client.postRequest("login/", requestBody, object : Callback { override fun onFailure(call: Call, e: IOException) { toastResponse("Ошибка соединения" + e.message) } override fun onResponse(call: Call, response: Response) { if (response.isSuccessful) { if (response.header("status") == Constance.CORRECT_AUTH_STATUS) { Client.token = response.body?.string().toString() toastResponse("Успешная авторизация") onTokenReceived.invoke() } else { when (response.header("status")) { Constance.EMAIL_ERROR -> toastResponse("Неверная почта") Constance.PASSWORD_ERROR -> toastResponse("Неверный пароль") } } } else toastResponse("Ошибка авторизации") } }) } /** * Method gets number of analysed videos. */ fun getNumberOfFiles(onNumberReceived: (FilesNumbers) -> Unit) { val requestBody = FormBody.Builder() .add("token", Client.token) .build() val client = Client.client.getClient() val request = Client.client.getRequest("archive/number_of_files/", requestBody) try { client.newCall(request).execute().use { response -> if (response.isSuccessful) { if (response.header("status") == Constance.FILES_FOUND) { try { val gson = Gson() val responseData = gson.fromJson( response.body?.string(), FilesNumbers::class.java ) onNumberReceived.invoke(responseData) } catch (ex: Exception) { Log.d("tag", ex.message.toString()) toastResponse(ex.message.toString()) } } else toastResponse("Ошибка загрузки. Пользователь не найден") } else toastResponse("Ошибка загрузки статистики") } } catch (ex: IOException) { toastResponse("Ошибка соединения") } } /** * Method send request to change password. * * @param email an email of user who changes password. * @param password a new password of user. */ fun changePassword(email: String, password: String, onTokenReceived: () -> Unit) { val requestBody = FormBody.Builder() .add("email", email) .add("password", password) .build() Client.client.postRequest("password_update/", requestBody, object : Callback { override fun onFailure(call: Call, e: IOException) { toastResponse("Ошибка соединения") } override fun onResponse(call: Call, response: Response) { val responseBody = response.body if (response.isSuccessful) { if (response.header("status") == Constance.PASSWORD_CHANGED) { Client.token = responseBody?.string().toString() toastResponse("Успешная смена пароля") onTokenReceived.invoke() } else { toastResponse("Ошибка сервера. Повторите позже") } } else toastResponse("Ошибка смены пароля") } }) } /** * Post request to get recommendations for authorized user. */ fun getRecommendations(onRecommendationsReceived: (RecommendationsInfo) -> Unit) { val requestBody = FormBody.Builder() .add("token", Client.token) .build() Client.client.postRequest("recommendations/", requestBody, object : Callback { override fun onFailure(call: Call, e: IOException) { toastResponse("Ошибка соединения") } override fun onResponse(call: Call, response: Response) { if (response.isSuccessful) { if (response.header("status") == Constance.UNKNOWN_ERROR) { toastResponse("Ошибка загрузки файла. Пользователь не найден") } else { val gson = Gson() val info = gson.fromJson( response.body?.string(), RecommendationsInfo::class.java ) onRecommendationsReceived.invoke(info) } } else toastResponse("Ошибка загрузки информации") } }) } /** * Method post request for user registration. * * @param username is an email to registrate user. * @param password ia users password. */ fun register(username: String, password: String, onRegister:() -> Unit) { val requestBody = FormBody.Builder() .add("email", username) .add("password", password) .build() Client.client.postRequest("register/", requestBody, object : Callback { override fun onFailure(call: Call, e: IOException) { toastResponse("Ошибка соединения") } override fun onResponse(call: Call, response: Response) { val responseBody = response.body if (response.isSuccessful) { if (response.header("status") == Constance.REGISTRATION_SUCCESS) { Client.token = responseBody?.string().toString() toastResponse("Успешная регистрация") onRegister.invoke() } else { when (response.header("status")) { Constance.ACCOUNT_EXIST_STATUS -> toastResponse("Аккаунт с такой почтой уже существует") Constance.UNKNOWN_ERROR -> toastResponse("Ошибка сервера. Обратитесь в поддержку") else -> toastResponse("Неверный формат данных") } } } else toastResponse("Ошибка регистрации") } }) } /** * Method make toast with message to user. */ fun toastResponse(text: String) { (context as? Activity)?.runOnUiThread { Toast.makeText(context, text, Toast.LENGTH_SHORT).show() } } }
Speaker-Trainer/app/src/main/java/com/app/speakertrainer/modules/TypefaceSpan.kt
62095089
package com.app.speakertrainer.modules import android.graphics.Typeface import android.text.TextPaint import android.text.style.MetricAffectingSpan /** * Class is a custom implementation of MetricAffectingSpan that applies a custom typeface to text. */ class TypefaceSpan(private val typeface: Typeface) : MetricAffectingSpan() { /** * Method sets typeface. * * @param paint a TextPaint to change typeface. */ override fun updateDrawState(paint: TextPaint) { paint.typeface = typeface } /** * Method updates measure state. * * @param paint a TextPaint to change typeface. */ override fun updateMeasureState(paint: TextPaint) { paint.typeface = typeface } }
Speaker-Trainer/app/src/main/java/com/app/speakertrainer/modules/RecordAdapter.kt
2556448732
package com.app.speakertrainer.modules import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.app.speakertrainer.R import com.app.speakertrainer.data.Record import com.app.speakertrainer.databinding.RecordItemBinding /** * Class is an adapter for displaying records in a RecyclerView. */ class RecordAdapter : RecyclerView.Adapter<RecordAdapter.RecordHolder>() { /** * It includes an interface for item click events and a ViewHolder inner class to bind data to views. */ interface onItemClickListener { fun onItemClick(position: Int) } val recordList = ArrayList<Record>() private lateinit var mListener: onItemClickListener /** * Class for setting records to corresponded binding. * * @param item a View to set elements. * @param listener a listener to click on item event. */ class RecordHolder(item: View, listener: onItemClickListener) : RecyclerView.ViewHolder(item) { val binding = RecordItemBinding.bind(item) /** * Method binds record. * * @param record a record to bind. */ fun bind(record: Record) = with(binding) { im.setImageBitmap(record.image) tvName.text = record.title tvDate.text = record.date } /** * Set click listener. */ init { itemView.setOnClickListener { listener.onItemClick(adapterPosition) } } } /** * Method inflates the layout for each item in the RecyclerView. * * @param parent a ViewGroup to get context from. * @param viewType an Int value used for identifying the type of view to be created. * @return a RecordHolder instance associated with the inflated view. */ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecordHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.record_item, parent, false) return RecordHolder(view, mListener) } /** * Gets number of records in recordList. */ override fun getItemCount(): Int { return recordList.size } /** * Method binds data to the ViewHolder. * * @param holder a RecordHolder to bind element. * @param position a Int index of recordList element to bind. */ override fun onBindViewHolder(holder: RecordHolder, position: Int) { holder.bind(recordList[position]) } /** * Method adds record to recordList. * * @param record a record to add to reordList. */ fun addRecord(record: Record) { recordList.add(record) notifyDataSetChanged() } /** * Method set click listener to items. * * @param listener a listener to notify item click events. */ fun setOnItemClickListener(listener: onItemClickListener) { mListener = listener } }
Speaker-Trainer/app/src/main/java/com/app/speakertrainer/modules/NetworkClient.kt
1585401364
package com.app.speakertrainer.modules import okhttp3.Callback import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody import java.util.concurrent.TimeUnit /** * This Class defines the `NetworkClient` class responsible for making HTTP requests using OkHttp library. */ class NetworkClient { var partUrl = "http://10.0.2.2:8000/" private val client = OkHttpClient.Builder() .readTimeout(600, TimeUnit.SECONDS) .writeTimeout(600, TimeUnit.SECONDS) .build() /** * The `postRequest` function sends a POST request with the specified URL and request body. * * @param url a string url to post request. * @param requestBody a request bode to post request. */ fun postRequest(url: String, requestBody: RequestBody, callback: Callback) { val request = Request.Builder() .url(partUrl + url) .post(requestBody) .build() client.newCall(request).enqueue(callback) } /** * The `getRequest` function creates a GET request with the specified URL and request body. * * @param url a string url to post request. * @param requestBody a request bode to post request. */ fun getRequest(url: String, requestBody: RequestBody): Request { return Request.Builder() .url(partUrl + url) .post(requestBody) .build() } /** * Method gets client. */ fun getClient(): OkHttpClient { return client } }
Speaker-Trainer/app/src/main/java/com/app/speakertrainer/modules/Client.kt
1160391479
package com.app.speakertrainer.modules import android.content.Context import android.graphics.Color import android.text.Spannable import android.text.SpannableString import androidx.core.content.res.ResourcesCompat import com.app.speakertrainer.R import com.app.speakertrainer.data.Record import com.github.mikephil.charting.data.Entry import com.github.mikephil.charting.data.PieEntry /** * This Class contains the `Client` object which holds network client, data, and text entries. */ object Client { val client: NetworkClient = NetworkClient() var token: String = "" var graphEntries = arrayListOf( Entry(0f, 10f), Entry(1f, 20f), Entry(2f, 15f), Entry(3f, 30f), Entry(4f, 25f) ) var lineGraphEntries = arrayListOf( Entry(0f, 4f), Entry(1f, 5f), Entry(2f, 11f), Entry(3f, 3f), Entry(4f, 21f), Entry(5f, 26f) ) var pieEntries = arrayListOf(PieEntry(1f, 25f), PieEntry(2f, 75f)) var recordList = ArrayList<Record>() var pieText = "Здесь будет отображаться ваш прогресс. Пример" var lineText = "Здесь будет отображаться ваш прогресс. Пример" val colors = arrayListOf(Color.rgb(64, 224, 208), Color.rgb(60, 179, 113), Color.rgb(60, 179, 113), Color.rgb(70, 130, 180), Color.rgb(169, 169, 169)) /** * The `resetData` function resets all the data fields to their initial values. */ fun resetData() { token = "" recordList = ArrayList<Record>() graphEntries = arrayListOf( Entry(0f, 10f), Entry(1f, 20f), Entry(2f, 15f), Entry(3f, 30f), Entry(4f, 25f), Entry(5f, 35f) ) pieEntries = arrayListOf(PieEntry(1f, 25f), PieEntry(2f, 75f)) lineGraphEntries = arrayListOf( Entry(0f, 4f), Entry(1f, 5f), Entry(2f, 11f), Entry(3f, 3f), Entry(4f, 21f), Entry(5f, 26f) ) pieText = "Здесь будет отображаться ваш прогресс. Пример" lineText = "Здесь будет отображаться ваш прогресс. Пример" } /** * The `setCustomString` function creates a SpannableString with custom typefaces for different parts. * * @param boldText is string to make bold. * @param regularText is string to concatenate with bold text. */ fun setCustomString(boldText: String, regularText: String, context: Context): SpannableString { val boldTypeface = ResourcesCompat.getFont(context, R.font.comfortaa_bold) val regularTypeface = ResourcesCompat.getFont(context, R.font.comfortaa_light) val spannableString = SpannableString("$boldText: $regularText") spannableString.setSpan( TypefaceSpan(boldTypeface!!), 0, boldText.length + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) spannableString.setSpan( TypefaceSpan(regularTypeface!!), boldText.length + 2, spannableString.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) return spannableString } }
Speaker-Trainer/app/src/main/java/com/app/speakertrainer/data/Record.kt
873651075
package com.app.speakertrainer.data import android.graphics.Bitmap /** * Data class containing record data. */ data class Record(val image: Bitmap, val title: String, val date: String, val index: Int)
Speaker-Trainer/app/src/main/java/com/app/speakertrainer/data/FileInfo.kt
1370980745
package com.app.speakertrainer.data /** * Data class containing filename and datetime when video record was sent to server. */ data class FileInfo(val filename: String, val datetime: String)
Speaker-Trainer/app/src/main/java/com/app/speakertrainer/data/ResponseResults.kt
592390480
package com.app.speakertrainer.data /** * Data class containing analysis results. */ data class ResponseResults( val clean_speech: String?, val speech_rate: String?, val background_noise: String?, val intelligibility: String?, val clothes: String?, val gestures: String?, val angle: String?, val glances: String?, val emotionality: String?, val low_speech_rate_timestamps: List<List<String>>?, val background_noise_timestamps: List<List<String>>?, val filler_words: List<String>? )
Speaker-Trainer/app/src/main/java/com/app/speakertrainer/data/FilesNumbers.kt
2410999460
package com.app.speakertrainer.data /** * Data containing info about number af files and ids. */ data class FilesNumbers(val num_of_files: Int, val file_ids: List<Int>)
Speaker-Trainer/app/src/main/java/com/app/speakertrainer/data/Statistics.kt
2049379067
package com.app.speakertrainer.data /** * Data class for converting values from json. These values are used for drawing graphs. */ data class Statistics( val speech_rate: List<Float>?, val angle: List<Float>?, val filler_words: List<String>?, val filler_words_percentage: List<Float>? )
Speaker-Trainer/app/src/main/java/com/app/speakertrainer/data/RecommendationsInfo.kt
149278697
package com.app.speakertrainer.data /** * Data class containing recommendations after analysing. */ data class RecommendationsInfo( val clean_speech: String?, val speech_rate: String?, val background_noise: String?, val intelligibility: String?, val clothes: String?, val gestures: String?, val angle: String?, val glances: String?, val emotionality: String? )
notes-api/src/main/kotlin/com/jalloft/noteskt/dto/OtherResponse.kt
3508296939
package com.jalloft.noteskt.dto import kotlinx.serialization.Serializable @Serializable data class OtherResponse( val code: Int, val message: String )
notes-api/src/main/kotlin/com/jalloft/noteskt/dto/AuthRequest.kt
3448066750
package com.jalloft.noteskt.dto import kotlinx.serialization.Serializable @Serializable data class AuthRequest( val email: String, val password: String )
notes-api/src/main/kotlin/com/jalloft/noteskt/dto/NoteResponse.kt
2062847933
package com.jalloft.noteskt.dto import com.jalloft.noteskt.models.Note import com.jalloft.noteskt.serialization.LocalDateSerializer import kotlinx.serialization.Serializable import java.time.LocalDateTime @Serializable data class NoteResponse( val id: String, val title: String, val content: String, @Serializable(with = LocalDateSerializer::class) val createdAt: LocalDateTime ) fun Note.toNoteResponse() = NoteResponse( id.toString(), title, content, createdAt )
notes-api/src/main/kotlin/com/jalloft/noteskt/dto/AuthResponse.kt
3929482064
package com.jalloft.noteskt.dto import kotlinx.serialization.Serializable @Serializable data class AuthResponse( val token: String )
notes-api/src/main/kotlin/com/jalloft/noteskt/dto/NoteRequest.kt
114961162
package com.jalloft.noteskt.dto import com.jalloft.noteskt.models.Note import com.jalloft.noteskt.serialization.UUIDSerializer import kotlinx.serialization.Serializable import java.util.* @Serializable data class NoteRequest( val title: String, val content: String, @Serializable(with = UUIDSerializer::class) val userId: UUID? = null, ) { fun toNote() = Note(title = title, content = content, userId = userId) }
notes-api/src/main/kotlin/com/jalloft/noteskt/database/DatabaseFactory.kt
910673858
package com.jalloft.noteskt.database import com.jalloft.noteskt.models.Notes import kotlinx.coroutines.Dispatchers import org.jetbrains.exposed.sql.Database import org.jetbrains.exposed.sql.SchemaUtils import org.jetbrains.exposed.sql.transactions.experimental.newSuspendedTransaction import org.jetbrains.exposed.sql.transactions.transaction object DatabaseFactory { fun init(){ val database = Database.connect( url = System.getenv("DATABASE_URL"), driver = "org.postgresql.Driver", user = System.getenv("DATABASE_USERNAME"), password = System.getenv("DATABASE_PASSWORD") ) transaction(database){ SchemaUtils.create(Notes) } } suspend fun <T> dbQuery(block: suspend () -> T): T = newSuspendedTransaction(Dispatchers.IO) { block() } }
notes-api/src/main/kotlin/com/jalloft/noteskt/repository/NoteRepository.kt
2643890809
package com.jalloft.noteskt.repository import com.jalloft.noteskt.dao.note.NoteDao import com.jalloft.noteskt.dao.note.NoteDaoImpl import com.jalloft.noteskt.models.Note class NoteRepository( private val dao: NoteDao = NoteDaoImpl() ) { suspend fun notes(userId: String) = dao.allNotes(userId) suspend fun note(noteId: String, userId: String) = dao.note(noteId, userId) suspend fun save(note: Note) = dao.save(note) suspend fun edit(noteId: String, note: Note) = dao.edit(noteId, note) suspend fun saveAll(notes: List<Note>) = dao.saveAll(notes) suspend fun delete(noteId: String) = dao.delete(noteId) }
notes-api/src/main/kotlin/com/jalloft/noteskt/repository/UserRepository.kt
523977395
package com.jalloft.noteskt.repository import com.jalloft.noteskt.dao.user.UserDao import com.jalloft.noteskt.dao.user.UserDaoImpl import com.jalloft.noteskt.models.User class UserRepository( private val dao: UserDao = UserDaoImpl() ) { suspend fun findUserByEmail(email: String) = dao.findUserByEmail(email) suspend fun saveUser(user: User) = dao.saveUser(user) }
notes-api/src/main/kotlin/com/jalloft/noteskt/Application.kt
4187176
package com.jalloft.noteskt import com.jalloft.noteskt.database.DatabaseFactory import com.jalloft.noteskt.plugins.configureRouting import com.jalloft.noteskt.plugins.configureSecurity import com.jalloft.noteskt.plugins.configureSerialization import com.jalloft.noteskt.plugins.configureStatusPage import com.jalloft.noteskt.repository.NoteRepository import com.jalloft.noteskt.repository.UserRepository import com.jalloft.noteskt.security.hashing.SHA256HashingService import com.jalloft.noteskt.security.token.JwtTokenService import com.jalloft.noteskt.security.token.TokenConfig import io.ktor.server.application.* fun main(args: Array<String>) { io.ktor.server.netty.EngineMain.main(args) } fun Application.module() { val tokenService = JwtTokenService() val tokenConfig = TokenConfig( issuer = environment.config.property("jwt.issuer").getString(), audience = environment.config.property("jwt.audience").getString(), expiresIn = 365L * 1000L * 60L * 60L * 24L, secret = System.getenv("JWT_SECRET") ) val hashingService = SHA256HashingService() val noteRepo = NoteRepository() val userRepo = UserRepository() DatabaseFactory.init() configureSerialization() configureStatusPage() configureSecurity(tokenConfig) configureRouting(noteRepo, userRepo, hashingService, tokenService, tokenConfig) }
notes-api/src/main/kotlin/com/jalloft/noteskt/security/token/TokenClaim.kt
2609684956
package com.jalloft.noteskt.security.token data class TokenClaim( val name: String, val value: String )
notes-api/src/main/kotlin/com/jalloft/noteskt/security/token/TokenService.kt
3132866280
package com.jalloft.noteskt.security.token interface TokenService { fun generate( config: TokenConfig, vararg claims: TokenClaim ): String }
notes-api/src/main/kotlin/com/jalloft/noteskt/security/token/JwtTokenService.kt
744943561
package com.jalloft.noteskt.security.token import com.auth0.jwt.JWT import com.auth0.jwt.algorithms.Algorithm import java.util.* class JwtTokenService: TokenService { override fun generate(config: TokenConfig, vararg claims: TokenClaim): String { var token = JWT.create() .withAudience(config.audience) .withIssuer(config.issuer) .withExpiresAt(Date(System.currentTimeMillis() + config.expiresIn)) claims.forEach { claim -> token = token.withClaim(claim.name, claim.value) } return token.sign(Algorithm.HMAC256(config.secret)) } }
notes-api/src/main/kotlin/com/jalloft/noteskt/security/token/TokenConfig.kt
1793161922
package com.jalloft.noteskt.security.token data class TokenConfig( val issuer: String, val audience: String, val expiresIn: Long, val secret: String )
notes-api/src/main/kotlin/com/jalloft/noteskt/security/hashing/HashingService.kt
1627462456
package com.jalloft.noteskt.security.hashing interface HashingService { fun generateSaltedHash(value: String, saltLength: Int = 32): SaltedHash fun verify(value: String, saltedHash: SaltedHash): Boolean }
notes-api/src/main/kotlin/com/jalloft/noteskt/security/hashing/SaltedHash.kt
123645532
package com.jalloft.noteskt.security.hashing data class SaltedHash( val hash: String, val salt: String )
notes-api/src/main/kotlin/com/jalloft/noteskt/security/hashing/SHA256HashingService.kt
2619393247
package com.jalloft.noteskt.security.hashing import org.apache.commons.codec.binary.Hex import org.apache.commons.codec.digest.DigestUtils import java.security.SecureRandom class SHA256HashingService: HashingService { override fun generateSaltedHash(value: String, saltLength: Int): SaltedHash { val salt = SecureRandom.getInstance("SHA1PRNG").generateSeed(saltLength) val saltAsHex = Hex.encodeHexString(salt) val hash = DigestUtils.sha256Hex("$saltAsHex$value") return SaltedHash( hash = hash, salt = saltAsHex ) } override fun verify(value: String, saltedHash: SaltedHash): Boolean { return DigestUtils.sha256Hex(saltedHash.salt + value) == saltedHash.hash } }
notes-api/src/main/kotlin/com/jalloft/noteskt/plugins/Routing.kt
267905119
package com.jalloft.noteskt.plugins import com.jalloft.noteskt.repository.NoteRepository import com.jalloft.noteskt.repository.UserRepository import com.jalloft.noteskt.routes.* import com.jalloft.noteskt.security.hashing.HashingService import com.jalloft.noteskt.security.token.TokenConfig import com.jalloft.noteskt.security.token.TokenService import io.ktor.server.application.* import io.ktor.server.auth.* import io.ktor.server.routing.* fun Application.configureRouting( noteRepo: NoteRepository, userRepo: UserRepository, hashingService: HashingService, tokenService: TokenService, tokenConfig: TokenConfig ) { routing { authenticate { getNotes(noteRepo) getNote(noteRepo) postNote(noteRepo) postNotes(noteRepo) deleteNote(noteRepo) putNote(noteRepo) } signIn(userRepo, hashingService, tokenService, tokenConfig) signUp(hashingService, userRepo) authenticate() getSecretInfo() } }
notes-api/src/main/kotlin/com/jalloft/noteskt/plugins/Serialization.kt
1473978943
package com.jalloft.noteskt.plugins import io.ktor.serialization.kotlinx.json.* import io.ktor.server.application.* import io.ktor.server.plugins.contentnegotiation.* import kotlinx.serialization.json.Json fun Application.configureSerialization() { install(ContentNegotiation) { json(Json { ignoreUnknownKeys = true }) } }
notes-api/src/main/kotlin/com/jalloft/noteskt/plugins/Status.kt
2808075603
package com.jalloft.noteskt.plugins import com.jalloft.noteskt.exceptions.AuthenticationException import com.jalloft.noteskt.exceptions.UserNotFoundException import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.plugins.statuspages.* import io.ktor.server.response.* fun Application.configureStatusPage(){ install(StatusPages) { exception<AuthenticationException> { call, cause -> call.respond(status = HttpStatusCode.Unauthorized, message = cause.message ?: "Authentication failed!") } exception<UserNotFoundException> { call, cause -> call.respond(status = HttpStatusCode.Unauthorized, message = cause.message ?: "Authentication failed!") } status(HttpStatusCode.NotFound) { call, status -> call.respond(message = "404: Page Not Found", status = status) } } }
notes-api/src/main/kotlin/com/jalloft/noteskt/plugins/Security.kt
3448442348
package com.jalloft.noteskt.plugins import com.auth0.jwt.JWT import com.auth0.jwt.algorithms.Algorithm import com.jalloft.noteskt.exceptions.AuthenticationException import com.jalloft.noteskt.security.token.TokenConfig import io.ktor.server.application.* import io.ktor.server.auth.* import io.ktor.server.auth.jwt.* import io.ktor.server.plugins.* fun Application.configureSecurity(config: TokenConfig) { install(Authentication) { jwt { realm = [email protected]("jwt.realm").getString() verifier( JWT .require(Algorithm.HMAC256(config.secret)) .withAudience(config.audience) .withIssuer(config.issuer) .build() ) validate { credential -> if (credential.payload.audience.contains(config.audience)) { JWTPrincipal(credential.payload) } else null } challenge { _, _ -> call.request.headers["Authorization"]?.let { if (it.isNotEmpty()) { throw AuthenticationException("Token Expired") } else { throw BadRequestException("Authorization header can not be blank!") } } ?: throw AuthenticationException("You are not authorized to access") } } } }
notes-api/src/main/kotlin/com/jalloft/noteskt/serialization/UUIDSerializer.kt
2891912568
package com.jalloft.noteskt.serialization import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializer import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import java.util.* @OptIn(ExperimentalSerializationApi::class) @Serializer(forClass = UUID::class) object UUIDSerializer : KSerializer<UUID> { override fun serialize(encoder: Encoder, value: UUID) { encoder.encodeString(value.toString()) } override fun deserialize(decoder: Decoder): UUID { return UUID.fromString(decoder.decodeString()) } }
notes-api/src/main/kotlin/com/jalloft/noteskt/serialization/LocalDateSerializer.kt
225923155
package com.jalloft.noteskt.serialization import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializer import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import java.time.LocalDateTime import java.time.format.DateTimeFormatter @OptIn(ExperimentalSerializationApi::class) @Serializer(forClass = LocalDateTime::class) object LocalDateSerializer : KSerializer<LocalDateTime> { private val formatter: DateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME override fun serialize(encoder: Encoder, value: LocalDateTime) { encoder.encodeString(value.format(formatter)) } override fun deserialize(decoder: Decoder): LocalDateTime { return LocalDateTime.parse(decoder.decodeString(), formatter) } }
notes-api/src/main/kotlin/com/jalloft/noteskt/dao/note/NoteDaoImpl.kt
3475208618
package com.jalloft.noteskt.dao.note import com.jalloft.noteskt.database.DatabaseFactory import com.jalloft.noteskt.models.Note import com.jalloft.noteskt.models.Notes import com.jalloft.noteskt.utils.toUUID import org.jetbrains.exposed.sql.* import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq import org.jetbrains.exposed.sql.statements.InsertStatement class NoteDaoImpl : NoteDao { override suspend fun allNotes(userId: String): List<Note> = DatabaseFactory.dbQuery { val uuid = userId.toUUID() ?: return@dbQuery emptyList() Notes.selectAll().where { Notes.userId eq uuid }.map(::resultRowToNote) } override suspend fun note(noteId: String, userId: String): Note? = DatabaseFactory.dbQuery { val uuidNote = noteId.toUUID() ?: return@dbQuery null val uuidUser = userId.toUUID() ?: return@dbQuery null Notes.selectAll().where { Notes.userId eq uuidUser }.andWhere { Notes.id eq uuidNote } .map(::resultRowToNote) .singleOrNull() } override suspend fun save(note: Note) = DatabaseFactory.dbQuery { val insertStatement = Notes.insert { insertNoteRows(it, note) } insertStatement.resultedValues?.singleOrNull()?.let(::resultRowToNote) } override suspend fun edit(noteId: String, note: Note): Boolean { val uuid = noteId.toUUID() ?: return false return Notes.update({ Notes.id eq uuid }) { it[Notes.title] = note.title it[Notes.content] = note.content } > 0 } override suspend fun delete(noteId: String): Boolean { val uuid = noteId.toUUID() ?: return false return Notes.deleteWhere { Notes.id eq uuid } > 0 } override suspend fun saveAll(notes: List<Note>) = DatabaseFactory.dbQuery { val insertStatements = notes.map { note -> Notes.insert { insertNoteRows(it, note) } } insertStatements.map { it.resultedValues?.singleOrNull()?.let(::resultRowToNote) } } private fun resultRowToNote(row: ResultRow) = Note( id = row[Notes.id], userId = row[Notes.userId], title = row[Notes.title], content = row[Notes.content], createdAt = row[Notes.createdAt] ) private fun insertNoteRows(insertStatement: InsertStatement<Number>, note: Note) { insertStatement[Notes.id] = note.id note.userId?.let { insertStatement[Notes.userId] = it } insertStatement[Notes.title] = note.title insertStatement[Notes.content] = note.content insertStatement[Notes.createdAt] = note.createdAt } }
notes-api/src/main/kotlin/com/jalloft/noteskt/dao/note/NoteDao.kt
256896980
package com.jalloft.noteskt.dao.note import com.jalloft.noteskt.models.Note interface NoteDao { suspend fun allNotes(userId: String): List<Note> suspend fun note(noteId: String, userId: String): Note? suspend fun save(note: Note): Note? suspend fun edit(noteId: String, note: Note): Boolean suspend fun delete(noteId: String): Boolean suspend fun saveAll(notes: List<Note>): List<Note?> }
notes-api/src/main/kotlin/com/jalloft/noteskt/dao/user/UserDaoImpl.kt
3548208924
package com.jalloft.noteskt.dao.user import com.jalloft.noteskt.database.DatabaseFactory import com.jalloft.noteskt.models.User import com.jalloft.noteskt.models.Users import org.jetbrains.exposed.sql.insert import org.jetbrains.exposed.sql.selectAll class UserDaoImpl : UserDao { override suspend fun findUserByEmail(email: String): User? = DatabaseFactory.dbQuery { Users.selectAll() .where { Users.email eq email } .map { User(it[Users.id], it[Users.email], it[Users.password], it[Users.salt]) } .singleOrNull() } override suspend fun saveUser(user: User) = DatabaseFactory.dbQuery { val insertStatement = Users.insert { it[id] = user.id it[email] = user.email it[password] = user.password it[salt] = user.salt } insertStatement.resultedValues.orEmpty().isNotEmpty() } }
notes-api/src/main/kotlin/com/jalloft/noteskt/dao/user/UserDao.kt
2059403877
package com.jalloft.noteskt.dao.user import com.jalloft.noteskt.models.User interface UserDao { suspend fun findUserByEmail(email: String): User? suspend fun saveUser(user: User): Boolean }
notes-api/src/main/kotlin/com/jalloft/noteskt/utils/Extensions.kt
1403201659
package com.jalloft.noteskt.utils import java.util.* fun String.toUUID(): UUID? = try { UUID.fromString(this) } catch (_: Throwable) { null }
notes-api/src/main/kotlin/com/jalloft/noteskt/models/Note.kt
1773077157
package com.jalloft.noteskt.models import org.jetbrains.exposed.sql.Table import org.jetbrains.exposed.sql.javatime.CurrentDateTime import org.jetbrains.exposed.sql.javatime.datetime import java.time.LocalDateTime import java.util.* data class Note( val id: UUID = UUID.randomUUID(), val userId: UUID? = null, val title: String, val content: String, val createdAt: LocalDateTime = LocalDateTime.now() ) object Notes : Table() { val id = uuid("id").autoGenerate() val userId = uuid("userId").references(Users.id) val title = varchar("title", 128) val content = varchar("content", 1024) val createdAt = datetime("createdIn").defaultExpression(CurrentDateTime) override val primaryKey = PrimaryKey(id) }
notes-api/src/main/kotlin/com/jalloft/noteskt/models/User.kt
1666993124
package com.jalloft.noteskt.models import org.jetbrains.exposed.sql.Table import java.util.* data class User( val id: UUID = UUID.randomUUID(), val email: String, val password: String, val salt: String, ) object Users: Table(){ val id = uuid("id").autoGenerate() val email = varchar("email", 255) val password = varchar("password", 255) val salt = varchar("salt", 128) override val primaryKey = PrimaryKey(id) }
notes-api/src/main/kotlin/com/jalloft/noteskt/exceptions/AuthenticationException.kt
1518596341
package com.jalloft.noteskt.exceptions data class AuthenticationException( override val message: String? = null, override val cause: Throwable? = null ): Throwable(message, cause)
notes-api/src/main/kotlin/com/jalloft/noteskt/exceptions/UserNotFoundException.kt
2817984432
package com.jalloft.noteskt.exceptions data class UserNotFoundException( override val message: String? = null, override val cause: Throwable? = null ): Throwable(message, cause)
notes-api/src/main/kotlin/com/jalloft/noteskt/routes/NoteRoutes.kt
994202199
package com.jalloft.noteskt.routes import com.jalloft.noteskt.dto.NoteRequest import com.jalloft.noteskt.dto.OtherResponse import com.jalloft.noteskt.dto.toNoteResponse import com.jalloft.noteskt.repository.NoteRepository import com.jalloft.noteskt.utils.toUUID import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.auth.* import io.ktor.server.auth.jwt.* import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* import org.jetbrains.exposed.sql.transactions.experimental.newSuspendedTransaction fun Route.getNotes(noteRepo: NoteRepository){ get("/notes") { val principal = call.principal<JWTPrincipal>() val userId = principal?.payload?.getClaim("userId")?.asString() if (userId != null){ val notes = noteRepo.notes(userId).map { it.toNoteResponse() } call.respond(HttpStatusCode.OK, notes) }else{ call.respond(HttpStatusCode.Unauthorized) } } } fun Route.getNote(noteRepo: NoteRepository){ get("/note/{id?}") { val noteId = call.parameters["id"] ?: return@get call.respond( HttpStatusCode.BadRequest, OtherResponse(HttpStatusCode.BadRequest.value, "ID ausente") ) val principal = call.principal<JWTPrincipal>() val userId = principal?.payload?.getClaim("userId")?.asString() if (userId != null) { val note = noteRepo.note(noteId, userId) ?: return@get call.respond( HttpStatusCode.NotFound, OtherResponse(HttpStatusCode.NotFound.value, "Nenhuma anotação encontrada com este ID") ) call.respond(HttpStatusCode.OK, note.toNoteResponse()) } else { call.respond(HttpStatusCode.Unauthorized) } } } fun Route.deleteNote(noteRepo: NoteRepository){ delete("/note/{id?}") { val noteId = call.parameters["id"] ?: return@delete call.respond(HttpStatusCode.BadRequest) newSuspendedTransaction { val isDeleted = noteRepo.delete(noteId) if (isDeleted) { call.respond( HttpStatusCode.Accepted, OtherResponse(HttpStatusCode.Accepted.value, "Anotação excluída com sucesso") ) } else { call.respond( HttpStatusCode.NotFound, OtherResponse(HttpStatusCode.NotFound.value, "Nenhuma anotação encontrada com este ID") ) } } } } fun Route.postNote(noteRepo: NoteRepository){ post("/note") { val principal = call.principal<JWTPrincipal>() val userId = principal?.payload?.getClaim("userId")?.asString()?.toUUID() if (userId != null) { val noteRequest = call.receive<NoteRequest>() val note = noteRepo.save(noteRequest.copy(userId = userId).toNote()) ?: return@post call.respond(HttpStatusCode.BadRequest) call.respond(HttpStatusCode.Created, note.toNoteResponse()) }else{ call.respond(HttpStatusCode.Unauthorized) } } } fun Route.postNotes(noteRepo: NoteRepository){ post("/notes") { val notesRequest = call.receive<List<NoteRequest>>() val savedNotes = noteRepo.saveAll(notesRequest.map { it.toNote() }) call.respond(HttpStatusCode.Created, savedNotes.map { it?.toNoteResponse() }) } } fun Route.putNote(noteRepo: NoteRepository){ put("/note/{id?}") { val noteId = call.parameters["id"] ?: return@put call.respond(HttpStatusCode.BadRequest) val noteRequest = call.receive<NoteRequest>() val isUpdated = noteRepo.edit(noteId, noteRequest.toNote()) if (isUpdated) { call.respond( HttpStatusCode.Accepted, OtherResponse(HttpStatusCode.Accepted.value, "Anotação atualizada com sucesso") ) } else { call.respond( HttpStatusCode.NotFound, OtherResponse(HttpStatusCode.NotFound.value, "Nenhuma anotação encontrada com este ID") ) } } }
notes-api/src/main/kotlin/com/jalloft/noteskt/routes/UserRoutes.kt
1947460051
package com.jalloft.noteskt.routes import com.jalloft.noteskt.dto.AuthRequest import com.jalloft.noteskt.dto.AuthResponse import com.jalloft.noteskt.models.User import com.jalloft.noteskt.repository.UserRepository import com.jalloft.noteskt.security.hashing.HashingService import com.jalloft.noteskt.security.hashing.SaltedHash import com.jalloft.noteskt.security.token.TokenClaim import com.jalloft.noteskt.security.token.TokenConfig import com.jalloft.noteskt.security.token.TokenService import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.auth.* import io.ktor.server.auth.jwt.* import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* import org.apache.commons.codec.digest.DigestUtils fun Route.signUp( hashingService: HashingService, repo: UserRepository ){ post("signup"){ val request = call.receive<AuthRequest>() val areFieldsBlank = request.email.isBlank() || request.password.isBlank() val isPwTooShort = request.password.length < 8 if(areFieldsBlank || isPwTooShort) { call.respond(HttpStatusCode.Conflict) return@post } val saltedHash = hashingService.generateSaltedHash(request.password) val user = User( email = request.email, password = saltedHash.hash, salt = saltedHash.salt ) val wasAcknowledged = repo.saveUser(user) if(!wasAcknowledged) { call.respond(HttpStatusCode.Conflict) return@post } call.respond(HttpStatusCode.OK) } } fun Route.signIn( repo: UserRepository, hashingService: HashingService, tokenService: TokenService, tokenConfig: TokenConfig ) { post("signin") { val request = call.receive<AuthRequest>() val user = repo.findUserByEmail(request.email) if(user == null) { call.respond(HttpStatusCode.Conflict, "Incorrect username or password") return@post } val isValidPassword = hashingService.verify( value = request.password, saltedHash = SaltedHash( hash = user.password, salt = user.salt ) ) if(!isValidPassword) { println("Entered hash: ${DigestUtils.sha256Hex("${user.salt}${request.password}")}, Hashed PW: ${user.password}") call.respond(HttpStatusCode.Conflict, "Incorrect username or password") return@post } val token = tokenService.generate( config = tokenConfig, TokenClaim( name = "userId", value = user.id.toString() ) ) call.respond( status = HttpStatusCode.OK, message = AuthResponse( token = token ) ) } } fun Route.authenticate() { authenticate { get("authenticate") { call.respond(HttpStatusCode.OK) } } } fun Route.getSecretInfo() { authenticate { get("secret") { val principal = call.principal<JWTPrincipal>() val userId = principal?.getClaim("userId", String::class) call.respond(HttpStatusCode.OK, "Your userId is $userId") } } }
Custom-Radio-Group-Buttons/radio-group-buttons/src/androidTest/java/com/muindi/stephen/radio_group_buttons/ExampleInstrumentedTest.kt
2012737974
package com.muindi.stephen.radio_group_buttons 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.muindi.stephen.radio_group_buttons.test", appContext.packageName) } }
Custom-Radio-Group-Buttons/radio-group-buttons/src/test/java/com/muindi/stephen/radio_group_buttons/ExampleUnitTest.kt
870396780
package com.muindi.stephen.radio_group_buttons 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) } }
Custom-Radio-Group-Buttons/radio-group-buttons/src/main/java/com/muindi/stephen/radio_group_buttons/RadioGroupButtons.kt
2173639334
package com.muindi.stephen.radio_group_buttons import android.annotation.SuppressLint import android.os.Bundle import android.view.View import android.widget.RadioButton import android.widget.RadioGroup import android.widget.TextView import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import com.muindi.stephen.radio_group_buttons.R.* class RadioGroupButtons : AppCompatActivity() { @SuppressLint("SetTextI18n") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContentView(R.layout.activity_radio_group_buttons) ViewCompat.setOnApplyWindowInsetsListener(findViewById(id.radio_group_buttons)) { v, insets -> val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom) insets } // This will get the radiogroup val rGroup = findViewById<View>(R.id.radioGroup1) as RadioGroup val tv = findViewById<TextView>(R.id.textView2) // This will get the radiobutton in the radiogroup that is checked val checkedRadioButton = rGroup.findViewById<View>(rGroup.checkedRadioButtonId) as RadioButton // This overrides the radiogroup onCheckListener rGroup.setOnCheckedChangeListener { group, checkedId -> // This will get the radiobutton that has changed in its check state val checkedRadioButton = group.findViewById<View>(checkedId) as RadioButton // This puts the value (true/false) into the variable val isChecked = checkedRadioButton.isChecked // If the radiobutton that has changed in check state is now checked... if (isChecked) { // Changes the textview's text to "Checked: example radiobutton text" tv.text = checkedRadioButton.getText() checkedRadioButton.setBackgroundResource(drawable.frame_51) checkedRadioButton.setTextColor(ContextCompat.getColor(this,color.white)) for (i in 0 until group.childCount) { val radioButton = group.getChildAt(i) as RadioButton if (radioButton.id != checkedId) { radioButton.setBackgroundResource(drawable.frame_52) radioButton.setTextColor(ContextCompat.getColor(this,color.black)) } } } } } }
Custom-Radio-Group-Buttons/app/src/androidTest/java/com/muindi/stephen/radiogrouplibrary/ExampleInstrumentedTest.kt
1969169547
package com.muindi.stephen.radiogrouplibrary 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.muindi.stephen.radiogrouplibrary", appContext.packageName) } }
Custom-Radio-Group-Buttons/app/src/test/java/com/muindi/stephen/radiogrouplibrary/ExampleUnitTest.kt
632537617
package com.muindi.stephen.radiogrouplibrary 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) } }
Custom-Radio-Group-Buttons/app/src/main/java/com/muindi/stephen/radiogrouplibrary/MainActivity.kt
838673152
package com.muindi.stephen.radiogrouplibrary /** * Stephen Muindi (c) 2024 * Radio Group Library */ import android.annotation.SuppressLint import android.os.Bundle import android.view.View import android.widget.RadioButton import android.widget.RadioGroup import android.widget.TextView import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import com.muindi.stephen.radiogrouplibrary.R.* class MainActivity : AppCompatActivity() { @SuppressLint("SetTextI18n") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContentView(layout.activity_main) ViewCompat.setOnApplyWindowInsetsListener(findViewById(id.main)) { v, insets -> val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom) insets } } }
beer-advisor/src/test/kotlin/io/github/mpichler94/beeradvisor/BeerAdvisorApplicationTests.kt
1135471001
package io.github.mpichler94.beeradvisor import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class BeerAdvisorApplicationTests { @Test fun contextLoads() { } }
beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/beer/BeerRepository.kt
4145510135
package io.github.mpichler94.beeradvisor.beer import org.springframework.data.repository.CrudRepository interface BeerRepository : CrudRepository<Beer, Long>
beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/beer/BreweryRepository.kt
2473079072
package io.github.mpichler94.beeradvisor.beer import org.springframework.data.repository.CrudRepository interface BreweryRepository : CrudRepository<Brewery, Long>
beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/beer/BreweryController.kt
3336414844
package io.github.mpichler94.beeradvisor.beer import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import org.springframework.web.server.ResponseStatusException import kotlin.jvm.optionals.getOrNull @RestController @RequestMapping(value = ["/api/brewery"], produces = [MediaType.APPLICATION_JSON_VALUE]) class BreweryController(private val repository: BreweryRepository) { @PostMapping private fun createBrewery( @RequestBody brewery: BreweryDto, ): BreweryDto { val created = repository.save(Brewery(null, brewery.name)) return BreweryDto(created.name) } @GetMapping private fun breweries(): Iterable<BreweryDto> { return repository.findAll().map { BreweryDto(it.name) } } @GetMapping("/{breweryId}") private fun brewery( @PathVariable breweryId: Long, ): BreweryDto { val brewery = repository.findById(breweryId).getOrNull() ?: throw ResponseStatusException(HttpStatus.NOT_FOUND) return BreweryDto(brewery.name) } } internal class BreweryDto(val name: String)
beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/beer/Beer.kt
462941442
package io.github.mpichler94.beeradvisor.beer import jakarta.persistence.Column import jakarta.persistence.Entity import jakarta.persistence.GeneratedValue import jakarta.persistence.GenerationType import jakarta.persistence.Id import jakarta.persistence.JoinColumn import jakarta.persistence.ManyToOne import jakarta.persistence.SequenceGenerator @Entity(name = "Beers") class Beer( @Id @Column(nullable = false, updatable = false) @SequenceGenerator(name = "beer_sequence", sequenceName = "beer_sequence", allocationSize = 1, initialValue = 10000) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "beer_sequence") val id: Long?, val name: String, @ManyToOne @JoinColumn(name = "brewery_id") val brewery: Brewery, val type: String, val alcohol: Float, @Column(columnDefinition = "TEXT") val description: String, val reviews: Int = 0, val stars: Float = 0f, )
beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/beer/BeerController.kt
1678546817
package io.github.mpichler94.beeradvisor.beer import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.util.Assert import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import org.springframework.web.server.ResponseStatusException import kotlin.jvm.optionals.getOrNull @RestController @RequestMapping(value = ["/api/beer"], produces = [MediaType.APPLICATION_JSON_VALUE]) class BeerController(private val repository: BeerRepository, private val breweryRepository: BreweryRepository) { @PostMapping private fun createBeer( @RequestBody beer: BeerDto, ): BeerDto { val brewery = breweryRepository.findById(beer.breweryId) Assert.state(brewery.isPresent, "Brewery ${beer.breweryId} not found") val created = repository.save(Beer(null, beer.name, brewery.get(), beer.type, beer.alcohol, beer.description)) return BeerDto( created.name, created.type, created.brewery.id!!, created.alcohol, created.description, created.reviews, created.stars, ) } @GetMapping private fun beers(): Iterable<BeerDto> { return repository.findAll().map { BeerDto(it.name, it.type, it.brewery.id!!, it.alcohol, it.description, it.reviews, it.stars) } } @GetMapping("/{beerId}") private fun beer( @PathVariable beerId: Long, ): BeerDto { val beer = repository.findById(beerId).getOrNull() ?: throw ResponseStatusException(HttpStatus.NOT_FOUND) return BeerDto(beer.name, beer.type, beer.brewery.id!!, beer.alcohol, beer.description, beer.reviews, beer.stars) } } internal class BeerDto( val name: String, val type: String, val breweryId: Long, val alcohol: Float, val description: String, val reviews: Int = 0, val stars: Float = 0f, )
beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/beer/Brewery.kt
2332135694
package io.github.mpichler94.beeradvisor.beer import jakarta.persistence.Column import jakarta.persistence.Entity import jakarta.persistence.FetchType import jakarta.persistence.GeneratedValue import jakarta.persistence.GenerationType import jakarta.persistence.Id import jakarta.persistence.OneToMany import jakarta.persistence.SequenceGenerator @Entity(name = "Breweries") class Brewery( @Id @Column(nullable = false, updatable = false) @SequenceGenerator(name = "brewery_sequence", sequenceName = "brewery_sequence", allocationSize = 1, initialValue = 10000) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "brewery_sequence") val id: Long?, val name: String, @OneToMany(mappedBy = "brewery", fetch = FetchType.EAGER) val beers: Set<Beer> = setOf(), )
beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/util/NotFoundException.kt
140719055
package io.github.mpichler94.beeradvisor.util class NotFoundException : RuntimeException { constructor() : super() constructor(message: String) : super(message) }
beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/util/MdcFilter.kt
3164015132
package io.github.mpichler94.beeradvisor.util import jakarta.servlet.FilterChain import jakarta.servlet.ServletException import jakarta.servlet.http.HttpServletRequest import jakarta.servlet.http.HttpServletResponse import org.slf4j.MDC import org.springframework.beans.factory.annotation.Value import org.springframework.stereotype.Component import org.springframework.web.filter.OncePerRequestFilter import java.io.IOException import java.util.UUID @Component class MdcFilter(@Value("\${beer.web.requestHeader:X-Header-Token}") private val requestHeader: String?, @Value("\${beer.web.responseHeader:Response_Token}") private val responseHeader: String?, @Value("\${beer.web.mdcTokenKey:requestId}") private val mdcTokenKey: String?) : OncePerRequestFilter() { @Throws(ServletException::class, IOException::class) override fun doFilterInternal( request: HttpServletRequest, response: HttpServletResponse, filterChain: FilterChain, ) { try { val token = if (!requestHeader.isNullOrEmpty() && !request.getHeader(requestHeader).isNullOrEmpty()) { request.getHeader(requestHeader) } else { UUID.randomUUID().toString().replace("-", "") } MDC.put(mdcTokenKey, token) if (!responseHeader.isNullOrEmpty()) { response.addHeader(responseHeader, token) } filterChain.doFilter(request, response) } finally { MDC.remove(mdcTokenKey) } } }
beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/config/ErrorResponse.kt
2377727256
package io.github.mpichler94.beeradvisor.config data class ErrorResponse( var httpStatus: Int? = null, var exception: String? = null, var message: String? = null, var fieldErrors: List<FieldError>? = null, )
beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/config/SecurityConfig.kt
2472000589
package io.github.mpichler94.beeradvisor.config import com.fasterxml.jackson.databind.ObjectMapper import jakarta.servlet.http.HttpServletResponse import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.http.HttpStatus import org.springframework.http.ProblemDetail import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.config.annotation.web.invoke import org.springframework.security.crypto.factory.PasswordEncoderFactories import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.security.web.SecurityFilterChain import org.springframework.security.web.authentication.AuthenticationFailureHandler import org.springframework.security.web.authentication.AuthenticationSuccessHandler import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint import org.springframework.security.web.authentication.logout.LogoutSuccessHandler import org.springframework.security.web.context.DelegatingSecurityContextRepository import org.springframework.security.web.context.HttpSessionSecurityContextRepository import org.springframework.security.web.context.RequestAttributeSecurityContextRepository import org.springframework.web.cors.CorsConfiguration import org.springframework.web.cors.CorsConfigurationSource import org.springframework.web.cors.UrlBasedCorsConfigurationSource import java.net.URI @Configuration @EnableWebSecurity class SecurityConfig(private val mapper: ObjectMapper) { @Bean fun securityFilterChain(http: HttpSecurity): SecurityFilterChain { http { cors {} csrf { disable() } // FIXME: Enable in production authorizeRequests { authorize("/api/user/**", permitAll) authorize("/api/**", authenticated) authorize("/**", permitAll) } securityContext { securityContextRepository = DelegatingSecurityContextRepository( RequestAttributeSecurityContextRepository(), HttpSessionSecurityContextRepository(), ) } formLogin { loginProcessingUrl = "/api/user/login" authenticationSuccessHandler = AuthenticationSuccessHandler { _, response, _, -> response.status = HttpServletResponse.SC_OK } authenticationFailureHandler = AuthenticationFailureHandler { _, response, exception -> val detail = ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, "Invalid credentials provided") detail.type = URI.create("about:blank") detail.title = "Bad Credentials" detail.properties = mapOf("message" to exception.message) response.status = HttpServletResponse.SC_BAD_REQUEST mapper.writeValue(response.writer, detail) } permitAll = true } exceptionHandling { authenticationEntryPoint = Http403ForbiddenEntryPoint() } logout { logoutUrl = "/api/user/logout" logoutSuccessHandler = LogoutSuccessHandler { _, response, _ -> response.status = HttpServletResponse.SC_OK } } } return http.build() } @Bean fun corsConfigurationSource(): CorsConfigurationSource { val config = CorsConfiguration().apply { allowedOrigins = listOf("http://localhost:8081") allowedMethods = listOf("*") allowedHeaders = listOf("*") allowCredentials = true } return UrlBasedCorsConfigurationSource().apply { registerCorsConfiguration("/**", config) } } @Bean fun passwordEncoder(): PasswordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder() }
beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/config/RestExceptionHandler.kt
3082929302
package io.github.mpichler94.beeradvisor.config import io.github.mpichler94.beeradvisor.util.NotFoundException import io.swagger.v3.oas.annotations.responses.ApiResponse import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.validation.BindingResult import org.springframework.web.bind.MethodArgumentNotValidException import org.springframework.web.bind.annotation.ExceptionHandler import org.springframework.web.bind.annotation.RestController import org.springframework.web.bind.annotation.RestControllerAdvice import org.springframework.web.server.ResponseStatusException @RestControllerAdvice(annotations = [RestController::class]) class RestExceptionHandler { @ExceptionHandler(NotFoundException::class) fun handleNotFound(exception: NotFoundException): ResponseEntity<ErrorResponse> { val errorResponse = ErrorResponse() errorResponse.httpStatus = HttpStatus.NOT_FOUND.value() errorResponse.exception = exception::class.simpleName errorResponse.message = exception.message return ResponseEntity(errorResponse, HttpStatus.NOT_FOUND) } @ExceptionHandler(MethodArgumentNotValidException::class) fun handleMethodArgumentNotValid(exception: MethodArgumentNotValidException): ResponseEntity<ErrorResponse> { val bindingResult: BindingResult = exception.bindingResult val fieldErrors: List<FieldError> = bindingResult.fieldErrors .stream() .map { error -> var fieldError = FieldError() fieldError.errorCode = error.code fieldError.field = error.field fieldError } .toList() val errorResponse = ErrorResponse() errorResponse.httpStatus = HttpStatus.BAD_REQUEST.value() errorResponse.exception = exception::class.simpleName errorResponse.fieldErrors = fieldErrors return ResponseEntity(errorResponse, HttpStatus.BAD_REQUEST) } @ExceptionHandler(ResponseStatusException::class) fun handleResponseStatus(exception: ResponseStatusException): ResponseEntity<ErrorResponse> { val errorResponse = ErrorResponse() errorResponse.httpStatus = exception.statusCode.value() errorResponse.exception = exception::class.simpleName errorResponse.message = exception.message return ResponseEntity(errorResponse, exception.statusCode) } @ExceptionHandler(Throwable::class) @ApiResponse( responseCode = "4xx/5xx", description = "Error", ) fun handleThrowable(exception: Throwable): ResponseEntity<ErrorResponse> { exception.printStackTrace() val errorResponse = ErrorResponse() errorResponse.httpStatus = HttpStatus.INTERNAL_SERVER_ERROR.value() errorResponse.exception = exception::class.simpleName return ResponseEntity(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR) } }
beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/config/FieldError.kt
1303870783
package io.github.mpichler94.beeradvisor.config data class FieldError( var `field`: String? = null, var errorCode: String? = null, )
beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/user/BeerAuthority.kt
4284293695
package io.github.mpichler94.beeradvisor.user import jakarta.persistence.Column import jakarta.persistence.Entity import jakarta.persistence.GeneratedValue import jakarta.persistence.GenerationType import jakarta.persistence.Id import jakarta.persistence.JoinColumn import jakarta.persistence.ManyToOne import jakarta.persistence.SequenceGenerator import org.springframework.security.core.GrantedAuthority @Entity(name = "Authorities") class BeerAuthority( @Id @Column(nullable = false, updatable = false) @SequenceGenerator(name = "authority_sequence", sequenceName = "authority_sequence", allocationSize = 1, initialValue = 10000) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "authority_sequence") private val id: Long, private val authority: String, @ManyToOne @JoinColumn(name = "user_id") private val user: BeerUser, ) : GrantedAuthority { override fun getAuthority(): String { TODO("Not yet implemented") } }
beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/user/AuthorityRepository.kt
2548948384
package io.github.mpichler94.beeradvisor.user import org.springframework.data.repository.CrudRepository import java.util.Optional interface AuthorityRepository : CrudRepository<BeerAuthority, Long> { fun findByAuthority(authority: String): Optional<BeerAuthority> }
beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/user/BeerUserDetailsService.kt
1849527729
package io.github.mpichler94.beeradvisor.user import org.springframework.security.core.userdetails.UserDetails import org.springframework.security.core.userdetails.UserDetailsService import org.springframework.security.core.userdetails.UsernameNotFoundException import org.springframework.stereotype.Service import kotlin.jvm.optionals.getOrElse @Service class BeerUserDetailsService(private val repository: UserRepository) : UserDetailsService { override fun loadUserByUsername(username: String?): UserDetails { return repository.findByUsername(username!!).getOrElse { throw UsernameNotFoundException(username) } } }
beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/user/UserRepository.kt
1159183251
package io.github.mpichler94.beeradvisor.user import org.springframework.data.repository.CrudRepository import java.util.Optional interface UserRepository : CrudRepository<BeerUser, Long> { fun findByUsername(username: String): Optional<BeerUser> }
beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/user/UserController.kt
3767632855
package io.github.mpichler94.beeradvisor.user import jakarta.servlet.http.HttpServletRequest import org.springframework.http.HttpStatus import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import org.springframework.web.server.ResponseStatusException @RestController @RequestMapping("/api/user") class UserController( private val userRepository: UserRepository, private val authorityRepository: AuthorityRepository, private val passwordEncoder: PasswordEncoder, ) { @PostMapping("/register") private fun createUser( @RequestBody user: UserDto, ): UserDto { if (userRepository.findByUsername(user.username).isPresent) { throw IllegalStateException("Username already exists") } val authority = authorityRepository.findByAuthority("user") if (authority.isEmpty) { throw java.lang.IllegalStateException("Authority does not exist") } val createdUser = userRepository.save( BeerUser( null, user.username, passwordEncoder.encode(user.password), setOf(authority.get()), ), ) return UserDto(createdUser.username) } @GetMapping private fun user(request: HttpServletRequest): UserDto { return UserDto(request.userPrincipal?.name ?: throw ResponseStatusException(HttpStatus.UNAUTHORIZED)) } } internal class UserDto(val username: String, val password: String? = null)
beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/user/BeerUser.kt
104281037
package io.github.mpichler94.beeradvisor.user import jakarta.persistence.Column import jakarta.persistence.Entity import jakarta.persistence.FetchType import jakarta.persistence.GeneratedValue import jakarta.persistence.GenerationType import jakarta.persistence.Id import jakarta.persistence.OneToMany import jakarta.persistence.SequenceGenerator import org.springframework.security.core.GrantedAuthority import org.springframework.security.core.userdetails.UserDetails @Entity(name = "Users") class BeerUser( @Id @Column(nullable = false, updatable = false) @SequenceGenerator(name = "user_sequence", sequenceName = "user_sequence", allocationSize = 1, initialValue = 10000) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_sequence") val id: Long?, private val username: String, private val password: String, @OneToMany(mappedBy = "user", fetch = FetchType.EAGER) private val authorities: Set<BeerAuthority> = setOf(), @Column(columnDefinition = "boolean default true") private val accountNonExpired: Boolean = true, @Column(columnDefinition = "boolean default true") private val accountNonLocked: Boolean = true, @Column(columnDefinition = "boolean default true") private val credentialsNonExpired: Boolean = true, ) : UserDetails { override fun getAuthorities(): MutableCollection<out GrantedAuthority> { return authorities.toMutableSet() } override fun getPassword(): String { return password } override fun getUsername(): String { return username } override fun isAccountNonExpired(): Boolean { return accountNonExpired } override fun isAccountNonLocked(): Boolean { return accountNonLocked } override fun isCredentialsNonExpired(): Boolean { return credentialsNonExpired } override fun isEnabled(): Boolean { return true } }
beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/review/ReviewRepository.kt
2300176885
package io.github.mpichler94.beeradvisor.review import org.springframework.data.repository.CrudRepository interface ReviewRepository : CrudRepository<Review, Long>
beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/review/ReviewController.kt
4134357939
package io.github.mpichler94.beeradvisor.review import io.github.mpichler94.beeradvisor.beer.BeerRepository import io.github.mpichler94.beeradvisor.user.UserRepository import io.swagger.v3.oas.annotations.responses.ApiResponse import jakarta.servlet.http.HttpServletRequest import jakarta.validation.Valid import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.util.Assert import org.springframework.web.bind.annotation.DeleteMapping import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.PutMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController import java.util.Optional @RestController @RequestMapping(value = ["/api/beer/{beerId}/review"], produces = [MediaType.APPLICATION_JSON_VALUE]) class ReviewController( private val repository: ReviewRepository, private val beerRepository: BeerRepository, private val userRepository: UserRepository, ) { @PostMapping @ApiResponse(responseCode = "201") private fun createReview( @PathVariable beerId: Long, @RequestBody @Valid review: ReviewDto, request: HttpServletRequest, ): ResponseEntity<ReviewDto> { val beer = beerRepository.findById(beerId) Assert.state(beer.isPresent, "Beer $beerId does not exist") val username = request.userPrincipal.name val user = userRepository.findByUsername(username) Assert.state(user.isPresent, "User DB corrupt") val result = repository.save(Review(null, user.get(), beer.get(), review.stars, review.content)) return ResponseEntity( ReviewDto(result.author.username, result.content, result.stars), HttpStatus.CREATED, ) } @GetMapping private fun reviews(): Iterable<ReviewDto> { return repository.findAll().map { ReviewDto(it.author.username, it.content, it.stars) } } @GetMapping("/:beerId") private fun reviewsForBeer( @RequestParam beerId: Optional<Long>, ): Iterable<ReviewDto> { return repository.findAll().map { ReviewDto(it.author.username, it.content, it.stars) } } @GetMapping("/{id}") private fun getReview( @PathVariable id: Long, ): Optional<ReviewDto> { return repository.findById(id).map { ReviewDto(it.author.username, it.content, it.stars) } } @PutMapping("/{id}") private fun updateReview( @PathVariable id: Long, @RequestBody @Valid reviewDTO: ReviewDto, ): ResponseEntity<Long> { // reviewService.update(id, reviewDTO) return ResponseEntity.ok(id) } @DeleteMapping("/{id}") @ApiResponse(responseCode = "204") fun deleteReview( @PathVariable(name = "id") id: Long, ) { // reviewService.delete(id) } } internal class ReviewDto(val author: String?, val content: String, val stars: Int)
beer-advisor/src/main/kotlin/io/github/mpichler94/beeradvisor/review/Review.kt
809180342
package io.github.mpichler94.beeradvisor.review import io.github.mpichler94.beeradvisor.beer.Beer import io.github.mpichler94.beeradvisor.user.BeerUser import jakarta.persistence.Column import jakarta.persistence.Entity import jakarta.persistence.GeneratedValue import jakarta.persistence.GenerationType import jakarta.persistence.Id import jakarta.persistence.JoinColumn import jakarta.persistence.ManyToOne import jakarta.persistence.SequenceGenerator @Entity(name = "Reviews") class Review( @Id @Column(nullable = false, updatable = false) @SequenceGenerator(name = "review_sequence", sequenceName = "review_sequence", allocationSize = 1, initialValue = 10000) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "review_sequence") val id: Long? = null, @ManyToOne @JoinColumn(name = "user_id") val author: BeerUser, @ManyToOne @JoinColumn(name = "beer_id") val beer: Beer, val stars: Int, val content: String = "", )