content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package com.example.robota
sealed class CalculatorAction {
data class Number(val value: Int) : CalculatorAction()
data class Operation(val operation: CalculatorOperation) : CalculatorAction()
object Decimal : CalculatorAction()
object Calculate : CalculatorAction()
object Clear : CalculatorAction()
object Delete : CalculatorAction()
}
| Simple-Calculator-/app/src/main/java/com/example/robota/Action.kt | 882964951 |
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import kotlin.test.DefaultAsserter
import kotlin.test.DefaultAsserter.fail
import kotlin.test.fail
/*
Testes Unitários
-> Testam pequenas unidades do código, geralmente funções, garantindo o funcionamento do código.
-> *Obs:* São códigos que irão testar outras partes do código.
-> Gera um processo automatizado de testes:
-> O teste escrito pode ser executado diversas vezes garantindo que a função faz o que propõe
-> Pode ser executado vários testes ao mesmo tempo (*suíte de testes*)
-> reduz a verificação manual como o *debugger ou println*
-> Melhor design de funções.
-> Ferramenta útil para regressão
*/
class MainTest {
var mainClass = Main()
@Test
@DisplayName("Teste do metodo -> ContagemDeLetrasXO")
@Disabled // -> É utilizado para desativar o teste
fun testecontagemDeLetrasXO() {
/*
* Caso seja usado apenas o assertTrue ele para os testes assim que
* algum não passe, para os demais testes aconteceçam independentes
* do problema, deve-se usar o Assertions.assertAll({})
*/
Assertions.assertAll(
{ Assertions.assertTrue(mainClass.contagemDeLetrasXO("xxoo")) },
{ Assertions.assertTrue(mainClass.contagemDeLetrasXO("xxooox")) }
)
}
@Test
@Disabled
fun falhar() {
DefaultAsserter.fail("Não posso terminar essa classe sem finalizar os testes. -> exemplo")
}
@Test
@DisplayName("Teste Portaria")
fun testeVerificarInformacoesNaPortaria() {
Assertions.assertAll({
Assertions.assertEquals(
mainClass.verificarInformacoesNaPortaria(
15, "", ""
), "Negado"
)
Assertions.assertEquals(
mainClass.verificarInformacoesNaPortaria(
20, "", ""
), "Negado"
)
Assertions.assertEquals(
mainClass.verificarInformacoesNaPortaria(
25, "VIP", ""
), "Negado"
)
Assertions.assertEquals(
mainClass.verificarInformacoesNaPortaria(
25, "comum", "xt45696"
), "Welcome"
)
Assertions.assertEquals(
mainClass.verificarInformacoesNaPortaria(
25, "COMUM", "xt45696"
), "Welcome"
)
Assertions.assertEquals(
mainClass.verificarInformacoesNaPortaria(
25, "comum", "86963512"
), "Negado"
)
Assertions.assertEquals(
mainClass.verificarInformacoesNaPortaria(
25, "premium", "xl86963512"
), "Welcome"
)
Assertions.assertEquals(
mainClass.verificarInformacoesNaPortaria(
25, "luxo", "XL86963512"
), "Welcome"
)
})
}
} | testes-unitarios/src/test/kotlin/MainTest.kt | 2625089603 |
class Main() {
fun main() {
println(verificarInformacoesNaPortaria(25, "comum", "Xl"))
}
fun contagemDeLetrasXO(frase: String): Boolean {
var x = 0
var o = 0
frase.let {
for (char: Char in frase.lowercase()) {
if (char == 'x') x++
if (char == 'o') o++
}
if ((x > 0 && o > 0) && x == o) return true
}
return false
}
fun verificarInformacoesNaPortaria(idade: Int, convite: String, codigo: String): String {
if (idade < 18) return "Negado"
if (convite.isNotEmpty()) {
val tipoDoConvite = convite.lowercase()
if (tipoDoConvite != "comum" && tipoDoConvite != "premium" && tipoDoConvite != "luxo")
return "Negado"
if (codigo.isNotEmpty()) {
val tipoCodigo = codigo.lowercase()
return if (tipoDoConvite == "comum" && tipoCodigo.startsWith("xt"))
"Welcome"
else if (tipoDoConvite == "premium" || tipoDoConvite == "luxo" &&
tipoCodigo.startsWith("xl")
) "Welcome"
else "Negado"
}
}
return "Negado"
}
}
| testes-unitarios/src/main/kotlin/Main.kt | 2727059038 |
package com.example.myhistorydiscoveryapp
import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
class MainActivity : AppCompatActivity() {
@SuppressLint("MissingInflatedId")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val generateHistoryButton = findViewById<Button>(R.id.generateHistoryButton)
val ageEditText = findViewById<EditText>(R.id.ageEditText)
val infoTextView = findViewById<TextView>(R.id.infoTextView)
generateHistoryButton.setOnClickListener {
val ageText = ageEditText.text.toString()
if (ageText.isNotEmpty()) {
val age = ageText.toIntOrNull()
if (age != null) {
val historicFigure = findHistoricFigure(age)
infoTextView.text = "Historic Figure: $historicFigure"
} else {
infoTextView.text = "Please enter a valid age"
}
} else {
infoTextView.text = "Please enter an age"
}
}
}
private fun findHistoricFigure(age: Int): String {
return when {
age in 20..40 -> "Martin Luther King Jr."
age in 41..59 -> "Napoleon Bonaparte"
age in 51..69 -> "Christopher Columbus"
// Add more cases for other age ranges
else -> "No historic figure found for this age"
}
}
}
| DwaynePassenz_ST10453003_Assignment-1/app/src/main/java/com/example/myhistorydiscoveryapp/MainActivity.kt | 2726247094 |
package spelldnd
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.server.testing.*
import kotlin.test.*
import spelldnd.plugins.*
import kotlin.test.Test
class ApplicationTest {
// @Test
// fun testRoot() = testApplication {
// application {
// configureRouting()
// }
// client.get("/").apply {
// assertEquals(HttpStatusCode.OK, status)
// assertEquals("Hello World!", bodyAsText())
// }
// }
}
| spellDndMultiplatform-backend/src/test/kotlin/spelldnd/ApplicationTest.kt | 734611210 |
import io.ktor.server.application.*
import io.ktor.server.cio.*
import io.ktor.server.engine.*
import org.jetbrains.exposed.sql.Database
import com.spelldnd.features.login.configureLoginRouting
import com.spelldnd.features.register.configureRegisterRouting
import com.spelldnd.features.spells.configureSpellsRouting
import com.spelldnd.plugins.*
import java.io.File
@Throws(Exception::class)
fun main() {
val file = File("example.txt")
try {
//throw Exception("Hi There!")
Database.connect(
url = "jdbc:postgresql://localhost:5432/spelldnd",
driver = "org.postgresql.Driver",
user = "postgres",
password = "rfvsikjdrf1"
)
embeddedServer(CIO, port = 8080, host = "0.0.0.0", module = Application::module)
.start(wait = true)
} catch (e: Exception) {
file.appendText(e.toString() + "\n")
}
}
fun Application.module() {
configureLoginRouting()
configureRegisterRouting()
configureSpellsRouting()
configureSerialization()
}
| spellDndMultiplatform-backend/src/main/kotlin/Application.kt | 2141926165 |
package com.spelldnd.database.users
class UserDTO(
val login: String,
val password: String,
val email: String?,
val username: String
) | spellDndMultiplatform-backend/src/main/kotlin/com/spelldnd/database/users/UserDTO.kt | 4219710533 |
package com.spelldnd.database.users
import org.jetbrains.exposed.sql.Table
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.select
import org.jetbrains.exposed.sql.transactions.transaction
object Users: Table("users") {
private val login = Users.varchar("login", 25)
private val password = Users.varchar("password", 25)
private val username = Users.varchar("username", 30)
private val email = Users.varchar("email", 25)
fun insert(userDTO: UserDTO) {
transaction {
Users.insert {
it[login] = userDTO.login
it[password] = userDTO.password
it[username] = userDTO.username
it[email] = userDTO.email ?: ""
}
}
}
fun fetchUser(login: String): UserDTO? {
return try{
transaction {
val userModel = Users.select { Users.login.eq(login) }.single()
UserDTO(
login = userModel[Users.login],
password = userModel[Users.password],
email = userModel[Users.email],
username = userModel[Users.username]
)
}
} catch (e: Exception) {
null
}
}
} | spellDndMultiplatform-backend/src/main/kotlin/com/spelldnd/database/users/Users.kt | 3703962069 |
package com.spelldnd.database.spells
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.transaction
object Spells: Table("spells_ru"){
private val slug = com.spelldnd.database.spells.Spells.varchar("slug", 255)
private val name = com.spelldnd.database.spells.Spells.varchar("name", 255)
private val desc = com.spelldnd.database.spells.Spells.text("desc")
private val higher_level = com.spelldnd.database.spells.Spells.text("higher_level")
private val range = com.spelldnd.database.spells.Spells.text("range")
private val components = com.spelldnd.database.spells.Spells.text("components")
private val material = com.spelldnd.database.spells.Spells.text("material")
private val ritual = com.spelldnd.database.spells.Spells.varchar("ritual", 25)
private val duration = com.spelldnd.database.spells.Spells.text("duration")
private val concentration = com.spelldnd.database.spells.Spells.varchar("concentration", 25)
private val casting_time = com.spelldnd.database.spells.Spells.text("casting_time")
private val level = com.spelldnd.database.spells.Spells.varchar("level", 25)
private val level_int = com.spelldnd.database.spells.Spells.integer("level_int")
private val school = com.spelldnd.database.spells.Spells.varchar("school", 255)
private val dnd_class = com.spelldnd.database.spells.Spells.text("dnd_class")
private val archetype = com.spelldnd.database.spells.Spells.text("archetype")
fun insert(spellDTO: com.spelldnd.database.spells.SpellDTO) {
transaction {
com.spelldnd.database.spells.Spells.insert {
it[com.spelldnd.database.spells.Spells.slug] = spellDTO.slug
it[com.spelldnd.database.spells.Spells.name] = spellDTO.name
it[com.spelldnd.database.spells.Spells.desc] = spellDTO.desc
it[com.spelldnd.database.spells.Spells.higher_level] = spellDTO.higher_level
it[com.spelldnd.database.spells.Spells.range] = spellDTO.range
it[com.spelldnd.database.spells.Spells.components] = spellDTO.components
it[com.spelldnd.database.spells.Spells.material] = spellDTO.material
it[com.spelldnd.database.spells.Spells.ritual] = spellDTO.ritual
it[com.spelldnd.database.spells.Spells.duration] = spellDTO.duration
it[com.spelldnd.database.spells.Spells.concentration] = spellDTO.concentration
it[com.spelldnd.database.spells.Spells.casting_time] = spellDTO.casting_time
it[com.spelldnd.database.spells.Spells.level] = spellDTO.level
it[com.spelldnd.database.spells.Spells.level_int] = spellDTO.level_int
it[com.spelldnd.database.spells.Spells.school] = spellDTO.school
it[com.spelldnd.database.spells.Spells.dnd_class] = spellDTO.dnd_class
it[com.spelldnd.database.spells.Spells.archetype] = spellDTO.archetype
}
}
}
fun delete(slug: String) {
transaction {
com.spelldnd.database.spells.Spells.deleteWhere { com.spelldnd.database.spells.Spells.slug eq slug }
}
}
fun fetchSpell(slug: String): com.spelldnd.database.spells.SpellDTO? {
return try{
transaction {
val spellsModel = com.spelldnd.database.spells.Spells.select { com.spelldnd.database.spells.Spells.slug.eq(slug) }.single()
com.spelldnd.database.spells.SpellDTO(
slug = spellsModel[com.spelldnd.database.spells.Spells.slug],
name = spellsModel[com.spelldnd.database.spells.Spells.name],
desc = spellsModel[com.spelldnd.database.spells.Spells.desc],
higher_level = spellsModel[com.spelldnd.database.spells.Spells.higher_level],
range = spellsModel[com.spelldnd.database.spells.Spells.range],
components = spellsModel[com.spelldnd.database.spells.Spells.components],
material = spellsModel[com.spelldnd.database.spells.Spells.material],
ritual = spellsModel[com.spelldnd.database.spells.Spells.ritual],
duration = spellsModel[com.spelldnd.database.spells.Spells.duration],
concentration = spellsModel[com.spelldnd.database.spells.Spells.concentration],
casting_time = spellsModel[com.spelldnd.database.spells.Spells.casting_time],
level = spellsModel[com.spelldnd.database.spells.Spells.level],
level_int = spellsModel[com.spelldnd.database.spells.Spells.level_int],
school = spellsModel[com.spelldnd.database.spells.Spells.school],
dnd_class = spellsModel[com.spelldnd.database.spells.Spells.dnd_class],
archetype = spellsModel[com.spelldnd.database.spells.Spells.archetype]
)
}
} catch (e: Exception) {
null
}
}
fun fetchAll(): List<com.spelldnd.database.spells.SpellDTO> {
return try {
transaction {
val spellsList = com.spelldnd.database.spells.Spells.selectAll().map {
com.spelldnd.database.spells.SpellDTO(
slug = it[com.spelldnd.database.spells.Spells.slug],
name = it[com.spelldnd.database.spells.Spells.name],
desc = it[com.spelldnd.database.spells.Spells.desc],
higher_level = it[com.spelldnd.database.spells.Spells.higher_level],
range = it[com.spelldnd.database.spells.Spells.range],
components = it[com.spelldnd.database.spells.Spells.components],
material = it[com.spelldnd.database.spells.Spells.material],
ritual = it[com.spelldnd.database.spells.Spells.ritual],
duration = it[com.spelldnd.database.spells.Spells.duration],
concentration = it[com.spelldnd.database.spells.Spells.concentration],
casting_time = it[com.spelldnd.database.spells.Spells.casting_time],
level = it[com.spelldnd.database.spells.Spells.level],
level_int = it[com.spelldnd.database.spells.Spells.level_int],
school = it[com.spelldnd.database.spells.Spells.school],
dnd_class = it[com.spelldnd.database.spells.Spells.dnd_class],
archetype = it[com.spelldnd.database.spells.Spells.archetype]
)
}
println(spellsList::class.simpleName)
spellsList
}
} catch (e: Exception) {
emptyList()
}
}
} | spellDndMultiplatform-backend/src/main/kotlin/com/spelldnd/database/spells/Spells.kt | 1971019995 |
package com.spelldnd.database.spells
import kotlinx.serialization.Serializable
@Serializable
class SpellDTO(
val slug: String,
val name: String,
val desc: String,
val higher_level: String,
val range: String,
val components: String,
val material: String,
val ritual: String,
val duration: String,
val concentration: String,
val casting_time: String,
val level: String,
val level_int: Int,
val school: String,
val dnd_class: String,
val archetype: String
)
| spellDndMultiplatform-backend/src/main/kotlin/com/spelldnd/database/spells/SpellDTO.kt | 3539364802 |
package com.spelldnd.database.tokens
class TokenDTO (
val rowId: String,
val login: String,
val token: String
) | spellDndMultiplatform-backend/src/main/kotlin/com/spelldnd/database/tokens/TokenDTO.kt | 2351643611 |
package com.spelldnd.database.tokens
import org.jetbrains.exposed.sql.Table
import org.jetbrains.exposed.sql.insert
import org.jetbrains.exposed.sql.selectAll
import org.jetbrains.exposed.sql.transactions.transaction
object Tokens: Table("tokens") {
private val id = Tokens.varchar("id", 50)
private val login = Tokens.varchar("login", 25)
private val token = Tokens.varchar("token", 75)
fun insert(tokenDTO: TokenDTO) {
transaction {
Tokens.insert {
it[id] = tokenDTO.rowId
it[login] = tokenDTO.login
it[token] = tokenDTO.token
}
}
}
fun fetchTokens(): List<TokenDTO> {
return try {
transaction {
Tokens.selectAll().toList()
.map {
TokenDTO(
rowId = it[Tokens.id],
token = it[Tokens.token],
login = it[Tokens.login]
)
}
}
} catch (e: Exception) {
emptyList()
}
}
} | spellDndMultiplatform-backend/src/main/kotlin/com/spelldnd/database/tokens/Tokens.kt | 2350532962 |
package com.spelldnd.plugins
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.serialization.Serializable
@Serializable
data class Test(
val text: String
)
fun Application.configureRouting() {
routing {
get("/") {
call.respond(Test(text = "Hello world"))
}
}
}
| spellDndMultiplatform-backend/src/main/kotlin/com/spelldnd/plugins/Routing.kt | 2863915491 |
package com.spelldnd.plugins
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.plugins.contentnegotiation.*
fun Application.configureSerialization() {
install(ContentNegotiation) {
json()
}
} | spellDndMultiplatform-backend/src/main/kotlin/com/spelldnd/plugins/Serialization.kt | 810834156 |
package com.spelldnd.features.register
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import org.jetbrains.exposed.exceptions.ExposedSQLException
import com.spelldnd.database.tokens.TokenDTO
import com.spelldnd.database.tokens.Tokens
import com.spelldnd.database.users.UserDTO
import com.spelldnd.database.users.Users
import com.spelldnd.utils.isValidEmail
import java.util.*
class RegisterController(private val call: ApplicationCall) {
suspend fun registerNewUser() {
val registerReceiveRemote = call.receive<RegisterReceiveRemote>()
if (!registerReceiveRemote.email.isValidEmail()) {
call.respond(HttpStatusCode.BadRequest, "Email is not valid")
}
val userDTO = Users.fetchUser(registerReceiveRemote.login)
if (userDTO != null) {
call.respond(HttpStatusCode.Conflict, "User already exists")
} else {
val token = UUID.randomUUID().toString()
try {
Users.insert(
UserDTO(
login = registerReceiveRemote.login,
password = registerReceiveRemote.password,
email = registerReceiveRemote.email ?: "",
username = ""
)
)
} catch (e: ExposedSQLException) {
call.respond(HttpStatusCode.Conflict, "User already exists")
}
Tokens.insert(
TokenDTO(
rowId = UUID.randomUUID().toString(),
login = registerReceiveRemote.login,
token = token)
)
call.respond(RegisterResponseRemote(token = token))
}
}
} | spellDndMultiplatform-backend/src/main/kotlin/com/spelldnd/features/register/RegisterController.kt | 1824787662 |
package com.spelldnd.features.register
import kotlinx.serialization.Serializable
@Serializable
data class RegisterReceiveRemote(
val login: String,
val email: String,
val password: String
)
@Serializable
data class RegisterResponseRemote(
val token: String
)
| spellDndMultiplatform-backend/src/main/kotlin/com/spelldnd/features/register/RegisterRemote.kt | 993662983 |
package com.spelldnd.features.register
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import com.spelldnd.cashe.InMemoryCache
import com.spelldnd.cashe.TokenCache
import com.spelldnd.utils.isValidEmail
import java.util.*
fun Application.configureRegisterRouting() {
routing {
post("/register") {
val registerController = RegisterController(call)
registerController.registerNewUser()
}
}
}
| spellDndMultiplatform-backend/src/main/kotlin/com/spelldnd/features/register/RegisterRouting.kt | 2893771031 |
package com.spelldnd.features.spells
import kotlinx.serialization.Serializable
@Serializable
data class SpellsRequest(
val slug: String,
val name: String,
val desc: String,
val higher_level: String,
val range: String,
val components: String,
val material: String,
val ritual: String,
val duration: String,
val concentration: String,
val casting_time: String,
val level: String,
val level_int: Int,
val school: String,
val dnd_class: String,
val archetype: String,
)
@Serializable
data class SpellsResponse(
val slug: String,
val name: String,
val desc: String,
val higher_level: String,
val range: String,
val components: String,
val material: String,
val ritual: String,
val duration: String,
val concentration: String,
val casting_time: String,
val level: String,
val level_int: Int,
val school: String,
val dnd_class: String,
val archetype: String,
)
@Serializable
data class FetchSpellsRequest(
val searchQuery: String
)
data class FetchSpellRequest(
val slug: String
) | spellDndMultiplatform-backend/src/main/kotlin/com/spelldnd/features/spells/SpellsRemote.kt | 1576192852 |
package com.spelldnd.features.spells
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import org.jetbrains.exposed.exceptions.ExposedSQLException
import com.spelldnd.database.spells.SpellDTO
import com.spelldnd.database.spells.Spells
class SpellsController(private val call: ApplicationCall) {
suspend fun createSpell() {
val receive = call.receive<SpellsRequest>()
if (receive.slug.isEmpty()) {
call.respond(HttpStatusCode.BadRequest, "slug is empty")
}
val spellsDTO = com.spelldnd.database.spells.Spells.fetchSpell(receive.slug)
if (spellsDTO != null) {
call.respond(HttpStatusCode.Conflict, "User already exists")
} else {
try {
com.spelldnd.database.spells.Spells.insert(
com.spelldnd.database.spells.SpellDTO(
slug = receive.slug,
name = receive.name,
desc = receive.desc,
higher_level = receive.higher_level,
range = receive.range,
components = receive.components,
material = receive.material,
ritual = receive.ritual,
duration = receive.duration,
concentration = receive.concentration,
casting_time = receive.casting_time,
level = receive.level,
level_int = receive.level_int,
school = receive.school,
dnd_class = receive.dnd_class,
archetype = receive.archetype
)
)
} catch (e: ExposedSQLException) {
call.respond(HttpStatusCode.Conflict, "Spell already exists")
}
call.respond("Spell added")
}
}
suspend fun addSpells() {
val spellsList = call.receive<List<SpellsRequest>>()
if (spellsList.isEmpty()) {
call.respond(HttpStatusCode.BadRequest, "Empty list of spells")
return
}
for (spell in spellsList) {
if (spell.slug.isEmpty()) {
call.respond(HttpStatusCode.BadRequest, "Slug is empty")
return
}
val spellsDTO = com.spelldnd.database.spells.Spells.fetchSpell(spell.slug)
if (spellsDTO != null) {
call.respond(HttpStatusCode.Conflict, "Spell with slug ${spell.slug} already exists")
return
} else {
try {
com.spelldnd.database.spells.Spells.insert(
com.spelldnd.database.spells.SpellDTO(
slug = spell.slug,
name = spell.name,
desc = spell.desc,
higher_level = spell.higher_level,
range = spell.range,
components = spell.components,
material = spell.material,
ritual = spell.ritual,
duration = spell.duration,
concentration = spell.concentration,
casting_time = spell.casting_time,
level = spell.level,
level_int = spell.level_int,
school = spell.school,
dnd_class = spell.dnd_class,
archetype = spell.archetype
)
)
} catch (e: ExposedSQLException) {
call.respond(HttpStatusCode.Conflict, "Spell with slug ${spell.slug} already exists")
return
}
}
}
call.respond("Spells added")
}
suspend fun deleteSpell() {
val receive = call.receive<SpellsRequest>()
val spell = com.spelldnd.database.spells.Spells.fetchSpell(receive.slug)
if (spell == null) {
call.respond(HttpStatusCode.NotFound, "Spell not found")
return
}
com.spelldnd.database.spells.Spells.delete(receive.slug)
call.respond("Spell deleted")
}
suspend fun deleteSpells() {
val receive = call.receive<List<SpellsRequest>>()
if (receive.isEmpty()) {
call.respond(HttpStatusCode.BadRequest, "Empty list of spells")
return
}
for (spell in receive) {
if (spell.slug.isEmpty()) {
call.respond(HttpStatusCode.BadRequest, "Slug is empty")
return
}
try {
com.spelldnd.database.spells.Spells.delete(slug = spell.slug)
} catch (e: ExposedSQLException) {
call.respond(HttpStatusCode.Conflict, "Spell with slug ${spell.slug} already exists")
return
}
}
call.respond("Spells deleted")
}
suspend fun performSearch() {
val searchQuery = call.parameters["searchQuery"] ?: ""
val searchProperties = call.parameters.getAll("searchProperty")?.toSet() ?: emptySet()
if (searchQuery.isBlank()) {
call.respond(com.spelldnd.database.spells.Spells.fetchAll())
} else {
val filteredSpells = com.spelldnd.database.spells.Spells.fetchAll().filter { spell ->
if (searchProperties.isNotEmpty()) {
searchProperties.any { property ->
when (property) {
"name" -> spell.name.contains(searchQuery, ignoreCase = true)
"desc" -> spell.desc.contains(searchQuery, ignoreCase = true)
"higher_level" -> spell.higher_level.contains(searchQuery, ignoreCase = true)
"range" -> spell.range.contains(searchQuery, ignoreCase = true)
"components" -> spell.components.contains(searchQuery, ignoreCase = true)
"material" -> spell.material.contains(searchQuery, ignoreCase = true)
"ritual" -> spell.ritual.contains(searchQuery, ignoreCase = true)
"duration" -> spell.duration.contains(searchQuery, ignoreCase = true)
"concentration" -> spell.concentration.contains(searchQuery, ignoreCase = true)
"casting_time" -> spell.casting_time.contains(searchQuery, ignoreCase = true)
"level" -> spell.level.contains(searchQuery, ignoreCase = true)
"school" -> spell.school.contains(searchQuery, ignoreCase = true)
"dnd_class" -> spell.dnd_class.contains(searchQuery, ignoreCase = true)
"archetype" -> spell.archetype.contains(searchQuery, ignoreCase = true)
else -> false
}
}
} else {
// Если свойство не выбрано, ищем по всем свойствам
spell.name.contains(searchQuery, ignoreCase = true) ||
spell.desc.contains(searchQuery, ignoreCase = true) ||
spell.higher_level.contains(searchQuery, ignoreCase = true) ||
spell.range.contains(searchQuery, ignoreCase = true) ||
spell.components.contains(searchQuery, ignoreCase = true) ||
spell.material.contains(searchQuery, ignoreCase = true) ||
spell.ritual.contains(searchQuery, ignoreCase = true) ||
spell.duration.contains(searchQuery, ignoreCase = true) ||
spell.concentration.contains(searchQuery, ignoreCase = true) ||
spell.casting_time.contains(searchQuery, ignoreCase = true) ||
spell.level.contains(searchQuery, ignoreCase = true) ||
spell.school.contains(searchQuery, ignoreCase = true) ||
spell.dnd_class.contains(searchQuery, ignoreCase = true) ||
spell.archetype.contains(searchQuery, ignoreCase = true)
}
}
call.respond(filteredSpells)
}
}
suspend fun getSpells() {
call.respond(com.spelldnd.database.spells.Spells.fetchAll().toList())
}
suspend fun getSpell(slug: String) {
if (slug.isBlank()) {
call.respond(HttpStatusCode.BadRequest, "Slug parameter is missing")
return
}
val spell = com.spelldnd.database.spells.Spells.fetchSpell(slug)
if (spell == null) {
call.respond(HttpStatusCode.NotFound, "Spell not found")
} else {
call.respond(spell)
}
}
} | spellDndMultiplatform-backend/src/main/kotlin/com/spelldnd/features/spells/SpellsController.kt | 1743788685 |
package com.spelldnd.features.spells
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.routing.*
import io.ktor.server.response.respond
fun Application.configureSpellsRouting() {
routing {
post("/spells/create") {
SpellsController(call).createSpell()
}
post("/spells/add-spells") {
SpellsController(call).addSpells()
}
post("/spells/delete") {
SpellsController(call).deleteSpell()
}
post("/spells/delete-spells") {
SpellsController(call).deleteSpells()
}
get("/spells/search") {
SpellsController(call).performSearch()
}
get("/spells") {
SpellsController(call).getSpells()
}
get("/spells/{slug}") {
val slug = call.parameters["slug"]
if (slug != null) {
SpellsController(call).getSpell(slug)
} else {
call.respond(HttpStatusCode.BadRequest, "Slug parameter is missing")
}
}
}
} | spellDndMultiplatform-backend/src/main/kotlin/com/spelldnd/features/spells/SpellsRouting.kt | 3439614402 |
package com.spelldnd.features.login
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import com.spelldnd.database.tokens.TokenDTO
import com.spelldnd.database.tokens.Tokens
import com.spelldnd.database.users.Users
import java.util.*
class LoginController(private val call: ApplicationCall) {
suspend fun performLogin() {
val receive = call.receive<LoginReceiveRemote>()
val userDTO = Users.fetchUser(receive.login)
println("receive -> $receive, dto -> $userDTO")
if (userDTO == null) {
call.respond(HttpStatusCode.BadRequest, "User not found")
} else {
if (userDTO.password == receive.password) {
val token = UUID.randomUUID().toString()
Tokens.insert(
TokenDTO(
rowId = UUID.randomUUID().toString(),
login = receive.login,
token = token)
)
call.respond(LoginResponseRemote(token = token))
} else {
call.respond(HttpStatusCode.BadRequest, "Invalid password")
}
}
}
} | spellDndMultiplatform-backend/src/main/kotlin/com/spelldnd/features/login/LoginController.kt | 4001341648 |
package com.spelldnd.features.login
import kotlinx.serialization.Serializable
@Serializable
data class LoginReceiveRemote(
val login: String,
val password: String
)
@Serializable
data class LoginResponseRemote(
val token: String
) | spellDndMultiplatform-backend/src/main/kotlin/com/spelldnd/features/login/LoginRemote.kt | 1669289579 |
package com.spelldnd.features.login
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import com.spelldnd.cashe.InMemoryCache
import com.spelldnd.cashe.TokenCache
import com.spelldnd.features.register.RegisterReceiveRemote
import com.spelldnd.plugins.Test
import java.util.UUID
fun Application.configureLoginRouting() {
routing {
post("/login") {
val loginController = LoginController(call)
loginController.performLogin()
}
}
}
| spellDndMultiplatform-backend/src/main/kotlin/com/spelldnd/features/login/LoginRouting.kt | 1907658270 |
package com.spelldnd.utils
fun String.isValidEmail(): Boolean = true | spellDndMultiplatform-backend/src/main/kotlin/com/spelldnd/utils/Validator.kt | 1385078378 |
package com.spelldnd.utils
import com.spelldnd.database.tokens.Tokens
object TokenCheck {
fun isTokenValid(token: String): Boolean = Tokens.fetchTokens().firstOrNull { it.token == token } != null
fun isTokenAdmin(token: String): Boolean = token == "bf8487ae-7d47-11ec-90d6-0242ac120003"
} | spellDndMultiplatform-backend/src/main/kotlin/com/spelldnd/utils/TokenCheck.kt | 454744770 |
package com.spelldnd.cashe
import com.spelldnd.features.register.RegisterReceiveRemote
data class TokenCache(
val login: String,
val token: String
)
object InMemoryCache {
val userList: MutableList<RegisterReceiveRemote> = mutableListOf()
val token: MutableList<com.spelldnd.cashe.TokenCache> = mutableListOf()
} | spellDndMultiplatform-backend/src/main/kotlin/com/spelldnd/cashe/InMemoryCache.kt | 193790245 |
package com.jolufeja.tudas
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.jolufeja.tudas", appContext.packageName)
}
} | tudas-app/tudas-app/app/src/androidTest/java/com/jolufeja/tudas/ExampleInstrumentedTest.kt | 1537415651 |
package com.jolufeja.tudas
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import androidx.fragment.app.Fragment
import com.jolufeja.authentication.UserAuthenticationService
import com.jolufeja.tudas.service.SettingsService
import com.jolufeja.tudas.service.UserSettings
import com.jolufeja.tudas.service.UserSettings.Companion.byAuthenticatedUser
class ChangeEmailFragment(
private val settingsService: SettingsService,
private val authenticationService: UserAuthenticationService
) : Fragment(R.layout.fragment_change_email) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
var saveButton: Button = view.findViewById<View>(R.id.save) as Button
var cancelButton: Button = view.findViewById<View>(R.id.cancel) as Button
cancelButton.setOnClickListener {
requireActivity().supportFragmentManager.popBackStack();
}
saveButton.setOnClickListener {
val newEmailAddress = view.findViewById<EditText>(R.id.newEmail)
.text.toString()
requireActivity().supportFragmentManager.popBackStack();
}
}
suspend fun updateSettings(emailAddress: String) = with(authenticationService) {
val userSettings = byAuthenticatedUser()
}
} | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/ChangeEmailFragment.kt | 2320218545 |
package com.jolufeja.tudas
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import arrow.core.computations.either
import arrow.core.identity
import com.jolufeja.httpclient.error.CommonErrors
import com.jolufeja.tudas.adapters.RecycleViewAdapter
import com.jolufeja.tudas.data.FriendsItem
import com.jolufeja.tudas.data.ListItem
import com.jolufeja.tudas.service.user.FriendEntry
import com.jolufeja.tudas.service.user.UserService
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import org.koin.android.ext.android.get
private val DefaultFriendsList = listOf(
FriendsItem().apply {
id = 0
text = "Such empty :("
}
)
class FriendsSettingsFragment(
private val userService: UserService
) : Fragment(R.layout.fragment_friends_settings) {
private var mRecyclerView: RecyclerView? = null
private var mAdapter: RecyclerView.Adapter<*>? = null
private var listOfFriends: ArrayList<FriendsItem> = ArrayList()
private var finalList: MutableList<ListItem> = mutableListOf()
private suspend fun buildFriendsList() = flow {
either<CommonErrors, Unit> {
emit(emptyList())
val friends = userService
.getFriendsOfCurrentUser()
.bind()
.toFriendsListItems()
val friendsNonEmpty = when (friends.isEmpty()) {
true -> DefaultFriendsList
false -> friends
}
emit(friendsNonEmpty)
}.fold(
ifLeft = {
Log.d("FriendsSettingsFragment", it.toString())
emit(DefaultFriendsList)
},
ifRight = ::identity
)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
mRecyclerView = view.findViewById(R.id.lists_recycler_view)
var mLayoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
mRecyclerView!!.layoutManager = mLayoutManager
mAdapter =
context?.let {
RecycleViewAdapter(
it,
finalList,
0,
0,
0,
0,
0,
R.layout.card_friends_settings,
0
) {
null
}
}
mRecyclerView!!.adapter = mAdapter
lifecycleScope.launchWhenCreated {
buildFriendsList().collect { friends ->
finalList = friends.toMutableList()
(mAdapter as? RecycleViewAdapter)?.refreshData(friends)
mAdapter?.notifyDataSetChanged()
}
}
var addNewFriendsButton: Button = view.findViewById<View>(R.id.add_friends_button) as Button
addNewFriendsButton.setOnClickListener {
val addFriendFragment = AddFriendFragment(get())
val transaction: FragmentTransaction =
requireActivity().supportFragmentManager.beginTransaction()
transaction.replace(
((view as ViewGroup).parent as View).id,
addFriendFragment
)
transaction.addToBackStack("friends_list")
transaction.commit()
}
var cancelButton: TextView = view.findViewById<View>(R.id.back_button) as TextView
cancelButton.setOnClickListener {
requireActivity().supportFragmentManager.popBackStack();
}
}
}
fun List<FriendEntry>.toFriendsListItems(): List<ListItem> = mapIndexed { i, friendEntry ->
FriendsItem().apply {
id = i
text = friendEntry.name
}
}
| tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/FriendsSettingsFragment.kt | 2797814808 |
package com.jolufeja.tudas
import android.view.View
import com.jolufeja.presentation.fragment.DataBoundFragment
import com.jolufeja.tudas.databinding.FragmentRegistrationBinding
class RegistrationFragment : DataBoundFragment<RegistrationViewModel, FragmentRegistrationBinding>(
R.layout.fragment_registration,
RegistrationViewModel::class,
BR.registrationViewModel
) {
override fun createBinding(view: View) = FragmentRegistrationBinding.bind(view)
}
| tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/RegistrationFragment.kt | 2921089487 |
package com.jolufeja.tudas
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import arrow.core.Either
import arrow.core.computations.either
import arrow.core.identity
import com.jolufeja.httpclient.error.CommonErrors
import com.jolufeja.httpclient.error.ErrorHandler
import com.jolufeja.presentation.viewmodel.FetcherViewModel
import com.jolufeja.tudas.adapters.RecycleViewAdapter
import com.jolufeja.tudas.data.ChallengesItem
import com.jolufeja.tudas.data.HeaderItem
import com.jolufeja.tudas.data.ListItem
import com.jolufeja.tudas.service.challenges.Challenge
import com.jolufeja.tudas.service.challenges.ChallengeService
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import org.koin.android.ext.android.get
import org.koin.android.ext.android.inject
import java.time.LocalDate
import java.time.temporal.ChronoUnit
import java.util.*
import java.util.concurrent.TimeUnit
import kotlin.collections.ArrayList
internal val ChallengeErrorHandler = ErrorHandler(CommonErrors::GenericError)
class ChallengesPublicViewModel(
private val challengeService: ChallengeService
) : FetcherViewModel<CommonErrors, List<ListItem>>(ChallengeErrorHandler) {
override suspend fun fetchData(): List<ListItem> =
when (val publicChallenges = challengeService.getPublicChallenges()) {
is Either.Right ->
listOf(HeaderItem("Public Challenges")) + publicChallenges.value.toChallengeListItems()
is Either.Left ->
throw Throwable("Unable to fetch public challenges ${publicChallenges.value}")
}
}
class ChallengesPublicFragment(
private val challengeService: ChallengeService
) : Fragment(R.layout.fragment_challenges_public) {
private var mRecyclerView: RecyclerView? = null
private var mAdapter: RecyclerView.Adapter<*>? = null
private var listOfChallenges: ArrayList<ChallengesItem> = ArrayList()
private var createChallengeButton: Button? = null
private var finalList: MutableList<ListItem> = mutableListOf()
private val viewModel: ChallengesPublicViewModel by inject()
private suspend fun buildChallengeList() = flow<List<ListItem>> {
either<CommonErrors, Unit> {
emit(emptyList())
val publicChallenges = challengeService
.getPublicChallenges()
.bind()
.toChallengeListItems()
emit(publicChallenges)
}.fold(
ifLeft = { emit(emptyList()) },
ifRight = ::identity
)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val refreshLayout = view.findViewById<SwipeRefreshLayout>(R.id.public_swiperefresh)
refreshLayout?.setOnRefreshListener {
lifecycleScope.launch {
buildChallengeList().collect { challenges ->
refreshLayout.isRefreshing = false
finalList = challenges.toMutableList()
(mAdapter as? RecycleViewAdapter)?.refreshData(challenges)
mAdapter?.notifyDataSetChanged()
}
}
}
mRecyclerView = view.findViewById(R.id.challenges_public_recycler_view)
var mLayoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
mRecyclerView!!.layoutManager = mLayoutManager
// Add Adapter so cards will be displayed
mAdapter = context?.let {
RecycleViewAdapter(
it,
finalList,
R.layout.card_challenges_public,
R.layout.card_header,
0,
0,
0,
0,
0
) { item ->
// Open New Fragment
val challengeArgs = Bundle().also { bundle ->
bundle.putSerializable(CHALLENGE_KEY, (item as ChallengesItem).challenge)
}
val individualChallengePublicFragment = IndividualChallengePublicFragment(get())
individualChallengePublicFragment.arguments = challengeArgs
val transaction: FragmentTransaction =
requireActivity().supportFragmentManager.beginTransaction()
transaction.replace(
((view as ViewGroup).parent as View).id,
individualChallengePublicFragment
)
transaction.addToBackStack("challenge_sent_info")
transaction.commit()
item.id.let { Log.d("TAG", it.toString()) }
}
}
mRecyclerView!!.adapter = mAdapter
// Handle Create Challenge Button
createChallengeButton = view.findViewById(R.id.create_challenge_button) as Button
createChallengeButton!!.setOnClickListener {
// Open New Fragment
val individualChallengePublicFragment = IndividualChallengeSentFragment(get())
val transaction: FragmentTransaction =
requireActivity().supportFragmentManager.beginTransaction()
transaction.replace(
((view as ViewGroup).parent as View).id,
individualChallengePublicFragment
)
transaction.addToBackStack("challenge_sent_info")
transaction.commit()
}
lifecycleScope.launch {
buildChallengeList().collect { challenges ->
finalList = challenges.toMutableList()
(mAdapter as? RecycleViewAdapter)?.refreshData(challenges)
mAdapter?.notifyDataSetChanged()
}
}
}
}
fun List<Challenge>.toChallengeListItems(): List<ListItem> = mapIndexed { i, publicChallenge ->
ChallengesItem().apply {
val diff = publicChallenge.dueDate.time - Calendar.getInstance().time.time
val diffInDays = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS)
id = i
title = publicChallenge.name
author = publicChallenge.creator
description = publicChallenge.description
points = publicChallenge.worth
timeLeft = diffInDays.toInt()
challenge = publicChallenge
}
}
| tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/ChallengesPublicFragment.kt | 276971032 |
package com.jolufeja.tudas
import android.app.Application
import org.koin.android.ext.koin.androidContext
import org.koin.androidx.fragment.koin.fragmentFactory
import org.koin.core.KoinExperimentalAPI
import org.koin.core.context.startKoin
class TudasApplication : Application() {
@KoinExperimentalAPI
override fun onCreate() {
super.onCreate()
startKoin {
androidContext(this@TudasApplication)
fragmentFactory()
modules(ApplicationModule.withDependencies.toList())
}
}
} | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/TudasApplication.kt | 3636531746 |
package com.jolufeja.tudas
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import androidx.core.content.FileProvider
import androidx.core.net.toFile
import androidx.lifecycle.lifecycleScope
import arrow.core.computations.nullable
import com.jolufeja.presentation.fragment.DataBoundFragment
import com.jolufeja.tudas.databinding.FragmentChallengeReceivedInfoBinding
import com.jolufeja.tudas.service.challenges.ChallengeService
import com.jolufeja.tudas.service.challenges.ProofKind
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.viewModel
import org.koin.core.parameter.parametersOf
import java.io.File
import java.nio.file.Files
import java.nio.file.StandardCopyOption
import java.text.SimpleDateFormat
import java.util.*
sealed class ChallengeErrors(reason: String) : Throwable(reason)
object FailedToGetChallenge : ChallengeErrors("Couldn't retrieve challenge from backend.")
object NonExistentChallenge : ChallengeErrors("No challenge associated with given name found.")
object MissingChallengeName : ChallengeErrors("No challenge name passed to fragment.")
const val CHALLENGE_KEY = "challenge"
class IndividualChallengeReceivedFragment(
private val challengeService: ChallengeService
) :
DataBoundFragment<IndividualChallengeReceivedViewModel, FragmentChallengeReceivedInfoBinding>(
R.layout.fragment_challenge_received_info,
IndividualChallengeReceivedViewModel::class,
BR.challengeReceivedViewModel
) {
companion object {
private const val REQUEST_CODE_CAMERA = 1
private const val REQUEST_CODE_IMAGE = 2
private const val FILE_INTENT_TYPE = "image/*"
}
private lateinit var filePhoto: File
private lateinit var takenImage: Bitmap
private lateinit var viewImage: ImageView
private lateinit var tempPhotoFile: File
private var pictureWasTaken = false
private var pictureWasTakenAsFile = false
override val viewModel: IndividualChallengeReceivedViewModel by viewModel {
val challenge = arguments?.getSerializable(CHALLENGE_KEY) ?: throw MissingChallengeName
parametersOf(challenge)
}
override fun createBinding(view: View) = FragmentChallengeReceivedInfoBinding.bind(view)
private fun createTempImageFile(): File {
val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.GERMANY).format(Date())
val fileName = "JPEG_${timeStamp}_"
val storageDir = requireContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES)
return File.createTempFile(
fileName,
".jpg",
storageDir
)
}
private fun getCamera() {
if ((activity as MainActivity?)!!.hasNoPermissions()) {
(activity as MainActivity?)!!.requestPermission()
}
val takePhotoIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE).also {
val photoFile = tempPhotoFile
val photoURI = FileProvider
.getUriForFile(requireContext(), "com.jolufeja.tudas.fileprovider", photoFile)
it.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
}
startActivityForResult(
takePhotoIntent,
REQUEST_CODE_CAMERA
);
}
private fun getImage() {
if ((activity as MainActivity?)!!.hasNoPermissions()) {
(activity as MainActivity?)!!.requestPermission()
}
val fileIntent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
fileIntent.type = FILE_INTENT_TYPE
startActivityForResult(fileIntent, REQUEST_CODE_IMAGE);
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_CODE_CAMERA && resultCode == Activity.RESULT_OK) {
// takenImage = data?.extras?.get("data") as? Bitmap
// viewImage.setImageBitmap(takenImage);
pictureWasTaken = true
val bitmap = BitmapFactory.decodeFile(tempPhotoFile.path)
viewImage.setImageBitmap(bitmap)
}
if (requestCode == REQUEST_CODE_IMAGE && resultCode == Activity.RESULT_OK) {
viewImage.setImageURI(data?.data)
pictureWasTakenAsFile = true
nullable.eager<Unit> {
val uri = data?.data.bind()
val inputStream = requireContext().contentResolver.openInputStream(uri).bind()
val tempFile = createTempImageFile()
Files.copy(inputStream, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING)
filePhoto = tempFile
Unit
}
}
super.onActivityResult(requestCode, resultCode, data)
}
override fun onViewAndBindingCreated(
view: View,
binding: FragmentChallengeReceivedInfoBinding,
savedInstanceState: Bundle?
) {
tempPhotoFile = createTempImageFile()
viewImage = binding.imageView
binding.addFile.setOnClickListener { getImage() }
binding.openCamera.setOnClickListener { getCamera() }
binding.backButton.setOnClickListener {
requireActivity().supportFragmentManager.popBackStack()
}
/*
Only try to complete the challenge if the user has selected an image already.
*/
lifecycleScope.launch {
viewModel.completeChallenge.receiveAsFlow().collect { finishChallenge ->
val proof = when {
pictureWasTaken -> ProofKind.ProofImage(tempPhotoFile)
pictureWasTakenAsFile -> ProofKind.ProofImage(filePhoto)
else -> null
}
proof?.let { proofKind ->
challengeService.finishChallengeWithProof(
finishChallenge,
proofKind
).fold(
ifLeft = { err ->
showToast("Could not complete challenge. Please try again.")
},
ifRight = {
showToast("Challenge successfully completed!")
requireActivity().supportFragmentManager.popBackStack()
}
)
}
}
}
}
} | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/IndividualChallengeReceivedFragment.kt | 2190006608 |
package com.jolufeja.tudas
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.jolufeja.tudas.adapters.RecycleViewAdapter
import com.jolufeja.tudas.data.*
import java.util.ArrayList
class CreateGroupFragment : Fragment(R.layout.fragment_create_group) {
private var mRecyclerView: RecyclerView? = null
private var mAdapter: RecyclerView.Adapter<*>? = null
private var listOfFriends: ArrayList<CreateGroupItem> = ArrayList()
private var finalList: ArrayList<ListItem> = ArrayList()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// Back Button
var backButton: TextView = view.findViewById<View>(R.id.back_button) as TextView
// Send challenge Button
var createButton: Button = view.findViewById<View>(R.id.create_group_button) as Button
// Listener for Back Button to close fragment
backButton.setOnClickListener {
requireActivity().supportFragmentManager.popBackStack();
}
// Listener for challenge completed button
createButton.setOnClickListener {
// TO DO
}
//adding items in list
for (i in 0..20) {
val friend = CreateGroupItem()
friend.id = i
friend.text = "Marc"
if (i === 5) {
friend.rankingType = 1
} else {
friend.rankingType = 0
}
listOfFriends.add(friend)
}
listOfFriends.forEach {
finalList.add(it)
}
mRecyclerView = view.findViewById(R.id.create_group_recycler_view)
var mLayoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
mRecyclerView!!.layoutManager = mLayoutManager
// Add Adapter so cards will be displayed
mAdapter =
context?.let {
RecycleViewAdapter(
it,
finalList,
0,
0,
0,
0,
0,
0,
R.layout.card_friends,
) {
item ->
// Add to group
}
}
mRecyclerView!!.adapter = mAdapter
}
} | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/CreateGroupFragment.kt | 2681190699 |
package com.jolufeja.tudas
import android.Manifest
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.findNavController
import androidx.navigation.ui.setupWithNavController
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.jolufeja.navigation.NavigationEventBus
import com.jolufeja.navigation.eventDrivenNavigation
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import org.koin.android.ext.android.inject
import org.koin.androidx.fragment.android.setupKoinFragmentFactory
import org.koin.core.KoinExperimentalAPI
fun Fragment.showToast(message: String) {
Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show()
}
class MainActivity : AppCompatActivity(R.layout.activity_main) {
private val CHANNEL_ID = "channel_id_test_01"
private val notificationId = 101
val statsChannel: Channel<Int> = Channel()
val permissions = arrayOf(android.Manifest.permission.CAMERA, android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE)
private val navigationEventBus: NavigationEventBus by inject()
@KoinExperimentalAPI
override fun onCreate(savedInstanceState: Bundle?) {
setupKoinFragmentFactory()
super.onCreate(savedInstanceState)
val bottomNavigationView: BottomNavigationView = findViewById(R.id.bottom_navigation_view)
// toolbar
val toolbar: Toolbar = findViewById(R.id.toolbar);
val toolbarTitle: TextView = findViewById(R.id.toolbar_title);
toolbarTitle.text = "TUDAS";
createNotificationChannel()
val navController = findNavController(R.id.nav_fragment).also {
it.addOnDestinationChangedListener { _, dest, _ ->
if (dest.id == R.id.loginFragment || dest.id == R.id.registrationFragment ) {
bottomNavigationView.visibility = View.GONE
} else {
// Change App Title on Toolbar according to current fragment
when (dest.id ) {
R.id.challengesFragment -> toolbarTitle.text = "Challenges";
R.id.feedFragment -> toolbarTitle.text = "Feed";
R.id.rankingsFragment -> toolbarTitle.text = "Rankings";
R.id.profileFragment -> toolbarTitle.text = "Profile";
else -> { toolbarTitle.text = "TUDAS";
}
}
bottomNavigationView.visibility = View.VISIBLE
}
}
}
bottomNavigationView.setupWithNavController(navController)
lifecycleScope.launch {
navigationEventBus.subscribe { navigationSubscriptions(navController)(it) }
}
updateCoins()
}
private fun updateCoins() {
val pointsLayout = findViewById<TextView>(R.id.user_points_main)
lifecycleScope.launch {
statsChannel.receiveAsFlow().collect {
pointsLayout.text = it.toString()
}
}
}
private fun navigationSubscriptions(navController: NavController) = eventDrivenNavigation(navController) {
register(RegistrationNavigationEvents.PROCEED_TO_HOME, R.id.nav_graph_authenticated)
register(RegistrationNavigationEvents.PROCEED_TO_LOGIN, R.id.loginFragment)
register(LoginNavigationEvents.PROCEED_TO_HOME, R.id.nav_graph_authenticated)
register(LoginNavigationEvents.PROCEED_TO_REGISTRATION, R.id.registrationFragment)
}
fun hasNoPermissions(): Boolean{
return ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
}
fun requestPermission(){
ActivityCompat.requestPermissions(this, permissions,0)
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val name = "TUDAS Notification Channel"
val descriptionText = "This is the Channel for all TUDAS Notifications"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
description = descriptionText
}
val notificationManager: NotificationManager =
this.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}
fun sendNotification(title: String, description: String) {
val intent = Intent(this, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, 0)
val builder = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle(title)
.setContentText(description)
.setContentIntent((pendingIntent))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
builder.setAutoCancel(true);
with(NotificationManagerCompat.from(this)) {
notify(notificationId, builder.build())
}
}
} | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/MainActivity.kt | 2441217441 |
package com.jolufeja.tudas
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import arrow.core.computations.either
import com.jolufeja.httpclient.error.CommonErrors
import com.jolufeja.presentation.fragment.DataBoundFragment
import com.jolufeja.tudas.databinding.FragmentLoginBinding
import com.jolufeja.tudas.databinding.FragmentRegistrationBinding
import com.jolufeja.tudas.service.user.UserService
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
class LoginFragment(
private val userService: UserService
) : DataBoundFragment<LoginViewModel, FragmentLoginBinding>(
R.layout.fragment_login,
LoginViewModel::class,
BR.loginViewModel
) {
override fun createBinding(view: View) = FragmentLoginBinding.bind(view)
override fun onViewAndBindingCreated(
view: View,
binding: FragmentLoginBinding,
savedInstanceState: Bundle?
) {
lifecycleScope.launch {
viewModel.hasLoggedIn.receiveAsFlow().collect {
updatePoints()
}
}
}
private suspend fun updatePoints() {
either<CommonErrors, Unit> {
val currentPoints = userService.getPointsOfCurrentUser().bind()
(activity as MainActivity).statsChannel.trySend(currentPoints)
}.fold(
ifLeft = { Log.d("LoginFragment", "$it")},
ifRight = {}
)
}
}
| tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/LoginFragment.kt | 505073352 |
package com.jolufeja.tudas
import android.app.DatePickerDialog
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.*
import androidx.appcompat.widget.SwitchCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewModelScope
import arrow.core.computations.either
import arrow.core.computations.nullable
import com.jolufeja.authentication.UserAuthenticationService
import com.jolufeja.httpclient.error.CommonErrors
import com.jolufeja.navigation.NavigationEventPublisher
import com.jolufeja.presentation.fragment.DataBoundFragment
import com.jolufeja.tudas.databinding.FragmentChallengeSentInfoBinding
import com.jolufeja.tudas.service.challenges.ChallengeService
import com.jolufeja.tudas.service.challenges.InitialChallenge
import com.jolufeja.tudas.service.user.FriendEntry
import com.jolufeja.tudas.service.user.UserService
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import java.time.DayOfWeek
import java.time.LocalDate
import java.util.*
private val DefaultDueDate = LocalDate.now().plusDays(1)
class IndividualChallengeSentViewModel(
private val navigator: NavigationEventPublisher,
private val challengeService: ChallengeService,
private val authenticationService: UserAuthenticationService
) : ViewModel() {
val challengeName: MutableLiveData<String> = MutableLiveData("")
val creatorName: MutableLiveData<String> = MutableLiveData("")
val description: MutableLiveData<String> = MutableLiveData("")
val dueDate: MutableLiveData<String> = MutableLiveData("")
val reward: MutableLiveData<String> = MutableLiveData("")
val isPublic: MutableLiveData<Boolean> = MutableLiveData(false)
val addressedTo: MutableLiveData<String> = MutableLiveData("")
val worth: MutableLiveData<Int> = MutableLiveData(200)
var recipient: String? = null
var day: Int = Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
var month: Int = Calendar.getInstance().get(Calendar.MONTH)
var year: Int = Calendar.getInstance().get(Calendar.YEAR)
fun calculateTime(): Date {
val calendar: Calendar = Calendar.getInstance()
calendar.set(year, month, day)
return calendar.time
}
val challengeCreated: Channel<Boolean> = Channel()
fun createChallenge() {
viewModelScope.launch {
nullable {
val initialChallenge = InitialChallenge(
challengeName.value.bind(),
authenticationService.authentication.await().user.name,
description.value.bind(),
calculateTime(),
reward.value.bind(),
recipient.bind(),
200
)
challengeService.createChallenge(initialChallenge).fold(
ifLeft = {
Log.d("IndividualChallengeSentViewModel", "Challenge creation failed: $it")
challengeCreated.trySend(false)
},
ifRight = { challengeCreated.trySend(true) }
)
}
}
}
}
class IndividualChallengeSentFragment(
private val userService: UserService
) :
DataBoundFragment<IndividualChallengeSentViewModel, FragmentChallengeSentInfoBinding>(
R.layout.fragment_challenge_sent_info,
IndividualChallengeSentViewModel::class,
BR.challengeSentViewModel
) {
private val friends = flow {
either<CommonErrors, List<FriendEntry>> {
userService.getFriendsOfCurrentUser().bind().also { emit(it) }
}.fold(
ifLeft = { Log.d("ERROR", it.toString()) },
ifRight = { }
)
}
override fun createBinding(view: View): FragmentChallengeSentInfoBinding =
FragmentChallengeSentInfoBinding.bind(view)
override fun onViewAndBindingCreated(
view: View,
binding: FragmentChallengeSentInfoBinding,
savedInstanceState: Bundle?
) {
lifecycleScope.launchWhenCreated {
friends.collect { friendList ->
binding.challengeReceiver.adapter = ArrayAdapter(
requireContext(),
R.layout.support_simple_spinner_dropdown_item,
friendList.map { it.name }
)
}
viewModel.challengeCreated.receiveAsFlow().collect { success ->
if (success) {
showToast("Challenge successfully created!")
requireActivity().supportFragmentManager.popBackStack()
} else {
showToast("Could not create challenge. Please try again.")
}
}
}
binding.challengeTime.setOnClickListener { challengeTime ->
val calendar = Calendar.getInstance()
val picker = DatePickerDialog(requireContext())
picker.setOnDateSetListener { view, year, month, dayOfMonth ->
val dateString = "${dayOfMonth}.${month}.${year}"
viewModel.day = dayOfMonth
viewModel.month = month
viewModel.year = year
binding.challengeTime.setText(dateString)
}
picker.show()
}
binding.backButton.setOnClickListener {
requireActivity().supportFragmentManager.popBackStack()
}
binding.showGroupsOnlySwitch.setOnCheckedChangeListener { buttonView, isChecked ->
binding.challengeReceiver.isEnabled = !isChecked
when {
isChecked -> viewModel.recipient = "public"
binding.challengeReceiver.adapter.count > 0 -> {
viewModel.recipient = binding.challengeReceiver.adapter.getItem(0).toString()
}
}
}
val itemListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
viewModel.recipient = parent?.getItemAtPosition(position).toString()
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
}
binding.challengeReceiver.onItemSelectedListener = itemListener
}
}
| tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/IndividualChallengeSentFragment.kt | 1079021943 |
package com.jolufeja.tudas
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.jolufeja.tudas.adapters.ViewPagerFragmentAdapter
import org.koin.android.ext.android.get
class ChallengesFragment : Fragment(R.layout.fragment_challenges) {
var tabLayout: TabLayout? = null
var viewPager: ViewPager2? = null
var tabTitles: Array<String> = arrayOf("Received", "Sent", "Public")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
setHasOptionsMenu(true);
tabLayout = view.findViewById(R.id.tabLayout)
viewPager = view.findViewById(R.id.viewPager)
// create a new tab for each challenge fragment
for (item in tabTitles)
tabLayout!!.addTab(tabLayout!!.newTab().setText(item))
tabLayout!!.tabGravity = TabLayout.GRAVITY_FILL
// create adapter
val adapter = ViewPagerFragmentAdapter(
this,
ChallengesReceivedFragment(get()),
ChallengesSentFragment(get()),
ChallengesPublicFragment(get()),
ChallengesReceivedFragment(get())
)
viewPager!!.adapter = adapter
TabLayoutMediator(tabLayout!!, viewPager!!) { tab, position ->
tab.text = tabTitles[position]
}.attach()
}
}
| tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/ChallengesFragment.kt | 3696898713 |
package com.jolufeja.tudas
import com.jolufeja.authentication.AuthenticationModule
import com.jolufeja.authentication.AuthenticationQualifiers
import com.jolufeja.httpclient.HttpClientModule
import com.jolufeja.navigation.EventDrivenNavigationModule
import com.jolufeja.tudas.service.DefaultSettingsService
import com.jolufeja.tudas.service.SettingsService
import com.jolufeja.tudas.service.challenges.Challenge
import com.jolufeja.tudas.service.challenges.ChallengeService
import com.jolufeja.tudas.service.challenges.DefaultChallengeService
import com.jolufeja.tudas.service.user.DefaultUserService
import com.jolufeja.tudas.service.user.UserService
import get
import org.koin.androidx.fragment.dsl.fragment
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.core.module.Module
import org.koin.core.qualifier.qualifier
import org.koin.dsl.module
object ApplicationModule {
private val module = module {
fragment { MainFragment(get(), get()) }
fragment { ChallengesFragment() }
fragment { FeedFragment(get()) }
fragment { ProfileFragment(get(), get()) }
fragment { RankingsFragment() }
fragment { LoginFragment(get()) }
fragment { RegistrationFragment() }
fragment { IndividualChallengeSentFragment(get()) }
fragment { ChallengesPublicFragment(get()) }
fragment { ChallengesReceivedFragment(get()) }
fragment { ChallengesSentFragment(get()) }
fragment { RankingsFriendsFragment(get()) }
fragment { RankingsWorldFragment(get()) }
fragment { IndividualChallengeReceivedFragment(get()) }
fragment { IndividualChallengePublicFragment(get()) }
fragment { AddFriendFragment(get()) }
viewModel { LoginViewModel(get(), get()) }
viewModel { RegistrationViewModel(get(), get()) }
viewModel { IndividualChallengeSentViewModel(get(), get(), get()) }
viewModel { ChallengesPublicViewModel(get()) }
viewModel { (challenge: Challenge) ->
IndividualChallengeReceivedViewModel(challenge)
}
viewModel { (challenge: Challenge) ->
IndividualChallengePublicViewModel(challenge) }
single<UserService> {
DefaultUserService(
get(qualifier(AuthenticationQualifiers.WithUserAuthentication)),
get()
)
}
single<ChallengeService> {
DefaultChallengeService(
get(qualifier(AuthenticationQualifiers.WithUserAuthentication)),
get()
)
}
single<SettingsService> {
DefaultSettingsService(get(qualifier(AuthenticationQualifiers.WithUserAuthentication)))
}
}
private val dependencies
get() = sequenceOf(
HttpClientModule.withDependencies,
EventDrivenNavigationModule.withDependencies,
AuthenticationModule.withDependencies
).reduce(Set<Module>::plus)
val withDependencies
get() = setOf(module) + dependencies
} | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/ApplicationModule.kt | 3497314586 |
package com.jolufeja.tudas
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.jolufeja.tudas.adapters.RecycleViewAdapter
import com.jolufeja.tudas.data.ListItem
import com.jolufeja.tudas.data.RankingItem
import java.util.ArrayList
class RankingsGroupFragment : Fragment(R.layout.fragment_rankings_group){
private var mRecyclerView: RecyclerView? = null
private var mAdapter: RecyclerView.Adapter<*>? = null
private var listOfRankings: ArrayList<RankingItem> = ArrayList()
private var finalList: ArrayList<ListItem> = ArrayList()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
//adding items in list
for (i in 0..20) {
val rank = RankingItem()
rank.id = i
rank.ranking = i + 1
rank.name = "Marc"
rank.points = 100000 / (i+1)
if(i === 5){
rank.rankingType = 1
} else {
rank.rankingType = 0
}
listOfRankings.add(rank)
}
listOfRankings.forEach {
finalList.add(it)
}
mRecyclerView = view.findViewById(R.id.rankings_recycler_view)
var mLayoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
mRecyclerView!!.layoutManager = mLayoutManager
// Add Adapter so cards will be displayed
mAdapter =
context?.let {
RecycleViewAdapter(
it,
finalList,
0,
0,
0,
R.layout.card_rankings_friends,
0,
0,
0
) {
null
}
}
mRecyclerView!!.adapter = mAdapter
}
} | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/RankingsGroupFragment.kt | 2072055320 |
package com.jolufeja.tudas
import android.util.Log
import androidx.lifecycle.*
import arrow.core.computations.either
import com.jolufeja.authentication.UserAuthenticationService
import com.jolufeja.authentication.UserCredentials
import com.jolufeja.httpclient.error.CommonErrors
import com.jolufeja.navigation.NavigationEvent
import com.jolufeja.navigation.NavigationEventPublisher
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
enum class LoginNavigationEvents : NavigationEvent {
PROCEED_TO_REGISTRATION,
PROCEED_TO_HOME
}
class LoginViewModel(
private val authenticationService: UserAuthenticationService,
private val navigator: NavigationEventPublisher
) : ViewModel() {
val hasLoggedIn: Channel<Unit> = Channel()
val userNameData: MutableLiveData<String> = MutableLiveData("")
val passwordData: MutableLiveData<String> = MutableLiveData("")
private val userNameState: StateFlow<String> =
userNameData.asFlow().stateIn(viewModelScope, SharingStarted.Lazily, "")
private val passwordState: StateFlow<String> =
passwordData.asFlow().stateIn(viewModelScope, SharingStarted.Lazily, "")
val canPerformLogin: LiveData<Boolean> = combine(
userNameState,
passwordState
) { (userName, password) ->
userName.isNotEmpty() && password.isNotEmpty()
}.asLiveData()
fun performLogin() {
viewModelScope.launch {
val credentials = UserCredentials(userNameState.value, passwordState.value)
authenticationService.login(credentials).fold(
ifLeft = { Log.d("LoginViewModel", "Login failed. $it") },
ifRight = {
hasLoggedIn.trySend(Unit)
navigator.publish(LoginNavigationEvents.PROCEED_TO_HOME)
}
)
}
}
fun switchToRegistration() = navigator.publish(LoginNavigationEvents.PROCEED_TO_REGISTRATION)
} | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/LoginViewModel.kt | 1199089665 |
package com.jolufeja.tudas
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import android.widget.Toast.LENGTH_SHORT
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.jolufeja.tudas.service.user.UserService
class AddFriendFragment(
private val userService: UserService
) : Fragment(R.layout.fragment_add_friend) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
var newFriendTextField : EditText = view.findViewById<View>(R.id.newFriend) as EditText
var addButton: Button = view.findViewById<View>(R.id.add) as Button
addButton.setOnClickListener {
if (newFriendTextField.text.isEmpty()){
Toast.makeText(requireContext(), "Please enter a username", Toast.LENGTH_SHORT).show() }
else {
lifecycleScope.launchWhenCreated {
val friendName = newFriendTextField.text.toString()
userService.addFriend(friendName).fold(
ifLeft = {
Log.d("AddFriendFragment", "Couldn't add friend: $it")
},
ifRight = {
requireActivity().supportFragmentManager.popBackStack()
}
)
}
}
}
var cancelButton: Button = view.findViewById<View>(R.id.cancel) as Button
cancelButton.setOnClickListener {
requireActivity().supportFragmentManager.popBackStack();
}
}
} | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/AddFriendFragment.kt | 859755426 |
package com.jolufeja.tudas
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.lifecycleScope
import com.jolufeja.presentation.fragment.DataBoundFragment
import com.jolufeja.tudas.databinding.FragmentChallengePublicInfoBinding
import com.jolufeja.tudas.service.challenges.Challenge
import com.jolufeja.tudas.service.challenges.ChallengeService
import com.jolufeja.tudas.service.challenges.ProofKind
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.viewModel
import org.koin.core.parameter.parametersOf
class IndividualChallengePublicViewModel(private val challenge: Challenge) : ViewModel() {
val name = MutableLiveData(challenge.name)
val creator = MutableLiveData(challenge.creator)
val creationDate = MutableLiveData(challenge.creationDate)
val description = MutableLiveData(challenge.description)
val dueDate = MutableLiveData(challenge.dueDate)
val reward = MutableLiveData(challenge.reward)
val worth = MutableLiveData(challenge.worth)
val addressedTo = MutableLiveData(challenge.addressedTo)
val completeChallenge: Channel<Challenge> = Channel()
fun completeChallenge() {
Log.d("IndividualChallengeReceivedViewModel", name.value.toString())
completeChallenge.trySend(challenge)
}
}
class IndividualChallengePublicFragment(
private val challengeService: ChallengeService
) :
DataBoundFragment<IndividualChallengePublicViewModel, FragmentChallengePublicInfoBinding>(
R.layout.fragment_challenge_public_info,
IndividualChallengePublicViewModel::class,
BR.challengePublicViewModel
) {
override val viewModel: IndividualChallengePublicViewModel by viewModel {
val challenge =
arguments?.getSerializable(CHALLENGE_KEY)
?: throw MissingChallengeName
parametersOf(challenge)
}
override fun createBinding(view: View) = FragmentChallengePublicInfoBinding.bind(view)
override fun onViewAndBindingCreated(
view: View,
binding: FragmentChallengePublicInfoBinding,
savedInstanceState: Bundle?
) {
binding.backButton.setOnClickListener {
requireActivity().supportFragmentManager.popBackStack()
}
lifecycleScope.launch {
viewModel.completeChallenge.receiveAsFlow().collect { finishChallenge ->
val proof = ProofKind.SocialMediaLink("Public-Challenge")
challengeService.finishChallengeWithProof(finishChallenge, proof).fold(
ifLeft = { err ->
showToast("Could not complete challenge. Please try again.")
},
ifRight = {
showToast("Challenge successfully completed!")
requireActivity().supportFragmentManager.popBackStack()
}
)
}
}
}
} | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/IndividualChallengePublicFragment.kt | 3811413780 |
package com.jolufeja.tudas.adapters
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.jolufeja.tudas.ChallengesPublicFragment
import com.jolufeja.tudas.ChallengesReceivedFragment
import com.jolufeja.tudas.ChallengesSentFragment
// Adapter to create the three challenge fragments
class ViewPagerFragmentAdapter(fragment: Fragment, private val firstPage: Fragment, private val secondPage: Fragment, private val thirdPage: Fragment, private val defaultPage: Fragment) : FragmentStateAdapter(fragment) {
override fun getItemCount(): Int = 3;
override fun createFragment(position: Int): Fragment {
return when (position) {
0 -> {
firstPage;
}
1 -> {
secondPage;
}
2 -> {
thirdPage;
}
else -> defaultPage;
}
}
} | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/adapters/ViewPagerFragmentAdapter.kt | 1086351616 |
package com.jolufeja.tudas.adapters
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.FrameLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.jolufeja.tudas.R
import com.jolufeja.tudas.data.ListItem
import java.util.*
// Adapter to create a challenge card
class RecycleViewAdapter(
private val context: Context,
private var mDataList: List<ListItem>,
private val layoutCard: Int,
private val layoutHeader: Int,
private val layoutFeedCard: Int,
private val layoutRankingCard: Int,
private val layoutGroupsRankingCard: Int,
private val layoutFriendsCard: Int,
private val layoutCreateGroupCard: Int,
private val listener: (ListItem) -> Unit
) :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
fun refreshData(items: List<ListItem>) {
mDataList = items
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): RecyclerView.ViewHolder {
when (viewType) {
0 -> return CardViewHolder(
LayoutInflater.from(context).inflate(layoutCard, parent, false)
)
2 -> return FeedViewHolder(
LayoutInflater.from(context).inflate(layoutFeedCard, parent, false)
)
3 -> return RankingViewHolder(
LayoutInflater.from(context).inflate(layoutRankingCard, parent, false)
)
4 -> return GroupsViewHolder (
LayoutInflater.from(context).inflate(layoutGroupsRankingCard, parent, false)
)
5 -> return FriendsViewHolder (
LayoutInflater.from(context).inflate(layoutFriendsCard, parent, false)
)
6 -> return CreateGroupViewHolder(
LayoutInflater.from(context).inflate(layoutCreateGroupCard, parent, false)
)
}
return HeaderViewHolder(
LayoutInflater.from(context).inflate(layoutHeader, parent, false)
)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (mDataList[position].getType()) {
0 -> {
(holder as RecycleViewAdapter.CardViewHolder).bind(position)
}
1 -> {
(holder as RecycleViewAdapter.HeaderViewHolder).bind(position)
}
2 -> {
(holder as RecycleViewAdapter.FeedViewHolder).bind(position)
}
3 -> {
(holder as RecycleViewAdapter.RankingViewHolder).bind(position)
}
4 -> {
(holder as RecycleViewAdapter.GroupsViewHolder).bind(position)
}
5 -> {
(holder as RecycleViewAdapter.FriendsViewHolder).bind(position)
}
6 -> {
(holder as RecycleViewAdapter.CreateGroupViewHolder).bind(position)
}
}
}
override fun getItemCount(): Int {
return mDataList.size
}
override fun getItemViewType(position: Int): Int {
return mDataList[position].getType()
}
private inner class CardViewHolder(itemView: View) :
RecyclerView.ViewHolder(itemView) {
var title: TextView = itemView.findViewById<View>(R.id.challenge_title) as TextView
var author: TextView =
itemView.findViewById<View>(R.id.challenge_author) as TextView
var timeLeft: TextView =
itemView.findViewById<View>(R.id.challenge_time_left) as TextView
var description: TextView =
itemView.findViewById<View>(R.id.challenge_description) as TextView
var reward: TextView =
itemView.findViewById<View>(R.id.challenge_reward) as TextView
var points: TextView =
itemView.findViewById<View>(R.id.challenge_points) as TextView
var button: Button = itemView.findViewById<View>(R.id.challenge_button) as Button
fun bind(position: Int) {
val recyclerViewModel = mDataList[position]
title.text = recyclerViewModel.title
author.text = recyclerViewModel.author
timeLeft.text = "${recyclerViewModel.timeLeft.toString()} days"
reward.text = recyclerViewModel.reward
points.text = recyclerViewModel.points.toString();
description.text = recyclerViewModel.description
// OnClick Listener on Button
button.setOnClickListener { listener(recyclerViewModel) }
}
}
private inner class HeaderViewHolder(itemView: View) :
RecyclerView.ViewHolder(itemView) {
var text: TextView = itemView.findViewById(R.id.header_text) as TextView
fun bind(position: Int) {
val recyclerViewModel = mDataList[position]
text.text = recyclerViewModel.text
}
}
private inner class FeedViewHolder(itemView: View) :
RecyclerView.ViewHolder(itemView) {
var text: TextView = itemView.findViewById(R.id.feed_text) as TextView
var cardFrameLayout: FrameLayout = itemView.findViewById(R.id.card_feed) as FrameLayout
fun bind(position: Int) {
val recyclerViewModel = mDataList[position]
text.text = recyclerViewModel.text
val androidColors : IntArray = context.resources.getIntArray(R.array.colorarray)
val randomAndroidColor: Int = androidColors[Random().nextInt(androidColors.size)]
cardFrameLayout.background.setTint(randomAndroidColor)
}
}
private inner class RankingViewHolder(itemView: View) :
RecyclerView.ViewHolder(itemView) {
var name: TextView = itemView.findViewById(R.id.ranking_name) as TextView
var ranking: TextView = itemView.findViewById(R.id.ranking_ranking) as TextView
var points: TextView = itemView.findViewById(R.id.ranking_points) as TextView
var cardFrameLayout: FrameLayout = itemView.findViewById(R.id.card_feed) as FrameLayout
fun bind(position: Int) {
val recyclerViewModel = mDataList[position]
if(recyclerViewModel.rankingType == 1){
cardFrameLayout.background.setTint(ContextCompat.getColor(context,R.color.orange));
} else {
cardFrameLayout.background.setTint(ContextCompat.getColor(context,R.color.primary));
}
name.text = recyclerViewModel.name
ranking.text = recyclerViewModel.ranking.toString()
points.text = recyclerViewModel.points.toString()
//val androidColors : IntArray = context.resources.getIntArray(R.array.colorarray)
// val randomAndroidColor: Int = androidColors[Random().nextInt(androidColors.size)]
// cardFrameLayout.background.setTint(randomAndroidColor)
}
}
private inner class GroupsViewHolder(itemView: View) :
RecyclerView.ViewHolder(itemView) {
var groupName: TextView = itemView.findViewById<View>(R.id.group_name) as TextView
var groupSize: TextView =
itemView.findViewById<View>(R.id.group_size) as TextView
var openGroupButton: Button = itemView.findViewById<View>(R.id.open_group_button) as Button
fun bind(position: Int) {
val recyclerViewModel = mDataList[position]
groupName.text = recyclerViewModel.name
groupSize.text = recyclerViewModel.size.toString();
// OnClick Listener on Button
openGroupButton.setOnClickListener { listener(recyclerViewModel) }
}
}
private inner class FriendsViewHolder(itemView: View) :
RecyclerView.ViewHolder(itemView) {
var username: TextView = itemView.findViewById(R.id.friend_username) as TextView
var deleteButton: Button = itemView.findViewById<View>(R.id.delete_button) as Button
fun bind(position: Int) {
val recyclerViewModel = mDataList[position]
username.text = recyclerViewModel.text
// OnClick Listener on Button
deleteButton.setOnClickListener { listener(recyclerViewModel) }
}
}
private inner class CreateGroupViewHolder(itemView: View) :
RecyclerView.ViewHolder(itemView) {
var username: TextView = itemView.findViewById(R.id.friend_username) as TextView
var button: Button = itemView.findViewById<View>(R.id.add_friend_to_group) as Button
fun bind(position: Int) {
val recyclerViewModel = mDataList[position]
username.text = recyclerViewModel.text
// OnClick Listener on Button
button.setOnClickListener { listener(recyclerViewModel) }
}
}
} | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/adapters/RecycleViewAdapter.kt | 1211662428 |
package com.jolufeja.tudas
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import arrow.core.computations.either
import arrow.core.identity
import com.jolufeja.httpclient.error.CommonErrors
import com.jolufeja.tudas.adapters.RecycleViewAdapter
import com.jolufeja.tudas.data.FeedItem
import com.jolufeja.tudas.data.ListItem
import com.jolufeja.tudas.data.RankingItem
import com.jolufeja.tudas.service.user.Ranking
import com.jolufeja.tudas.service.user.User
import com.jolufeja.tudas.service.user.UserService
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import java.time.LocalDate
import java.util.ArrayList
class RankingsWorldFragment(
private val userService: UserService
) : Fragment(R.layout.fragment_rankings_world){
private var mRecyclerView: RecyclerView? = null
private var mAdapter: RecyclerView.Adapter<*>? = null
private var listOfRankings: ArrayList<RankingItem> = ArrayList()
private var finalList: MutableList<ListItem> = mutableListOf()
private suspend fun buildRankingsList() = flow<List<ListItem>> {
either<CommonErrors, Unit> {
emit(emptyList())
val feedElements = userService
.getPublicRanking()
.bind()
.toRankingListItems()
emit(feedElements)
}.fold(
ifLeft = { emit(emptyList()) },
ifRight = ::identity
)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// //adding items in list
// for (i in 0..20) {
// val rank = RankingItem()
// rank.id = i
// rank.ranking = i + 1
// rank.name = "Marc"
// rank.points = 100000 / (i+1)
// if(i === 5){
// rank.rankingType = 1
// } else {
// rank.rankingType = 0
// }
// listOfRankings.add(rank)
// }
//
// listOfRankings.forEach {
// finalList.add(it)
// }
mRecyclerView = view.findViewById(R.id.rankings_recycler_view)
var mLayoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
mRecyclerView!!.layoutManager = mLayoutManager
// Add Adapter so cards will be displayed
mAdapter =
context?.let {
RecycleViewAdapter(
it,
finalList,
0,
0,
0,
R.layout.card_rankings_friends,
0,
0,
0
) {
null
}
}
mRecyclerView!!.adapter = mAdapter
lifecycleScope.launch {
buildRankingsList().collect { rankings ->
finalList = rankings.toMutableList()
(mAdapter as? RecycleViewAdapter)?.refreshData(rankings)
mAdapter?.notifyDataSetChanged()
}
}
}
}
fun List<Ranking>.toRankingListItems(): List<ListItem> = mapIndexed { i, entry ->
RankingItem().apply {
id = i
ranking = i + 1
name = entry.name
points = entry.points
}
}
| tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/RankingsWorldFragment.kt | 2209388517 |
package com.jolufeja.tudas
import android.util.Log
import androidx.lifecycle.*
import com.jolufeja.authentication.registration.RegistrationCredentials
import com.jolufeja.authentication.registration.RegistrationService
import com.jolufeja.navigation.NavigationEvent
import com.jolufeja.navigation.NavigationEventPublisher
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
enum class RegistrationNavigationEvents : NavigationEvent {
PROCEED_TO_HOME,
PROCEED_TO_LOGIN
}
class RegistrationViewModel(
private val registrationService: RegistrationService,
private val navigator: NavigationEventPublisher
) : ViewModel() {
val userNameData: MutableLiveData<String> = MutableLiveData("")
val passwordData: MutableLiveData<String> = MutableLiveData("")
val emailAddressData: MutableLiveData<String> = MutableLiveData("")
private val userNameState: StateFlow<String> =
userNameData.asFlow().stateIn(viewModelScope, SharingStarted.Lazily, "")
private val passwordState: StateFlow<String> =
passwordData.asFlow().stateIn(viewModelScope, SharingStarted.Lazily, "")
private val emailAddressState: StateFlow<String> =
emailAddressData.asFlow().stateIn(viewModelScope, SharingStarted.Lazily, "")
val canPerformRegistration: LiveData<Boolean> = combine(
userNameState,
passwordState,
emailAddressState
) { (userName, password, emailAddress) ->
userName.isNotBlank() && password.isNotBlank() && emailAddress.isNotBlank()
}.asLiveData()
fun performRegistration() {
viewModelScope.launch {
val credentials = RegistrationCredentials(
name = userNameState.value,
password = passwordState.value,
email = emailAddressState.value
)
registrationService.registerUser(credentials).fold(
ifLeft = { Log.d("RegistrationViewModel", "Registration failed. $it") },
ifRight = {
navigator.publish(LoginNavigationEvents.PROCEED_TO_HOME)
}
)
}
}
fun switchToLogin() = navigator.publish(RegistrationNavigationEvents.PROCEED_TO_LOGIN)
}
| tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/RegistrationViewModel.kt | 1765722010 |
package com.jolufeja.tudas
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import arrow.core.computations.either
import arrow.core.identity
import com.jolufeja.httpclient.error.CommonErrors
import com.jolufeja.tudas.adapters.RecycleViewAdapter
import com.jolufeja.tudas.data.ListItem
import com.jolufeja.tudas.data.RankingItem
import com.jolufeja.tudas.service.user.UserService
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import java.util.ArrayList
class RankingsFriendsFragment(
private val userService: UserService
) : Fragment(R.layout.fragment_rankings_friends) {
private var mRecyclerView: RecyclerView? = null
private var mAdapter: RecyclerView.Adapter<*>? = null
private var listOfRankings: ArrayList<RankingItem> = ArrayList()
private var finalList: MutableList<ListItem> = mutableListOf()
private suspend fun buildRankingsList() = flow<List<ListItem>> {
either<CommonErrors, Unit> {
emit(emptyList())
val feedElements = userService
.getFriendsRanking()
.bind()
.toRankingListItems()
emit(feedElements)
}.fold(
ifLeft = { emit(emptyList()) },
ifRight = ::identity
)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
mRecyclerView = view.findViewById(R.id.rankings_recycler_view)
var mLayoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
mRecyclerView!!.layoutManager = mLayoutManager
// Add Adapter so cards will be displayed
mAdapter =
context?.let {
RecycleViewAdapter(
it,
finalList,
0,
0,
0,
R.layout.card_rankings_friends,
0,
0,
0
) {
null
}
}
mRecyclerView!!.adapter = mAdapter
lifecycleScope.launch {
buildRankingsList().collect { rankings ->
finalList = rankings.toMutableList()
(mAdapter as? RecycleViewAdapter)?.refreshData(rankings)
mAdapter?.notifyDataSetChanged()
}
}
}
}
| tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/RankingsFriendsFragment.kt | 3381110947 |
package com.jolufeja.tudas
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import arrow.core.computations.either
import arrow.core.identity
import com.jolufeja.authentication.FeedEntry
import com.jolufeja.httpclient.error.CommonErrors
import com.jolufeja.tudas.adapters.RecycleViewAdapter
import com.jolufeja.tudas.data.FeedItem
import com.jolufeja.tudas.data.ListItem
import com.jolufeja.tudas.service.user.UserService
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import java.time.LocalDate
class FeedFragment(
private val userService: UserService
) : Fragment(R.layout.fragment_feed) {
private var mRecyclerView: RecyclerView? = null
private var mAdapter: RecyclerView.Adapter<*>? = null
private var listOfActivities: ArrayList<FeedItem> = ArrayList()
private var finalList: MutableList<ListItem> = mutableListOf()
private suspend fun buildFeedList() = flow<List<ListItem>> {
either<CommonErrors, Unit> {
emit(emptyList())
val feedElements = userService
.getFeed()
.bind()
.toFeedListItems()
emit(feedElements)
}.fold(
ifLeft = {
Log.d("FeedFragment", it.toString())
showToast("Could not fetch feed. Please try again.")
emit(emptyList())
},
ifRight = ::identity
)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val refreshLayout = view.findViewById<SwipeRefreshLayout>(R.id.feed_swiperefresh)
refreshLayout?.setOnRefreshListener {
lifecycleScope.launch {
buildFeedList().collect { feed ->
refreshLayout.isRefreshing = false
finalList = feed.toMutableList()
(mAdapter as? RecycleViewAdapter)?.refreshData(feed)
mAdapter?.notifyDataSetChanged()
}
}
}
mRecyclerView = view.findViewById(R.id.feed_recycler_view)
var mLayoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
mRecyclerView!!.layoutManager = mLayoutManager
// Add Adapter so cards will be displayed
mAdapter =
context?.let {
RecycleViewAdapter(
it,
finalList,
0,
R.layout.card_feed_header,
R.layout.card_feed,
0,
0,
0,
0
) {
null
}
}
mRecyclerView!!.adapter = mAdapter
lifecycleScope.launch {
buildFeedList().collect { feed ->
finalList = feed.toMutableList()
(mAdapter as? RecycleViewAdapter)?.refreshData(feed)
mAdapter?.notifyDataSetChanged()
}
}
}
}
private fun List<FeedEntry>.toFeedListItems(): List<ListItem> = mapIndexed { i, entry ->
FeedItem().apply {
id = i
text = entry.message
date = LocalDate.now().toString()
type = "Sent challenge"
}
}
| tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/FeedFragment.kt | 3003331109 |
package com.jolufeja.tudas
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import arrow.core.computations.either
import arrow.core.identity
import com.jolufeja.httpclient.error.CommonErrors
import com.jolufeja.tudas.adapters.RecycleViewAdapter
import com.jolufeja.tudas.data.ChallengesItem
import com.jolufeja.tudas.data.HeaderItem
import com.jolufeja.tudas.data.ListItem
import com.jolufeja.tudas.service.challenges.ChallengeService
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import org.koin.android.ext.android.get
class ChallengesSentFragment(
private val challengeService: ChallengeService
) : Fragment(R.layout.fragment_challenges_sent) {
private var mRecyclerView: RecyclerView? = null
private var mAdapter: RecyclerView.Adapter<*>? = null
private var listOfChallenges: ArrayList<ChallengesItem> = ArrayList()
private var createChallengeButton: Button? = null
private var finalList: MutableList<ListItem> = mutableListOf()
private suspend fun buildChallengeList() = flow<List<ListItem>> {
either<CommonErrors, Unit> {
emit(emptyList())
val sentChallenges = challengeService
.getOwnCreatedChallenges()
.bind()
.toChallengeListItems()
val combined = listOf(HeaderItem("Sent Challenges")) + sentChallenges
emit(combined)
}.fold(
ifLeft = { emit(emptyList()) },
ifRight = ::identity
)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val refreshLayout = view.findViewById<SwipeRefreshLayout>(R.id.sent_swiperefresh)
refreshLayout?.setOnRefreshListener {
lifecycleScope.launch {
buildChallengeList().collect { challenges ->
refreshLayout.isRefreshing = false
finalList = challenges.toMutableList()
(mAdapter as? RecycleViewAdapter)?.refreshData(challenges)
mAdapter?.notifyDataSetChanged()
}
}
}
mRecyclerView = view.findViewById(R.id.challenges_sent_recycler_view)
var mLayoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
mRecyclerView!!.layoutManager = mLayoutManager
// Add Adapter so cards will be displayed
mAdapter =
context?.let {
RecycleViewAdapter(
it,
finalList,
R.layout.card_challenges_sent,
R.layout.card_header,
0,
0,
0,
0,
0
) { item ->
// Open New Fragment
val individualChallengeSentFragment = IndividualChallengeSentFragment(get())
val transaction: FragmentTransaction =
requireActivity().supportFragmentManager.beginTransaction()
transaction.replace(
((view as ViewGroup).parent as View).id,
individualChallengeSentFragment
)
transaction.addToBackStack("challenge_sent_info")
transaction.commit()
item.id.let { Log.d("TAG", it.toString()) }
}
}
mRecyclerView!!.adapter = mAdapter
lifecycleScope.launch {
buildChallengeList().collect { challenges ->
finalList = challenges.toMutableList()
(mAdapter as? RecycleViewAdapter)?.refreshData(challenges)
mAdapter?.notifyDataSetChanged()
}
}
// Handle Create Challenge Button
createChallengeButton = view.findViewById(R.id.create_challenge_button) as Button
createChallengeButton!!.setOnClickListener {
// Open New Fragment
val individualChallengeSentFragment = IndividualChallengeSentFragment(get())
val transaction: FragmentTransaction =
requireActivity().supportFragmentManager.beginTransaction()
transaction.replace(
((view as ViewGroup).parent as View).id,
individualChallengeSentFragment
)
transaction.addToBackStack("challenge_sent_info")
transaction.commit()
}
}
} | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/ChallengesSentFragment.kt | 1422998743 |
package com.jolufeja.tudas
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.jolufeja.tudas.adapters.ViewPagerFragmentAdapter
import org.koin.android.ext.android.get
class RankingsFragment : Fragment(R.layout.fragment_rankings) {
var tabLayout: TabLayout? = null
var viewPager: ViewPager2? = null
var tabTitles: Array<String> = arrayOf("Friends", "Groups", "World")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
setHasOptionsMenu(true);
tabLayout = view.findViewById<TabLayout>(R.id.tabLayout)
viewPager = view.findViewById<ViewPager2>(R.id.viewPager)
// create a new tab for each rankings fragment
for (item in tabTitles)
tabLayout!!.addTab(tabLayout!!.newTab().setText(item))
tabLayout!!.tabGravity = TabLayout.GRAVITY_FILL
// create adapter
val adapter = ViewPagerFragmentAdapter(
this,
RankingsFriendsFragment(get()),
RankingsGroupsFragment(),
RankingsWorldFragment(get()),
RankingsFriendsFragment(get())
)
viewPager!!.adapter = adapter
TabLayoutMediator(tabLayout!!, viewPager!!) { tab, position ->
tab.text = tabTitles[position]
}.attach()
}
} | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/RankingsFragment.kt | 1082905579 |
package com.jolufeja.tudas
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import arrow.core.computations.either
import arrow.core.identity
import com.jolufeja.httpclient.error.CommonErrors
import com.jolufeja.tudas.adapters.RecycleViewAdapter
import com.jolufeja.tudas.data.ChallengesItem
import com.jolufeja.tudas.data.HeaderItem
import com.jolufeja.tudas.data.ListItem
import com.jolufeja.tudas.service.challenges.ChallengeService
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch
import org.koin.android.ext.android.get
class ChallengesReceivedFragment(
private val challengeService: ChallengeService
) : Fragment(R.layout.fragment_challenges_received) {
private var mRecyclerView: RecyclerView? = null
private var mAdapter: RecyclerView.Adapter<*>? = null
private var listOfChallenges: ArrayList<ChallengesItem> = ArrayList()
private var finalList: MutableList<ListItem> = mutableListOf()
private suspend fun buildChallengeList() = flow<List<ListItem>> {
either<CommonErrors, Unit> {
emit(emptyList())
val openChallenges = challengeService
.getOpenChallenges()
.bind()
.toChallengeListItems()
val completedChallenges = challengeService
.getFinishedChallenges()
.bind()
.toChallengeListItems()
val combined = listOf(HeaderItem("Open Challenges")) + openChallenges +
listOf(HeaderItem("Completed")) + completedChallenges
emit(combined)
}.fold(
ifLeft = { emit(emptyList()) },
ifRight = ::identity
)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val refreshLayout = view.findViewById<SwipeRefreshLayout>(R.id.received_swiperefresh)
refreshLayout?.setOnRefreshListener {
lifecycleScope.launch {
buildChallengeList().collect { challenges ->
refreshLayout.isRefreshing = false
finalList = challenges.toMutableList()
(mAdapter as? RecycleViewAdapter)?.refreshData(challenges)
mAdapter?.notifyDataSetChanged()
}
}
}
mRecyclerView = view.findViewById(R.id.challenges_received_recycler_view)
var mLayoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
mRecyclerView!!.layoutManager = mLayoutManager
// Add Adapter so cards will be displayed
mAdapter = context?.let {
RecycleViewAdapter(
it,
finalList,
R.layout.card_challenges_received,
R.layout.card_header,
0,
0,
0,
0,
0
) { item ->
// Open New Fragment
val challengeArgs = Bundle().also { bundle ->
bundle.putSerializable(CHALLENGE_KEY, (item as ChallengesItem).challenge)
}
val individualChallengeReceivedFragment = IndividualChallengeReceivedFragment(get())
individualChallengeReceivedFragment.arguments = challengeArgs
val transaction: FragmentTransaction =
requireActivity().supportFragmentManager.beginTransaction()
transaction.replace(
((view as ViewGroup).parent as View).id,
individualChallengeReceivedFragment
)
transaction.addToBackStack("challenge_received_info")
transaction.commit()
item.id.let { Log.d("TAG", it.toString()) }
}
}
mRecyclerView!!.adapter = mAdapter
lifecycleScope.launch {
buildChallengeList().collect { challenges ->
finalList = challenges.toMutableList()
(mAdapter as? RecycleViewAdapter)?.refreshData(challenges)
mAdapter?.notifyDataSetChanged()
}
}
}
} | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/ChallengesReceivedFragment.kt | 3191011123 |
package com.jolufeja.tudas.service.challenges
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import java.io.Serializable
import java.time.LocalDate
import java.util.*
@JsonIgnoreProperties(ignoreUnknown = true)
data class Challenge(
val id: Int? = null,
val name: String,
val creator: String,
val creationDate: LocalDate,
val description: String,
val dueDate: Date,
val reward: String,
val worth: Int,
val addressedTo: String
) : Serializable | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/service/challenges/Challenge.kt | 3394380654 |
package com.jolufeja.tudas.service.challenges
import java.util.*
data class InitialChallenge(
val challengeName: String,
val creatorName: String,
val description: String,
val dueDate: Date,
val reward: String,
val addressedTo: String,
val worth: Int,
) | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/service/challenges/InitialChallenge.kt | 3673580008 |
package com.jolufeja.tudas.service.challenges
import android.content.Context
import android.graphics.Bitmap
import android.os.Environment
import android.provider.MediaStore
import arrow.core.Either
import arrow.core.flatMap
import com.jolufeja.authentication.UserAuthenticationService
import com.jolufeja.httpclient.*
import com.jolufeja.httpclient.error.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.ByteArrayOutputStream
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
sealed interface ProofKind {
interface Body
fun buildJsonBody(challenge: Challenge, userName: String): Body
data class ProofImage(val image: File) : ProofKind {
data class WithImageBody(
val challengeName: String,
val userName: String
) : Body
override fun buildJsonBody(challenge: Challenge, userName: String) =
WithImageBody(challenge.name, userName)
fun contentToRequestBody(challenge: Challenge, userName: String) = MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file",image.name, image.asRequestBody("image/jpeg".toMediaType()))
.addFormDataPart("challengeName", challenge.name)
.addFormDataPart("userName", userName)
.build()
}
data class SocialMediaLink(val link: String) : ProofKind {
data class WithLinkBody(
val challengeName: String,
val userName: String,
val url: String
) : Body
override fun buildJsonBody(challenge: Challenge, userName: String) =
WithLinkBody(challenge.name, userName, link)
}
}
interface ChallengeService {
suspend fun createChallenge(challenge: InitialChallenge): Either<CommonErrors, Unit>
suspend fun getChallenge(name: String): Either<CommonErrors, Challenge?>
suspend fun getPublicChallenges(): Either<CommonErrors, List<Challenge>>
suspend fun getFriendChallenges(): Either<CommonErrors, List<Challenge>>
suspend fun getOwnCreatedChallenges(): Either<CommonErrors, List<Challenge>>
suspend fun getFinishedChallenges(): Either<CommonErrors, List<Challenge>>
suspend fun getOpenChallenges(): Either<CommonErrors, List<Challenge>>
suspend fun finishChallengeWithProof(
challenge: Challenge,
proofKind: ProofKind
): Either<CommonErrors, Unit>
}
data class UserName(val userName: String)
data class ChallengeName(val challengeName: String)
class DefaultChallengeService(
private val httpClient: HttpClient,
private val authenticationService: UserAuthenticationService
) : ChallengeService {
override suspend fun createChallenge(
challenge: InitialChallenge
): Either<CommonErrors, Unit> =
httpClient.post("challenge/addchallenge")
.jsonBody(challenge)
.tryExecute()
.void()
override suspend fun getChallenge(
name: String
): Either<CommonErrors, Challenge?> =
httpClient.post("challenge/getchallenge")
.jsonBody(ChallengeName(name))
.tryExecute()
.awaitJsonBodyOrNull()
override suspend fun getPublicChallenges(): Either<CommonErrors, List<Challenge>> =
httpClient.get("challenge/getpublicchallenges")
.tryExecute()
.awaitJsonBody(jsonListOf<Challenge>())
override suspend fun getFriendChallenges(): Either<CommonErrors, List<Challenge>> =
httpClient.post("challenge/getchallengesfromfriends")
.jsonBodyOfCurrentUser()
.tryExecute()
.awaitJsonBody(jsonListOf<Challenge>())
override suspend fun getOwnCreatedChallenges(): Either<CommonErrors, List<Challenge>> =
httpClient.post("user/getcreatedchallenges")
.jsonBodyOfCurrentUser()
.tryExecute()
.awaitJsonBody(jsonListOf<Challenge>())
override suspend fun getFinishedChallenges(): Either<CommonErrors, List<Challenge>> =
httpClient.post("user/getfinishedchallenges")
.jsonBodyOfCurrentUser()
.tryExecute()
.awaitJsonBody(jsonListOf<Challenge>())
override suspend fun getOpenChallenges(): Either<CommonErrors, List<Challenge>> =
httpClient.post("user/getopenchallenges")
.jsonBodyOfCurrentUser()
.tryExecute()
.awaitJsonBody(jsonListOf<Challenge>())
override suspend fun finishChallengeWithProof(
challenge: Challenge,
proofKind: ProofKind
): Either<CommonErrors, Unit> {
val userName = authenticationService.authentication.await().user.name
return when (proofKind) {
is ProofKind.ProofImage -> {
val body = proofKind.contentToRequestBody(challenge, userName)
httpClient.post("challenge/uploadPicture")
.body(body)
.tryExecute()
.void()
}
is ProofKind.SocialMediaLink -> {
httpClient.post("challenge/uploadsocialmedia")
.jsonBody(proofKind.buildJsonBody(challenge, userName))
.tryExecute()
.void()
}
}
}
private suspend fun HttpClientRequest.Builder.jsonBodyOfCurrentUser() =
jsonBody(UserName(authenticationService.authentication.await().user.name))
private fun HttpClientRequest.Builder.emptyBody(): HttpClientRequest.Builder =
jsonBody("")
}
suspend fun <T : Any> Either<CommonErrors, HttpClientResponse>.awaitJsonBody(
payloadType: JsonTypeSupplier<T>
): Either<CommonErrors, T> =
flatMap { response -> catchError { response.awaitJsonBody(payloadType) } }
fun Bitmap.asByteArray(): ByteArray {
val ostream = ByteArrayOutputStream()
this.compress(Bitmap.CompressFormat.JPEG,100,ostream)
return ostream.toByteArray()
} | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/service/challenges/ChallengeService.kt | 3055005834 |
package com.jolufeja.tudas.service.user
import com.jolufeja.tudas.service.challenges.Challenge
data class User(
val name: String,
val password: String,
val emailAddress: String,
val profilePicture: String,
val points: Int,
val friends: List<FriendEntry>,
val createdChallenges: List<Challenge>,
val openChallenges: List<Challenge>,
val finishedChallenges: List<Challenge>
) | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/service/user/User.kt | 3025403561 |
package com.jolufeja.tudas.service.user
import arrow.core.Either
import arrow.core.flatMap
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.jolufeja.authentication.FeedEntry
import com.jolufeja.authentication.UserAuthenticationService
import com.jolufeja.httpclient.HttpClient
import com.jolufeja.httpclient.HttpClientResponse
import com.jolufeja.httpclient.JsonTypeSupplier
import com.jolufeja.httpclient.error.*
import com.jolufeja.httpclient.jsonListOf
import com.jolufeja.tudas.data.FeedItem
import com.jolufeja.tudas.service.challenges.UserName
import com.jolufeja.tudas.service.challenges.awaitJsonBody
@JsonIgnoreProperties(ignoreUnknown = true)
data class Ranking(val name: String, val points: Int)
@JsonIgnoreProperties(ignoreUnknown = true)
data class FriendEntry(val name: String, val streak: Int)
@JsonIgnoreProperties(ignoreUnknown = true)
data class Friendship(val userName: String, val friendName: String)
@JsonIgnoreProperties(ignoreUnknown = true)
private data class FriendResult(val friends: List<FriendEntry>)
@JsonIgnoreProperties(ignoreUnknown = true)
private data class PointResult(val points: Int)
@JsonIgnoreProperties(ignoreUnknown = true)
private data class FeedResult(val name: String, val feed: List<FeedEntry>)
@JsonIgnoreProperties(ignoreUnknown = true)
data class AddedFriendResult(val name: String, val friends: List<FriendEntry>)
interface UserService {
suspend fun getUser(userName: String): Either<CommonErrors, User?>
suspend fun addFriend(friendName: String): Either<CommonErrors, AddedFriendResult>
suspend fun removeFriend(friendName: String): Either<CommonErrors, AddedFriendResult>
suspend fun getFriends(userName: String): Either<CommonErrors, List<FriendEntry>>
suspend fun getFriendsOfCurrentUser(): Either<CommonErrors, List<FriendEntry>>
suspend fun getPointsOfUser(userName: String): Either<CommonErrors, Int>
suspend fun getPointsOfCurrentUser(): Either<CommonErrors, Int>
suspend fun getFeed(): Either<CommonErrors, List<FeedEntry>>
suspend fun getFriendsRanking(): Either<CommonErrors, List<Ranking>>
suspend fun getPublicRanking(): Either<CommonErrors, List<Ranking>>
}
class DefaultUserService(
private val httpClient: HttpClient,
private val authService: UserAuthenticationService
) : UserService {
override suspend fun getUser(userName: String): Either<CommonErrors, User?> =
httpClient.post("user/getuser")
.jsonBody(UserName(userName))
.tryExecute()
.awaitJsonBody()
override suspend fun addFriend(friendName: String): Either<CommonErrors, AddedFriendResult> =
httpClient.post("user/addfriend")
.jsonBody(
Friendship(
userName = authService.authentication.await().user.name,
friendName = friendName
)
)
.tryExecute()
.awaitJsonBody()
override suspend fun removeFriend(friendName: String): Either<CommonErrors, AddedFriendResult> =
httpClient.post("user/removefriend")
.jsonBody(
Friendship(
userName = authService.authentication.await().user.name,
friendName = friendName
)
)
.tryExecute()
.awaitJsonBody()
override suspend fun getFriends(userName: String): Either<CommonErrors, List<FriendEntry>> =
httpClient.post("user/getfriends")
.jsonBody(UserName(userName))
.tryExecute()
.awaitJsonBodyOrNull<FriendResult>()
.map { it?.friends ?: emptyList() }
override suspend fun getFriendsOfCurrentUser(): Either<CommonErrors, List<FriendEntry>> =
httpClient.post("user/getfriends")
.jsonBody(UserName(authService.authentication.await().user.name))
.tryExecute()
.awaitJsonBodyOrNull<FriendResult>()
.map { it?.friends ?: emptyList() }
override suspend fun getPointsOfUser(userName: String): Either<CommonErrors, Int> =
httpClient.post("user/getpointsofuser")
.jsonBody(UserName(userName))
.tryExecute()
.awaitJsonBody<PointResult>()
.map { it.points }
override suspend fun getPointsOfCurrentUser(): Either<CommonErrors, Int> =
httpClient.post("user/getpointsofuser")
.jsonBody(UserName(authService.authentication.await().user.name))
.tryExecute()
.awaitJsonBody<PointResult>()
.map { it.points }
override suspend fun getFeed(): Either<CommonErrors, List<FeedEntry>> =
httpClient.post("user/getfeed")
.jsonBody(UserName(authService.authentication.await().user.name))
.tryExecute()
.awaitJsonBody<FeedResult>()
.map { it.feed }
override suspend fun getFriendsRanking(): Either<CommonErrors, List<Ranking>> =
httpClient.post("user/getfriendranking")
.jsonBody(UserName(authService.authentication.await().user.name))
.tryExecute()
.awaitJsonBody(jsonListOf<Ranking>())
override suspend fun getPublicRanking(): Either<CommonErrors, List<Ranking>> =
httpClient.get("user/getpublicranking")
.tryExecute()
.awaitJsonBody(jsonListOf<Ranking>())
}
suspend fun <T : Any> Either<CommonErrors, HttpClientResponse>.awaitJsonBodyOrNull(
payloadType: JsonTypeSupplier<T>
): Either<CommonErrors, T?> =
flatMap { response -> catchError { response.awaitJsonBodyOrNull(payloadType) } }
| tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/service/user/UserService.kt | 3414186831 |
package com.jolufeja.tudas.service
import arrow.core.Either
import com.jolufeja.authentication.UserAuthenticationService
import com.jolufeja.httpclient.HttpClient
import com.jolufeja.httpclient.error.CommonErrors
import com.jolufeja.httpclient.error.awaitJsonBody
import com.jolufeja.httpclient.error.tryExecute
data class UserSettings(
val name: String,
val email: String,
val password: String
) {
companion object {
/*
Currently missing a way to access the password of the current user.
Ideally, the password should only be passed if it actually *changed*.
That way, I don't have to persist the user password anywhere.
*/
suspend fun UserAuthenticationService.byAuthenticatedUser() {
val user = authentication.await().user
return TODO()
}
}
}
fun interface SettingsService {
suspend fun updateSettings(settings: UserSettings): Either<CommonErrors, UserSettings>
}
class DefaultSettingsService(
private val httpClient: HttpClient
) : SettingsService {
override suspend fun updateSettings(settings: UserSettings): Either<CommonErrors, UserSettings> =
httpClient.post("/user/updateSettings")
.jsonBody(settings)
.tryExecute()
.awaitJsonBody()
} | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/service/SettingsService.kt | 2802031513 |
package com.jolufeja.tudas
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
class ChangePasswordFragment : Fragment(R.layout.fragment_change_password) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
var saveButton: Button = view.findViewById<View>(R.id.save) as Button
saveButton.setOnClickListener {
// save new password
requireActivity().supportFragmentManager.popBackStack();
}
var cancelButton: Button = view.findViewById<View>(R.id.cancel) as Button
cancelButton.setOnClickListener {
requireActivity().supportFragmentManager.popBackStack();
}
}
} | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/ChangePasswordFragment.kt | 1841547695 |
package com.jolufeja.tudas
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.Navigation.findNavController
import androidx.navigation.fragment.findNavController
import androidx.navigation.ui.setupWithNavController
import arrow.core.computations.either
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.jolufeja.authentication.AuthenticationStore
import com.jolufeja.httpclient.error.CommonErrors
import com.jolufeja.tudas.service.user.UserService
import kotlinx.coroutines.launch
class MainFragment(
private val authenticationStore: AuthenticationStore,
private val userService: UserService
) : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycleScope.launch {
val destination = authenticationStore.retrieve()?.let {
Log.d("MainFragment","Found authToken - proceeding to authenticated area.")
updatePoints()
R.id.nav_graph_authenticated
} ?: R.id.nav_graph_unauthenticated
findNavController().navigate(destination)
}
}
private suspend fun updatePoints() {
either<CommonErrors, Unit> {
val currentPoints = userService.getPointsOfCurrentUser().bind()
(activity as MainActivity).statsChannel.trySend(currentPoints)
}.fold(
ifLeft = { Log.d("MainFragment", "$it")},
ifRight = {}
)
}
} | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/MainFragment.kt | 1430650290 |
package com.jolufeja.tudas.data
class FriendsItem : ListItem() {
override var id: Int = 0
override var text: String? = null
override fun getType(): Int {
return 5;
}
} | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/data/FriendsItem.kt | 3624444004 |
package com.jolufeja.tudas.data
class RankingGroupsItem : ListItem() {
override var id: Int = 0
override var name: String? = null
override var size: Int = 0
override fun getType(): Int {
return 4;
}
} | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/data/RankingGroupsItem.kt | 2570526427 |
package com.jolufeja.tudas.data
import com.jolufeja.tudas.service.challenges.Challenge
class ChallengesItem : ListItem() {
override var id: Int = 0
override var title: String? = null
override var author: String? = null
override var timeLeft: Int = 0
override var description: String? = null
override var reward: String? = null
override var points: Int = 0
lateinit var challenge: Challenge
override fun getType(): Int {
return 0;
}
} | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/data/ChallengesItem.kt | 559571843 |
package com.jolufeja.tudas.data
import java.util.*
class HeaderItem : ListItem() {
companion object {
operator fun invoke(text: String) = HeaderItem().apply { this.text = text }
}
override var text: String? = null
override fun getType(): Int {
return 1;
}
} | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/data/HeaderItem.kt | 530671124 |
package com.jolufeja.tudas.data
class FeedItem : ListItem() {
override var id: Int = 0
override var text: String? = null
override var type: String? = null
override var date: String? = null
override fun getType(): Int {
return 2;
}
} | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/data/FeedItem.kt | 3383946113 |
package com.jolufeja.tudas.data
open class ListItem {
open var text: String? = null
open var id: Int = 0
open var title: String? = null
open var author: String? = null
open var timeLeft: Int = 0
open var description: String? = null
open var reward: String? = null
open var points: Int = 0
open var type: String? = null
open var rankingType: Int = 0
open var date: String? = null
open var name: String? = null
open var ranking: Int = 0
open fun getType(): Int {
return -1
}
open var size: Int = 0
} | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/data/ListItem.kt | 1490146894 |
package com.jolufeja.tudas.data
class RankingItem : ListItem() {
override var id: Int = 0
override var name: String? = null
override var points: Int = 0
override var ranking: Int = 0
override var rankingType: Int = 0
override fun getType(): Int {
return 3;
}
} | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/data/RankingItem.kt | 2711371210 |
package com.jolufeja.tudas.data
class CreateGroupItem : ListItem() {
override var id: Int = 0
override var text: String? = null
override fun getType(): Int {
return 6;
}
} | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/data/CreateGroupItem.kt | 2336301526 |
package com.jolufeja.tudas
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import arrow.core.computations.either
import com.jolufeja.authentication.UserAuthenticationService
import com.jolufeja.httpclient.error.CommonErrors
import com.jolufeja.tudas.service.user.UserService
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.koin.android.ext.android.get
class ProfileFragment(
private val authenticationService: UserAuthenticationService,
private val userService: UserService
) : Fragment(R.layout.fragment_profile) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// val profileFragment = ProfileFragment(get())
val userName = view.findViewById<TextView>(R.id.userName).let {
runBlocking {
it.text = authenticationService.authentication.await().user.name
}
}
view.findViewById<TextView>(R.id.userPoints).let {
runBlocking {
either<CommonErrors, Unit> {
val points = userService.getPointsOfCurrentUser().bind()
it.text = points.toString()
}
}
}
var profileImage: ImageView = view.findViewById<View>(R.id.profileImage) as ImageView
var friendsButton: Button = view.findViewById<View>(R.id.friendsButton) as Button
var changeEmailButton: Button = view.findViewById<View>(R.id.changeEmail) as Button
var changePasswordButton: Button = view.findViewById<View>(R.id.changePassword) as Button
var notificationButton: Button = view.findViewById<View>(R.id.notificationButton) as Button
var logOutButton: Button = view.findViewById<View>(R.id.logOutButton) as Button
var testNotificationsButton: Button = view.findViewById<View>(R.id.testNotificationsButton) as Button
profileImage.setOnClickListener{
//upload profile picture
//profileImage.setImageResource()
}
friendsButton.setOnClickListener{
val friendsSettingsFragment = FriendsSettingsFragment(get())
val transaction: FragmentTransaction =
requireActivity().supportFragmentManager.beginTransaction()
transaction.replace(
((view as ViewGroup).parent as View).id,
friendsSettingsFragment
)
transaction.addToBackStack("friends_list")
transaction.commit()
}
changeEmailButton.setOnClickListener{
val changeEmailFragment = ChangeEmailFragment(get(), get())
val transaction: FragmentTransaction =
requireActivity().supportFragmentManager.beginTransaction()
transaction.replace(
((view as ViewGroup).parent as View).id,
changeEmailFragment
)
transaction.addToBackStack("change_email")
transaction.commit()
}
changePasswordButton.setOnClickListener{
val changePasswordFragment = ChangePasswordFragment()
val transaction: FragmentTransaction =
requireActivity().supportFragmentManager.beginTransaction()
transaction.replace(
((view as ViewGroup).parent as View).id,
changePasswordFragment
)
transaction.addToBackStack("change_password")
transaction.commit()
}
notificationButton.setOnClickListener{
val notificationSettingsFragment = NotificationSettingsFragment()
val transaction: FragmentTransaction =
requireActivity().supportFragmentManager.beginTransaction()
transaction.replace(
((view as ViewGroup).parent as View).id,
notificationSettingsFragment
)
transaction.addToBackStack("notification")
transaction.commit()
}
logOutButton.setOnClickListener {
lifecycleScope.launch {
authenticationService.logout()
requireActivity().supportFragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
(activity as MainActivity).statsChannel.trySend(0)
findNavController().navigate(R.id.nav_graph_unauthenticated)
}
}
testNotificationsButton.setOnClickListener {
(activity as MainActivity).sendNotification(
"Test Notification",
"Click me to open TUDAS"
)
}
}
} | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/ProfileFragment.kt | 3787784744 |
package com.jolufeja.tudas
import android.content.Context
import android.content.SharedPreferences
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.Switch
import android.widget.Toast
import androidx.fragment.app.Fragment
class NotificationSettingsFragment : Fragment(R.layout.fragment_notification_settings) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
var preferences: SharedPreferences = this.requireActivity().getSharedPreferences("pref", Context.MODE_PRIVATE)
var editor = preferences.edit()
var anyNotification: Boolean = preferences.getBoolean("anyNotification",true)
var challengeReceivedNotification: Boolean = preferences.getBoolean("challengeReceivedNotification",true)
var friendsRequestNotification: Boolean = preferences.getBoolean("friendsRequestNotification",true)
var challengeEndsNotification: Boolean = preferences.getBoolean("challengeEndsNotification",true)
var switchNotifications: Switch = view.findViewById<View>(R.id.switchNotifications) as Switch
switchNotifications.isChecked = anyNotification
var switchChallengeReceived: Switch = view.findViewById<View>(R.id.switchChallengeReceived) as Switch
if (!anyNotification) {
switchChallengeReceived.isChecked = false
switchChallengeReceived.visibility = View.GONE
}
else{
switchChallengeReceived.visibility = View.VISIBLE
switchChallengeReceived.isChecked = challengeReceivedNotification
}
var switchFriendRequest: Switch = view.findViewById<View>(R.id.switchFriendRequest) as Switch
if (!anyNotification) {
switchFriendRequest.isChecked = false
switchFriendRequest.visibility = View.GONE
}
else{
switchFriendRequest.visibility = View.VISIBLE
switchFriendRequest.isChecked = friendsRequestNotification
}
var switchChallengeEnds: Switch = view.findViewById<View>(R.id.switchChallengeEnds) as Switch
if (!anyNotification) {
switchChallengeEnds.isChecked = false
switchChallengeEnds.visibility = View.GONE
}
else{
switchChallengeEnds.visibility = View.VISIBLE
switchChallengeEnds.isChecked = challengeEndsNotification
}
var saveButton: Button = view.findViewById<View>(R.id.save) as Button
var cancelButton: Button = view.findViewById<View>(R.id.cancel) as Button
switchNotifications.setOnCheckedChangeListener { _, isChecked ->
anyNotification = isChecked
if (!isChecked){
switchFriendRequest.isChecked = false
switchChallengeReceived.isChecked = false
switchChallengeEnds.isChecked = false
challengeReceivedNotification = false
friendsRequestNotification = false
challengeEndsNotification = false
switchFriendRequest.visibility = View.GONE
switchChallengeReceived.visibility = View.GONE
switchChallengeEnds.visibility = View.GONE
}
else{
switchFriendRequest.visibility = View.VISIBLE
switchChallengeReceived.visibility = View.VISIBLE
switchChallengeEnds.visibility = View.VISIBLE
}
}
switchChallengeReceived.setOnCheckedChangeListener { _, isChecked ->
challengeReceivedNotification = isChecked
}
switchFriendRequest.setOnCheckedChangeListener { _, isChecked ->
friendsRequestNotification = isChecked
}
switchChallengeEnds.setOnCheckedChangeListener { _, isChecked ->
challengeEndsNotification = isChecked
}
saveButton.setOnClickListener {
editor.putBoolean("anyNotification", anyNotification)
editor.putBoolean("challengeReceivedNotification", challengeReceivedNotification)
editor.putBoolean("friendsRequestNotification", friendsRequestNotification)
editor.putBoolean("challengeEndsNotification", challengeEndsNotification)
editor.apply()
requireActivity().supportFragmentManager.popBackStack()
}
cancelButton.setOnClickListener {
requireActivity().supportFragmentManager.popBackStack();
}
}
}
| tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/NotificationSettingsFragment.kt | 837810441 |
package com.jolufeja.tudas
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.jolufeja.tudas.adapters.RecycleViewAdapter
import com.jolufeja.tudas.data.ListItem
import com.jolufeja.tudas.data.RankingGroupsItem
import java.util.ArrayList
class RankingsGroupsFragment : Fragment(R.layout.fragment_rankings_groups) {
private var mRecyclerView: RecyclerView? = null
private var mAdapter: RecyclerView.Adapter<*>? = null
private var listOfGroups: ArrayList<RankingGroupsItem> = ArrayList()
private var finalList: ArrayList<ListItem> = ArrayList()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// Button create group
var createGroupButton: Button = view.findViewById<View>(R.id.create_group_button) as Button
//adding items in list
for (i in 0..20) {
val group = RankingGroupsItem()
group.id = i
group.name = "Group Don"
group.size = 12
listOfGroups.add(group)
}
listOfGroups.forEach {
finalList.add(it)
}
mRecyclerView = view.findViewById(R.id.group_recycler_view)
var mLayoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
mRecyclerView!!.layoutManager = mLayoutManager
// Add Adapter so cards will be displayed
mAdapter =
context?.let {
RecycleViewAdapter(
it,
finalList,
0,
0,
0,
0,
R.layout.card_rankings_groups,
0,
0
) { item ->
// Open New Fragment
val rankingsGroupFragment = RankingsGroupFragment()
val transaction: FragmentTransaction =
requireActivity().supportFragmentManager.beginTransaction()
transaction.replace(
((view as ViewGroup).parent as View).id,
rankingsGroupFragment
)
transaction.addToBackStack("ranking_group_fragment")
transaction.commit()
item.id.let { Log.d("TAG", item. toString()) }
}
}
mRecyclerView!!.adapter = mAdapter
// Listener for Back Button to close fragment
createGroupButton.setOnClickListener {
// Open New Fragment
val createGroupFragment = CreateGroupFragment()
val transaction: FragmentTransaction =
requireActivity().supportFragmentManager.beginTransaction()
transaction.replace(
((view as ViewGroup).parent as View).id,
createGroupFragment
)
transaction.addToBackStack("create group")
transaction.commit()
}
}
} | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/RankingsGroupsFragment.kt | 902920246 |
package com.jolufeja.tudas
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.jolufeja.tudas.service.challenges.Challenge
import kotlinx.coroutines.channels.Channel
class IndividualChallengeReceivedViewModel(private val challenge: Challenge) : ViewModel() {
val name = MutableLiveData(challenge.name)
val creator = MutableLiveData(challenge.creator)
val creationDate = MutableLiveData(challenge.creationDate)
val description = MutableLiveData(challenge.description)
val dueDate = MutableLiveData(challenge.dueDate)
val reward = MutableLiveData(challenge.reward)
val worth = MutableLiveData(challenge.worth)
val addressedTo = MutableLiveData(challenge.addressedTo)
val completeChallenge: Channel<Challenge> = Channel()
fun completeChallenge() {
Log.d("IndividualChallengeReceivedViewModel", name.value.toString())
completeChallenge.trySend(challenge)
}
} | tudas-app/tudas-app/app/src/main/java/com/jolufeja/tudas/IndividualChallengeReceivedViewModel.kt | 879038442 |
package com.jolufeja.navigation
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.jolufeja.navigation.test", appContext.packageName)
}
} | tudas-app/tudas-app/lib/navigation/src/androidTest/java/com/jolufeja/navigation/ExampleInstrumentedTest.kt | 551312814 |
package com.jolufeja.navigation
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)
}
} | tudas-app/tudas-app/lib/navigation/src/test/java/com/jolufeja/navigation/ExampleUnitTest.kt | 3743828222 |
package com.jolufeja.navigation
interface NavigationEvent | tudas-app/tudas-app/lib/navigation/src/main/java/com/jolufeja/navigation/NavigationEvent.kt | 1792761203 |
package com.jolufeja.navigation
import org.koin.dsl.bind
import org.koin.dsl.module
object EventDrivenNavigationModule {
val module = module {
single { DefaultNavigationEventBus() }
.bind<NavigationEventBus>()
.bind<NavigationEventPublisher>()
}
val withDependencies
get() = setOf(module)
} | tudas-app/tudas-app/lib/navigation/src/main/java/com/jolufeja/navigation/EventDrivenNavigationModule.kt | 854947986 |
package com.jolufeja.navigation
import android.os.Bundle
import androidx.annotation.IdRes
import androidx.navigation.NavController
import androidx.navigation.NavOptions
fun eventDrivenNavigation(
navController: NavController,
spec: EventDrivenNavigationBuilder.() -> Unit
): (NavigationEvent) -> Unit = EventDrivenNavigationBuilderImpl(navController)
.apply(spec)
.build()
@DslMarker
annotation class EventDrivenNavigationDsl
@EventDrivenNavigationDsl
interface EventDrivenNavigationBuilder {
fun register(
event: NavigationEvent,
@IdRes actionId: Int,
options: NavOptions? = null,
args: Bundle = Bundle.EMPTY
)
fun register(
event: NavigationEvent,
@IdRes actionId: Int,
options: NavOptions? = null,
argsSpec: Bundle.() -> Unit
)
fun <T : NavigationEvent> register(
eventType: Class<T>,
@IdRes actionId: Int,
options: NavOptions? = null,
argsSpec: Bundle.(T) -> Unit
)
fun register(event: NavigationEvent, action: NavController.() -> Unit)
fun <T : NavigationEvent> register(eventType: Class<T>, action: NavController.(T) -> Unit)
}
inline fun <reified T : NavigationEvent> EventDrivenNavigationBuilder.register(
@IdRes actionId: Int,
options: NavOptions? = null,
noinline argsSpec: Bundle.(T) -> Unit
) = register(T::class.java, actionId, options, argsSpec)
inline fun <reified T : NavigationEvent> EventDrivenNavigationBuilder.register(
noinline action: NavController.(T) -> Unit
) = register(T::class.java, action)
private class EventDrivenNavigationBuilderImpl(
private val navController: NavController
) : EventDrivenNavigationBuilder {
private val navActionsByInstance =
mutableMapOf<NavigationEvent, (NavController) -> Unit>()
private val navActionsByType =
mutableMapOf<Class<out NavigationEvent>, (NavController, NavigationEvent) -> Unit>()
override fun register(event: NavigationEvent, actionId: Int, options: NavOptions?, args: Bundle) {
navActionsByInstance[event] = { navController ->
navController.navigate(actionId, args, options)
}
}
override fun register(event: NavigationEvent, actionId: Int, options: NavOptions?, argsSpec: Bundle.() -> Unit) {
navActionsByInstance[event] = { navController ->
navController.navigate(
actionId,
Bundle().apply(argsSpec),
options
)
}
}
override fun <T : NavigationEvent> register(
eventType: Class<T>,
actionId: Int,
options: NavOptions?,
argsSpec: Bundle.(T) -> Unit
) {
navActionsByType[eventType] = { navController, navigationEvent ->
val args = Bundle().apply {
@Suppress("UNCHECKED_CAST")
argsSpec(navigationEvent as T)
}
navController.navigate(actionId, args, options)
}
}
override fun register(event: NavigationEvent, action: NavController.() -> Unit) {
navActionsByInstance[event] = action
}
override fun <T : NavigationEvent> register(eventType: Class<T>, action: NavController.(T) -> Unit) {
@Suppress("UNCHECKED_CAST")
navActionsByType[eventType] = action as (NavController, NavigationEvent) -> Unit
}
fun build() = NavControllerNavigator(
navController,
navActionsByInstance.toMap(),
navActionsByType.toMap()
)
}
| tudas-app/tudas-app/lib/navigation/src/main/java/com/jolufeja/navigation/EventDrivenNavigation.kt | 2421365778 |
package com.jolufeja.navigation
import android.util.Log
import kotlinx.coroutines.flow.*
interface NavigationEventPublisher {
fun publish(event: NavigationEvent)
}
interface NavigationEventBus {
fun asFlow(): Flow<NavigationEvent>
suspend fun subscribe(subscriber: suspend (NavigationEvent) -> Unit) =
asFlow().collect(subscriber)
}
internal class DefaultNavigationEventBus : NavigationEventBus, NavigationEventPublisher {
private val _sharedFlow = MutableSharedFlow<NavigationEvent>(10)
override fun asFlow(): Flow<NavigationEvent> =
_sharedFlow.asSharedFlow()
override fun publish(event: NavigationEvent) {
_sharedFlow.tryEmit(event)
}
} | tudas-app/tudas-app/lib/navigation/src/main/java/com/jolufeja/navigation/NavigationEventBus.kt | 2244545507 |
package com.jolufeja.navigation
import android.util.Log
import androidx.navigation.NavController
internal class NavControllerNavigator(
private val navController: NavController,
private val navActionsByInstance: Map<NavigationEvent, (NavController) -> Unit>,
private val navActionsByType: Map<Class<out NavigationEvent>, (NavController, NavigationEvent) -> Unit>
) : (NavigationEvent) -> Unit {
override fun invoke(event: NavigationEvent) {
navActionsByInstance[event]?.invoke(navController)
?: navActionsByType[event.javaClass]?.invoke(navController, event)
?: run { return }
}
} | tudas-app/tudas-app/lib/navigation/src/main/java/com/jolufeja/navigation/NavControllerNavigator.kt | 3611516870 |
package com.jolufeja.httpclient
internal class InterceptingHttpRequestExecutor(
delegate: HttpRequestExecutor,
interceptors: List<HttpInterceptor>
) : HttpRequestExecutor {
private class DelegateChain(
private val delegate: HttpRequestExecutor
) : HttpInterceptor.Chain {
override suspend fun proceed(request: HttpClientRequest): HttpClientResponse =
delegate.execute(request)
}
private class InterceptingChain(
private val interceptor: HttpInterceptor,
private val next: HttpInterceptor.Chain
) : HttpInterceptor.Chain {
override suspend fun proceed(request: HttpClientRequest): HttpClientResponse =
interceptor.intercept(request, next)
}
private val chain: HttpInterceptor.Chain =
interceptors.fold(DelegateChain(delegate) as HttpInterceptor.Chain) { chain, interceptor ->
InterceptingChain(interceptor, chain)
}
override suspend fun execute(request: HttpClientRequest): HttpClientResponse =
chain.proceed(request)
} | tudas-app/tudas-app/lib/http-client/src/main/kotlin/com/jolufeja/httpclient/InterceptingHttpRequestExecutor.kt | 2001222862 |
package com.jolufeja.httpclient
import com.fasterxml.jackson.databind.ObjectMapper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.*
import java.io.InputStream
fun interface HttpRequestExecutor {
suspend fun execute(request: HttpClientRequest): HttpClientResponse
}
internal class OkHttpRequestExecutor(
private val callFactory: Call.Factory,
private val objectMapper: ObjectMapper
) : HttpRequestExecutor {
override suspend fun execute(request: HttpClientRequest): HttpClientResponse =
callFactory.newCall(request.toOkHttpRequest())
.await()
.let { response ->
OkHttpClientResponse(response, objectMapper)
}
private fun HttpClientRequest.toOkHttpRequest(): Request =
Request.Builder().run {
url(url)
method(method, body)
headers(headers)
build()
}
}
private class OkHttpClientResponse(
private val response: Response,
private val objectMapper: ObjectMapper
) : HttpClientResponse {
override val statusCode: Int
get() = response.code
override val statusReason: String
get() = response.message
override val headers: Headers
get() = response.headers
override val body: ResponseBody?
get() = response.body
override suspend fun <T : Any> awaitReadBodyOrNull(reader: (InputStream) -> T): T? =
body?.let { body ->
withContext(Dispatchers.IO) {
body.byteStream().use(reader)
}
}
override suspend fun <T : Any> awaitJsonBodyOrNull(payloadType: JsonTypeSupplier<T>): T? =
awaitReadBodyOrNull { input ->
objectMapper.readValue(input, objectMapper.typeFactory.let(payloadType)) as T
}
}
| tudas-app/tudas-app/lib/http-client/src/main/kotlin/com/jolufeja/httpclient/HttpRequestExecutor.kt | 4171481913 |
package com.jolufeja.httpclient
import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.ObjectMapper
import okhttp3.Response
import java.io.InputStream
fun <T> Response.readBody(reader: (InputStream) -> T): T? =
body?.byteStream()?.use { input ->
reader(input)
}
fun <T : Any> Response.jsonBody(objectMapper: ObjectMapper, type: Class<T>): T? =
readBody { input ->
objectMapper.readValue(input, type)
}
inline fun <reified T : Any> Response.jsonBody(objectMapper: ObjectMapper): T? =
jsonBody(objectMapper, T::class.java)
fun <T : Any> Response.jsonBody(objectMapper: ObjectMapper, type: TypeReference<T>): T? =
readBody { input ->
objectMapper.readerFor(type).readValue(input)
}
| tudas-app/tudas-app/lib/http-client/src/main/kotlin/com/jolufeja/httpclient/ResponseBodyHelpers.kt | 3140509281 |
package com.jolufeja.httpclient
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.suspendCancellableCoroutine
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import kotlin.coroutines.resumeWithException
@OptIn(ExperimentalCoroutinesApi::class)
suspend fun Call.await(): Response =
suspendCancellableCoroutine { continuation ->
continuation.invokeOnCancellation { cancel() }
enqueue(object : Callback {
override fun onResponse(call: Call, response: Response) {
continuation.resume(response) {}
}
override fun onFailure(call: Call, e: IOException) {
continuation.resumeWithException(e)
}
})
}
suspend fun Call.Factory.execute(request: Request): Response =
newCall(request).await() | tudas-app/tudas-app/lib/http-client/src/main/kotlin/com/jolufeja/httpclient/OkHttpExtensions.kt | 3544031611 |
package com.jolufeja.httpclient
import com.fasterxml.jackson.databind.ObjectMapper
import okhttp3.*
import okhttp3.HttpUrl.Companion.toHttpUrl
import java.net.URI
interface HttpClientRequest {
val method: String
val url: HttpUrl
val headers: Headers
val body: RequestBody?
fun cloneAsBuilder(): Builder
fun cloneWith(spec: Builder.() -> Unit): HttpClientRequest =
cloneAsBuilder().apply(spec).build()
suspend fun awaitExecute(): HttpClientResponse
interface Builder {
fun url(url: HttpUrl): Builder
fun url(link: URI) =
url(link.toString())
fun url(link: String): Builder
fun url(link: String?, spec: HttpUrl.Builder.() -> Unit): Builder
fun url(spec: (HttpUrl.Builder) -> Unit) =
url(null, spec)
fun headers(headers: Headers): Builder
fun headers(spec: (Headers.Builder) -> Unit): Builder
fun body(body: RequestBody?): Builder
fun jsonBody(payload: Any, contentType: MediaType = JsonRequestBody.DEFAULT_MEDIA_TYPE): Builder
fun jsonRequestBodyOf(payload: Any, contentType: MediaType = JsonRequestBody.DEFAULT_MEDIA_TYPE): RequestBody
fun formBody(spec: (FormBody.Builder) -> Unit): Builder =
body(FormBody.Builder().apply(spec).build())
fun build(): HttpClientRequest
suspend fun awaitExecute(): HttpClientResponse =
build().awaitExecute()
}
companion object {
fun builder(objectMapper: ObjectMapper, requestExecutor: HttpRequestExecutor, method: String): Builder =
DefaultHttpClientRequest.Builder(objectMapper, requestExecutor, method)
}
}
private class DefaultHttpClientRequest(
override val method: String,
override val url: HttpUrl,
override val headers: Headers,
override val body: RequestBody?,
private val objectMapper: ObjectMapper,
private val requestExecutor: HttpRequestExecutor
) : HttpClientRequest {
override suspend fun awaitExecute(): HttpClientResponse =
requestExecutor.execute(this)
override fun cloneAsBuilder(): HttpClientRequest.Builder =
Builder(objectMapper, requestExecutor, this)
class Builder private constructor(
private val objectMapper: ObjectMapper,
private val requestExecutor: HttpRequestExecutor,
val method: String,
var url: HttpUrl?,
var headers: Headers?,
var body: RequestBody?
) : HttpClientRequest.Builder {
private companion object {
val EmptyHeaders = Headers.headersOf()
}
internal constructor(
objectMapper: ObjectMapper, requestExecutor: HttpRequestExecutor, request: HttpClientRequest
) : this(objectMapper, requestExecutor, request.method, request.url, request.headers, request.body)
internal constructor(objectMapper: ObjectMapper, requestExecutor: HttpRequestExecutor, method: String = "GET")
: this(objectMapper, requestExecutor, method, null, null, null)
override fun url(url: HttpUrl) = apply {
this.url = url
}
override fun url(link: String) = url(
this.url?.resolve(link) ?: link.toHttpUrl()
)
override fun url(link: String?, spec: HttpUrl.Builder.() -> Unit) = run {
val urlBuilder = this.url
?.let {
if (link != null) it.newBuilder(link) else it.newBuilder()
}
?: link?.toHttpUrl()?.newBuilder()
?: HttpUrl.Builder()
url(urlBuilder.apply(spec).build())
}
override fun headers(headers: Headers) = apply {
this.headers = headers
}
override fun headers(spec: Headers.Builder.() -> Unit) =
headers(
(headers?.newBuilder() ?: Headers.Builder()).apply(spec).build()
)
override fun body(body: RequestBody?) = apply {
this.body = body
}
override fun jsonBody(payload: Any, contentType: MediaType) = body(
JsonRequestBody(payload, objectMapper, contentType)
)
override fun jsonRequestBodyOf(payload: Any, contentType: MediaType): RequestBody =
JsonRequestBody(payload, objectMapper, contentType)
override fun build(): HttpClientRequest =
DefaultHttpClientRequest(
method = method,
url = checkNotNull(url) { "Request URL must be set" },
headers = headers ?: EmptyHeaders,
body = body,
objectMapper = objectMapper,
requestExecutor = requestExecutor
)
}
}
| tudas-app/tudas-app/lib/http-client/src/main/kotlin/com/jolufeja/httpclient/HttpClientRequest.kt | 3612125331 |
package com.jolufeja.httpclient
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import okhttp3.Call
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
internal typealias UrlSupplier = () -> HttpUrl
interface HttpClient : RequestBuilderFactory, HttpRequestExecutor {
companion object {
fun builder(): Builder =
DefaultHttpClient.Builder()
}
interface Builder {
fun baseUrl(urlProvider: UrlSupplier): Builder
fun okHttpRequestExecutor(callFactory: Call.Factory): Builder
fun objectMapper(mapper: ObjectMapper): Builder
fun addInterceptor(interceptor: HttpInterceptor): Builder
fun build(): HttpClient
}
}
private class DefaultHttpClient(
private val requestBuilderFactory: RequestBuilderFactory,
private val requestExecutor: HttpRequestExecutor
) : HttpClient, RequestBuilderFactory by requestBuilderFactory, HttpRequestExecutor by requestExecutor {
class Builder : HttpClient.Builder {
private var objectMapper: ObjectMapper? = null
private var baseUrlProvider: UrlSupplier? = null
private var callFactory: Call.Factory? = null
private val interceptors = mutableListOf<HttpInterceptor>()
override fun baseUrl(urlProvider: UrlSupplier) = apply {
this.baseUrlProvider = urlProvider
}
override fun okHttpRequestExecutor(callFactory: Call.Factory) = apply {
this.callFactory = callFactory
}
override fun objectMapper(mapper: ObjectMapper) = apply {
this.objectMapper = mapper
}
override fun addInterceptor(interceptor: HttpInterceptor): HttpClient.Builder = apply {
interceptors.add(interceptor)
}
override fun build(): HttpClient {
val objectMapper = this.objectMapper ?: jacksonObjectMapper()
val requestExecutor = OkHttpRequestExecutor(
callFactory = callFactory ?: OkHttpClient(),
objectMapper = objectMapper
).run {
if (interceptors.isNotEmpty()) {
InterceptingHttpRequestExecutor(this, interceptors)
} else this
}
val requestBuilderFactory = DefaultRequestBuilderFactory(objectMapper, requestExecutor)
.run {
baseUrlProvider?.let { BaseUrlAwareRequestBuilderFactory(this, it) } ?: this
}
return DefaultHttpClient(requestBuilderFactory, requestExecutor)
}
}
} | tudas-app/tudas-app/lib/http-client/src/main/kotlin/com/jolufeja/httpclient/HttpClient.kt | 3395359452 |
package com.jolufeja.httpclient
import com.fasterxml.jackson.databind.ObjectMapper
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.OkHttpClient
import org.koin.core.qualifier.named
import org.koin.dsl.module
fun provideUrl(): String = "http://10.0.2.2:3000/"
object HttpClientModule {
private val module = module {
single {
OkHttpClient.Builder()
.retryOnConnectionFailure(true)
.build()
}
single(qualifier = named("baseUrl")) {
{ provideUrl().toHttpUrlOrNull()!! }
}
factory {
HttpClient.builder()
.baseUrl(get(qualifier = named("baseUrl")))
.okHttpRequestExecutor(get<OkHttpClient>())
.objectMapper(get())
}
single {
get<HttpClient.Builder>()
.build()
}
single {
ObjectMapper()
.findAndRegisterModules()
}
}
val withDependencies
get() = setOf(module)
} | tudas-app/tudas-app/lib/http-client/src/main/kotlin/com/jolufeja/httpclient/HttpClientModule.kt | 2036697832 |
package com.jolufeja.httpclient
import okhttp3.Headers
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.Request
import okhttp3.RequestBody
import java.net.URI
interface RequestBuilder {
fun method(method: String, body: RequestBody? = null): RequestBuilder
fun get() = method("GET")
fun head() = method("HEAD")
fun post(body: RequestBody? = null) = method("POST", body)
fun put(body: RequestBody? = null) = method("PUT", body)
fun delete(body: RequestBody? = null) = method("DELETE", body)
fun url(url: HttpUrl): RequestBuilder
fun url(link: String): RequestBuilder
fun url(link: String?, spec: HttpUrl.Builder.() -> Unit): RequestBuilder
fun url(spec: HttpUrl.Builder.() -> Unit) = url(null, spec)
fun url(url: URI) =
url(url.toString())
fun headers(headers: Headers): RequestBuilder
fun headers(spec: Headers.Builder.() -> Unit): RequestBuilder
fun build(): Request
}
@Suppress("FunctionName")
fun RequestBuilder(): RequestBuilder = DefaultRequestBuilder()
private class DefaultRequestBuilder : RequestBuilder {
private var method: String = "GET"
private var url: HttpUrl? = null
private var headers: Headers? = null
private var body: RequestBody? = null
override fun method(method: String, body: RequestBody?) = apply {
this.method = method
this.body = body
}
override fun url(url: HttpUrl) = apply {
this.url = url
}
override fun url(link: String) = url(
this.url?.resolve(link) ?: link.toHttpUrl()
)
override fun url(link: String?, spec: HttpUrl.Builder.() -> Unit) = run {
val urlBuilder = this.url
?.let {
if (link != null) it.newBuilder(link) else it.newBuilder()
}
?: link?.toHttpUrl()?.newBuilder()
?: HttpUrl.Builder()
url(urlBuilder.apply(spec).build())
}
override fun headers(headers: Headers) = apply {
this.headers = headers
}
override fun headers(spec: Headers.Builder.() -> Unit) =
headers(
(headers?.newBuilder() ?: Headers.Builder()).apply(spec).build()
)
override fun build(): Request =
Request.Builder().run {
method(method, body)
url(checkNotNull(url) { "url is not set" })
headers?.let { headers(it) }
build()
}
}
| tudas-app/tudas-app/lib/http-client/src/main/kotlin/com/jolufeja/httpclient/RequestBuilder.kt | 256300055 |
package com.jolufeja.httpclient
import com.fasterxml.jackson.databind.ObjectMapper
interface RequestBuilderFactory {
fun request(method: String): HttpClientRequest.Builder
fun get() = request("GET")
fun get(url: String) = get().url(url)
fun head() = request("HEAD")
fun head(url: String) = head().url(url)
fun post() = request("POST")
fun post(url: String) = post().url(url)
fun put() = request("PUT")
fun put(url: String) = put().url(url)
fun delete() = request("DELETE")
fun delete(url: String) = delete().url(url)
}
internal class DefaultRequestBuilderFactory(
private val objectMapper: ObjectMapper,
private val requestExecutor: HttpRequestExecutor
) : RequestBuilderFactory {
override fun request(method: String): HttpClientRequest.Builder =
HttpClientRequest.builder(objectMapper, requestExecutor, method)
} | tudas-app/tudas-app/lib/http-client/src/main/kotlin/com/jolufeja/httpclient/RequestBuilderFactory.kt | 2061072466 |
package com.jolufeja.httpclient
import com.fasterxml.jackson.databind.ObjectMapper
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody
import okio.Buffer
import okio.BufferedSink
class JsonRequestBody(
private val payload: Any,
private val objectMapper: ObjectMapper,
private val contentType: MediaType = DEFAULT_MEDIA_TYPE
) : RequestBody() {
companion object {
val DEFAULT_MEDIA_TYPE: MediaType = "application/json;charset=UTF-8".toMediaType()
}
private val jsonData: Buffer by lazy(LazyThreadSafetyMode.NONE) {
Buffer().also { buffer ->
buffer.outputStream().use { output ->
objectMapper.writeValue(output, payload)
}
}
}
override fun contentType(): MediaType =
this.contentType
override fun contentLength(): Long =
jsonData.size
override fun writeTo(sink: BufferedSink) {
jsonData.use { jsonData ->
sink.outputStream().use { output ->
jsonData.writeTo(output)
}
}
}
} | tudas-app/tudas-app/lib/http-client/src/main/kotlin/com/jolufeja/httpclient/JsonRequestBody.kt | 4110896785 |
package com.jolufeja.httpclient
import okhttp3.Headers
import okhttp3.ResponseBody
import java.io.InputStream
interface HttpClientResponse {
val statusCode: Int
val statusReason: String
val headers: Headers
val body: ResponseBody?
suspend fun <T : Any> awaitReadBodyOrNull(reader: (InputStream) -> T): T?
suspend fun <T : Any> awaitReadBody(reader: (InputStream) -> T): T =
awaitReadBodyOrNull(reader) ?: throw MissingResponseBodyException()
suspend fun <T : Any> awaitJsonBodyOrNull(payloadType: JsonTypeSupplier<T>): T?
suspend fun <T : Any> awaitJsonBody(payloadType: JsonTypeSupplier<T>): T =
awaitJsonBodyOrNull(payloadType) ?: throw MissingResponseBodyException()
}
suspend inline fun <reified T : Any> HttpClientResponse.awaitJsonBodyOrNull(): T? =
awaitJsonBodyOrNull(jsonTypeOf<T>())
suspend inline fun <reified T : Any> HttpClientResponse.awaitJsonBody(): T =
awaitJsonBody(jsonTypeOf<T>()) | tudas-app/tudas-app/lib/http-client/src/main/kotlin/com/jolufeja/httpclient/HttpClientResponse.kt | 76271840 |
package com.jolufeja.httpclient.error
data class ErrorBody(val msg: String) | tudas-app/tudas-app/lib/http-client/src/main/kotlin/com/jolufeja/httpclient/error/ErrorBody.kt | 1328737570 |
package com.jolufeja.httpclient.error
import arrow.core.Either
import arrow.core.flatMap
import arrow.core.left
import arrow.core.right
import com.jolufeja.httpclient.HttpClientRequest
import com.jolufeja.httpclient.HttpClientResponse
import com.jolufeja.httpclient.awaitJsonBody
import com.jolufeja.httpclient.awaitJsonBodyOrNull
typealias Result<T> = Either<CommonErrors, T>
typealias ErrorConstructor = (String) -> CommonErrors
fun interface ErrorHandler<E> : (Throwable) -> E {
override operator fun invoke(err: Throwable): E
}
interface MapDomain<T, E> : ErrorHandler<E> {
suspend fun T.toDomain(): Either<E, T>
}
suspend fun HttpClientResponse.readErrorBody(ctor: ErrorConstructor): CommonErrors =
awaitJsonBodyOrNull<ErrorBody>()?.let { err ->
ctor(err.msg)
}
?: CommonErrors.GenericError("Response body is empty - can't construct specific error instance.")
val HttpErrorHandler = ErrorHandler<CommonErrors>(CommonErrors::GenericError)
internal object HttpMapDomain :
MapDomain<HttpClientResponse, CommonErrors>,
ErrorHandler<CommonErrors> by HttpErrorHandler {
override suspend fun HttpClientResponse.toDomain(): Either<CommonErrors, HttpClientResponse> =
when (statusCode) {
in 500..600 -> CommonErrors.InternalServerError(body?.string() ?: "Internal server error").left()
in 400..410 -> try {
readErrorBody(CommonErrors::BadRequest)
} catch (err: Throwable) {
CommonErrors.GenericError("Request failed with $statusCode, but cant read error body. ${body?.string()}")
}.left()
in 200..305 -> this.right()
else -> CommonErrors.GenericError("Request successful, but response has unrecognisable status code. ${body?.string()}")
.left()
}
}
suspend fun HttpClientRequest.tryExecute(): Either<CommonErrors, HttpClientResponse> =
with(CommonErrors.Companion) {
Either
.catch { awaitExecute() }
.mapLeft(this)
.flatMap { it.toDomain() }
}
suspend fun HttpClientRequest.Builder.tryExecute(): Either<CommonErrors, HttpClientResponse> =
build().tryExecute()
inline fun <T> catchError(fn: () -> T): Either<CommonErrors, T> =
Either.catch(fn).mapLeft(CommonErrors)
suspend inline fun <reified T : Any> Either<CommonErrors, HttpClientResponse>.awaitJsonBody() =
flatMap { response -> catchError { response.awaitJsonBody<T>() } }
suspend inline fun <reified T : Any> Either<CommonErrors, HttpClientResponse>.awaitJsonBodyOrNull(): Either<CommonErrors, T?> =
flatMap { response -> catchError { response.awaitJsonBodyOrNull<T>() } }
sealed interface CommonErrors {
companion object : MapDomain<HttpClientResponse, CommonErrors> by HttpMapDomain
val message: String
data class GenericError(override val message: String, val cause: Throwable? = null) :
CommonErrors {
constructor(message: String) : this(message, null)
constructor(error: Throwable) : this(error.message ?: "Unknown error.")
}
data class BadRequest(override val message: String) : CommonErrors
data class InternalServerError(override val message: String) : CommonErrors
}
| tudas-app/tudas-app/lib/http-client/src/main/kotlin/com/jolufeja/httpclient/error/CommonErrors.kt | 3827692811 |
package com.jolufeja.httpclient
internal class BaseUrlAwareRequestBuilderFactory(
private val delegate: RequestBuilderFactory,
private val baseUrlProvider: UrlSupplier
) : RequestBuilderFactory {
override fun request(method: String): HttpClientRequest.Builder =
delegate.request(method)
.url(baseUrlProvider())
}
| tudas-app/tudas-app/lib/http-client/src/main/kotlin/com/jolufeja/httpclient/BaseUrl.kt | 1983440343 |
package com.jolufeja.httpclient
import okhttp3.HttpUrl
import okhttp3.Request
fun httpRequest(spec: Request.Builder.() -> Unit): Request =
Request.Builder().apply(spec).build()
fun httpGet(spec: Request.Builder.() -> Unit): Request =
httpRequest { get(); spec() }
fun Request.cloneWith(spec: Request.Builder.() -> Unit): Request =
newBuilder().apply(spec).build()
fun Request.Builder.url(spec: HttpUrl.Builder.() -> Unit) {
val url = HttpUrl.Builder().apply(spec).build()
url(url)
} | tudas-app/tudas-app/lib/http-client/src/main/kotlin/com/jolufeja/httpclient/RequestBuilderExtensions.kt | 1874562897 |
package com.jolufeja.httpclient
class MissingResponseBodyException(
message: String = "Response body expected, but response did not have a body"
) : Exception(message) | tudas-app/tudas-app/lib/http-client/src/main/kotlin/com/jolufeja/httpclient/MissingResponseBodyException.kt | 3461574579 |
package com.jolufeja.httpclient
import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.JavaType
import com.fasterxml.jackson.databind.type.TypeFactory
typealias JsonTypeSupplier<@Suppress("unused", "UNUSED_TYPEALIAS_PARAMETER") T> =
(typeFactory: TypeFactory) -> JavaType
fun <T : Any> jsonTypeOf(clazz: Class<T>): JsonTypeSupplier<T> =
{ tf -> tf.constructType(clazz) }
fun <T : Any> jsonTypeOf(typeRef: TypeReference<T>): JsonTypeSupplier<T> =
{ tf -> tf.constructType(typeRef) }
inline fun <reified T : Any> jsonTypeOf(): JsonTypeSupplier<T> =
jsonTypeOf(T::class.java)
inline fun <reified T : Any> jsonTypeOfGeneric(): JsonTypeSupplier<T> =
jsonTypeOf(object : TypeReference<T>() {})
fun <T : Any> jsonListOf(elementType: Class<T>): JsonTypeSupplier<List<T>> =
{ tf -> tf.constructCollectionType(List::class.java, elementType) }
fun <T : Any> jsonListOf(elementTypeSupplier: JsonTypeSupplier<T>): JsonTypeSupplier<List<T>> =
{ tf -> tf.constructCollectionType(List::class.java, elementTypeSupplier(tf)) }
inline fun <reified T : Any> jsonListOf(): JsonTypeSupplier<List<T>> =
jsonListOf(T::class.java)
fun <K : Any, V : Any> jsonMapOf(keyType: Class<K>, valueType: Class<V>): JsonTypeSupplier<Map<K, V>> =
{ tf -> tf.constructMapType(Map::class.java, keyType, valueType) }
fun <K : Any, V : Any> jsonMapOf(
keyTypeSupplier: JsonTypeSupplier<K>, valueTypeSupplier: JsonTypeSupplier<V>
): JsonTypeSupplier<Map<K, V>> =
{ tf -> tf.constructMapType(Map::class.java, keyTypeSupplier(tf), valueTypeSupplier(tf)) }
fun <K : Any, V : Any> jsonMapOf(
keyType: Class<K>, valueTypeSupplier: JsonTypeSupplier<V>
): JsonTypeSupplier<Map<K, V>> =
{ tf -> tf.constructMapType(Map::class.java, tf.constructType(keyType), valueTypeSupplier(tf)) }
inline fun <reified K : Any, reified V : Any> jsonMapOf() =
jsonMapOf(K::class.java, V::class.java) | tudas-app/tudas-app/lib/http-client/src/main/kotlin/com/jolufeja/httpclient/JsonTypes.kt | 736321129 |
package com.jolufeja.httpclient
fun interface HttpInterceptor {
suspend fun intercept(request: HttpClientRequest, chain: Chain): HttpClientResponse
fun interface Chain {
suspend fun proceed(request: HttpClientRequest): HttpClientResponse
}
}
| tudas-app/tudas-app/lib/http-client/src/main/kotlin/com/jolufeja/httpclient/HttpInterceptor.kt | 3673165343 |
package com.jolufeja.authentication
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.jolufeja.authentication.test", appContext.packageName)
}
} | tudas-app/tudas-app/lib/authentication/src/androidTest/java/com/jolufeja/authentication/ExampleInstrumentedTest.kt | 3636517165 |
package com.jolufeja.authentication.registration
import arrow.core.Either
import com.jolufeja.authentication.AuthenticationStore
import com.jolufeja.authentication.AuthenticationTestModule
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.nulls.shouldNotBeNull
import io.kotest.matchers.types.shouldBeInstanceOf
import kotlinx.coroutines.runBlocking
import org.koin.test.KoinTest
import org.koin.test.inject
fun randomString() = java.util.UUID.randomUUID().toString()
class DefaultRegistrationServiceTest : FunSpec(), KoinTest {
private val registrationService: RegistrationService by inject()
private val authStore: AuthenticationStore by inject()
init {
AuthenticationTestModule.init()
test("User registration returns valid auth token for new user") {
runBlocking {
val result = registrationService.registerUser(
RegistrationCredentials(randomString(), randomString(), randomString())
)
when(result) {
is Either.Left -> println(result.value.toString())
}
result.shouldBeInstanceOf<Either.Right<Unit>>()
authStore.retrieve().shouldNotBeNull().let(::println)
}
}
}
}
| tudas-app/tudas-app/lib/authentication/src/test/java/com/jolufeja/authentication/registration/DefaultRegistrationServiceTest.kt | 736769812 |
package com.jolufeja.authentication
import io.kotest.assertions.throwables.shouldNotThrowAny
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.nulls.shouldBeNull
import kotlinx.coroutines.runBlocking
import org.koin.test.KoinTest
import org.koin.test.inject
class DefaultUserAuthenticationServiceTest : FunSpec(), KoinTest {
private val authService: UserAuthenticationService by inject()
private val authStore: AuthenticationStore by inject()
init {
AuthenticationTestModule.init()
test("login") { }
test("logout clears the AuthenticationStore and succeeds on empty") {
runBlocking {
shouldNotThrowAny { authStore.clear() }
shouldNotThrowAny { authStore.retrieve().shouldBeNull() }
}
}
test("authentication") { }
}
}
| tudas-app/tudas-app/lib/authentication/src/test/java/com/jolufeja/authentication/DefaultUserAuthenticationServiceTest.kt | 248055288 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.