content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package com.example.plugins
import io.ktor.server.application.Application
import io.ktor.server.plugins.swagger.swaggerUI
import io.ktor.server.routing.routing
fun Application.configureSwagger() {
routing {
swaggerUI(path = "/docs/swagger", swaggerFile = "openapi/documentation.yaml")
}
}
| amount-counter/src/main/kotlin/com/example/plugins/Swagger.kt | 3240219953 |
package com.example.plugins
import io.ktor.server.application.Application
import io.ktor.server.application.install
import io.ktor.server.plugins.callloging.CallLogging
import io.ktor.server.request.path
import org.slf4j.event.Level
fun Application.configureLogging() {
install(CallLogging) {
level = Level.INFO
filter { call -> call.request.path().startsWith("/") }
}
}
| amount-counter/src/main/kotlin/com/example/plugins/Logging.kt | 3207583169 |
package com.example.plugins
import com.example.db.ProductsTable
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.SchemaUtils
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.transactions.transaction
import java.util.UUID
fun configureDatabases(): Database {
return Database.connect(
url = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1",
user = "root",
driver = "org.h2.Driver",
password = "",
).also { initDb(it) }
}
@Suppress("MagicNumber")
fun initDb(db: Database) {
transaction(db) {
SchemaUtils.create(ProductsTable)
ProductsTable.insert {
it[uuid] = UUID.fromString("5d6aa284-0f05-49f5-b563-f83c3d2ffd90")
it[name] = "Diablo IV"
it[amount] = 10L
}
ProductsTable.insert {
it[uuid] = UUID.fromString("77ac3a82-6a9c-427e-b281-a0a73b8a5847")
it[name] = "Overwatch 2"
it[amount] = 1L
}
ProductsTable.insert {
it[uuid] = UUID.fromString("1e0b7134-cfd1-4a0b-89b2-9c2616478f36")
it[name] = "Half-Life 3"
it[amount] = 10000L
}
ProductsTable.insert {
it[uuid] = UUID.fromString("d8806e47-5aa1-4dc1-8aba-f0c98d063422")
it[name] = "CyberPunk 2077"
it[amount] = 50L
}
ProductsTable.insert {
it[uuid] = UUID.fromString("56795b27-73e5-4d59-b579-15bf14452302")
it[name] = "God of War: Ragnarok"
it[amount] = 5L
}
}
}
| amount-counter/src/main/kotlin/com/example/plugins/Databases.kt | 105411478 |
package com.example.plugins
import io.ktor.server.application.Application
import io.ktor.server.application.call
import io.ktor.server.application.install
import io.ktor.server.metrics.micrometer.MicrometerMetrics
import io.ktor.server.response.respond
import io.ktor.server.routing.get
import io.ktor.server.routing.routing
import io.micrometer.prometheus.PrometheusConfig
import io.micrometer.prometheus.PrometheusMeterRegistry
fun Application.configureMonitoring() {
val appMicrometerRegistry = PrometheusMeterRegistry(PrometheusConfig.DEFAULT)
install(MicrometerMetrics) {
registry = appMicrometerRegistry
}
routing {
get("/metrics-micrometer") {
call.respond(appMicrometerRegistry.scrape())
}
}
}
| amount-counter/src/main/kotlin/com/example/plugins/Monitoring.kt | 3789788478 |
package com.example.model
import com.example.db.ProductsTable
import org.jetbrains.exposed.sql.ResultRow
import java.util.UUID
data class Product(
val id: Long,
val uuid: UUID,
val name: String,
val amount: Long,
)
fun ResultRow.toProduct(): Product {
return Product(
id = get(ProductsTable.id),
uuid = get(ProductsTable.uuid),
name = get(ProductsTable.name),
amount = get(ProductsTable.amount),
)
}
| amount-counter/src/main/kotlin/com/example/model/Product.kt | 2580211215 |
package com.example.model
data class ProductsSummary(val products: List<Product>, val total: Long) {
fun isEmpty(): Boolean {
return products.isEmpty()
}
}
| amount-counter/src/main/kotlin/com/example/model/ProductsSummary.kt | 101826230 |
package com.example.db
import org.jetbrains.exposed.sql.Table
private const val VARCHAR_LENGTH = 256
object ProductsTable : Table("Products") {
val id = long("id").uniqueIndex().autoIncrement()
val uuid = uuid("uuid").uniqueIndex().autoGenerate().index()
val name = varchar("name", VARCHAR_LENGTH)
val amount = long("amount")
override val primaryKey = PrimaryKey(id, name = "PK_Products_Id")
}
| amount-counter/src/main/kotlin/com/example/db/ProductsTable.kt | 1466681104 |
package com.example.routing
import com.example.dto.toProductDto
import com.example.exception.PdfWriterException
import com.example.service.PdfPrinterService
import com.example.service.ProductsService
import com.example.validation.ProductRequestValidator
import io.ktor.http.ContentType
import io.ktor.http.HttpHeaders
import io.ktor.server.application.Application
import io.ktor.server.application.call
import io.ktor.server.response.header
import io.ktor.server.response.respond
import io.ktor.server.response.respondOutputStream
import io.ktor.server.routing.get
import io.ktor.server.routing.post
import io.ktor.server.routing.route
import io.ktor.server.routing.routing
fun Application.configureProductRouting(
productsService: ProductsService,
pdfPrinterService: PdfPrinterService = PdfPrinterService(),
validator: ProductRequestValidator = ProductRequestValidator(),
) {
routing {
route("/api") {
get("/getProducts") {
call.respond(productsService.getAllProducts().map { it.toProductDto() })
}
post("/getSummary") {
val uuids = validator.validateRequestBodyAndReturnUuids(call)
val productsSummary = productsService.getProductsSummary(uuids)
runCatching {
val outputStream = pdfPrinterService.printProductSummaryToByteArray(productsSummary)
call.response.header(HttpHeaders.ContentDisposition, "attachment; filename=SummaryTable.pdf")
call.respondOutputStream(ContentType.Application.OctetStream) {
outputStream.use { it.writeTo(this) }
}
}
.onFailure { ex -> throw PdfWriterException(ex) }
.getOrThrow()
}
}
}
}
| amount-counter/src/main/kotlin/com/example/routing/ProductRouting.kt | 2605297699 |
package com.example.service
import com.example.model.ProductsSummary
import com.lowagie.text.Document
import com.lowagie.text.FontFactory
import com.lowagie.text.PageSize
import com.lowagie.text.Phrase
import com.lowagie.text.Rectangle
import com.lowagie.text.pdf.PdfPCell
import com.lowagie.text.pdf.PdfPTable
import com.lowagie.text.pdf.PdfWriter
import java.io.ByteArrayOutputStream
private const val COLUMN_RATIO = 33.33f
private const val PAGE_INDENTATION = 72
private const val FONT_SIZE = 8f
class PdfPrinterService {
fun printProductSummaryToByteArray(productsSummary: ProductsSummary): ByteArrayOutputStream {
val document = Document(PageSize.A4)
val outputStream = ByteArrayOutputStream()
PdfWriter.getInstance(document, outputStream)
document.open()
document.add(createPdfTable(document.pageSize.width, productsSummary))
document.close()
return outputStream
}
private fun createPdfTable(
pageWidth: Float,
productsSummary: ProductsSummary,
): PdfPTable {
val columnDefinitionSize = floatArrayOf(COLUMN_RATIO, COLUMN_RATIO, COLUMN_RATIO)
return PdfPTable(columnDefinitionSize).apply {
defaultCell.border = Rectangle.BOX
horizontalAlignment = 0
totalWidth = pageWidth - PAGE_INDENTATION
isLockedWidth = true
addCells(productsSummary, columnDefinitionSize.size)
}
}
private fun PdfPTable.addCells(
productsSummary: ProductsSummary,
size: Int,
) {
addCell(
PdfPCell(Phrase("Summary table")).apply {
colspan = size
},
)
productsSummary.products.map {
addTextCell(it.uuid)
addTextCell(it.name)
addTextCell(it.amount)
}
addTextCell("")
addTextCell("Total")
addTextCell(productsSummary.total)
}
private fun PdfPTable.addTextCell(value: Any) {
return addCell(Phrase(value.toString(), FontFactory.getFont(FontFactory.HELVETICA, FONT_SIZE)))
}
}
| amount-counter/src/main/kotlin/com/example/service/PdfPrinterService.kt | 4241799027 |
package com.example.service
import com.example.db.ProductsTable
import com.example.exception.ItemsNotFoundException
import com.example.model.Product
import com.example.model.ProductsSummary
import com.example.model.toProduct
import org.jetbrains.exposed.sql.Database
import org.jetbrains.exposed.sql.select
import org.jetbrains.exposed.sql.selectAll
import org.jetbrains.exposed.sql.transactions.transaction
import java.util.UUID
class ProductsService(private val db: Database) {
fun getAllProducts(): List<Product> {
return transaction(db) { ProductsTable.selectAll().map { it.toProduct() }.sortedBy { it.id } }
}
fun getProductsSummary(uuids: List<UUID>): ProductsSummary {
val products =
transaction(db) {
ProductsTable.select { ProductsTable.uuid inList uuids }.map { it.toProduct() }.sortedBy { it.id }
}
if (products.size != uuids.size) {
throw ItemsNotFoundException(uuids.filter { it !in products.map { product -> product.uuid } })
}
return ProductsSummary(
products = products,
total = products.sumOf { it.amount },
)
}
}
| amount-counter/src/main/kotlin/com/example/service/ProductsService.kt | 930243108 |
package com.example.exception
class BadRequestException(override val message: String, override val cause: Throwable? = null) :
RuntimeException(message, cause)
| amount-counter/src/main/kotlin/com/example/exception/BadRequestException.kt | 1590910692 |
package com.example.exception
import java.util.UUID
class ItemsNotFoundException(uuids: List<UUID>) : RuntimeException("Requested ids $uuids not found")
| amount-counter/src/main/kotlin/com/example/exception/ItemsNotFoundException.kt | 518103969 |
package com.example.exception
class PdfWriterException(override val cause: Throwable? = null) :
RuntimeException("Pdf writer exception", cause)
| amount-counter/src/main/kotlin/com/example/exception/PdfWriterException.kt | 3134096908 |
package com.example.validation
import com.example.dto.IdsRequestDto
import com.example.exception.BadRequestException
import io.ktor.server.application.ApplicationCall
import io.ktor.server.request.receive
import java.util.UUID
class ProductRequestValidator {
suspend fun validateRequestBodyAndReturnUuids(call: ApplicationCall): List<UUID> {
return runCatching {
call.receive<IdsRequestDto>().ids.takeUnless { it.isEmpty() }?.map(UUID::fromString)
?: throw BadRequestException("'ids' list is empty")
}
.onFailure { ex ->
throw BadRequestException("Request body should contain ids list in form '{\"ids\":[\"id1\",\"id2\"]}'", ex)
}
.getOrThrow()
}
}
| amount-counter/src/main/kotlin/com/example/validation/ProductRequestValidator.kt | 1873223592 |
package com.example.updatedemo
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.updatedemo", appContext.packageName)
}
} | update-demo-app/app/src/androidTest/java/com/example/updatedemo/ExampleInstrumentedTest.kt | 3949068833 |
package com.example.updatedemo
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)
}
} | update-demo-app/app/src/test/java/com/example/updatedemo/ExampleUnitTest.kt | 146704787 |
package com.example.updatedemo
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.updatedemo.util.featureDownload.AppUpgraderManager
import com.example.updatedemo.util.featureDownload.InstallPermissionChecker
class MainActivity : AppCompatActivity() {
companion object {
private const val APK_URL = "your apk url"
}
private lateinit var permissionChecker: InstallPermissionChecker
private lateinit var appUpgraderManager: AppUpgraderManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
permissionChecker = InstallPermissionChecker(this)
appUpgraderManager = AppUpgraderManager.getInstance(this)
findViewById<Button>(R.id.button).setOnClickListener {
checkAndStartDownloading()
}
}
private fun checkAndStartDownloading() {
permissionChecker.checkPermission(
onGranted = {
startDownloading()
showToast(getString(R.string.downloading))
},
onDenied = {
showToast(getString(R.string.permission_required_toast))
}
)
}
private fun startDownloading() {
appUpgraderManager.startApkUpgradingFlow(APK_URL)
}
private fun showToast(text: CharSequence) {
Toast.makeText(this, text, Toast.LENGTH_LONG).show()
}
}
| update-demo-app/app/src/main/java/com/example/updatedemo/MainActivity.kt | 1039381883 |
package com.example.updatedemo.util.featureDownload
import android.content.Context
interface AppUpgrader {
fun startApkUpgradingFlow(url: String)
suspend fun downloadApk(url: String, context: Context)
fun installApk(context: Context, apkFilePath: String)
} | update-demo-app/app/src/main/java/com/example/updatedemo/util/featureDownload/AppUpgrader.kt | 2630204556 |
package com.example.updatedemo.util.featureDownload
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
class InstallPermissionChecker(private val activity: AppCompatActivity) {
private var onPermissionGranted: (() -> Unit)? = null
private var onPermissionDenied: (() -> Unit)? = null
private val requestPermissionLauncher = activity.registerForActivityResult(
ActivityResultContracts.StartActivityForResult()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (activity.packageManager.canRequestPackageInstalls()) {
onPermissionGranted?.invoke()
} else {
onPermissionDenied?.invoke()
}
}
}
fun checkPermission(onGranted: () -> Unit, onDenied: () -> Unit) {
this.onPermissionGranted = onGranted
this.onPermissionDenied = onDenied
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (!activity.packageManager.canRequestPackageInstalls()) {
val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES).apply {
data = Uri.parse("package:${activity.packageName}")
}
requestPermissionLauncher.launch(intent)
} else {
onPermissionGranted?.invoke()
}
} else {
onPermissionGranted?.invoke()
}
}
}
| update-demo-app/app/src/main/java/com/example/updatedemo/util/featureDownload/InstallPermissionChecker.kt | 3156682677 |
package com.example.updatedemo.util.featureDownload
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.core.content.FileProvider
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
class AppUpgraderManager private constructor(context: Context) : AppUpgrader {
private val appContext = context.applicationContext
private val upgradingFlowScope = CoroutineScope(Job() + Dispatchers.IO)
private var currentDownloadCall: Call? = null
companion object {
@Volatile private var AppUpgraderManagerInstance: AppUpgraderManager? = null
private const val CHILD_NAME = "downloaded_apk.apk"
private const val TYPE = "application/vnd.android.package-archive"
private const val PROVIDER_PATH = ".provider"
fun getInstance(context: Context): AppUpgraderManager =
AppUpgraderManagerInstance ?: synchronized(this) {
AppUpgraderManagerInstance ?: AppUpgraderManager(context).also { AppUpgraderManagerInstance = it }
}
}
override fun startApkUpgradingFlow(url: String) {
upgradingFlowScope.launch {
downloadApk(url, appContext)
}
}
override suspend fun downloadApk(url: String, context: Context) {
withContext(Dispatchers.IO) {
val okHttpClient = OkHttpClient()
val request = Request.Builder().url(url).build()
okHttpClient.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
e.printStackTrace()
}
override fun onResponse(call: Call, response: Response) {
val inputStream = response.body?.byteStream()
val apkFile = File(context.getExternalFilesDir(null), CHILD_NAME)
val outputStream = FileOutputStream(apkFile)
inputStream.use { input ->
outputStream.use { output ->
input?.copyTo(output)
}
}
installApk(context, apkFile.absolutePath)
}
})
if (!isActive) cancelUpgradingTasks()
}
}
override fun installApk(context: Context, apkFilePath: String) {
val apkUri: Uri =
FileProvider.getUriForFile(context, context.applicationContext.packageName + PROVIDER_PATH, File(apkFilePath))
val intent = Intent(Intent.ACTION_VIEW).apply {
setDataAndType(apkUri, TYPE)
flags = Intent.FLAG_ACTIVITY_NEW_TASK
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
context.startActivity(intent)
}
private fun cancelUpgradingTasks() {
upgradingFlowScope.coroutineContext.cancelChildren()
currentDownloadCall?.cancel()
}
} | update-demo-app/app/src/main/java/com/example/updatedemo/util/featureDownload/AppUpgraderManager.kt | 137487769 |
package com.hancock.dontgethangry
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.hancock.dontgethangry", appContext.packageName)
}
} | dont-get-hangry/app/src/androidTest/java/com/hancock/dontgethangry/ExampleInstrumentedTest.kt | 22375681 |
package com.hancock.dontgethangry
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)
}
} | dont-get-hangry/app/src/test/java/com/hancock/dontgethangry/ExampleUnitTest.kt | 744791336 |
package com.hancock.dontgethangry.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) | dont-get-hangry/app/src/main/java/com/hancock/dontgethangry/ui/theme/Color.kt | 3721273759 |
package com.hancock.dontgethangry.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 DontGetHangryTheme(
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
)
} | dont-get-hangry/app/src/main/java/com/hancock/dontgethangry/ui/theme/Theme.kt | 3093119205 |
package com.hancock.dontgethangry.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
)
*/
) | dont-get-hangry/app/src/main/java/com/hancock/dontgethangry/ui/theme/Type.kt | 1478003041 |
package com.hancock.dontgethangry
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier
import com.hancock.dontgethangry.composables.DGHTextField
import com.hancock.dontgethangry.ui.theme.DontGetHangryTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
DontGetHangryTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
DGHTextField(
hint = "Android",
validChecker = {s -> s.length > 2},
onValidChanged = {isValid -> println("JEH onValidChanged: $isValid")}
)
}
}
}
}
}
| dont-get-hangry/app/src/main/java/com/hancock/dontgethangry/MainActivity.kt | 3835128139 |
package com.hancock.dontgethangry.composables
import android.content.res.Configuration
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.hancock.dontgethangry.ui.theme.DontGetHangryTheme
@Composable
fun DGHTextField(
hint: String,
validChecker: ((String) -> Boolean)?,// = null,
onValidChanged: ((Boolean) -> Unit)?,// = null
) {
var textInput by remember { mutableStateOf(TextFieldValue()) }
fun checkValid(): Boolean {
val x = validChecker?.invoke(textInput.text) ?: true
println("JEH checkValid - $x ")
return x
}
var isValid by remember { mutableStateOf(false)}
OutlinedTextField(
value = textInput,
onValueChange = {
textInput = it
isValid = checkValid()
},
label = { Text(hint) },
modifier = Modifier
.padding(all = 16.dp)
.wrapContentHeight()
.fillMaxWidth(),
keyboardOptions = KeyboardOptions(
capitalization = KeyboardCapitalization.None,
autoCorrect = false,
keyboardType = KeyboardType.Text
),
textStyle = TextStyle(
color = MaterialTheme.colorScheme.secondary,
fontSize = 16.sp,
fontFamily = FontFamily.SansSerif
),
singleLine = true,
trailingIcon = { DGHIcon(
icon = Icons.Filled.Clear,
modifier = Modifier.clickable {
textInput = TextFieldValue()
isValid = checkValid()
},
)}
)
}
@Preview(name = "Light Mode")
@Preview(name = "Dark Mode", uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
fun PreviewEmptyTextField() {
DontGetHangryTheme {
Surface(color = MaterialTheme.colorScheme.background) {
DGHTextField(
hint = "hint",
validChecker = {s -> s.length > 2},
onValidChanged = {isValid -> println("JEH onValidChanged: $isValid")}
)
}
}
} | dont-get-hangry/app/src/main/java/com/hancock/dontgethangry/composables/DGHTextFields.kt | 238067073 |
package com.hancock.dontgethangry.composables
import android.content.res.Configuration
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.tooling.preview.Preview
import com.hancock.dontgethangry.ui.theme.DontGetHangryTheme
@Composable
fun DGHIcon(
icon: ImageVector,
modifier: Modifier = Modifier,
contentDescription: String = "",
tint: Color = Color.Black,
) {
Icon(
imageVector = icon,
contentDescription = contentDescription,
tint = tint,
modifier = modifier
)
}
@Preview(name = "Light Mode")
@Preview(name = "Dark Mode", uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
fun PreviewDGHIcon() {
DontGetHangryTheme {
Surface(color = MaterialTheme.colorScheme.background) {
DGHIcon(icon = Icons.Filled.Clear, tint = Color.Magenta)
}
}
} | dont-get-hangry/app/src/main/java/com/hancock/dontgethangry/composables/DGHIcons.kt | 1099802409 |
package com.dynamicradiobutton
import com.facebook.react.ReactActivity
import com.facebook.react.ReactActivityDelegate
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled
import com.facebook.react.defaults.DefaultReactActivityDelegate
class MainActivity : ReactActivity() {
/**
* Returns the name of the main component registered from JavaScript. This is used to schedule
* rendering of the component.
*/
override fun getMainComponentName(): String = "DynamicRadioButton"
/**
* Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate]
* which allows you to enable New Architecture with a single boolean flags [fabricEnabled]
*/
override fun createReactActivityDelegate(): ReactActivityDelegate =
DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled)
}
| DynamicRadioButton/android/app/src/main/java/com/dynamicradiobutton/MainActivity.kt | 2071254757 |
package com.dynamicradiobutton
import android.app.Application
import com.facebook.react.PackageList
import com.facebook.react.ReactApplication
import com.facebook.react.ReactHost
import com.facebook.react.ReactNativeHost
import com.facebook.react.ReactPackage
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load
import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost
import com.facebook.react.defaults.DefaultReactNativeHost
import com.facebook.react.flipper.ReactNativeFlipper
import com.facebook.soloader.SoLoader
class MainApplication : Application(), ReactApplication {
override val reactNativeHost: ReactNativeHost =
object : DefaultReactNativeHost(this) {
override fun getPackages(): List<ReactPackage> =
PackageList(this).packages.apply {
// Packages that cannot be autolinked yet can be added manually here, for example:
// add(MyReactNativePackage())
}
override fun getJSMainModuleName(): String = "index"
override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG
override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED
override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED
}
override val reactHost: ReactHost
get() = getDefaultReactHost(this.applicationContext, reactNativeHost)
override fun onCreate() {
super.onCreate()
SoLoader.init(this, false)
if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
// If you opted-in for the New Architecture, we load the native entry point for this app.
load()
}
ReactNativeFlipper.initializeFlipper(this, reactNativeHost.reactInstanceManager)
}
}
| DynamicRadioButton/android/app/src/main/java/com/dynamicradiobutton/MainApplication.kt | 2899774710 |
package com.topic3.android.reddit
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.raywenderlich.android.jetreddit", appContext.packageName)
}
} | lab10/app/src/androidTest/java/com/topic3/android/reddit/ExampleInstrumentedTest.kt | 2749661737 |
package com.topic3.android.reddit
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)
}
} | lab10/app/src/test/java/com/topic3/android/reddit/ExampleUnitTest.kt | 305007576 |
package com.topic3.android.reddit.viewmodel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.topic3.android.reddit.data.repository.Repository
import com.topic3.android.reddit.domain.model.PostModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class MainViewModel(private val repository: Repository) : ViewModel() {
val allPosts by lazy { repository.getAllPosts() }
val myPosts by lazy { repository.getAllOwnedPosts() }
val subreddits by lazy { MutableLiveData<List<String>>() }
val selectedCommunity: MutableLiveData<String> by lazy { MutableLiveData<String>() }
fun searchCommunities(searchedText: String) {
viewModelScope.launch(Dispatchers.Default) {
subreddits.postValue(repository.getAllSubreddits(searchedText))
}
}
fun savePost(post: PostModel) {
viewModelScope.launch(Dispatchers.Default) {
repository.insert(post.copy(subreddit = selectedCommunity.value ?: ""))
}
}
} | lab10/app/src/main/java/com/topic3/android/reddit/viewmodel/MainViewModel.kt | 2019844107 |
package com.topic3.android.reddit.viewmodel
import android.os.Bundle
import androidx.lifecycle.AbstractSavedStateViewModelFactory
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.savedstate.SavedStateRegistryOwner
import com.topic3.android.reddit.data.repository.Repository
class MainViewModelFactory(
owner: SavedStateRegistryOwner,
private val repository: Repository,
private val defaultArgs: Bundle? = null
) : AbstractSavedStateViewModelFactory(owner, defaultArgs) {
override fun <T : ViewModel?> create(
key: String,
modelClass: Class<T>,
handle: SavedStateHandle
): T & Any {
return (MainViewModel(repository) as T)!!
}
} | lab10/app/src/main/java/com/topic3/android/reddit/viewmodel/MainViewModelFactory.kt | 3748045815 |
package com.topic3.android.reddit
import android.app.Application
import com.topic3.android.reddit.dependencyinjection.DependencyInjector
class RedditApplication : Application() {
lateinit var dependencyInjector: DependencyInjector
override fun onCreate() {
super.onCreate()
initDependencyInjector()
}
private fun initDependencyInjector() {
dependencyInjector = DependencyInjector(this)
}
} | lab10/app/src/main/java/com/topic3/android/reddit/RedditApplication.kt | 3970999801 |
package com.topic3.android.reddit
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import com.topic3.android.reddit.viewmodel.MainViewModel
import com.topic3.android.reddit.viewmodel.MainViewModelFactory
class MainActivity : AppCompatActivity() {
private val viewModel: MainViewModel by viewModels(factoryProducer = {
MainViewModelFactory(
this,
(application as RedditApplication).dependencyInjector.repository
)
})
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
RedditApp(viewModel)
}
}
} | lab10/app/src/main/java/com/topic3/android/reddit/MainActivity.kt | 2186626954 |
package com.topic3.android.reddit.models
import androidx.annotation.StringRes
import com.topic3.android.reddit.R
data class SubredditModel(
@StringRes val nameStringRes: Int,
@StringRes val membersStringRes: Int,
@StringRes val descriptionStringRes: Int
) {
companion object {
val DEFAULT_SUBREDDIT =
SubredditModel(
R.string.android,
R.string.members_400k,
R.string.welcome_to_android
)
}
} | lab10/app/src/main/java/com/topic3/android/reddit/models/SubredditModel.kt | 2310480849 |
package com.topic3.android.reddit.screens
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Search
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.topic3.android.reddit.R
import com.topic3.android.reddit.routing.BackButtonAction
import com.topic3.android.reddit.routing.RedditRouter
import com.topic3.android.reddit.viewmodel.MainViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
private const val SEARCH_DELAY_MILLIS = 300L
private val defaultCommunities = listOf("raywenderlich", "androiddev", "puppies")
@Composable
fun ChooseCommunityScreen(viewModel: MainViewModel, modifier: Modifier = Modifier) {
//TODO Add your code here
val scope = rememberCoroutineScope()
val communities: List<String> by viewModel.subreddits.observeAsState(emptyList())
var searchedText by remember { mutableStateOf("") }
var currentJob by remember { mutableStateOf<Job?>(null) }
val activeColor = MaterialTheme.colors.onSurface
LaunchedEffect(Unit) {
viewModel.searchCommunities(searchedText)
}
Column {
ChooseCommunityTopBar()
TextField(
value = searchedText,
onValueChange = {
searchedText = it
currentJob?.cancel()
currentJob = scope.async {
delay(SEARCH_DELAY_MILLIS)
viewModel.searchCommunities(searchedText)
}
},
leadingIcon = {
Icon(Icons.Default.Search, contentDescription = stringResource(id = R.string.search))
},
label = { Text(stringResource(R.string.search)) },
modifier = modifier
.fillMaxWidth()
.padding(horizontal = 8.dp),
colors = TextFieldDefaults.outlinedTextFieldColors(
focusedBorderColor = activeColor,
focusedLabelColor = activeColor,
cursorColor = activeColor,
backgroundColor = MaterialTheme.colors.surface
)
)
SearchedCommunities(communities, viewModel, modifier)
}
BackButtonAction {
RedditRouter.goBack()
}
}
@Composable
fun SearchedCommunities(
communities: List<String>,
viewModel: MainViewModel?,
modifier: Modifier = Modifier
) {
//TODO Add your code here
communities.forEach { Community(
text = it,
modifier = modifier,
onCommunityClicked = {
viewModel?.selectedCommunity?.postValue(it)
RedditRouter.goBack()
}
)
}
}
@Composable
fun ChooseCommunityTopBar(modifier: Modifier = Modifier) {
val colors = MaterialTheme.colors
TopAppBar(
title = {
Text(
fontSize = 16.sp,
text = stringResource(R.string.choose_community),
color = colors.primaryVariant
)
},
navigationIcon = {
IconButton(
onClick = { RedditRouter.goBack() }
) {
Icon(
imageVector = Icons.Default.Close,
tint = colors.primaryVariant,
contentDescription = stringResource(id = R.string.close)
)
}
},
backgroundColor = colors.primary,
elevation = 0.dp,
modifier = modifier
.height(48.dp)
.background(Color.Blue)
)
}
@Preview
@Composable
fun SearchedCommunitiesPreview(){
Column {
SearchedCommunities(
defaultCommunities,
null,
Modifier)
}
} | lab10/app/src/main/java/com/topic3/android/reddit/screens/ChooseCommunityScreen.kt | 1260531621 |
package com.topic3.android.reddit.screens
import androidx.compose.animation.Crossfade
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Star
import androidx.compose.runtime.*
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.imageResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.ConstraintLayout
import com.topic3.android.reddit.R
import com.topic3.android.reddit.appdrawer.ProfileInfo
import com.topic3.android.reddit.components.PostAction
import com.topic3.android.reddit.domain.model.PostModel
import com.topic3.android.reddit.routing.MyProfileRouter
import com.topic3.android.reddit.routing.MyProfileScreenType
import com.topic3.android.reddit.routing.RedditRouter
import com.topic3.android.reddit.viewmodel.MainViewModel
import kotlinx.coroutines.NonDisposableHandle.parent
private val tabNames = listOf(R.string.posts, R.string.about)
@Composable
fun MyProfileScreen(viewModel: MainViewModel, modifier: Modifier = Modifier) {
ConstraintLayout(modifier = modifier.fillMaxSize()) {
val (topAppBar, tabs, bodyContent) = createRefs()
val colors = MaterialTheme.colors
TopAppBar(
title = {
Text(
fontSize = 12.sp,
text = stringResource(R.string.default_username),
color = colors.primaryVariant
)
},
navigationIcon = {
IconButton(
onClick = { RedditRouter.goBack() }
) {
Icon(
imageVector = Icons.Default.ArrowBack,
tint = colors.primaryVariant,
contentDescription = stringResource(id = R.string.back)
)
}
},
backgroundColor = colors.primary,
elevation = 0.dp,
modifier = modifier
.constrainAs(topAppBar) {
top.linkTo(parent.top)
start.linkTo(parent.start)
end.linkTo(parent.end)
}
.height(48.dp)
.background(Color.Blue)
)
MyProfileTabs(
modifier = modifier.constrainAs(tabs) {
top.linkTo(topAppBar.bottom)
start.linkTo(parent.start)
end.linkTo(parent.end)
}
)
Surface(
modifier = modifier
.constrainAs(bodyContent) {
top.linkTo(tabs.bottom)
start.linkTo(parent.start)
end.linkTo(parent.end)
}
.padding(bottom = 68.dp)
) {
Crossfade(targetState = MyProfileRouter.currentScreen) { screen ->
when (screen.value) {
MyProfileScreenType.Posts -> MyProfilePosts(modifier, viewModel)
MyProfileScreenType.About -> MyProfileAbout()
}
}
}
}
}
@Composable
fun MyProfileTabs(modifier: Modifier = Modifier) {
var selectedIndex by remember { mutableStateOf(0) }
TabRow(
selectedTabIndex = selectedIndex,
backgroundColor = MaterialTheme.colors.primary,
modifier = modifier
) {
tabNames.forEachIndexed { index, nameResource ->
Tab(
selected = index == selectedIndex,
onClick = {
selectedIndex = index
changeScreen(index)
}
) {
Text(
color = MaterialTheme.colors.primaryVariant,
fontSize = 12.sp,
text = stringResource(nameResource),
modifier = Modifier.padding(top = 8.dp, bottom = 8.dp)
)
}
}
}
}
private fun changeScreen(index: Int) {
return when (index) {
0 -> MyProfileRouter.navigateTo(MyProfileScreenType.Posts)
else -> MyProfileRouter.navigateTo(MyProfileScreenType.About)
}
}
@Composable
fun MyProfilePosts(modifier: Modifier, viewModel: MainViewModel) {
val posts: List<PostModel> by viewModel.myPosts.observeAsState(listOf())
LazyColumn(
modifier = modifier.background(color = MaterialTheme.colors.secondary)
) {
items(posts) { MyProfilePost(modifier, it) }
}
}
@Composable
fun MyProfilePost(modifier: Modifier, post: PostModel) {
Card(shape = MaterialTheme.shapes.large) {
ConstraintLayout(
modifier = modifier.fillMaxSize()
) {
val (redditIcon, subredditName, actionsBar, title, description, settingIcon) = createRefs()
val postModifier = Modifier
val colors = MaterialTheme.colors
Image(
imageVector = Icons.Default.Star,
contentDescription = stringResource(id = R.string.my_profile),
modifier = postModifier
.size(20.dp)
.constrainAs(redditIcon) {
top.linkTo(parent.top)
start.linkTo(parent.start)
}
.padding(start = 8.dp, top = 8.dp)
)
Image(
imageVector = ImageVector.vectorResource(id = R.drawable.ic_baseline_more_vert_24),
contentDescription = stringResource(id = R.string.more_actions),
modifier = postModifier
.size(20.dp)
.constrainAs(settingIcon) {
top.linkTo(parent.top)
end.linkTo(parent.end)
}
.padding(end = 8.dp, top = 8.dp)
)
Text(
text = "${post.username} • ${post.postedTime}",
fontSize = 8.sp,
modifier = postModifier
.constrainAs(subredditName) {
top.linkTo(redditIcon.top)
bottom.linkTo(redditIcon.bottom)
start.linkTo(redditIcon.end)
}
.padding(start = 2.dp, top = 8.dp)
)
Text(
text = post.title,
color = colors.primaryVariant,
fontSize = 12.sp,
modifier = postModifier
.constrainAs(title) {
top.linkTo(redditIcon.bottom)
start.linkTo(redditIcon.start)
}
.padding(start = 8.dp, top = 8.dp)
)
Text(
text = post.text,
color = Color.DarkGray,
fontSize = 10.sp,
modifier = postModifier
.constrainAs(description) {
top.linkTo(title.bottom)
start.linkTo(redditIcon.start)
}
.padding(start = 8.dp, top = 8.dp)
)
Row(
modifier = postModifier
.fillMaxWidth()
.constrainAs(actionsBar) {
top.linkTo(description.bottom)
start.linkTo(parent.start)
end.linkTo(parent.end)
}
.padding(
top = 8.dp,
bottom = 8.dp,
end = 16.dp,
start = 16.dp
),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
PostAction(
vectorResourceId = R.drawable.ic_baseline_arrow_upward_24,
text = post.likes,
onClickAction = {}
)
PostAction(
vectorResourceId = R.drawable.ic_baseline_comment_24,
text = post.comments,
onClickAction = {}
)
PostAction(
vectorResourceId = R.drawable.ic_baseline_share_24,
text = stringResource(R.string.share),
onClickAction = {}
)
}
}
}
Spacer(modifier = Modifier.height(6.dp))
}
@Composable
fun MyProfileAbout() {
Column {
ProfileInfo()
Spacer(modifier = Modifier.height(8.dp))
BackgroundText(stringResource(R.string.trophies))
val trophies = listOf(
R.string.verified_email,
R.string.gold_medal,
R.string.top_comment
)
LazyColumn {
items(trophies) { Trophy(text = stringResource(it)) }
}
}
}
@Composable
fun ColumnScope.BackgroundText(text: String) {
Text(
fontWeight = FontWeight.Medium,
text = text,
fontSize = 10.sp,
color = Color.DarkGray,
modifier = Modifier
.background(color = MaterialTheme.colors.secondary)
.padding(start = 16.dp, top = 4.dp, bottom = 4.dp)
.fillMaxWidth()
.align(Alignment.Start)
)
}
@Composable
fun Trophy(text: String, modifier: Modifier = Modifier) {
Spacer(modifier = modifier.height(16.dp))
Row(verticalAlignment = Alignment.CenterVertically) {
Spacer(modifier = modifier.width(16.dp))
Image(
bitmap = ImageBitmap.imageResource(id = R.drawable.trophy),
contentDescription = stringResource(id = R.string.trophies),
contentScale = ContentScale.Crop,
modifier = modifier.size(24.dp)
)
Spacer(modifier = modifier.width(16.dp))
Text(
text = text, fontSize = 12.sp,
color = MaterialTheme.colors.primaryVariant,
textAlign = TextAlign.Center,
fontWeight = FontWeight.Medium
)
}
} | lab10/app/src/main/java/com/topic3/android/reddit/screens/MyProfileScreen.kt | 164994388 |
package com.topic3.android.reddit.screens
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.res.imageResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.topic3.android.reddit.R
import com.topic3.android.reddit.domain.model.PostModel
import com.topic3.android.reddit.routing.RedditRouter
import com.topic3.android.reddit.routing.Screen
import com.topic3.android.reddit.viewmodel.MainViewModel
@Composable
fun AddScreen(viewModel: MainViewModel) {
val selectedCommunity: String by viewModel.selectedCommunity.observeAsState("")
var post by remember { mutableStateOf(PostModel.EMPTY) }
Column(modifier = Modifier.fillMaxSize()) {
CommunityPicker(selectedCommunity)
TitleTextField(post.title) { newTitle -> post = post.copy(title = newTitle) }
BodyTextField(post.text) { newContent -> post = post.copy(text = newContent) }
AddPostButton(selectedCommunity.isNotEmpty() && post.title.isNotEmpty()) {
viewModel.savePost(post)
RedditRouter.navigateTo(com.topic3.android.reddit.routing.Screen.Home)
}
}
}
/**
* Input view for the post title
*/
@Composable
private fun TitleTextField(text: String, onTextChange: (String) -> Unit) {
val activeColor = MaterialTheme.colors.onSurface
TextField(
value = text,
onValueChange = onTextChange,
label = { Text(stringResource(R.string.title)) },
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 8.dp),
colors = TextFieldDefaults.outlinedTextFieldColors(
focusedBorderColor = activeColor,
focusedLabelColor = activeColor,
cursorColor = activeColor,
backgroundColor = MaterialTheme.colors.surface
)
)
}
/**
* Input view for the post body
*/
@Composable
private fun BodyTextField(text: String, onTextChange: (String) -> Unit) {
val activeColor = MaterialTheme.colors.onSurface
TextField(
value = text,
onValueChange = onTextChange,
label = { Text(stringResource(R.string.body_text)) },
modifier = Modifier
.fillMaxWidth()
.heightIn(max = 240.dp)
.padding(horizontal = 8.dp)
.padding(top = 16.dp),
colors = TextFieldDefaults.outlinedTextFieldColors(
focusedBorderColor = activeColor,
focusedLabelColor = activeColor,
cursorColor = activeColor,
backgroundColor = MaterialTheme.colors.surface
)
)
}
/**
* Input view for the post body
*/
@Composable
private fun AddPostButton(isEnabled: Boolean, onSaveClicked: () -> Unit) {
Button(
onClick = onSaveClicked,
enabled = isEnabled,
content = {
Text(
text = stringResource(R.string.save_post),
color = MaterialTheme.colors.onSurface
)
},
modifier = Modifier
.fillMaxWidth()
.heightIn(max = 240.dp)
.padding(horizontal = 8.dp)
.padding(top = 16.dp),
)
}
@Composable
private fun CommunityPicker(selectedCommunity: String) {
val selectedText =
if (selectedCommunity.isEmpty()) stringResource(R.string.choose_community) else selectedCommunity
Row(
modifier = Modifier
.fillMaxWidth()
.heightIn(max = 240.dp)
.padding(horizontal = 8.dp)
.padding(top = 16.dp)
.clickable {
RedditRouter.navigateTo(Screen.ChooseCommunity)
},
) {
Image(
bitmap = ImageBitmap.imageResource(id = R.drawable.subreddit_placeholder),
contentDescription = stringResource(id = R.string.subreddits),
modifier = Modifier
.size(24.dp)
.clip(CircleShape)
)
Text(
text = selectedText,
modifier = Modifier.padding(start = 8.dp)
)
}
} | lab10/app/src/main/java/com/topic3/android/reddit/screens/AddScreen.kt | 3305704881 |
package com.topic3.android.reddit.components
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
@Composable
fun BackgroundText(text: String) {
Text(
fontWeight = FontWeight.Medium,
text = text,
fontSize = 10.sp,
color = Color.DarkGray,
modifier = Modifier
.background(color = MaterialTheme.colors.secondary)
.padding(start = 16.dp, top = 4.dp, bottom = 4.dp)
.fillMaxWidth()
)
} | lab10/app/src/main/java/com/topic3/android/reddit/components/BackgroundText.kt | 4268857193 |
package com.topic3.android.reddit.components
import androidx.annotation.DrawableRes
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.imageResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.topic3.android.reddit.R
import com.topic3.android.reddit.domain.model.PostModel
import com.topic3.android.reddit.domain.model.PostModel.Companion.DEFAULT_POST
@Composable
fun TextPost(post: PostModel) {
Post(post) {
TextContent(post.text)
}
}
@Composable
fun ImagePost(post: PostModel) {
Post(post) {
ImageContent(post.image ?: R.drawable.compose_course)
}
}
@Composable
fun Post(post: PostModel, content: @Composable () -> Unit = {}) {
Card(shape = MaterialTheme.shapes.large) {
Column(
modifier = Modifier.padding(
top = 8.dp, bottom = 8.dp
)
) {
Header(post)
Spacer(modifier = Modifier.height(4.dp))
content.invoke()
Spacer(modifier = Modifier.height(8.dp))
PostActions(post)
}
}
}
@Composable
fun Header(post: PostModel) {
Row(modifier = Modifier.padding(start = 16.dp)) {
Image(
ImageBitmap.imageResource(id = R.drawable.subreddit_placeholder),
contentDescription = stringResource(id = R.string.subreddits),
Modifier
.size(40.dp)
.clip(CircleShape)
)
Spacer(modifier = Modifier.width(8.dp))
Column(modifier = Modifier.weight(1f)) {
Text(
text = stringResource(R.string.subreddit_header, post.subreddit),
fontWeight = FontWeight.Medium,
color = MaterialTheme.colors.primaryVariant
)
Text(
text = stringResource(R.string.post_header, post.username, post.postedTime),
color = Color.Gray
)
}
MoreActionsMenu()
}
Title(text = post.title)
}
@Composable
fun MoreActionsMenu() {
var expanded by remember { mutableStateOf(false) }
Box(modifier = Modifier.wrapContentSize(Alignment.TopStart)) {
IconButton(onClick = { expanded = true }) {
Icon(
imageVector = Icons.Default.MoreVert,
tint = Color.DarkGray,
contentDescription = stringResource(id = R.string.more_actions)
)
}
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false }
) {
CustomDropdownMenuItem(
vectorResourceId = R.drawable.ic_baseline_bookmark_24,
text = stringResource(id = R.string.save)
)
}
}
}
@Composable
fun CustomDropdownMenuItem(
@DrawableRes vectorResourceId: Int,
color: Color = Color.Black,
text: String,
onClickAction: () -> Unit = {}
) {
DropdownMenuItem(onClick = onClickAction) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
imageVector = ImageVector.vectorResource(id = vectorResourceId),
tint = color,
contentDescription = stringResource(id = R.string.save)
)
Spacer(modifier = Modifier.width(8.dp))
Text(text = text, fontWeight = FontWeight.Medium, color = color)
}
}
}
@Composable
fun Title(text: String) {
Text(
text = text,
maxLines = 3,
fontWeight = FontWeight.Medium,
fontSize = 16.sp,
color = MaterialTheme.colors.primaryVariant,
modifier = Modifier.padding(start = 16.dp, end = 16.dp)
)
}
@Composable
fun TextContent(text: String) {
Text(
modifier = Modifier.padding(
start = 16.dp,
end = 16.dp
),
text = text,
color = Color.Gray,
fontSize = 12.sp,
maxLines = 3
)
}
@Composable
fun ImageContent(image: Int) {
val imageAsset = ImageBitmap.imageResource(id = image)
Image(
bitmap = imageAsset,
contentDescription = stringResource(id = R.string.post_header_description),
modifier = Modifier
.fillMaxWidth()
.aspectRatio(imageAsset.width.toFloat() / imageAsset.height),
contentScale = ContentScale.Crop
)
}
@Composable
fun PostActions(post: PostModel) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(start = 16.dp, end = 16.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
VotingAction(text = post.likes, onUpVoteAction = {}, onDownVoteAction = {})
PostAction(
vectorResourceId = R.drawable.ic_baseline_comment_24,
text = post.comments,
onClickAction = {}
)
PostAction(
vectorResourceId = R.drawable.ic_baseline_share_24,
text = stringResource(R.string.share),
onClickAction = {}
)
PostAction(
vectorResourceId = R.drawable.ic_baseline_emoji_events_24,
text = stringResource(R.string.award),
onClickAction = {}
)
}
}
@Composable
fun VotingAction(
text: String,
onUpVoteAction: () -> Unit,
onDownVoteAction: () -> Unit
) {
Row(verticalAlignment = Alignment.CenterVertically) {
ArrowButton(
onUpVoteAction,
R.drawable.ic_baseline_arrow_upward_24
)
Text(
text = text,
color = Color.Gray,
fontWeight = FontWeight.Medium, fontSize = 12.sp
)
ArrowButton(onDownVoteAction, R.drawable.ic_baseline_arrow_downward_24)
}
}
@Composable
fun ArrowButton(onClickAction: () -> Unit, arrowResourceId: Int) {
IconButton(onClick = onClickAction, modifier = Modifier.size(30.dp)) {
Icon(
imageVector = ImageVector.vectorResource(arrowResourceId),
contentDescription = stringResource(id = R.string.upvote),
modifier = Modifier.size(20.dp),
tint = Color.Gray
)
}
}
@Composable
fun PostAction(
@DrawableRes vectorResourceId: Int,
text: String,
onClickAction: () -> Unit
) {
Box(modifier = Modifier.clickable(onClick = onClickAction)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
ImageVector.vectorResource(id = vectorResourceId),
contentDescription = stringResource(id = R.string.post_action),
tint = Color.Gray,
modifier = Modifier.size(20.dp)
)
Spacer(modifier = Modifier.width(4.dp))
Text(text = text, fontWeight = FontWeight.Medium, color = Color.Gray, fontSize = 12.sp)
}
}
}
@Preview(showBackground = true)
@Composable
fun ArrowButtonPreview() {
ArrowButton({}, R.drawable.ic_baseline_arrow_upward_24)
}
@Preview(showBackground = true)
@Composable
fun HeaderPreview() {
Column {
Header(DEFAULT_POST)
}
}
@Preview
@Composable
fun VotingActionPreview() {
VotingAction("555", {}, {})
}
@Preview
@Composable
fun PostPreview() {
Post(DEFAULT_POST)
}
@Preview
@Composable
fun TextPostPreview() {
Post(DEFAULT_POST) {
TextContent(DEFAULT_POST.text)
}
}
@Preview
@Composable
fun ImagePostPreview() {
Post(DEFAULT_POST) {
ImageContent(DEFAULT_POST.image ?: R.drawable.compose_course)
}
} | lab10/app/src/main/java/com/topic3/android/reddit/components/Post.kt | 885420117 |
package com.topic3.android.reddit
import android.annotation.SuppressLint
import androidx.compose.animation.Crossfade
import androidx.compose.foundation.layout.padding
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountCircle
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.unit.dp
import com.topic3.android.reddit.appdrawer.AppDrawer
import com.topic3.android.reddit.routing.RedditRouter
import com.topic3.android.reddit.routing.Screen
import com.topic3.android.reddit.screens.*
import com.topic3.android.reddit.theme.RedditTheme
import com.topic3.android.reddit.viewmodel.MainViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
@Composable
fun RedditApp(viewModel: MainViewModel) {
RedditTheme {
AppContent(viewModel)
}
}
@SuppressLint("UnusedMaterialScaffoldPaddingParameter")
@Composable
private fun AppContent(viewModel: MainViewModel) {
val scaffoldState: ScaffoldState = rememberScaffoldState()
val coroutineScope: CoroutineScope = rememberCoroutineScope()
Crossfade(targetState = RedditRouter.currentScreen) { screenState: MutableState<Screen> ->
Scaffold(
topBar = getTopBar(screenState.value, scaffoldState, coroutineScope),
drawerContent = {
AppDrawer(
closeDrawerAction = { coroutineScope.launch { scaffoldState.drawerState.close() } }
)
},
scaffoldState = scaffoldState,
bottomBar = {
BottomNavigationComponent(screenState = screenState)
},
content = {
MainScreenContainer(
modifier = Modifier.padding(bottom = 56.dp),
screenState = screenState,
viewModel = viewModel
)
}
)
}
}
fun getTopBar(
screenState: Screen,
scaffoldState: ScaffoldState,
coroutineScope: CoroutineScope
): @Composable (() -> Unit) {
if (screenState == Screen.MyProfile) {
return {}
} else {
return { TopAppBar(scaffoldState = scaffoldState, coroutineScope = coroutineScope) }
}
}
/**
* Представляет верхнюю панель приложений на экране
*/
@Composable
fun TopAppBar(scaffoldState: ScaffoldState, coroutineScope: CoroutineScope) {
val colors = MaterialTheme.colors
TopAppBar(
title = {
Text(
text = stringResource(RedditRouter.currentScreen.value.titleResId),
color = colors.primaryVariant
)
},
backgroundColor = colors.surface,
navigationIcon = {
IconButton(onClick = {
coroutineScope.launch { scaffoldState.drawerState.open() }
}) {
Icon(
Icons.Filled.AccountCircle,
tint = Color.LightGray,
contentDescription = stringResource(id = R.string.account)
)
}
}
)
}
@Composable
private fun MainScreenContainer(
modifier: Modifier = Modifier,
screenState: MutableState<Screen>,
viewModel: MainViewModel
) {
Surface(
modifier = modifier,
color = MaterialTheme.colors.background
) {
when (screenState.value) {
Screen.Home -> HomeScreen(viewModel)
Screen.Subscriptions -> SubredditsScreen()
Screen.NewPost -> AddScreen(viewModel)
Screen.MyProfile -> MyProfileScreen(viewModel)
Screen.ChooseCommunity -> ChooseCommunityScreen(viewModel)
}
}
}
@Composable
private fun BottomNavigationComponent(
modifier: Modifier = Modifier,
screenState: MutableState<Screen>
) {
var selectedItem by remember { mutableStateOf(0) }
val items = listOf(
NavigationItem(0, R.drawable.ic_baseline_home_24, R.string.home_icon, Screen.Home),
NavigationItem(
1,
R.drawable.ic_baseline_format_list_bulleted_24,
R.string.subscriptions_icon,
Screen.Subscriptions
),
NavigationItem(2, R.drawable.ic_baseline_add_24, R.string.post_icon, Screen.NewPost),
)
BottomNavigation(modifier = modifier) {
items.forEach {
BottomNavigationItem(
icon = {
Icon(
imageVector = ImageVector.vectorResource(id = it.vectorResourceId),
contentDescription = stringResource(id = it.contentDescriptionResourceId)
)
},
selected = selectedItem == it.index,
onClick = {
selectedItem = it.index
screenState.value = it.screen
}
)
}
}
}
private data class NavigationItem(
val index: Int,
val vectorResourceId: Int,
val contentDescriptionResourceId: Int,
val screen: Screen
) | lab10/app/src/main/java/com/topic3/android/reddit/RedditApp.kt | 1611890679 |
package com.topic3.android.reddit.theme
import androidx.compose.ui.graphics.Color
val RwPrimary = Color.White
val RwPrimaryDark = Color.Black
val RwAccent = Color(0xFF3F51B5)
val LightBlue = Color(0xFF2196F3)
val Red800 = Color(0xffd00036) | lab10/app/src/main/java/com/topic3/android/reddit/theme/Color.kt | 2345760543 |
package com.topic3.android.reddit.theme
import android.annotation.SuppressLint
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.graphics.Color
@SuppressLint("ConflictingOnColor")
private val LightThemeColors = lightColors(
primary = RwPrimary,
primaryVariant = RwPrimaryDark,
onPrimary = Color.Gray,
secondary = Color.LightGray,
secondaryVariant = RwPrimaryDark,
onSecondary = Color.Black,
error = Red800
)
@SuppressLint("ConflictingOnColor")
private val DarkThemeColors = darkColors(
primary = RwPrimaryDark,
primaryVariant = RwPrimary,
onPrimary = Color.Gray,
secondary = Color.Black,
onSecondary = Color.White,
error = Red800
)
@Composable
fun RedditTheme(
content: @Composable () -> Unit
) {
MaterialTheme(
colors = if (RedditThemeSettings.isInDarkTheme.value) DarkThemeColors else LightThemeColors,
content = content
)
}
object RedditThemeSettings {
var isInDarkTheme: MutableState<Boolean> = mutableStateOf(false)
} | lab10/app/src/main/java/com/topic3/android/reddit/theme/Theme.kt | 2416053452 |
package com.topic3.android.reddit.routing
import androidx.activity.ComponentActivity
import androidx.activity.OnBackPressedCallback
import androidx.activity.OnBackPressedDispatcher
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.platform.LocalLifecycleOwner
private val localBackPressedDispatcher = staticCompositionLocalOf<OnBackPressedDispatcher?> { null }
@Composable
fun BackButtonHandler(
enabled: Boolean = true,
onBackPressed: () -> Unit
){
val dispatcher = localBackPressedDispatcher.current ?: return
val backCallback = remember {
object : OnBackPressedCallback(enabled){
override fun handleOnBackPressed(){
onBackPressed.invoke()
}
}
}
DisposableEffect(dispatcher) {
dispatcher.addCallback(backCallback)
onDispose {
backCallback.remove()
}
}
}
@Composable
fun BackButtonAction(onBackPressed: () -> Unit){
CompositionLocalProvider (
localBackPressedDispatcher provides (
LocalLifecycleOwner.current as ComponentActivity
).onBackPressedDispatcher
){
BackButtonHandler {
onBackPressed.invoke()
}
}
} | lab10/app/src/main/java/com/topic3/android/reddit/routing/BackButtonHandler.kt | 2751911153 |
package com.topic3.android.reddit.routing
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import com.topic3.android.reddit.R
/**
* Класс, определяющий экраны, которые есть в нашем приложении.
*
* Эти объекты должны соответствовать файлам, которые есть в пакете screens
*/
sealed class Screen(val titleResId: Int) {
object Home : Screen(R.string.home)
object Subscriptions : Screen(R.string.subreddits)
object NewPost : Screen(R.string.new_post)
object MyProfile : Screen(R.string.my_profile)
object ChooseCommunity : Screen(R.string.choose_community)
}
object RedditRouter {
var currentScreen: MutableState<Screen> = mutableStateOf(
Screen.Home
)
private var previousScreen: MutableState<Screen> = mutableStateOf(
Screen.Home
)
fun navigateTo(destination: Screen) {
previousScreen.value = currentScreen.value
currentScreen.value = destination
}
fun goBack() {
currentScreen.value = previousScreen.value
}
} | lab10/app/src/main/java/com/topic3/android/reddit/routing/RedditRouter.kt | 3308827752 |
package com.topic3.android.reddit.routing
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
/**
* Класс, определяющий экраны, которые есть в нашем приложении.
*
* Эти объекты должны соответствовать файлам, которые есть в пакете screens
*/
sealed class MyProfileScreenType {
object Posts : MyProfileScreenType()
object About : MyProfileScreenType()
}
object MyProfileRouter {
var currentScreen: MutableState<MyProfileScreenType> = mutableStateOf(MyProfileScreenType.Posts)
fun navigateTo(destination: MyProfileScreenType) {
currentScreen.value = destination
}
} | lab10/app/src/main/java/com/topic3/android/reddit/routing/MyProfileRouter.kt | 361433758 |
package com.topic3.android.reddit.data.database.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.topic3.android.reddit.data.database.model.PostDbModel
/**
* Dao для управления таблицей сообщений в базе данных.
*/
@Dao
interface PostDao {
@Query("SELECT * FROM PostDbModel")
fun getAllPosts(): List<PostDbModel>
@Query("SELECT * FROM PostDbModel WHERE username = :username")
fun getAllOwnedPosts(username: String): List<PostDbModel>
@Query("SELECT DISTINCT subreddit FROM PostDbModel")
fun getAllSubreddits(): List<String>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(postDbModel: PostDbModel)
@Query("DELETE FROM PostDbModel")
fun deleteAll()
@Insert
fun insertAll(vararg PostDbModels: PostDbModel)
} | lab10/app/src/main/java/com/topic3/android/reddit/data/database/dao/PostDao.kt | 1611971120 |
package com.topic3.android.reddit.data.database
import androidx.room.Database
import androidx.room.RoomDatabase
import com.topic3.android.reddit.data.database.dao.PostDao
import com.topic3.android.reddit.data.database.model.PostDbModel
/**
* База данных приложения.
*
* Содержит таблицу для постов
*/
@Database(entities = [PostDbModel::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
companion object {
const val DATABASE_NAME = "jet-reddit-database"
}
abstract fun postDao(): PostDao
} | lab10/app/src/main/java/com/topic3/android/reddit/data/database/AppDatabase.kt | 3610982149 |
package com.topic3.android.reddit.data.database.dbmapper
import com.topic3.android.reddit.data.database.model.PostDbModel
import com.topic3.android.reddit.domain.model.PostModel
interface DbMapper {
fun mapPost(dbPostDbModel: PostDbModel): PostModel
fun mapDbPost(postModel: PostModel): PostDbModel
} | lab10/app/src/main/java/com/topic3/android/reddit/data/database/dbmapper/DbMapper.kt | 3705044081 |
package com.topic3.android.reddit.data.database.dbmapper
import com.topic3.android.reddit.data.database.model.PostDbModel
import com.topic3.android.reddit.domain.model.PostModel
import com.topic3.android.reddit.domain.model.PostType
import java.util.concurrent.TimeUnit
class DbMapperImpl : DbMapper {
override fun mapPost(dbPostDbModel: PostDbModel): PostModel {
with(dbPostDbModel) {
return PostModel(
username,
subreddit,
title,
text,
likes.toString(),
comments.toString(),
PostType.fromType(type),
getPostedDate(datePosted),
image
)
}
}
override fun mapDbPost(postModel: PostModel): PostDbModel {
with(postModel) {
return PostDbModel(
null,
"raywenderlich",
subreddit,
title,
text,
0,
0,
type.type,
System.currentTimeMillis(),
false,
image
)
}
}
private fun getPostedDate(date: Long): String {
val hoursPassed =
TimeUnit.HOURS.convert(System.currentTimeMillis() - date, TimeUnit.MILLISECONDS)
if (hoursPassed > 24) {
val daysPassed = TimeUnit.DAYS.convert(hoursPassed, TimeUnit.HOURS)
if (daysPassed > 30) {
if (daysPassed > 365) {
return (daysPassed / 365).toString() + "y"
}
return (daysPassed / 30).toString() + "mo"
}
return daysPassed.toString() + "d"
}
return hoursPassed.inc().toString() + "h"
}
} | lab10/app/src/main/java/com/topic3/android/reddit/data/database/dbmapper/DbMapperImpl.kt | 2909526430 |
package com.topic3.android.reddit.data.database.model
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.topic3.android.reddit.R
@Entity
data class PostDbModel(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id") val id: Long?,
@ColumnInfo(name = "username") val username: String,
@ColumnInfo(name = "subreddit") val subreddit: String,
@ColumnInfo(name = "title") val title: String,
@ColumnInfo(name = "text") val text: String,
@ColumnInfo(name = "likes") val likes: Int,
@ColumnInfo(name = "comments") val comments: Int,
@ColumnInfo(name = "type") val type: Int,
@ColumnInfo(name = "date_posted") val datePosted: Long,
@ColumnInfo(name = "is_saved") val isSaved: Boolean,
@ColumnInfo(name = "image") val image: Int? = null
) {
companion object {
val DEFAULT_POSTS = listOf(
PostDbModel(
1,
"raywenderlich",
"androiddev",
"Check out this new book about Jetpack Compose from raywenderlich.com!",
"Check out this new book about Jetpack Compose from raywenderlich.com!",
5614,
523,
0,
System.currentTimeMillis(),
false,
image = R.drawable.compose_course
),
PostDbModel(
2,
"pro_dev",
"digitalnomad",
"My ocean view in Thailand.",
"",
2314,
23,
1, System.currentTimeMillis(),
false,
image = R.drawable.thailand
),
PostDbModel(
3,
"raywenderlich",
"programming",
"Check out this new book about Jetpack Compose from raywenderlich.com!",
"Check out this new book about Jetpack Compose from raywenderlich.com!",
5214,
423,
0,
System.currentTimeMillis(),
false
),
PostDbModel(
4,
"raywenderlich",
"puppies",
"My puppy running around the house looks so cute!",
"My puppy running around the house looks so cute!",
25315,
1362,
0,
System.currentTimeMillis(),
false
),
PostDbModel(
5, "ps_guy", "playstation", "My PS5 just arrived!",
"", 56231, 823, 0, System.currentTimeMillis(), false
)
)
}
}
| lab10/app/src/main/java/com/topic3/android/reddit/data/database/model/PostDbModel.kt | 1108878045 |
package com.topic3.android.reddit.data.repository
import androidx.lifecycle.LiveData
import com.topic3.android.reddit.domain.model.PostModel
interface Repository {
fun getAllPosts(): LiveData<List<PostModel>>
fun getAllOwnedPosts(): LiveData<List<PostModel>>
fun getAllSubreddits(searchedText: String): List<String>
fun insert(post: PostModel)
fun deleteAll()
} | lab10/app/src/main/java/com/topic3/android/reddit/data/repository/Repository.kt | 2729691922 |
package com.topic3.android.reddit.data.repository
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.topic3.android.reddit.data.database.dao.PostDao
import com.topic3.android.reddit.data.database.dbmapper.DbMapper
import com.topic3.android.reddit.data.database.model.PostDbModel
import com.topic3.android.reddit.domain.model.PostModel
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
class RepositoryImpl(private val postDao: PostDao, private val mapper: DbMapper) : Repository {
private var searchedText = ""
private val allPostsLiveData: MutableLiveData<List<PostModel>> by lazy {
MutableLiveData<List<PostModel>>()
}
private val ownedPostsLiveData: MutableLiveData<List<PostModel>> by lazy {
MutableLiveData<List<PostModel>>()
}
init {
initDatabase(this::updatePostLiveData)
}
/**
* Populates database with posts if it is empty.
*/
private fun initDatabase(postInitAction: () -> Unit) {
GlobalScope.launch {
// Prepopulate posts
val posts = PostDbModel.DEFAULT_POSTS.toTypedArray()
val dbPosts = postDao.getAllPosts()
if (dbPosts.isNullOrEmpty()) {
postDao.insertAll(*posts)
}
postInitAction.invoke()
}
}
override fun getAllPosts(): LiveData<List<PostModel>> = allPostsLiveData
override fun getAllOwnedPosts(): LiveData<List<PostModel>> = ownedPostsLiveData
override fun getAllSubreddits(searchedText: String): List<String> {
this.searchedText = searchedText
if (searchedText.isNotEmpty()) {
return postDao.getAllSubreddits().filter { it.contains(searchedText) }
}
return postDao.getAllSubreddits()
}
private fun getAllPostsFromDatabase(): List<PostModel> =
postDao.getAllPosts().map(mapper::mapPost)
private fun getAllOwnedPostsFromDatabase(): List<PostModel> =
postDao.getAllOwnedPosts("raywenderlich").map(mapper::mapPost)
override fun insert(post: PostModel) {
postDao.insert(mapper.mapDbPost(post))
updatePostLiveData()
}
override fun deleteAll() {
postDao.deleteAll()
updatePostLiveData()
}
private fun updatePostLiveData() {
allPostsLiveData.postValue(getAllPostsFromDatabase())
ownedPostsLiveData.postValue(getAllOwnedPostsFromDatabase())
}
} | lab10/app/src/main/java/com/topic3/android/reddit/data/repository/RepositoryImpl.kt | 3304034557 |
package com.topic3.android.reddit.domain.model
import com.topic3.android.reddit.R
data class PostModel(
val username: String,
val subreddit: String,
val title: String,
val text: String,
val likes: String,
val comments: String,
val type: PostType,
val postedTime: String,
val image: Int?
) {
companion object {
val DEFAULT_POST = PostModel(
"raywenderlich",
"androiddev",
"Watch this awesome Jetpack Compose course!",
"",
"5614",
"523",
PostType.IMAGE,
"4h",
R.drawable.compose_course
)
val EMPTY = PostModel(
"raywenderlich",
"raywenderlich.com",
"",
"",
"0",
"0",
PostType.TEXT,
"0h",
R.drawable.compose_course
)
}
} | lab10/app/src/main/java/com/topic3/android/reddit/domain/model/PostModel.kt | 1666616389 |
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/domain/model/PostType.kt | 4180988263 |
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)
}
} | lab10/app/src/main/java/com/topic3/android/reddit/dependencyinjection/DependencyInjector.kt | 1317812683 |
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/androidTest/java/com/example/ass3/ExampleInstrumentedTest.kt | 4242128321 |
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/test/java/com/example/ass3/ExampleUnitTest.kt | 387910805 |
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/Color.kt | 1249147131 |
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/Theme.kt | 1398499533 |
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/ui/theme/Type.kt | 3779992505 |
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/MainActivity.kt | 1887902447 |
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/Schema.kt | 368039925 |
package com.example.ass3
sealed interface DataEvents{
data class addData(val data: OrientationData) : DataEvents
} | SensorApp/app/src/main/java/com/example/ass3/repository.kt | 3678087264 |
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/RealTimeDataScreen.kt | 3756018783 |
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/SensorData.kt | 3379681991 |
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/OrientationViewModel.kt | 1970166696 |
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/Database.kt | 483357133 |
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
)
}
| SensorApp/app/src/main/java/com/example/ass3/Graph.kt | 4102925157 |
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/androidTest/java/com/app/speakertrainer/ExampleInstrumentedTest.kt | 2268051502 |
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/ExampleUnitTest.kt | 4172038078 |
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/test/java/com/app/speakertrainer/ClientTest.kt | 51704763 |
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/constance/Constance.kt | 4251426676 |
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/CheckListActivity.kt | 2121492576 |
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/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.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/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 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/PreviewVideoActivity.kt | 1749811165 |
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/AnalysisResults.kt | 3704991230 |
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/Home.kt | 2527553485 |
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/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.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/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.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/activities/Recommendations.kt | 3867853625 |
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/ApiManager.kt | 4292543840 |
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/TypefaceSpan.kt | 62095089 |
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/RecordAdapter.kt | 2556448732 |
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/NetworkClient.kt | 1585401364 |
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/modules/Client.kt | 1160391479 |
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/Record.kt | 873651075 |
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/FileInfo.kt | 1370980745 |
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/ResponseResults.kt | 592390480 |
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/FilesNumbers.kt | 2410999460 |
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/Statistics.kt | 2049379067 |
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?
)
| Speaker-Trainer/app/src/main/java/com/app/speakertrainer/data/RecommendationsInfo.kt | 149278697 |
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/OtherResponse.kt | 3508296939 |
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/AuthRequest.kt | 3448066750 |
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/NoteResponse.kt | 2062847933 |
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/AuthResponse.kt | 3929482064 |
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/dto/NoteRequest.kt | 114961162 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.