Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions XiinderBackend/src/main/kotlin/com/example/Application.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import com.example.database.DatabaseFactory
import io.ktor.server.application.*
import io.ktor.server.netty.*
import com.example.plugins.*
import io.ktor.client.plugins.*
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.serialization.modules.SerializersModule
Expand All @@ -18,10 +19,12 @@ fun Application.module() {
{
json()
}

SerializersModule {
DateAsLongSerializer
}
DatabaseFactory.init(environment.config)
configureSecurity()
configureRouting()

}
26 changes: 26 additions & 0 deletions XiinderBackend/src/main/kotlin/com/example/CardService.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.example

import com.example.dao.CardsDAO
import com.example.dao.UserLoginInfoDAO
import com.example.models.Card
import com.example.plugins.CardItem
import com.example.plugins.User
import com.example.plugins.UserRegister
import com.example.repository.CardsRepository
import com.example.repository.UserLoginInfoRepository
import com.example.repository.UserRepository
import kotlinx.coroutines.runBlocking
import org.jetbrains.exposed.sql.transactions.transaction

class CardService {
private val cardRepository: CardsRepository = CardsDAO()
private val userRepository: UserLoginInfoRepository =UserLoginInfoDAO()
fun addCard(card: CardItem): Boolean {
transaction { Card.new { namee=card.namee;title=card.title;info=card.info;contact=card.contacts;image=card.image; } }
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я бы переименовал info, непонятно что значит

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

можно же тут вызывать add из CardRepository

return true
}
fun getCards(username: String): List<Card>?
{
return cardRepository.getBunchOfCards(username)
}
}
23 changes: 23 additions & 0 deletions XiinderBackend/src/main/kotlin/com/example/dao/CardsDAO.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.example.dao

import com.example.models.Card
import com.example.models.cards
import com.example.models.User
import com.example.repository.CardsRepository

import org.jetbrains.exposed.sql.SqlExpressionBuilder.neq
import org.jetbrains.exposed.sql.select
import org.jetbrains.exposed.sql.selectAll
import org.jetbrains.exposed.sql.transactions.transaction

class CardsDAO:CardsRepository {
override fun add(card: Card)=
transaction {
Card.new { namee=card.namee;title=card.title;info=card.info;contact=card.contact;image=card.image; }
}

override fun getBunchOfCards(name: String)= transaction { cards
.select(cards.namee neq name)
.limit(10).let { Card.wrapRows(it) }.toList() }
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. кажется лучше лимит передавать через аргументы
  2. Почему именно по name сортируем, с названия метода не понятно, даже если метод смотреть непонятно?


}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.example.database

import com.example.models.UserLoginInfos
import com.example.models.Users
import com.example.models.cards
import io.ktor.server.config.*
import kotlinx.coroutines.Dispatchers
import org.jetbrains.exposed.sql.*
Expand All @@ -18,6 +19,7 @@ object DatabaseFactory {
transaction(database) {
SchemaUtils.create(Users)
SchemaUtils.create(UserLoginInfos)
SchemaUtils.create(cards)
}
}

Expand Down
27 changes: 27 additions & 0 deletions XiinderBackend/src/main/kotlin/com/example/models/Card.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.example.models

import io.ktor.server.util.*
import org.jetbrains.exposed.dao.IntEntity
import org.jetbrains.exposed.dao.IntEntityClass
import org.jetbrains.exposed.dao.id.EntityID
import org.jetbrains.exposed.dao.id.IntIdTable


class Card(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<Card>(cards)
var namee by cards.namee
var title by cards.title
var info by cards.info
var contact by cards.contact
var image by cards.image


}
object cards : IntIdTable() {
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

С большой буквы Cards

val namee = varchar("namee", 40)
val title = varchar("title", 40)
val info = varchar("info",250)
val image= varchar("image",500)
val contact = varchar("telegram", 50)

}
22 changes: 22 additions & 0 deletions XiinderBackend/src/main/kotlin/com/example/plugins/Routing.kt
Original file line number Diff line number Diff line change
@@ -1,14 +1,22 @@
package com.example.plugins

import com.example.CardService
import com.example.dao.CardsDAO
import io.ktor.server.routing.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import kotlinx.serialization.Serializable


@Serializable
data class CardItem(val namee:String,val title:String, val info:String, val contacts:String, val image:String)
fun Application.configureRouting() {
routing {
authorizedRouting()
unauthorizedRouting()
cardsRouting()
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

роутинг надо в один из двух пихать, либо в авторизованные, либо не в авторизованные, скорее в первое

}
}

Expand All @@ -25,4 +33,18 @@ fun Route.unauthorizedRouting() {
call.respondText("Hello, world!")
}
}
fun Route.cardsRouting()
{
get("/get_cards")
{
val cards=CardService().getCards(call.receiveText())
if (cards != null) {
call.respond(cards.map {CardItem(it.namee,it.title,it.info,it.contact,it.image) })
}
}
post("/add_card") {
val cardItem=call.receive<CardItem>()
CardService().addCard(cardItem)
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.serialization.Serializable
import kotlinx.serialization.UseSerializers

import java.time.LocalDate
import java.util.*

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.example.repository

import com.example.models.Card
import com.example.models.User


interface CardsRepository {
fun add(card: Card) : Card
fun getBunchOfCards(name: String):List<Card>
}
Binary file added XiinderFront/Screenshot_20230201_141629.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
6 changes: 6 additions & 0 deletions XiinderFront/app/src/main/java/com/example/xiinder/Card.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package com.example.xiinder

import kotlinx.serialization.Serializable

@Serializable
data class Card(val namee:String, val title:String, val info:String, val contacts:String, val image:String)
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

может просто name а не namee? и что такое имя карточки, может лучше title, если это про заголовок

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Видимо не заголовок, непонятно в общем

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Username имелся в виду, все исправлю

Original file line number Diff line number Diff line change
@@ -1,18 +1,49 @@
package com.example.xiinder

import android.widget.Toast
import androidx.core.content.ContentProviderCompat.requireContext
import androidx.lifecycle.ViewModel
import com.example.xiinder.network.CardInfo
import com.example.xiinder.network.ProfileInfo
import io.ktor.client.call.*
import io.ktor.client.plugins.*
import io.ktor.client.request.*
import io.ktor.client.utils.EmptyContent.contentType
import io.ktor.http.*
import kotlinx.coroutines.coroutineScope

class DataSetForCards {
fun loadCards():Map<Int, CardInfo>
suspend fun loadCards(viewModel:SharedViewModel):Map<Int, CardInfo>
{
return hashMapOf(
0 to CardInfo(0,1,"Ищу сокомандника на icpc", "Let's go drink",R.drawable.mobile_01),
1 to CardInfo(1,2,"Помогите с задачей по матанализу", "Let's go study",R.drawable.mobile_02),
2 to CardInfo(2,3,"Продаю операционные системы Танненбаума", "Let's go sing",R.drawable.mobile_03),
3 to CardInfo(3,4,"Нужен человек, знающий js, для работы в проекте", "Let's go swim",R.drawable.mobile_04),
4 to CardInfo(4,5,"Придумайте заголовки за меня", "Let's go eat",R.drawable.mobile_05),
5 to CardInfo(5,6,"Ваше такси до Верхней Пышмы", "Let's go",R.drawable.mobile_06)
)
val message = viewModel.client.get("http://192.168.0.10:8888/get_cards"){ // or your data class
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

вынеси это(ip:port) куда нибудь в константу, или в conf файл, если еще нет, не надо дублировать

contentType(ContentType.Application.Json)
setBody(viewModel.getUsername())
timeout { requestTimeoutMillis=10000 }
}
when (message.status.value)
{
200->
{
var a=message.body<List<Card>>()
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

называй одинаковые модели которые гуляют по хттп одинаково, что на бэке то и на фронте

print(a)
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

зачем принт, ненужное убираем

a.map { CardInfo(0,1,it.title,it.info,R.drawable.mobile_01) }
return a.associate { a.indexOf(it) to CardInfo(0, 1, it.title, it.info, R.drawable.mobile_01) }
// return hashMapOf(
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

удали закоменченное, оно же не надо

// 0 to CardInfo(0,1,"Ищу сокомандника на icpc", "Let's go drink",R.drawable.mobile_01),
// 1 to CardInfo(1,2,"Помогите с задачей по матанализу", "Let's go study",R.drawable.mobile_02),
// 2 to CardInfo(2,3,"Продаю операционные системы Танненбаума", "Let's go sing",R.drawable.mobile_03),
// 3 to CardInfo(3,4,"Нужен человек, знающий js, для работы в проекте", "Let's go swim",R.drawable.mobile_04),
// 4 to CardInfo(4,5,"Придумайте заголовки за меня", "Let's go eat",R.drawable.mobile_05),
// 5 to CardInfo(5,6,"Ваше такси до Верхней Пышмы", "Let's go",R.drawable.mobile_06)

}
401->
{
return hashMapOf()
}
else ->{
Comment on lines +40 to +44
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

одно и то же

return hashMapOf()}
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package com.example.xiinder

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import androidx.activity.viewModels
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package com.example.xiinder
import androidx.lifecycle.ViewModel
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.engine.okhttp.*
import io.ktor.client.plugins.*
import io.ktor.client.plugins.auth.*
import io.ktor.client.plugins.auth.providers.*
import io.ktor.client.plugins.contentnegotiation.*
Expand All @@ -17,16 +19,23 @@ class SharedViewModel : ViewModel() {
install(ContentNegotiation) {
json()
}
install(HttpTimeout)
}
private lateinit var storeToken:StoreToken
fun setTokenStorage(storeToken: StoreToken)
private lateinit var userName:String
fun setTokenStorage(storeToken: StoreToken,username:String)
{
this.storeToken=storeToken
this.userName=username
}
suspend fun getToken(): String?
{
return storeToken.getToken()
}
suspend fun getUsername(): String?
{
return userName
}
fun configAuthClient(token:Token)
{
client.config { install(Auth)
Expand All @@ -40,7 +49,7 @@ class SharedViewModel : ViewModel() {
}
suspend fun clientCheck(token: Token)
{
client.get("http://192.168.0.101:8888/hello"){
client.get("http://192.168.0.10:8888/hello"){
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

в конфиги

bearerAuth(token.tokenData)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ class AuthFragment : Fragment() {
private suspend fun check(email:String, password:String):Boolean
{
val user= User(email,password)
val message = viewModel.client.post("http://192.168.0.104:8888/login"){ // or your data class
val message = viewModel.client.post("http://192.168.0.10:8888/login"){ // or your data class
contentType(ContentType.Application.Json)
setBody(user)
}
Expand All @@ -77,7 +77,7 @@ class AuthFragment : Fragment() {
val token= message.body<Map<String,String>>()["token"]?.let { Token(it) }
viewModel.configAuthClient(token!!)
coroutineScope { dataStore.saveToken(token.tokenData) }
viewModel.setTokenStorage(storeToken = dataStore)
viewModel.setTokenStorage(storeToken = dataStore, username = user.username)
return true
}
401->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,17 @@ import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.example.xiinder.DataSetForCards
import com.example.xiinder.SharedViewModel
import com.example.xiinder.databinding.FragmentCardDetailsBinding
import kotlinx.coroutines.launch

class CardDetailsFragment : Fragment() {
private val viewModel: SharedViewModel by activityViewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
Expand All @@ -20,17 +25,18 @@ class CardDetailsFragment : Fragment() {
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment

val args: CardDetailsFragmentArgs by navArgs()
val cardId = args.cardId
val currentCard = DataSetForCards().loadCards()[cardId]
val binding = FragmentCardDetailsBinding.inflate(layoutInflater)
val rootView = binding.root
lifecycleScope.launch{ val currentCard = DataSetForCards().loadCards(viewModel)[cardId]
if (currentCard != null) {
binding.CardImage.setImageResource(currentCard.imageId)
binding.CardInfo.text = currentCard.description
binding.CardTitle.text = currentCard.title
binding.executePendingBindings()
}
}}
return rootView
}
}
Loading