path
stringlengths 4
297
| contentHash
stringlengths 1
10
| content
stringlengths 0
13M
|
---|---|---|
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/interfaces/IWeatherView.kt | 3402014688 | package be.helmo.planivacances.presenter.interfaces
import be.helmo.planivacances.presenter.viewmodel.WeatherForecastVM
interface IWeatherView : IShowToast {
fun onForecastLoaded(weatherList: List<WeatherForecastVM>)
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/view/MainActivity.kt | 3236137920 | package be.helmo.planivacances.view
import android.content.Context
import android.os.Bundle
import android.view.Window
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import be.helmo.planivacances.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
this.supportRequestWindowFeature(Window.FEATURE_NO_TITLE)
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
}
/**
* Fonction qui cache le clavier
*/
fun hideKeyboard() {
val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
val currentFocus = currentFocus
if (currentFocus != null) {
inputMethodManager.hideSoftInputFromWindow(currentFocus.windowToken, 0)
}
}
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/view/fragments/home/GroupAdapter.kt | 2749820384 | package be.helmo.planivacances.view.fragments.home
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import be.helmo.planivacances.R
import be.helmo.planivacances.presenter.viewmodel.GroupListItemVM
import java.text.SimpleDateFormat
class GroupAdapter(val context: Context,
val groups: List<GroupListItemVM>,
val clickListener: (String) -> Unit) :
RecyclerView.Adapter<GroupAdapter.GroupViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GroupViewHolder {
val view = LayoutInflater
.from(parent.context)
.inflate(R.layout.group_item, parent, false)
return GroupViewHolder(view)
}
override fun onBindViewHolder(holder: GroupViewHolder, position: Int) {
val group = groups[position]
val formatter = SimpleDateFormat(context.getString(R.string.date_short_format))
val startDate = formatter.format(group.startDate)
val endDate = formatter.format(group.endDate)
holder.tvName.text = group.groupName
holder.tvDescription.text = group.description
holder.tvPeriod.text = "$startDate - $endDate"
// Set click listener to handle item clicks
holder.itemView.setOnClickListener { clickListener(group.gid!!) }
}
override fun getItemCount(): Int {
return groups.size
}
class GroupViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val tvName: TextView = itemView.findViewById(R.id.tvGroupItemName)
val tvDescription: TextView = itemView.findViewById(R.id.tvGroupItemDescription)
val tvPeriod: TextView = itemView.findViewById(R.id.tvGroupItemPeriod)
}
}
|
mobile-planivacances/app/src/main/java/be/helmo/planivacances/view/fragments/home/GroupInviteAdapter.kt | 122081815 | package be.helmo.planivacances.view.fragments.home
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import be.helmo.planivacances.R
import be.helmo.planivacances.presenter.viewmodel.GroupInvitationVM
class GroupInviteAdapter(val clickListener: (String,Boolean) -> Unit) : RecyclerView.Adapter<GroupInviteAdapter.ViewHolder>() {
val groupInvitationsList: MutableList<GroupInvitationVM> = mutableListOf()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view : View = LayoutInflater.from(parent.context).inflate(R.layout.group_invite_item,parent,false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return groupInvitationsList.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val groupInvitationVM: GroupInvitationVM = groupInvitationsList[position]
holder.bind(groupInvitationVM,clickListener)
}
fun clearInvitationsList() {
groupInvitationsList.clear()
notifyDataSetChanged()
}
fun addGroupInvitation(groupInvitation: GroupInvitationVM) {
groupInvitationsList.add(groupInvitation)
notifyItemInserted(groupInvitationsList.size - 1)
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val groupName: TextView = itemView.findViewById(R.id.tvGroupInviteTitle)
val content: TextView = itemView.findViewById(R.id.tvGroupInviteText)
val acceptBtn : ImageButton = itemView.findViewById(R.id.ibAcceptGroup)
val declineBtn : ImageButton = itemView.findViewById(R.id.ibDeclineGroup)
fun bind(groupInvitationVM: GroupInvitationVM, clickListener: (String,Boolean) -> Unit) {
groupName.text = groupInvitationVM.groupName
content.text = groupInvitationVM.content
acceptBtn.setOnClickListener {clickListener(groupInvitationVM.gid,true)}
declineBtn.setOnClickListener {clickListener(groupInvitationVM.gid,false)}
}
}
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/view/fragments/home/HomeFragment.kt | 2787075420 | package be.helmo.planivacances.view.fragments.home
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.addCallback
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import be.helmo.planivacances.R
import be.helmo.planivacances.databinding.FragmentHomeBinding
import be.helmo.planivacances.presenter.viewmodel.GroupListItemVM
import be.helmo.planivacances.factory.AppSingletonFactory
import be.helmo.planivacances.presenter.interfaces.IHomeView
import be.helmo.planivacances.presenter.viewmodel.GroupInvitationVM
import be.helmo.planivacances.view.interfaces.IGroupPresenter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
/**
* A simple [Fragment] subclass.
* Use the [HomeFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class HomeFragment : Fragment(), IHomeView {
lateinit var binding: FragmentHomeBinding
lateinit var groupPresenter: IGroupPresenter
lateinit var groupAdapter: GroupAdapter
lateinit var groupInviteAdapter: GroupInviteAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//prevent back button
requireActivity().onBackPressedDispatcher.addCallback(this) {}
groupPresenter = AppSingletonFactory.instance!!.getGroupPresenter(this)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
binding = FragmentHomeBinding.inflate(inflater, container,false)
initGroupInviteAdapter()
binding.addGroupBtn.setOnClickListener {
findNavController().navigate(R.id.action_homeFragment_to_createGroupFragment)
}
binding.notificationBtn.setOnClickListener {
if(binding.rvGroupInvites.visibility == View.GONE && groupInviteAdapter.itemCount > 0) {
binding.rvGroupInvites.visibility = View.VISIBLE
} else {
binding.rvGroupInvites.visibility = View.GONE
}
if(groupInviteAdapter.itemCount == 0) {
showToast("Aucune notification", 1)
}
}
binding.pbGroupList.visibility = View.VISIBLE
lifecycleScope.launch(Dispatchers.Default) {
groupPresenter.loadUserGroups()
}
return binding.root
}
override fun setGroupList(groups: List<GroupListItemVM>) {
MainScope().launch {
setGroupsAdapter(groups)
binding.pbGroupList.visibility = View.GONE
}
}
override fun onGroupInvitationsLoaded(invitations: List<GroupInvitationVM>) {
MainScope().launch {
groupInviteAdapter.clearInvitationsList()
for(invitation in invitations) {
groupInviteAdapter.addGroupInvitation(invitation)
}
if(invitations.isNotEmpty()) {
binding.notificationDot.visibility = View.VISIBLE
} else {
binding.notificationDot.visibility = View.GONE
}
}
}
override fun onGroupInvitationAccepted() {
MainScope().launch {
showToast("Invitation acceptée avec succès",1)
findNavController().navigate(R.id.homeFragment)
}
}
override fun onGroupInvitationDeclined() {
MainScope().launch {
showToast("Invitation refusée avec succès",1)
findNavController().navigate(R.id.homeFragment)
}
}
fun initGroupInviteAdapter() {
binding.rvGroupInvites.layoutManager = LinearLayoutManager(requireContext())
groupInviteAdapter = GroupInviteAdapter {gid,accepted ->
if(accepted) {
lifecycleScope.launch(Dispatchers.Default) {
groupPresenter.acceptGroupInvite(gid)
}
} else {
lifecycleScope.launch(Dispatchers.Default) {
groupPresenter.declineGroupInvite(gid)
}
}
}
binding.rvGroupInvites.adapter = groupInviteAdapter
lifecycleScope.launch(Dispatchers.Default) {
groupPresenter.loadUserGroupInvites()
}
}
fun setGroupsAdapter(groups : List<GroupListItemVM>) {
binding.rvGroups.layoutManager = LinearLayoutManager(requireContext())
groupAdapter = GroupAdapter(requireContext(), groups) { selectedGroupId ->
//selectionne le groupe
groupPresenter.setCurrentGroupId(selectedGroupId)
findNavController().navigate(R.id.action_homeFragment_to_groupFragment)
}
binding.rvGroups.adapter = groupAdapter
}
/**
* Affiche un message à l'écran
* @param message (String)
* @param length (Int) 0 = short, 1 = long
*/
override fun showToast(message: String, length: Int) {
MainScope().launch {
Toast.makeText(context, message, length).show()
}
}
companion object {
const val TAG = "HomeFragment"
fun newInstance(): HomeFragment {
return HomeFragment()
}
}
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/view/fragments/AuthFragment.kt | 903007799 | package be.helmo.planivacances.view.fragments
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import be.helmo.planivacances.BuildConfig
import be.helmo.planivacances.databinding.FragmentAuthBinding
import be.helmo.planivacances.R
import be.helmo.planivacances.factory.AppSingletonFactory
import be.helmo.planivacances.presenter.interfaces.IAuthView
import be.helmo.planivacances.view.MainActivity
import be.helmo.planivacances.view.interfaces.IAuthPresenter
import com.bumptech.glide.Glide
import com.bumptech.glide.load.MultiTransformation
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.ApiException
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.GoogleAuthProvider
import jp.wasabeef.glide.transformations.BlurTransformation
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
/**
* Fragment d'authentification (login et register)
*/
class AuthFragment : Fragment(), IAuthView {
lateinit var mAuth: FirebaseAuth
lateinit var signInLauncher: ActivityResultLauncher<Intent>
lateinit var binding : FragmentAuthBinding
var panelId : Int = 0
lateinit var authPresenter: IAuthPresenter
lateinit var sharedPreferences: SharedPreferences
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mAuth = FirebaseAuth.getInstance()
authPresenter = AppSingletonFactory.instance!!.getAuthPresenter(this)
sharedPreferences = requireContext().getSharedPreferences("PlanivacancesPreferences",
Context.MODE_PRIVATE)
authPresenter.setSharedPreference(sharedPreferences)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
binding = FragmentAuthBinding.inflate(inflater, container,false)
//Chargement du début : autoAuth
binding.pbAuth.visibility = View.VISIBLE
autoAuth()
//background blur
Glide.with(this)
.load(R.drawable.sun) // Replace with your image resource
.transform(MultiTransformation(RoundedCorners(25),
BlurTransformation(20)))
.into(binding.authSun)
Glide.with(this)
.load(R.drawable.sea) // Replace with your image resource
.transform(MultiTransformation(RoundedCorners(30),
BlurTransformation(30)))
.into(binding.authSea)
//Click listeners
binding.tvRegisterHelper.setOnClickListener {
switchAuthPanel()
}
binding.tvLoginHelper.setOnClickListener {
switchAuthPanel()
}
binding.btnAuthGoogle.setOnClickListener {
startGoogleAuth()
}
binding.btnLogin.setOnClickListener {
login()
}
binding.btnRegister.setOnClickListener {
register()
}
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
signInLauncher = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) { result ->
if (result.resultCode == Activity.RESULT_OK) {
val task = GoogleSignIn.getSignedInAccountFromIntent(result.data)
try {
val account = task.getResult(ApiException::class.java)
val credential = GoogleAuthProvider.getCredential(account.idToken,null)
mAuth.signInWithCredential(credential)
.addOnCompleteListener(requireActivity()) { t ->
if (t.isSuccessful) {
// Sign in success
Log.d(TAG, "signInWithCredential:success")
lifecycleScope.launch(Dispatchers.Default) {
val r = authPresenter.initAuthenticator()
if(r) { goToHome() }
}
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", t.exception)
// Handle sign-in failure here.
}
}
} catch (e: ApiException) {
Log.w(TAG, "Google Auth Failure " + e.statusCode + " : " + e.message)
}
} else {
Log.w(TAG, "Failed to auth with google")
}
}
}
/**
* lance l'activité d'authentification google
*/
fun startGoogleAuth() {
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(BuildConfig.OAUTH_CLIENT_ID)
.requestEmail()
.build()
val mGoogleSignInClient = GoogleSignIn.getClient(requireContext(), gso)
val signInIntent = mGoogleSignInClient.signInIntent
signInLauncher.launch(signInIntent)
}
/**
* Change le panneau d'authentification (login ou register)
*/
fun switchAuthPanel() {
panelId = ++panelId % 2
if(panelId == 0) {
binding.registerPanel.visibility = View.GONE
binding.loginPanel.visibility = View.VISIBLE
} else {
binding.registerPanel.visibility = View.VISIBLE
binding.loginPanel.visibility = View.GONE
}
}
/**
* Appel la fonction d'enregistrement asynchrone
*/
fun register() {
hideKeyboard()
binding.pbAuth.visibility = View.VISIBLE
lifecycleScope.launch(Dispatchers.Default) {
authPresenter.register(
binding.etRegisterName.text.toString(),
binding.etRegisterMail.text.toString(),
binding.etRegisterPassword.text.toString())
}
}
/**
* Appel la fonction de connexion asynchrone
*/
fun login() {
hideKeyboard()
binding.pbAuth.visibility = View.VISIBLE
lifecycleScope.launch(Dispatchers.Default) {
authPresenter.login(
binding.etLoginMail.text.toString(),
binding.etLoginPassword.text.toString(),
binding.cbKeepConnected.isChecked)
}
}
/**
* Appel la fonction d'authentification automatique asynchrone
*/
fun autoAuth() {
lifecycleScope.launch(Dispatchers.Default) {
authPresenter.autoAuth()
}
}
/**
* navigue vers le fragment home
*/
override fun goToHome() {
MainScope().launch {
findNavController().navigate(R.id.action_authFragment_to_homeFragment)
}
}
/**
* Affiche un message à l'écran
* @param message (String)
* @param length (Int) 0 = short, 1 = long
*/
override fun showToast(message: String, length: Int) {
MainScope().launch {
binding.pbAuth.visibility = View.GONE
Toast.makeText(context, message, length).show()
}
}
override fun stopLoading() {
MainScope().launch {
binding.pbAuth.visibility = View.GONE
}
}
/**
* Appel la fonction qui cache le clavier
*/
fun hideKeyboard() {
val activity: Activity? = activity
if (activity is MainActivity) {
activity.hideKeyboard()
}
}
companion object {
const val TAG = "AuthFragment"
fun newInstance(): AuthFragment {
return AuthFragment()
}
}
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/view/fragments/group/CreateGroupFragment.kt | 1484559517 | package be.helmo.planivacances.view.fragments.group
import android.app.Activity
import android.app.DatePickerDialog
import android.content.Context
import android.content.Intent
import android.location.Address
import android.location.Geocoder
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import be.helmo.planivacances.R
import be.helmo.planivacances.databinding.FragmentCreateGroupBinding
import be.helmo.planivacances.factory.AppSingletonFactory
import be.helmo.planivacances.presenter.interfaces.ICreateGroupView
import be.helmo.planivacances.presenter.viewmodel.GroupVM
import be.helmo.planivacances.presenter.viewmodel.PlaceVM
import be.helmo.planivacances.view.interfaces.IGroupPresenter
import com.adevinta.leku.*
import com.google.android.gms.maps.model.LatLng
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import java.io.IOException
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
/**
* Fragment de création de groupe
*/
class CreateGroupFragment : Fragment(), ICreateGroupView {
lateinit var binding : FragmentCreateGroupBinding
lateinit var groupPresenter : IGroupPresenter
lateinit var lekuActivityResultLauncher: ActivityResultLauncher<Intent>
var country: String? = null
var city: String? = null
var street: String? = null
var number: String? = null
var postalCode: String? = null
var location: LatLng? = null
var dateField: Int = 0
var startDate: String? = null
var endDate: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
groupPresenter = AppSingletonFactory.instance!!.getGroupPresenter(this)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
binding = FragmentCreateGroupBinding.inflate(inflater, container,false)
binding.addGroupBtn.setOnClickListener {
addGroup()
}
//back when backText is Clicked
binding.tvBack.setOnClickListener {
findNavController().navigate(R.id.action_createGroupFragment_to_homeFragment)
}
binding.tvGroupPlace.setOnClickListener {
createLocationPickerDialog()
}
binding.tvGroupStartDate.setOnClickListener {
dateField = 0
createDateHourDialog()
}
binding.tvGroupEndDate.setOnClickListener {
dateField = 1
createDateHourDialog()
}
lekuActivityResultLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
result: ActivityResult ->
if (result.resultCode == Activity.RESULT_OK) {
val data = result.data
val latitude = data?.getDoubleExtra(LATITUDE, 0.0)
val longitude = data?.getDoubleExtra(LONGITUDE, 0.0)
postalCode = data?.getStringExtra(ZIPCODE)
val addressFormated = getAddressFromLatLng(requireContext(),
latitude!!,
longitude!!)
this.location = LatLng(latitude, longitude)
binding.tvGroupPlace.text = addressFormated
} else {
showToast(
"Erreur lors de la récupération de la localisation",
1
)
}
}
return binding.root
}
fun getAddressFromLatLng(context: Context, lat: Double, lng: Double): String? {
val geocoder = Geocoder(context, Locale.getDefault())
try {
val addresses = geocoder.getFromLocation(lat, lng, 1) as List<Address>
if (addresses.isNotEmpty()) {
val address: Address = addresses[0]
country = address.countryName.trim()
city = address.locality.trim()
street = address.thoroughfare
number = address.subThoroughfare
return "$street, $number $city $country"
}
} catch (e: IOException) {
showToast("Erreur durant la récupération de l'adresse provenant de l'emplacement",1)
}
return null
}
/**
* Prépare et vérifie les inputs et appel la création de groupe
*/
fun addGroup() {
if(binding.etGroupName.text.isBlank()) {
showToast("Le titre n'a pas été rempli", 1)
return
}
try {
val formatter = SimpleDateFormat(getString(R.string.date_format))
val startDate = formatter.parse(binding.tvGroupStartDate.text.toString())!!
val endDate = formatter.parse(binding.tvGroupEndDate.text.toString())!!
val currentDate = Calendar.getInstance().time
if(startDate.before(currentDate) || endDate.before(currentDate)) {
showToast("La date de début et de fin doivent être supérieures ou égales à la date du jour",1)
return
}
if(startDate.after(endDate)) {
showToast(
"La date de fin ne peut pas être antérieure à la date de début",
1
)
return
}
if(country == null || city == null || street == null || postalCode == null) {
showToast("Adresse invalide", 1)
return
}
val place = PlaceVM(
country!!,
city!!,
street!!,
number!!,
postalCode!!,
location!!
)
val group = GroupVM(
binding.etGroupName.text.toString(),
binding.etGroupDescription.text.toString(),
startDate,
endDate,
place
)
lifecycleScope.launch(Dispatchers.Default) {
groupPresenter.createGroup(group)
}
}
catch (e: ParseException) {
showToast("Une des dates est mal encodée", 1)
}
}
/**
* Crée un dialog de récupération de lieu
*/
fun createLocationPickerDialog() {
val locationPickerIntent = LocationPickerActivity.Builder()
.withDefaultLocaleSearchZone()
.shouldReturnOkOnBackPressed()
.withZipCodeHidden()
.withVoiceSearchHidden()
if(location != null) {
locationPickerIntent.withLocation(location)
}
lekuActivityResultLauncher.launch(locationPickerIntent.build(requireContext()))
}
fun createDateHourDialog() {
val calendar: Calendar = Calendar.getInstance()
if(dateField == 0 && startDate != null) {
calendar.time = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()).parse(startDate!!)!!
} else if(dateField == 1 && endDate != null) {
calendar.time = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()).parse(endDate!!)!!
}
val day = calendar.get(Calendar.DAY_OF_MONTH)
val month = calendar.get(Calendar.MONTH)
val year = calendar.get(Calendar.YEAR)
val datePickerDialog = DatePickerDialog(
requireView().context,
DatePickerDialog.OnDateSetListener(::onDateSet),
year,
month,
day
)
datePickerDialog.show()
}
fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
val formattedDate = String.format("%02d/%02d/%d", dayOfMonth, month+1, year)
if(dateField == 0) {
startDate = formattedDate
binding.tvGroupStartDate.text = startDate
} else if (dateField == 1) {
endDate = formattedDate
binding.tvGroupEndDate.text = endDate
}
}
override fun onGroupCreated() {
MainScope().launch {
showToast("Groupe créé !", 0)
findNavController().navigate(R.id.action_createGroupFragment_to_groupFragment)
}
}
/**
* Affiche un message à l'écran
* @param message (String)
* @param length (Int) 0 = short, 1 = long
*/
override fun showToast(message: String, length: Int) {
MainScope().launch {
binding.pbCreateGroup.visibility = View.GONE
Toast.makeText(context, message, length).show()
}
}
companion object {
const val TAG = "CreateGroupFragment"
fun newInstance(): CreateGroupFragment {
return CreateGroupFragment()
}
}
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/view/fragments/group/GroupFragment.kt | 1455692541 | package be.helmo.planivacances.view.fragments.group
import android.app.AlertDialog
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import be.helmo.planivacances.R
import be.helmo.planivacances.databinding.FragmentGroupBinding
import be.helmo.planivacances.factory.AppSingletonFactory
import be.helmo.planivacances.presenter.interfaces.IGroupView
import be.helmo.planivacances.presenter.viewmodel.GroupDetailVM
import be.helmo.planivacances.view.interfaces.IGroupPresenter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
/**
* A simple [Fragment] subclass.
* Use the [GroupFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class GroupFragment : Fragment(), IGroupView {
lateinit var binding : FragmentGroupBinding
lateinit var groupPresenter : IGroupPresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
groupPresenter = AppSingletonFactory.instance!!.getGroupPresenter(this)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
binding = FragmentGroupBinding.inflate(inflater, container,false)
binding.updateGroupBtn.setOnClickListener {
findNavController().navigate(R.id.action_groupFragment_to_UpdateGroupFragment)
}
binding.deleteGroupBtn.setOnClickListener {
lifecycleScope.launch(Dispatchers.Default) {
groupPresenter.deleteCurrentGroup()
}
}
lifecycleScope.launch(Dispatchers.Default) {
groupPresenter.showGroupInfos()
}
binding.ibWeather.setOnClickListener {
findNavController().navigate(R.id.action_groupFragment_to_weatherFragment)
}
binding.ibCalendar.setOnClickListener {
findNavController().navigate(R.id.action_groupFragment_to_calendarFragment)
}
binding.ibItinerary.setOnClickListener {
lifecycleScope.launch(Dispatchers.Default) {
groupPresenter.loadItinerary()
}
}
binding.ibTchat.setOnClickListener {
findNavController().navigate(R.id.action_groupFragment_to_tchatFragment)
}
binding.tvBack.setOnClickListener {
findNavController().navigate(R.id.action_groupFragment_to_homeFragment)
}
binding.ibAddMemberToGroup.setOnClickListener {
displayAddMemberPrompt()
}
return binding.root
}
companion object {
const val TAG = "GroupFragment"
fun newInstance(): GroupFragment {
return GroupFragment()
}
}
fun displayAddMemberPrompt() {
val builder : AlertDialog.Builder = AlertDialog.Builder(requireContext())
val addMemberLayout = LayoutInflater.from(requireContext()).inflate(R.layout.add_group_user_popup,null)
builder.setView(addMemberLayout)
builder.setPositiveButton("Ajouter") {
_,_ ->
val etAddGroupUserMail: EditText = addMemberLayout.findViewById<EditText>(R.id.etAddGroupUserMail)
val email : String = etAddGroupUserMail.text.toString()
addMemberInGroup(email)
}
builder.setNegativeButton("Annuler") {
dialog,_ -> dialog.cancel()
}
var addMemberDialog: AlertDialog = builder.create()
addMemberDialog.show()
}
fun addMemberInGroup(email:String) {
val emailRegex = Regex("^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$")
if(emailRegex.matches(email)) {
lifecycleScope.launch(Dispatchers.Default) {
groupPresenter.sendGroupInvite(email)
}
} else {
showToast("Adresse e-mail invalide",1)
}
}
override fun buildItinerary(latitude: String, longitude: String) {
MainScope().launch {
val mapsUri = Uri.parse(
"https://www.google.com/maps/dir/?api=1&destination=$latitude,$longitude"
)
val mapIntent = Intent(Intent.ACTION_VIEW, mapsUri)
mapIntent.setPackage("com.google.android.apps.maps")
if (mapIntent.resolveActivity(requireActivity().packageManager) != null) {
startActivity(mapIntent)
} else {
showToast(
"L'application Google Maps doit être installée pour pouvoir utiliser cette fonctionnalité !",
1
)
}
}
}
override fun setGroupInfos(group: GroupDetailVM) {
MainScope().launch {
binding.tvGroupName.text = group.groupName
binding.tvGroupDescription.text = group.description
binding.tvGroupPeriod.text = group.period
binding.tvGroupPlace.text = group.address
}
}
override fun onGroupDeleted() {
MainScope().launch {
showToast("Le groupe a bien été supprimé", 1)
findNavController().navigate(R.id.action_groupFragment_to_homeFragment)
}
}
override fun showToast(message: String,length:Int) {
MainScope().launch {
Toast.makeText(context, message, length).show()
}
}
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/view/fragments/group/UpdateGroupFragment.kt | 178195900 | package be.helmo.planivacances.view.fragments.group
import android.app.Activity
import android.app.DatePickerDialog
import android.content.Context
import android.content.Intent
import android.location.Address
import android.location.Geocoder
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.DatePicker
import android.widget.Toast
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import be.helmo.planivacances.R
import be.helmo.planivacances.databinding.FragmentUpdateGroupBinding
import be.helmo.planivacances.factory.AppSingletonFactory
import be.helmo.planivacances.presenter.interfaces.IUpdateGroupView
import be.helmo.planivacances.presenter.viewmodel.GroupVM
import be.helmo.planivacances.presenter.viewmodel.PlaceVM
import be.helmo.planivacances.view.interfaces.IGroupPresenter
import com.adevinta.leku.LATITUDE
import com.adevinta.leku.LONGITUDE
import com.adevinta.leku.LocationPickerActivity
import com.adevinta.leku.ZIPCODE
import com.google.android.gms.maps.model.LatLng
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import java.io.IOException
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
class UpdateGroupFragment : Fragment(), IUpdateGroupView {
lateinit var binding : FragmentUpdateGroupBinding
lateinit var groupPresesenter : IGroupPresenter
lateinit var lekuActivityResultLauncher : ActivityResultLauncher<Intent>
var country: String? = null
var city: String? = null
var street: String? = null
var number: String? = null
var postalCode: String? = null
var location: LatLng? = null
var dateField: Int = 0
var startDate: String? = null
var endDate: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
groupPresesenter = AppSingletonFactory.instance!!.getGroupPresenter(this)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentUpdateGroupBinding.inflate(inflater,container,false)
lifecycleScope.launch(Dispatchers.Default) {
groupPresesenter.loadCurrentGroup()
}
binding.tvBackToHome.setOnClickListener {
findNavController().navigate(R.id.action_UpdateGroupFragment_to_groupFragment)
}
binding.tvUpdateGroupPlace.setOnClickListener {
createLocationPickerDialog()
}
binding.tvUpdateGroupStartDate.setOnClickListener {
dateField = 0
createDateHourDialog()
}
binding.tvUpdateGroupEndDate.setOnClickListener {
dateField = 1
createDateHourDialog()
}
binding.updateGroupBtn.setOnClickListener {
updateGroup()
}
lekuActivityResultLauncher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
result: ActivityResult ->
if (result.resultCode == Activity.RESULT_OK) {
val data = result.data
val latitude = data?.getDoubleExtra(LATITUDE, 0.0)
val longitude = data?.getDoubleExtra(LONGITUDE, 0.0)
postalCode = data?.getStringExtra(ZIPCODE)
val addressFormated = getAddressFromLatLng(requireContext(),
latitude!!,
longitude!!)
this.location = LatLng(latitude, longitude)
binding.tvUpdateGroupPlace.text = addressFormated
} else {
showToast(
"Erreur lors de la récupération de la localisation",
1
)
}
}
return binding.root
}
fun getAddressFromLatLng(context: Context, lat: Double, lng: Double): String? {
val geocoder = Geocoder(context, Locale.getDefault())
try {
val addresses = geocoder.getFromLocation(lat, lng, 1) as List<Address>
if (addresses.isNotEmpty()) {
val address: Address = addresses[0]
country = address.countryName.trim()
city = address.locality.trim()
street = address.thoroughfare
number = address.subThoroughfare
return "$street, $number $city $country"
}
} catch (e: IOException) {
showToast("Erreur durant la récupération de l'adresse provenant de l'emplacement",1)
}
return null
}
fun updateGroup() {
if(binding.etUpdateGroupName.text.isBlank()) {
showToast("Le titre doit être défini",1)
return
}
try {
val formatter = SimpleDateFormat(getString(R.string.date_format))
val startDate = formatter.parse(binding.tvUpdateGroupStartDate.text.toString())!!
val endDate = formatter.parse(binding.tvUpdateGroupEndDate.text.toString())!!
val currentDate = Calendar.getInstance().time
if (startDate.before(currentDate) || endDate.before(currentDate)) {
showToast(
"La date de début et de fin doivent être supérieures ou égales à la date du jour",
1
)
return
}
if (startDate.after(endDate)) {
showToast(
"La date de fin ne peut pas être antérieure à la date de début",
1
)
return
}
if (country == null || city == null || street == null || postalCode == null) {
showToast("Adresse invalide", 1)
return
}
val place = PlaceVM(street!!,number!!,postalCode!!,city!!,country!!,location!!)
val groupVM = GroupVM(binding.etUpdateGroupName.text.toString(),binding.etUpdateGroupDescription.text.toString(),startDate,endDate,place)
lifecycleScope.launch(Dispatchers.Default) {
groupPresesenter.updateCurrentGroup(groupVM)
}
} catch (e: ParseException) {
showToast("Une des dates est mal encodée",1)
}
}
fun createLocationPickerDialog() {
val locationPickerIntent = LocationPickerActivity.Builder()
.withDefaultLocaleSearchZone()
.shouldReturnOkOnBackPressed()
.withZipCodeHidden()
.withVoiceSearchHidden()
if(location != null) {
locationPickerIntent.withLocation(location)
}
lekuActivityResultLauncher.launch(locationPickerIntent.build(requireContext()))
}
fun createDateHourDialog() {
val calendar: Calendar = Calendar.getInstance()
if(dateField == 0 && startDate != null) {
calendar.time = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()).parse(startDate!!)!!
} else if(dateField == 1 && endDate != null) {
calendar.time = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()).parse(endDate!!)!!
}
val day = calendar.get(Calendar.DAY_OF_MONTH)
val month = calendar.get(Calendar.MONTH)
val year = calendar.get(Calendar.YEAR)
val datePickerDialog = DatePickerDialog(
requireView().context,
DatePickerDialog.OnDateSetListener(::onDateSet),
year,
month,
day
)
datePickerDialog.show()
}
fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
val formattedDate = String.format("%02d/%02d/%d", dayOfMonth, month+1, year)
if(dateField == 0) {
startDate = formattedDate
binding.tvUpdateGroupStartDate.text = startDate
} else if (dateField == 1) {
endDate = formattedDate
binding.tvUpdateGroupEndDate.text = endDate
}
}
override fun onGroupUpdated() {
MainScope().launch {
showToast("Groupe mis à jour !", 0)
findNavController().navigate(R.id.action_UpdateGroupFragment_to_homeFragment)
}
}
override fun setCurrentGroup(groupVM: GroupVM) {
MainScope().launch {
binding.etUpdateGroupName.setText(groupVM.name)
startDate = SimpleDateFormat("dd/MM/yyyy").format(groupVM.startDate)
binding.tvUpdateGroupStartDate.setText(startDate)
endDate = SimpleDateFormat("dd/MM/yyyy").format(groupVM.endDate)
binding.tvUpdateGroupEndDate.setText(endDate)
val placeVM: PlaceVM = groupVM.place
country = placeVM.country
city = placeVM.city
street = placeVM.street
number = placeVM.number
postalCode = placeVM.postalCode
location = LatLng(placeVM.latLng.latitude,placeVM.latLng.longitude)
val address = "$street, $number $city $country"
binding.tvUpdateGroupPlace.text = address
binding.etUpdateGroupDescription.setText(groupVM.description)
}
}
override fun showToast(message: String, length: Int) {
MainScope().launch {
Toast.makeText(context,message,length).show()
}
}
companion object {
const val TAG = "UpdateGroupFragment"
fun newInstance(): UpdateGroupFragment {
return UpdateGroupFragment()
}
}
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/view/fragments/activity/CalendarFragment.kt | 3262013934 | package be.helmo.planivacances.view.fragments.activity
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Environment
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.content.FileProvider
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import be.helmo.planivacances.R
import be.helmo.planivacances.databinding.FragmentCalendarBinding
import be.helmo.planivacances.factory.AppSingletonFactory
import be.helmo.planivacances.presenter.interfaces.ICalendarView
import be.helmo.planivacances.presenter.viewmodel.ActivityListItemVM
import be.helmo.planivacances.view.interfaces.IActivityPresenter
import com.prolificinteractive.materialcalendarview.*
import com.prolificinteractive.materialcalendarview.spans.DotSpan
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileOutputStream
import java.util.*
/**
* A simple [Fragment] subclass.
* Use the [CalendarFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class CalendarFragment : Fragment(), ICalendarView {
lateinit var binding : FragmentCalendarBinding
lateinit var activityPresenter: IActivityPresenter
lateinit var calendarAdapter: CalendarAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activityPresenter = AppSingletonFactory.instance!!.getCalendarPresenter(this)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentCalendarBinding.inflate(inflater,container,false)
calendarAdapter = CalendarAdapter() {selectedActivityId ->
activityPresenter.setCurrentActivity(selectedActivityId)
findNavController().navigate(R.id.action_CalendarFragment_to_ActivityFragment)
}
val layoutManager = LinearLayoutManager(requireContext())
binding.rvActivities.layoutManager = layoutManager
binding.rvActivities.adapter = calendarAdapter
binding.exportCalendarBtn.isEnabled = false
binding.exportCalendarBtn.isClickable = false
val currentDate = Date()
binding.calendarView.setSelectedDate(currentDate)
binding.tvBack2.setOnClickListener {
findNavController().navigate(R.id.action_CalendarFragment_to_groupFragment)
}
binding.calendarView.setOnDateChangedListener { _, date, _ ->
lifecycleScope.launch(Dispatchers.Default) {
activityPresenter.onActivityDateChanged(date.day,date.month,date.year)
// binding.calendarView.setDateSelected(currentDate,true)
}
}
lifecycleScope.launch(Dispatchers.Default) {
activityPresenter.loadActivities()
}
binding.createActivityBtn.setOnClickListener {
findNavController().navigate(R.id.action_CalendarFragment_to_CreateActivityFragment)
}
binding.exportCalendarBtn.setOnClickListener {
lifecycleScope.launch(Dispatchers.Default) {
activityPresenter.getCalendarFile()
}
}
return binding.root
}
companion object {
const val TAG = "CalendarFragment"
fun newInstance(): CalendarFragment {
return CalendarFragment()
}
}
override fun downloadCalendar(calendarContent: String,fileName:String) {
MainScope().launch {
val file = File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
fileName
)
try {
val outputStream = FileOutputStream(file)
outputStream.write(calendarContent.toByteArray())
outputStream.close()
val uri = FileProvider.getUriForFile(
context!!,
"${context!!.packageName}.provider",
file
)
val intent = Intent(Intent.ACTION_VIEW)
intent.setDataAndType(uri, "application/ics")
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
context?.startActivity(intent)
} catch (e: Exception) {
showToast("Erreur durant le téléchargement du calendrier",1)
}
}
}
override fun onActivitiesLoaded(activityDates: List<Date>) {
MainScope().launch {
binding.exportCalendarBtn.isEnabled = true
binding.exportCalendarBtn.isClickable = true
lifecycleScope.launch(Dispatchers.Default) {
val currentDate : CalendarDay = binding.calendarView.selectedDate
activityPresenter.onActivityDateChanged(currentDate.day,currentDate.month,currentDate.year)
}
binding.calendarView.removeDecorators()
for(date in activityDates) {
val calendarDay = CalendarDay.from(date)
binding.calendarView.addDecorator(EventDecorator(Color.BLUE,calendarDay))
}
}
}
override fun setDisplayedActivities(activities: List<ActivityListItemVM>) {
MainScope().launch {
calendarAdapter.clearActivitiesList()
activities.forEach {
calendarAdapter.addActivity(it)
}
}
}
override fun showToast(message: String,length:Int) {
MainScope().launch {
Toast.makeText(context, message, length).show()
}
}
private inner class EventDecorator(private val color: Int, private val date: CalendarDay) :
DayViewDecorator {
override fun shouldDecorate(day: CalendarDay): Boolean {
return day == date
}
override fun decorate(view: DayViewFacade) {
view.addSpan(DotSpan(5F, color))
}
}
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/view/fragments/activity/UpdateActivityFragment.kt | 2337178274 | package be.helmo.planivacances.view.fragments.activity
import android.app.Activity
import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.content.Context
import android.content.Intent
import android.location.Address
import android.location.Geocoder
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import be.helmo.planivacances.R
import be.helmo.planivacances.databinding.FragmentUpdateActivityBinding
import be.helmo.planivacances.factory.AppSingletonFactory
import be.helmo.planivacances.presenter.interfaces.IUpdateActivityView
import be.helmo.planivacances.presenter.viewmodel.ActivityVM
import be.helmo.planivacances.presenter.viewmodel.PlaceVM
import be.helmo.planivacances.view.interfaces.IActivityPresenter
import com.adevinta.leku.LATITUDE
import com.adevinta.leku.LONGITUDE
import com.adevinta.leku.LocationPickerActivity
import com.adevinta.leku.ZIPCODE
import com.google.android.gms.maps.model.LatLng
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import java.io.IOException
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit
class UpdateActivityFragment : Fragment(), IUpdateActivityView {
lateinit var binding : FragmentUpdateActivityBinding
lateinit var activityPresenter: IActivityPresenter
lateinit var lekuActivityResultLauncher: ActivityResultLauncher<Intent>
var dateField : Int = 0
var startDate: String? = null
var endDate: String? = null
var startTime: String? = null
var endTime: String? = null
var country: String? = null
var city: String? = null
var street: String? = null
var number: String? = null
var postalCode: String? = null
var location: LatLng? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activityPresenter = AppSingletonFactory.instance!!.getActivityPresenter(this)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentUpdateActivityBinding.inflate(inflater,container,false)
lifecycleScope.launch(Dispatchers.Default) {
activityPresenter.getCurrentActivity()
}
binding.tvUpdateActivityPlace.setOnClickListener {
createLocationPickerDialog()
}
binding.tvBackToCalendar.setOnClickListener {
findNavController().navigate(R.id.action_UpdateActivityFragment_to_ActivityFragment)
}
binding.tvUpdateActivityStartDate.setOnClickListener {
dateField = 0
createDateHourDialog()
}
binding.tvUpdateActivityEndDate.setOnClickListener {
dateField = 1
createDateHourDialog()
}
binding.updateActivityBtn.setOnClickListener {
updateActivity()
}
lekuActivityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
result: ActivityResult ->
if(result.resultCode == Activity.RESULT_OK) {
val data = result.data
val latitude = data?.getDoubleExtra(LATITUDE,0.0)
val longitude = data?.getDoubleExtra(LONGITUDE,0.0)
postalCode = data?.getStringExtra(ZIPCODE)
val addressFormatted = getAddressFromLatLng(requireContext(), latitude!!, longitude!!)
location = LatLng(latitude,longitude)
binding.tvUpdateActivityPlace.text = addressFormatted
} else {
showToast("Erreur lors de la récupération de la localisation",1)
}
}
return binding.root
}
fun updateActivity() {
if(binding.etUpdateActivityTitle.text.isBlank()) {
showToast("Le titre doit être défini",1)
return
}
try {
val formatter = SimpleDateFormat("dd/MM/yyyy HH:mm")
val startDate = formatter.parse(binding.tvUpdateActivityStartDate.text.toString())!!
val endDate = formatter.parse(binding.tvUpdateActivityEndDate.text.toString())!!
val currentDate = Calendar.getInstance().time
if(startDate.before(currentDate) || endDate.before(currentDate)) {
showToast("La date de début et de fin doivent être supérieures ou égales à la date du jour",1)
return
}
if(startDate.after(endDate)) {
showToast("La date de fin ne peut pas être antérieure à la date de début",1)
return
}
if(street == null || postalCode == null || city == null || country == null) {
showToast("Adresse invalide",1)
return
}
val duration: Int = TimeUnit.MILLISECONDS.toSeconds(endDate.time - startDate.time).toInt()
val place = PlaceVM(street!!,number!!,postalCode!!,city!!,country!!,location!!)
val activity : ActivityVM = ActivityVM(binding.etUpdateActivityTitle.text.toString(),binding.etUpdateActivityDescription.text.toString(),startDate,duration,place)
lifecycleScope.launch(Dispatchers.Default) {
activityPresenter.updateCurrentActivity(activity)
}
} catch(e : ParseException) {
showToast("Une des dates est mal encodée",1)
}
}
fun createLocationPickerDialog() {
val locationPickerIntent = LocationPickerActivity.Builder()
.withDefaultLocaleSearchZone()
.shouldReturnOkOnBackPressed()
.withZipCodeHidden()
.withVoiceSearchHidden()
if(location != null) {
locationPickerIntent.withLocation(location)
}
lekuActivityResultLauncher.launch(locationPickerIntent.build(requireContext()))
}
fun createDateHourDialog() {
val calendar: Calendar = Calendar.getInstance()
if(dateField == 0 && startDate != null) {
calendar.time = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()).parse(startDate)
} else if(dateField == 1 && endDate != null) {
calendar.time = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()).parse(endDate)
}
val day = calendar.get(Calendar.DAY_OF_MONTH)
val month = calendar.get(Calendar.MONTH)
val year = calendar.get(Calendar.YEAR)
val datePickerDialog = DatePickerDialog(
requireView().context,
DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth ->
onDateSet(year,month,dayOfMonth)
createTimePickerDialog()
},
year,
month,
day
)
datePickerDialog.show()
}
fun onDateSet(year: Int, month: Int, dayOfMonth: Int) {
val formattedDate = String.format("%02d/%02d/%d", dayOfMonth, month+1, year)
if (dateField == 0) {
startDate = formattedDate
} else if (dateField == 1) {
endDate = formattedDate
}
}
fun createTimePickerDialog() {
val calendar: Calendar = Calendar.getInstance()
if(dateField == 0 && startTime != null) {
calendar.time = SimpleDateFormat("HH:mm").parse(startTime)
} else if(dateField == 1 && endTime != null) {
calendar.time = SimpleDateFormat("HH:mm").parse(endTime)
}
val hour = calendar.get(Calendar.HOUR_OF_DAY)
val minute = calendar.get(Calendar.MINUTE)
val timePickerDialog = TimePickerDialog(
requireView().context,
TimePickerDialog.OnTimeSetListener { _, hour, minute ->
onTimeSet(hour,minute)
},
hour,
minute,
true
)
timePickerDialog.show()
}
fun onTimeSet(hour:Int,minute:Int) {
val formattedTime = String.format("%02d:%02d", hour, minute)
if(dateField == 0) {
startTime = formattedTime
binding.tvUpdateActivityStartDate.text = "$startDate $startTime"
} else if(dateField == 1) {
endTime = formattedTime
binding.tvUpdateActivityEndDate.text = "$endDate $endTime"
}
}
fun getAddressFromLatLng(context: Context, lat:Double, lng:Double) : String? {
val geocoder = Geocoder(context, Locale.getDefault())
try {
val addresses = geocoder.getFromLocation(lat,lng,1) as List<Address>
if(addresses.isNotEmpty()) {
val address: Address = addresses[0]
city = address.locality.trim()
number = address.subThoroughfare
street = address.thoroughfare
country = address.countryName.trim()
return "$street, $number $city $country"
}
} catch(e: IOException) {
showToast("Erreur durant la récupération de l'adresse provenant de l'emplacement",1)
}
return null
}
override fun setCurrentActivity(activityVM: ActivityVM) {
MainScope().launch {
binding.etUpdateActivityTitle.setText(activityVM.title)
startDate = SimpleDateFormat("dd/MM/yyyy").format(activityVM.startDate)
startTime = SimpleDateFormat("HH:mm").format(activityVM.startDate)
binding.tvUpdateActivityStartDate.setText("$startDate $startTime")
val calendar = Calendar.getInstance()
calendar.time = activityVM.startDate
calendar.add(Calendar.SECOND, activityVM.duration)
val currentEndDate = calendar.time
endDate = SimpleDateFormat("dd/MM/yyyy").format(currentEndDate)
endTime = SimpleDateFormat("HH:mm").format(currentEndDate)
binding.tvUpdateActivityEndDate.setText("$endDate $endTime")
val placeVM: PlaceVM = activityVM.place
country = placeVM.country
city = placeVM.city
street = placeVM.street
number = placeVM.number
postalCode = placeVM.postalCode
location = LatLng(placeVM.latLng.latitude, placeVM.latLng.longitude)
binding.tvUpdateActivityPlace.setText("$street, $number $city $country")
binding.etUpdateActivityDescription.setText(activityVM.description)
}
}
override fun onActivityUpdated() {
MainScope().launch {
showToast("Activité mise à jour avec succès",1)
findNavController().navigate(R.id.action_UpdateActivityFragment_to_CalendarFragment)
}
}
override fun showToast(message: String, length: Int) {
MainScope().launch {
Toast.makeText(context, message, length).show()
}
}
companion object {
const val TAG = "UpdateActivityFragment"
fun newInstance(): UpdateActivityFragment {
return UpdateActivityFragment()
}
}
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/view/fragments/activity/CalendarAdapter.kt | 837387627 | package be.helmo.planivacances.view.fragments.activity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.RecyclerView
import be.helmo.planivacances.R
import be.helmo.planivacances.presenter.viewmodel.ActivityListItemVM
class CalendarAdapter(val clickListener: (String) -> Unit) : RecyclerView.Adapter<CalendarAdapter.ViewHolder>() {
val activitiesList: MutableList<ActivityListItemVM> = mutableListOf()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view : View = LayoutInflater.from(parent.context).inflate(R.layout.calendar_activity_item,parent,false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return activitiesList.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val activityItemVM: ActivityListItemVM = activitiesList[position]
holder.bind(activityItemVM,clickListener)
}
fun clearActivitiesList() {
activitiesList.clear()
notifyDataSetChanged()
}
fun addActivity(activity: ActivityListItemVM) {
activitiesList.add(activity)
notifyItemInserted(activitiesList.size - 1)
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val activityContainer : ConstraintLayout = itemView.findViewById(R.id.clActivityCalendarItem)
val activityName: TextView = itemView.findViewById(R.id.tvActivityName)
val activityDate: TextView = itemView.findViewById(R.id.tvActivityTime)
fun bind(activityItemVM: ActivityListItemVM, clickListener: (String) -> Unit) {
activityName.text = activityItemVM.title
activityDate.text = String.format("Début : %s\nDurée : %s",activityItemVM.startHour,activityItemVM.duration)
activityContainer.setOnClickListener {clickListener(activityItemVM.aid)}
}
}
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/view/fragments/activity/CreateActivityFragment.kt | 277164909 | package be.helmo.planivacances.view.fragments.activity
import android.app.Activity
import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.content.Context
import android.content.Intent
import android.location.Address
import android.location.Geocoder
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import be.helmo.planivacances.R
import be.helmo.planivacances.databinding.FragmentCreateActivityBinding
import be.helmo.planivacances.factory.AppSingletonFactory
import be.helmo.planivacances.presenter.interfaces.ICreateActivityView
import be.helmo.planivacances.presenter.viewmodel.ActivityVM
import be.helmo.planivacances.presenter.viewmodel.PlaceVM
import be.helmo.planivacances.view.interfaces.IActivityPresenter
import com.adevinta.leku.LATITUDE
import com.adevinta.leku.LONGITUDE
import com.adevinta.leku.LocationPickerActivity
import com.adevinta.leku.ZIPCODE
import com.google.android.gms.maps.model.LatLng
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import java.io.IOException
import java.text.ParseException
import java.text.SimpleDateFormat
import java.time.Duration
import java.util.*
import java.util.concurrent.TimeUnit
class CreateActivityFragment : Fragment(), ICreateActivityView {
lateinit var binding : FragmentCreateActivityBinding
lateinit var activityPresenter: IActivityPresenter
lateinit var lekuActivityResultLauncher: ActivityResultLauncher<Intent>
var dateField : Int = 0
var startDate: String? = null
var endDate: String? = null
var startTime: String? = null
var endTime: String? = null
var country: String? = null
var city: String? = null
var street: String? = null
var number: String? = null
var postalCode: String? = null
var location: LatLng? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activityPresenter = AppSingletonFactory.instance!!.getActivityPresenter(this)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentCreateActivityBinding.inflate(inflater,container,false)
binding.tvCreateActivityPlace.setOnClickListener {
createLocationPickerDialog()
}
binding.tvBackToCalendar.setOnClickListener {
findNavController().navigate(R.id.action_CreateActivityFragment_to_CalendarFragment)
}
binding.tvCreateActivityStartDate.setOnClickListener {
dateField = 0
createDateHourDialog()
}
binding.tvCreateActivityEndDate.setOnClickListener {
dateField = 1
createDateHourDialog()
}
binding.createActivityBtn.setOnClickListener {
addActivity()
}
lekuActivityResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
result: ActivityResult ->
if(result.resultCode == Activity.RESULT_OK) {
val data = result.data
val latitude = data?.getDoubleExtra(LATITUDE,0.0)
val longitude = data?.getDoubleExtra(LONGITUDE,0.0)
postalCode = data?.getStringExtra(ZIPCODE)
val addressFormatted = getAddressFromLatLng(requireContext(), latitude!!, longitude!!)
location = LatLng(latitude,longitude)
binding.tvCreateActivityPlace.text = addressFormatted
} else {
showToast("Erreur lors de la récupération de la localisation",1)
}
}
return binding.root
}
fun addActivity() {
if(binding.etCreateActivityTitle.text.isBlank()) {
showToast("Le titre doit être défini",1)
return
}
try {
val formatter = SimpleDateFormat("dd/MM/yyyy HH:mm")
val startDate = formatter.parse(binding.tvCreateActivityStartDate.text.toString())!!
val endDate = formatter.parse(binding.tvCreateActivityEndDate.text.toString())!!
val currentDate = Calendar.getInstance().time
if(startDate.before(currentDate) || endDate.before(currentDate)) {
showToast("La date de début et de fin doivent être supérieures ou égales à la date du jour",1)
return
}
if(startDate.after(endDate)) {
showToast("La date de fin ne peut pas être antérieure à la date de début",1)
return
}
if(street == null || postalCode == null || city == null || country == null) {
showToast("Adresse invalide",1)
return
}
val duration: Int = TimeUnit.MILLISECONDS.toSeconds(endDate.time - startDate.time).toInt()
val place = PlaceVM(street!!,number!!,postalCode!!,city!!,country!!,location!!)
val activity : ActivityVM = ActivityVM(binding.etCreateActivityTitle.text.toString(),binding.etCreateActivityDescription.text.toString(),startDate,duration,place)
lifecycleScope.launch(Dispatchers.Default) {
activityPresenter.createActivity(activity)
}
} catch(e : ParseException) {
showToast("Une des dates est mal encodée",1)
}
}
fun createLocationPickerDialog() {
val locationPickerIntent = LocationPickerActivity.Builder()
.withDefaultLocaleSearchZone()
.shouldReturnOkOnBackPressed()
.withZipCodeHidden()
.withVoiceSearchHidden()
if(location != null) {
locationPickerIntent.withLocation(location)
}
lekuActivityResultLauncher.launch(locationPickerIntent.build(requireContext()))
}
fun createDateHourDialog() {
val calendar: Calendar = Calendar.getInstance()
if(dateField == 0 && startDate != null) {
calendar.time = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()).parse(startDate)
} else if(dateField == 1 && endDate != null) {
calendar.time = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()).parse(endDate)
}
val day = calendar.get(Calendar.DAY_OF_MONTH)
val month = calendar.get(Calendar.MONTH)
val year = calendar.get(Calendar.YEAR)
val datePickerDialog = DatePickerDialog(
requireView().context,
DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth ->
onDateSet(year,month,dayOfMonth)
createTimePickerDialog()
},
year,
month,
day
)
datePickerDialog.show()
}
fun onDateSet(year: Int, month: Int, dayOfMonth: Int) {
val formattedDate = String.format("%02d/%02d/%d", dayOfMonth, month+1, year)
if (dateField == 0) {
startDate = formattedDate
} else if (dateField == 1) {
endDate = formattedDate
}
}
fun createTimePickerDialog() {
val calendar: Calendar = Calendar.getInstance()
if(dateField == 0 && startTime != null) {
calendar.time = SimpleDateFormat("HH:mm").parse(startTime)
} else if(dateField == 1 && endTime != null) {
calendar.time = SimpleDateFormat("HH:mm").parse(endTime)
}
val hour = calendar.get(Calendar.HOUR_OF_DAY)
val minute = calendar.get(Calendar.MINUTE)
val timePickerDialog = TimePickerDialog(
requireView().context,
TimePickerDialog.OnTimeSetListener { _, hour, minute ->
onTimeSet(hour,minute)
},
hour,
minute,
true
)
timePickerDialog.show()
}
fun onTimeSet(hour:Int,minute:Int) {
val formattedTime = String.format("%02d:%02d", hour, minute)
if(dateField == 0) {
startTime = formattedTime
binding.tvCreateActivityStartDate.text = "$startDate $startTime"
} else if(dateField == 1) {
endTime = formattedTime
binding.tvCreateActivityEndDate.text = "$endDate $endTime"
}
}
fun getAddressFromLatLng(context: Context, lat:Double, lng:Double) : String? {
val geocoder = Geocoder(context,Locale.getDefault())
try {
val addresses = geocoder.getFromLocation(lat,lng,1) as List<Address>
if(addresses.isNotEmpty()) {
val address: Address = addresses[0]
city = address.locality.trim()
number = address.subThoroughfare
street = address.thoroughfare
country = address.countryName.trim()
return "$street, $number $city $country"
}
} catch(e: IOException) {
showToast("Erreur durant la récupération de l'adresse provenant de l'emplacement",1)
}
return null
}
override fun onActivityCreated() {
MainScope().launch {
showToast("Activité créée avec succès",1)
findNavController().navigate(R.id.action_CreateActivityFragment_to_CalendarFragment)
}
}
override fun showToast(message: String, length: Int) {
MainScope().launch {
Toast.makeText(context, message, length).show()
}
}
companion object {
const val TAG = "CreateActivityFragment"
fun newInstance(): CreateActivityFragment {
return CreateActivityFragment()
}
}
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/view/fragments/activity/ActivityFragment.kt | 1614630531 | package be.helmo.planivacances.view.fragments.activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import be.helmo.planivacances.R
import be.helmo.planivacances.databinding.FragmentActivityBinding
import be.helmo.planivacances.factory.AppSingletonFactory
import be.helmo.planivacances.presenter.interfaces.IActivityView
import be.helmo.planivacances.presenter.viewmodel.ActivityDetailVM
import be.helmo.planivacances.view.interfaces.IActivityPresenter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
class ActivityFragment : Fragment(), IActivityView {
lateinit var binding: FragmentActivityBinding
lateinit var activityPresenter : IActivityPresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activityPresenter = AppSingletonFactory.instance!!.getActivityPresenter(this)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentActivityBinding.inflate(inflater,container,false)
binding.tvBackToCalendar.setOnClickListener {
findNavController().navigate(R.id.action_ActivityFragment_to_CalendarFragment)
}
binding.ibItinerary.setOnClickListener {
lifecycleScope.launch(Dispatchers.Default) {
activityPresenter.loadItinerary()
}
}
binding.deleteActivityBtn.setOnClickListener {
lifecycleScope.launch(Dispatchers.Default) {
activityPresenter.deleteCurrentActivity()
}
}
lifecycleScope.launch(Dispatchers.Default) {
activityPresenter.loadCurrentActivity()
}
binding.updateActivityBtn.setOnClickListener {
findNavController().navigate(R.id.action_ActivityFragment_to_UpdateActivityFragment)
}
return binding.root
}
override fun loadActivity(activity: ActivityDetailVM) {
MainScope().launch {
binding.tvActivityName.text = activity.activityTitle
binding.tvActivityPeriod.text = activity.activityPeriod
binding.tvActivityPlace.text = activity.activityPlace
binding.tvActivityDescription.text = activity.activityDescription
}
}
override fun buildItinerary(latitude: String, longitude: String) {
MainScope().launch {
val mapsUri = Uri.parse(
"https://www.google.com/maps/dir/?api=1&destination=$latitude,$longitude"
)
val mapIntent = Intent(Intent.ACTION_VIEW, mapsUri)
mapIntent.setPackage("com.google.android.apps.maps")
if (mapIntent.resolveActivity(requireActivity().packageManager) != null) {
startActivity(mapIntent)
} else {
showToast(
"L'application Google Maps doit être installée pour pouvoir utiliser cette fonctionnalité !",
1
)
}
}
}
override fun onActivityDeleted() {
MainScope().launch {
showToast("L'activité a bien été supprimée",1)
findNavController().navigate(R.id.action_ActivityFragment_to_CalendarFragment)
}
}
override fun showToast(message: String, length: Int) {
MainScope().launch {
Toast.makeText(context,message,length).show()
}
}
companion object {
const val TAG = "ActivityFragment"
fun newInstance(): ActivityFragment {
return ActivityFragment()
}
}
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/view/fragments/tchat/TchatAdapter.kt | 1346828268 | package be.helmo.planivacances.view.fragments.tchat
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import be.helmo.planivacances.R
import be.helmo.planivacances.service.dto.MessageDTO
import be.helmo.planivacances.util.DateFormatter
class TchatAdapter() :
RecyclerView.Adapter<TchatAdapter.ViewHolder>() {
val messagesList: MutableList<MessageDTO> = mutableListOf()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val layoutResId = if (viewType == VIEW_TYPE_ME) {
R.layout.message_item_sending
} else {
R.layout.message_item_receiving
}
val view: View = LayoutInflater
.from(parent.context)
.inflate(layoutResId, parent, false)
return ViewHolder(view,viewType)
}
override fun getItemCount(): Int {
return messagesList.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val message: MessageDTO = messagesList[position]
holder.bind(message,getItemViewType(position))
}
override fun getItemViewType(position: Int): Int {
return if (messagesList[position].sender == "me") VIEW_TYPE_ME else VIEW_TYPE_OTHER
}
fun addMessage(message: MessageDTO) {
if (messagesList.size == 100) {
messagesList.removeAt(0)
}
messagesList.add(message)
notifyItemInserted(messagesList.size - 1)
}
companion object {
const val VIEW_TYPE_ME = 0
const val VIEW_TYPE_OTHER = 1
}
class ViewHolder(itemView: View,viewType: Int) : RecyclerView.ViewHolder(itemView) {
var displayName: TextView? = null
var messageText: TextView
var messageTime: TextView
init {
if (viewType == VIEW_TYPE_ME) {
messageText = itemView.findViewById(R.id.textMessageS)
messageTime = itemView.findViewById(R.id.messageTimeS)
} else {
displayName = itemView.findViewById(R.id.senderName)
messageText = itemView.findViewById(R.id.textMessageR)
messageTime = itemView.findViewById(R.id.messageTimeR)
}
}
fun bind(message: MessageDTO,viewType: Int) {
if (viewType == VIEW_TYPE_OTHER) {
displayName?.text = message.displayName
}
messageText.text = message.content
messageTime.text = DateFormatter.formatTimestampForDisplay(message.time)
}
}
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/view/fragments/tchat/TchatFragment.kt | 767451286 | package be.helmo.planivacances.view.fragments.tchat
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import be.helmo.planivacances.R
import be.helmo.planivacances.databinding.FragmentTchatBinding
import be.helmo.planivacances.factory.AppSingletonFactory
import be.helmo.planivacances.presenter.interfaces.ITchatView
import be.helmo.planivacances.service.dto.MessageDTO
import be.helmo.planivacances.view.interfaces.ITchatPresenter
import com.bumptech.glide.Glide
import com.bumptech.glide.load.MultiTransformation
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import jp.wasabeef.glide.transformations.BlurTransformation
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
/**
* A simple [Fragment] subclass.
* Use the [TchatFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class TchatFragment : Fragment(), ITchatView {
lateinit var binding : FragmentTchatBinding
lateinit var tchatPresenter: ITchatPresenter
lateinit var tchatAdapter: TchatAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
tchatPresenter = AppSingletonFactory.instance!!.getTchatPresenter(this)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
// Inflate the layout for this fragment
binding = FragmentTchatBinding.inflate(inflater, container, false)
Glide.with(this)
.load(R.drawable.sun)
.transform(MultiTransformation(RoundedCorners(25),
BlurTransformation(20)))
.into(binding.tchatSun)
Glide.with(this)
.load(R.drawable.palmtree)
.transform(MultiTransformation(RoundedCorners(25),
BlurTransformation(20)))
.into(binding.tchatPalmTree)
binding.tvBack.setOnClickListener {
findNavController().navigate(R.id.action_tchatFragment_to_groupFragment)
}
//chargement tchat
binding.pbTchat.visibility = View.VISIBLE
lifecycleScope.launch(Dispatchers.Default) {
initTchatComponents()
tchatPresenter.connectToTchat()
}
return binding.root
}
fun initTchatComponents() {
MainScope().launch {
tchatAdapter = TchatAdapter()
val layoutManager = LinearLayoutManager(requireContext())
layoutManager.isSmoothScrollbarEnabled = true
binding.rvTchatContainer.layoutManager = layoutManager
binding.rvTchatContainer.adapter = tchatAdapter
binding.ibSendTchat.setOnClickListener {
val message: String = binding.etTchatSendText.text.toString().trim()
if (message.isNotEmpty()) {
binding.etTchatSendText.text.clear()
lifecycleScope.launch(Dispatchers.Default) {
tchatPresenter.sendMessage(message)
}
}
}
}
}
override fun addMessageToView(message: MessageDTO) {
MainScope().launch {
stopLoading()
tchatAdapter.addMessage(message)
scrollToBottom()
}
}
private fun scrollToBottom() {
val layoutManager = binding.rvTchatContainer.layoutManager as LinearLayoutManager
layoutManager.smoothScrollToPosition(binding.rvTchatContainer,
null,
tchatAdapter.itemCount - 1)
}
override fun stopLoading() {
MainScope().launch {
binding.pbTchat.visibility = View.GONE
}
}
override fun onDestroyView() {
super.onDestroyView()
Log.d("TchatFragment","onDestroy called")
lifecycleScope.launch(Dispatchers.Default) {
tchatPresenter.disconnectToTchat()
}
}
override fun onDetach() {
super.onDetach()
Log.d("TchatFragment","onDetach called")
lifecycleScope.launch(Dispatchers.Default) {
tchatPresenter.disconnectToTchat()
}
}
companion object {
const val TAG = "TchatFragment"
fun newInstance(): TchatFragment {
return TchatFragment()
}
}
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/view/fragments/weather/WeatherFragment.kt | 2716934954 | package be.helmo.planivacances.view.fragments.weather
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import be.helmo.planivacances.R
import be.helmo.planivacances.databinding.FragmentWeatherBinding
import be.helmo.planivacances.presenter.viewmodel.WeatherForecastVM
import be.helmo.planivacances.factory.AppSingletonFactory
import be.helmo.planivacances.presenter.interfaces.IWeatherView
import be.helmo.planivacances.view.interfaces.IWeatherPresenter
import com.bumptech.glide.Glide
import com.bumptech.glide.load.MultiTransformation
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import jp.wasabeef.glide.transformations.BlurTransformation
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
/**
* A simple [Fragment] subclass.
* Use the [WeatherFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class WeatherFragment : Fragment(), IWeatherView {
lateinit var binding : FragmentWeatherBinding
lateinit var weatherPresenter: IWeatherPresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
weatherPresenter = AppSingletonFactory.instance!!.getWeatherPresenter(this)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
binding = FragmentWeatherBinding.inflate(inflater, container,false)
Glide.with(this)
.load(R.drawable.sun)
.transform(MultiTransformation(RoundedCorners(25),
BlurTransformation(20)))
.into(binding.weatherSun)
Glide.with(this)
.load(R.drawable.palmtree)
.transform(MultiTransformation(RoundedCorners(25),
BlurTransformation(20)))
.into(binding.weatherPalmTree)
binding.tvBack.setOnClickListener {
findNavController().navigate(R.id.action_weatherFragment_to_groupFragment)
}
binding.pbWeatherList.visibility = View.VISIBLE
lifecycleScope.launch(Dispatchers.Default) {
weatherPresenter.getForecast()
}
return binding.root
}
override fun onForecastLoaded(weatherList: List<WeatherForecastVM>) {
MainScope().launch {
val adapter = WeatherAdapter(weatherList, requireContext())
binding.rvWeatherContainer.layoutManager = LinearLayoutManager(requireContext())
binding.rvWeatherContainer.adapter = adapter
binding.pbWeatherList.visibility = View.GONE
}
}
/**
* Affiche un message à l'écran
* @param message (String)
* @param length (Int) 0 = short, 1 = long
*/
override fun showToast(message: String, length: Int) {
MainScope().launch {
binding.pbWeatherList.visibility = View.GONE
Toast.makeText(context, message, length).show()
}
}
companion object {
const val TAG = "WeatherFragment"
fun newInstance(): WeatherFragment {
return WeatherFragment()
}
}
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/view/fragments/weather/WeatherAdapter.kt | 1239923056 | package be.helmo.planivacances.view.fragments.weather
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import be.helmo.planivacances.R
import be.helmo.planivacances.presenter.viewmodel.WeatherForecastVM
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
class WeatherAdapter(weatherList: List<WeatherForecastVM>, context: Context) :
RecyclerView.Adapter<WeatherAdapter.ViewHolder>() {
val weatherList: List<WeatherForecastVM>
val context: Context
init {
this.weatherList = weatherList
this.context = context
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view: View =
LayoutInflater
.from(parent.context)
.inflate(R.layout.weather_item, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val weather: WeatherForecastVM = weatherList[position]
holder.tvWeatherTemperature.text = weather.temperature
holder.tvWeatherDate.text = weather.date
holder.tvWeatherInfos.text = weather.infos
Glide.with(context)
.load(weather.imageUrl)
.apply(RequestOptions().placeholder(R.drawable.logo)
.diskCacheStrategy(DiskCacheStrategy.ALL))
.into(holder.ivWeather)
}
override fun getItemCount(): Int {
return weatherList.size
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var ivWeather: ImageView
var tvWeatherTemperature: TextView
var tvWeatherDate: TextView
var tvWeatherInfos: TextView
init {
ivWeather = itemView.findViewById(R.id.ivWeather)
tvWeatherTemperature = itemView.findViewById(R.id.tvGroupItemName)
tvWeatherDate = itemView.findViewById(R.id.tvGroupItemPeriod)
tvWeatherInfos = itemView.findViewById(R.id.tvGroupItemDescription)
}
}
}
|
mobile-planivacances/app/src/main/java/be/helmo/planivacances/view/interfaces/IGroupPresenter.kt | 2032799998 | package be.helmo.planivacances.view.interfaces
import be.helmo.planivacances.domain.Group
import be.helmo.planivacances.domain.Place
import be.helmo.planivacances.presenter.interfaces.ICreateGroupView
import be.helmo.planivacances.presenter.interfaces.IGroupView
import be.helmo.planivacances.presenter.interfaces.IHomeView
import be.helmo.planivacances.presenter.interfaces.IUpdateGroupView
import be.helmo.planivacances.presenter.viewmodel.GroupVM
interface IGroupPresenter {
suspend fun createGroup(groupVM: GroupVM)
fun loadItinerary()
fun showGroupInfos()
suspend fun loadUserGroups()
fun getCurrentGroup(): Group?
fun getCurrentGroupPlace(): Place?
fun getCurrentGroupId() : String
fun setCurrentGroupId(gid: String)
fun setIGroupView(groupView:IGroupView)
fun setICreateGroupView(createGroupView: ICreateGroupView)
fun setIUpdateGroupView(updateGroupView: IUpdateGroupView)
fun setIHomeView(homeView: IHomeView)
fun loadCurrentGroup()
suspend fun updateCurrentGroup(groupVM:GroupVM)
suspend fun deleteCurrentGroup()
suspend fun loadUserGroupInvites()
suspend fun sendGroupInvite(email:String)
suspend fun acceptGroupInvite(gid:String)
suspend fun declineGroupInvite(gid: String)
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/view/interfaces/IActivityPresenter.kt | 2055172236 | package be.helmo.planivacances.view.interfaces
import be.helmo.planivacances.presenter.interfaces.IActivityView
import be.helmo.planivacances.presenter.interfaces.ICalendarView
import be.helmo.planivacances.presenter.interfaces.ICreateActivityView
import be.helmo.planivacances.presenter.interfaces.IUpdateActivityView
import be.helmo.planivacances.presenter.viewmodel.ActivityVM
interface IActivityPresenter {
fun setICalendarView(calendarView: ICalendarView)
fun setIActivityView(activityView: IActivityView)
fun setICreateActivityView(createIActivityView: ICreateActivityView)
fun setIUpdateActivityView(updateActivityView: IUpdateActivityView)
fun setCurrentActivity(activityId:String)
suspend fun getCalendarFile()
suspend fun loadActivities()
fun loadCurrentActivity()
fun loadItinerary()
suspend fun createActivity(activityVM: ActivityVM)
suspend fun updateCurrentActivity(activityVM: ActivityVM)
suspend fun deleteCurrentActivity()
fun getCurrentActivity()
fun onActivityDateChanged(dayOfMonth: Int,month: Int,year: Int)
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/view/interfaces/ITchatPresenter.kt | 1788054134 | package be.helmo.planivacances.view.interfaces
import be.helmo.planivacances.presenter.interfaces.ITchatView
interface ITchatPresenter {
fun setITchatView(tchatView: ITchatView)
suspend fun connectToTchat()
fun disconnectToTchat()
fun sendMessage(message: String)
}
|
mobile-planivacances/app/src/main/java/be/helmo/planivacances/view/interfaces/IAuthPresenter.kt | 3806182375 | package be.helmo.planivacances.view.interfaces
import android.content.SharedPreferences
import be.helmo.planivacances.presenter.interfaces.IAuthView
interface IAuthPresenter {
fun setSharedPreference(sharedPreferences: SharedPreferences)
fun getUid(): String
fun getDisplayName() : String
suspend fun loadIdToken(): Boolean
suspend fun register(username: String, mail: String, password: String)
suspend fun login(mail: String, password: String, keepConnected: Boolean)
suspend fun autoAuth()
suspend fun initAuthenticator(): Boolean
fun setIAuthView(authView : IAuthView)
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/view/interfaces/IWeatherPresenter.kt | 4033760169 | package be.helmo.planivacances.view.interfaces
import be.helmo.planivacances.presenter.interfaces.IWeatherView
interface IWeatherPresenter {
suspend fun getForecast()
fun setIWeatherView(weatherView: IWeatherView)
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/service/dto/LoginUserDTO.kt | 2114454019 | package be.helmo.planivacances.service.dto
/**
* Utilisateur de connexion
*/
data class LoginUserDTO(
val mail: String? = null,
val password: String? = null)
|
mobile-planivacances/app/src/main/java/be/helmo/planivacances/service/dto/PlaceDTO.kt | 2660271804 | package be.helmo.planivacances.service.dto
data class PlaceDTO(val country : String,
val city : String,
val street : String,
val number : String,
val postalCode : String,
val lat: Double,
val lon: Double)
|
mobile-planivacances/app/src/main/java/be/helmo/planivacances/service/dto/MessageDTO.kt | 3852202589 | package be.helmo.planivacances.service.dto
data class MessageDTO(
var sender : String,
val displayName: String,
val groupId : String,
val content: String,
val time: Long
) |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/service/dto/GroupInviteDTO.kt | 173532709 | package be.helmo.planivacances.service.dto
data class GroupInviteDTO(
val gid:String,
val groupName:String
) |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/service/dto/GroupDTO.kt | 3959535480 | package be.helmo.planivacances.service.dto
import java.util.*
data class GroupDTO(
var gid: String? = null,
val groupName: String,
val description: String,
val startDate: Date,
val endDate: Date,
val place: PlaceDTO,
var owner: String? = null)
|
mobile-planivacances/app/src/main/java/be/helmo/planivacances/service/dto/CreateGroupDTO.kt | 1305424804 | package be.helmo.planivacances.service.dto
import java.util.Date
data class CreateGroupDTO(
val groupName: String,
val description: String,
val startDate: Date,
val endDate: Date,
val placeId: String = "null",
val isPublished: Boolean = false,
val owner: String = "null")
|
mobile-planivacances/app/src/main/java/be/helmo/planivacances/service/dto/RegisterUserDTO.kt | 4111510833 | package be.helmo.planivacances.service.dto
/**
* Utilisateur d'enregistrement
*/
data class RegisterUserDTO(
val username: String? = null,
val mail: String? = null,
val password: String? = null)
|
mobile-planivacances/app/src/main/java/be/helmo/planivacances/service/dto/ActivityDTO.kt | 1231858590 | package be.helmo.planivacances.service.dto
import java.util.*
data class ActivityDTO(
var title: String,
var description: String,
var startDate: Date,
var duration: Int,
var place: PlaceDTO
) |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/service/dto/ActivitiesDTO.kt | 976572635 | package be.helmo.planivacances.service.dto
data class ActivitiesDTO(
var activitiesMap: HashMap<String,ActivityDTO>
) |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/service/dto/WeatherDTOs.kt | 2564388064 | package be.helmo.planivacances.service.dto
data class WeatherData(
val forecast: Forecast
)
data class Forecast(
val forecastday: List<ForecastDay>
)
data class ForecastDay(
val date: String,
val day: Day
)
data class Day(
val avgtemp_c: Double,
val condition: Condition,
val avghumidity: Double,
val daily_chance_of_rain: Int,
val maxwind_kph: Double
)
data class Condition(
val icon: String
)
|
mobile-planivacances/app/src/main/java/be/helmo/planivacances/service/IPlaceService.kt | 4258499378 | package be.helmo.planivacances.service
import be.helmo.planivacances.service.dto.PlaceDTO
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.DELETE
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.Path
interface IPlaceService {
@POST("place/{gid}")
suspend fun create(
@Body place: PlaceDTO,
@Path("gid") gid: String): Response<String>
@GET("place/{gid}/{pid}")
suspend fun getGroupPlace(
@Path("gid") gid: String,
@Path("pid") pid: String): Response<PlaceDTO>
@GET("place/{gid}")
suspend fun getPlaces(@Path("gid") gid: String): Response<List<PlaceDTO>>
@DELETE("place/{gid}/{pid}")
suspend fun deletePlace(
@Path("gid") gid: String,
@Path("pid") pid: String): Response<String>
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/service/IGroupService.kt | 911077402 | package be.helmo.planivacances.service
import be.helmo.planivacances.service.dto.GroupDTO
import be.helmo.planivacances.service.dto.GroupInviteDTO
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.DELETE
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.PUT
import retrofit2.http.Path
interface IGroupService {
@POST("group")
suspend fun create(@Body gp: GroupDTO): Response<String>
@GET("group/{gid}")
suspend fun get(@Path("gid") gid: String): Response<GroupDTO>
@GET("group/list")
suspend fun getList(): Response<List<GroupDTO>>
@PUT("group/{gid}")
suspend fun update(
@Path("gid") gid: String,
@Body group: GroupDTO): Response<String>
@DELETE("group/{gid}")
suspend fun delete(@Path("gid") gid: String): Response<String>
@POST("group/invitation/{gid}/{mail}")
suspend fun inviteUser(@Path("gid") gid:String, @Path("mail") mail: String) : Response<Boolean>
@GET("group/invitation")
suspend fun getUserGroupInvites() : Response<List<GroupInviteDTO>>
@POST("group/invitation/{gid}")
suspend fun acceptGroupInvite(@Path("gid") gid:String) : Response<Boolean>
@DELETE("group/invitation/{gid}")
suspend fun declineGroupInvite(@Path("gid") gid: String) : Response<String>
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/service/IActivityService.kt | 323497755 | package be.helmo.planivacances.service
import be.helmo.planivacances.service.dto.ActivityDTO
import be.helmo.planivacances.service.dto.GroupDTO
import retrofit2.Response
import retrofit2.http.*
interface IActivityService {
@GET("activity/{gid}")
suspend fun loadActivities(@Path("gid") gid: String): Response<Map<String,ActivityDTO>>
@POST("activity/{gid}")
suspend fun createActivity(@Path("gid") gid:String, @Body activityDTO: ActivityDTO): Response<String>
@PUT("activity/{gid}/{aid}")
suspend fun updateActivity(@Path("gid") gid:String, @Path("aid") aid:String, @Body activityDTO: ActivityDTO) : Response<Boolean>
@DELETE("activity/{gid}/{aid}")
suspend fun deleteActivity(@Path("gid") gid: String,@Path("aid") aid:String) : Response<String>
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/service/ICalendarService.kt | 4013081758 | package be.helmo.planivacances.service
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Path
interface ICalendarService {
@GET("activity/calendar/{gid}")
suspend fun getICS(@Path("gid") gid: String): Response<String>
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/service/ITchatService.kt | 3135314967 | package be.helmo.planivacances.service
import be.helmo.planivacances.service.dto.MessageDTO
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.Header
import retrofit2.http.POST
interface ITchatService {
@POST("chat/messages")
suspend fun getPreviousMessages(@Header("GID") gid:String): Response<List<MessageDTO>>
@POST("chat/message")
suspend fun sendMessage(@Body message: MessageDTO)
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/service/IWeatherService.kt | 1207584352 | package be.helmo.planivacances.service
import be.helmo.planivacances.BuildConfig
import be.helmo.planivacances.service.dto.WeatherData
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Query
interface IWeatherService {
@GET("forecast.json")
suspend fun getForecast(@Query("q") latLng: String,
@Query("days") days : Int = 14,
@Query("aqi") aqi : String = "no",
@Query("alerts") alerts : String = "no",
@Query("lang") lang : String = "fr",
@Query("key") api_key : String = BuildConfig.WEATHER_API_KEY): Response<WeatherData>
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/service/ApiClient.kt | 3478559398 | package be.helmo.planivacances.service
import be.helmo.planivacances.BuildConfig
import be.helmo.planivacances.service.dto.MessageDTO
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.pusher.client.Pusher
import com.pusher.client.PusherOptions
import com.pusher.client.util.HttpChannelAuthorizer
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.security.SecureRandom
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager
object ApiClient {
private const val BASE_API_URL: String = "https://studapps.cg.helmo.be:5011/REST_CAO_BART/api/" //"http://192.168.1.19:8080/api/"//addr ipv4 local
private const val WEATHER_API_URL: String = "https://api.weatherapi.com/v1/"
private const val TCHAT_AUTH_URL: String = "https://studapps.cg.helmo.be:5011/REST_CAO_BART/api/chat/" //"http://192.168.1.19:8080/api/chat/"
private val gson : Gson by lazy {
GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS")
.setLenient()
.create()
}
private val httpClient : OkHttpClient by lazy {
// Create a trust manager that does not validate certificate chains
val trustAllCerts = arrayOf<TrustManager>(
object : X509TrustManager {
@Throws(CertificateException::class)
override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {
}
@Throws(CertificateException::class)
override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {
}
override fun getAcceptedIssuers(): Array<X509Certificate> {
return arrayOf()
}
}
)
// Install the all-trusting trust manager
val sslContext = SSLContext.getInstance("SSL")
sslContext.init(null, trustAllCerts, SecureRandom())
OkHttpClient.Builder()
.authenticator(TokenAuthenticator.instance!!)
.sslSocketFactory(sslContext.socketFactory, trustAllCerts[0] as X509TrustManager)
.build()
}
private val retrofit : Retrofit by lazy {
Retrofit.Builder()
.baseUrl(BASE_API_URL)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.build()
}
private val weatherRetrofit : Retrofit by lazy {
Retrofit.Builder()
.baseUrl(WEATHER_API_URL)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.build()
}
private val retrofitForStringResult : Retrofit by lazy {
Retrofit.Builder()
.baseUrl(BASE_API_URL)
.client(httpClient)
.addConverterFactory(ScalarsConverterFactory.create())
.build()
}
val authService : IAuthService by lazy{
retrofit.create(IAuthService::class.java)
}
val groupService : IGroupService by lazy{
retrofit.create(IGroupService::class.java)
}
val weatherService : IWeatherService by lazy{
weatherRetrofit.create(IWeatherService::class.java)
}
val tchatService : ITchatService by lazy {
retrofit.create(ITchatService::class.java)
}
val calendarService : ICalendarService by lazy {
retrofitForStringResult.create(ICalendarService::class.java)
}
val activityService : IActivityService by lazy {
retrofit.create(IActivityService::class.java)
}
fun getTchatInstance(): Pusher {
val headers = HashMap<String,String>()
TokenAuthenticator.instance!!.idToken?.let { headers.put("Authorization", it) }
val authorizer = HttpChannelAuthorizer(TCHAT_AUTH_URL)
authorizer.setHeaders(headers)
val options = PusherOptions()
options.setCluster(BuildConfig.PUSHER_CLUSTER)
options.channelAuthorizer = authorizer
return Pusher(BuildConfig.PUSHER_KEY,options)
}
fun formatMessageToDisplay(message : String): MessageDTO? {
return gson.fromJson(message,MessageDTO::class.java)
}
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/service/TokenAuthenticator.kt | 616123181 | package be.helmo.planivacances.service
import android.util.Log
import be.helmo.planivacances.view.interfaces.IAuthPresenter
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import okhttp3.Authenticator
import okhttp3.Request
import okhttp3.Response
import okhttp3.Route
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicLong
class TokenAuthenticator : Authenticator {
var idToken: String? = null
lateinit var authPresenter: IAuthPresenter
//var token: String? = null // Initialize with your actual initial token
val requestLimit = 6 // Maximum allowed requests within a specified period
val requestLimitPeriodMillis = TimeUnit.SECONDS.toMillis(10) // 10 seconds
val requestCounter = AtomicLong(0)
var lastRequestTime = 0L
override fun authenticate(route: Route?, response: Response): Request? {
synchronized(this) {
val currentTime = System.currentTimeMillis()
// Reset request counter if a new period has started
if (currentTime - lastRequestTime > requestLimitPeriodMillis) {
requestCounter.set(0)
}
if (requestCounter.get() < requestLimit) {
// Allow the request and increment the counter
requestCounter.incrementAndGet()
lastRequestTime = currentTime
/*if (refreshToken != null) {
//todo runBlocking ?
GlobalScope.launch {
authPresenter.signInWithCustomToken(refreshToken!!)
}
}*/
runBlocking {
authPresenter.loadIdToken()
}
return if(idToken != null) {
return response.request().newBuilder()
.header("Authorization", idToken!!)
.build()
} else {
Log.d("TokenAuthenticator", "Token is null, not adding Authorization header to the request")
null
}
} else {
// Too many requests, handle accordingly (e.g., wait, throw an exception, etc.)
Log.d("TokenAuthenticator", "Too many requests. Please wait.")
return null
}
}
}
companion object {
var instance: TokenAuthenticator? = null
get() {
if (field == null) field = TokenAuthenticator()
return field
}
}
}
|
mobile-planivacances/app/src/main/java/be/helmo/planivacances/service/IAuthService.kt | 104691591 | package be.helmo.planivacances.service
import be.helmo.planivacances.service.dto.LoginUserDTO
import be.helmo.planivacances.service.dto.RegisterUserDTO
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.POST
interface IAuthService {
@POST("auth/register")
suspend fun register(@Body user: RegisterUserDTO): Response<String>
@POST("auth/login")
suspend fun login(@Body user: LoginUserDTO): Response<String>
} |
mobile-planivacances/app/src/main/java/be/helmo/planivacances/domain/Group.kt | 3391998362 | package be.helmo.planivacances.domain
import java.util.*
data class Group(val groupName: String,
val description: String,
val startDate: Date,
val endDate: Date,
val place: Place,
var owner: String = "null")
|
mobile-planivacances/app/src/main/java/be/helmo/planivacances/domain/Place.kt | 3492634135 | package be.helmo.planivacances.domain
import com.google.android.gms.maps.model.LatLng
data class Place(val country : String,
val city : String,
val street : String,
val number : String,
val postalCode : String,
val latLng: LatLng) {
val latLngString: String
get() = "${latLng.latitude},${latLng.longitude}"
val address: String
get() = "$street, $number, $city $postalCode, $country"
}
|
mobile-planivacances/app/src/main/java/be/helmo/planivacances/factory/AppSingletonFactory.kt | 1031874804 | package be.helmo.planivacances.factory
import be.helmo.planivacances.presenter.*
import be.helmo.planivacances.presenter.interfaces.*
import be.helmo.planivacances.view.interfaces.*
/**
* Factory de singleton + stockage du token
*/
class AppSingletonFactory() {
val authPresenter: AuthPresenter = AuthPresenter()
val groupPresenter: GroupPresenter = GroupPresenter()
val weatherPresenter: WeatherPresenter = WeatherPresenter(groupPresenter)
val tchatPresenter : TchatPresenter = TchatPresenter(groupPresenter, authPresenter)
val activityPresenter : ActivityPresenter = ActivityPresenter(groupPresenter)
fun getAuthPresenter(authView: IAuthView): IAuthPresenter {
authPresenter.setIAuthView(authView)
return authPresenter
}
//group presenter
fun getGroupPresenter(groupView:IGroupView): IGroupPresenter {
groupPresenter.setIGroupView(groupView)
return groupPresenter
}
fun getGroupPresenter(createGroupView:ICreateGroupView): IGroupPresenter {
groupPresenter.setICreateGroupView(createGroupView)
return groupPresenter
}
fun getGroupPresenter(homeView:IHomeView): IGroupPresenter {
groupPresenter.setIHomeView(homeView)
return groupPresenter
}
fun getGroupPresenter(updateGroupView: IUpdateGroupView) : IGroupPresenter {
groupPresenter.setIUpdateGroupView(updateGroupView)
return groupPresenter
}
//weather presenter
fun getWeatherPresenter(weatherView: IWeatherView): IWeatherPresenter {
weatherPresenter.setIWeatherView(weatherView)
return weatherPresenter
}
fun getTchatPresenter(tchatView : ITchatView) : ITchatPresenter {
tchatPresenter.setITchatView(tchatView)
return tchatPresenter
}
fun getCalendarPresenter(calendarView: ICalendarView) : IActivityPresenter {
activityPresenter.setICalendarView(calendarView)
return activityPresenter
}
fun getActivityPresenter(activityView: IActivityView) : IActivityPresenter {
activityPresenter.setIActivityView(activityView)
return activityPresenter
}
fun getActivityPresenter(createActivityView: ICreateActivityView) : IActivityPresenter {
activityPresenter.setICreateActivityView(createActivityView)
return activityPresenter
}
fun getActivityPresenter(updateActivityView: IUpdateActivityView) : IActivityPresenter {
activityPresenter.setIUpdateActivityView(updateActivityView)
return activityPresenter
}
companion object {
var instance: AppSingletonFactory? = null
get() {
if (field == null) field = AppSingletonFactory()
return field
}
}
} |
Amangeldi_Abdibaitov_mo5_hw_1/app/src/androidTest/java/com/example/amangeldi_abdibaitov_mo5_hw_1/ExampleInstrumentedTest.kt | 1227945962 | package com.example.amangeldi_abdibaitov_mo5_hw_1
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.amangeldi_abdibaitov_mo5_hw_1", appContext.packageName)
}
} |
Amangeldi_Abdibaitov_mo5_hw_1/app/src/test/java/com/example/amangeldi_abdibaitov_mo5_hw_1/ExampleUnitTest.kt | 650686106 | package com.example.amangeldi_abdibaitov_mo5_hw_1
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)
}
} |
Amangeldi_Abdibaitov_mo5_hw_1/app/src/main/java/com/example/amangeldi_abdibaitov_mo5_hw_1/mvp/MainActivity.kt | 940858306 | package com.example.amangeldi_abdibaitov_mo5_hw_1.mvp
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import com.example.amangeldi_abdibaitov_mo5_hw_1.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity(), CounterView {
private lateinit var binding: ActivityMainBinding
private val presenter = Injector.getPresenter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
presenter.attachView(this)
initListener()
}
private fun initListener() {
with(binding) {
incBtn.setOnClickListener {
presenter.increment()
presenter.checkNumber()
}
decBtn.setOnClickListener {
presenter.decrement()
presenter.checkNumber()
}
visibilityChangeBtn.setOnClickListener {
presenter.changeVisible()
}
clearBtn.setOnClickListener {
presenter.clear()
}
}
}
override fun showCount(count: Int) {
binding.resultTv.text = count.toString()
}
override fun changedVisible(isVisible: Boolean) {
binding.resultTv.isVisible = isVisible
}
override fun showToast(message: String) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
override fun changeTextColor() {
binding.resultTv.setTextColor(resources.getColor(android.R.color.holo_green_dark))
}
} |
Amangeldi_Abdibaitov_mo5_hw_1/app/src/main/java/com/example/amangeldi_abdibaitov_mo5_hw_1/mvp/CounterView.kt | 1956453293 | package com.example.amangeldi_abdibaitov_mo5_hw_1.mvp
interface CounterView {
fun showCount(count: Int)
fun changedVisible(isVisible: Boolean)
fun showToast(message: String)
fun changeTextColor()
} |
Amangeldi_Abdibaitov_mo5_hw_1/app/src/main/java/com/example/amangeldi_abdibaitov_mo5_hw_1/mvp/CounterModel.kt | 1646624222 | package com.example.amangeldi_abdibaitov_mo5_hw_1.mvp
class CounterModel {
var count = 0
var isVisible = true
fun inc() {
count++
}
fun dec() {
count--
}
fun clear() {
count = 0
}
fun changeVisibility(isVisible: Boolean) {
this.isVisible = isVisible
}
} |
Amangeldi_Abdibaitov_mo5_hw_1/app/src/main/java/com/example/amangeldi_abdibaitov_mo5_hw_1/mvp/Presenter.kt | 892313900 | package com.example.amangeldi_abdibaitov_mo5_hw_1.mvp
class Presenter {
private var model = Injector.getModel()
private lateinit var view: CounterView
fun increment() {
model.inc()
view.showCount(model.count)
}
fun checkNumber() {
if (model.count == 10) {
view.showToast("Поздравляем")
} else if (model.count == 15) {
view.changeTextColor()
}
}
fun decrement() {
model.dec()
view.showCount(model.count)
}
fun changeVisible() {
if (model.isVisible) {
model.changeVisibility(false)
} else model.changeVisibility(true)
view.changedVisible(model.isVisible)
}
fun clear() {
model.clear()
view.showCount(model.count)
}
fun attachView(view: CounterView) {
this.view = view
}
} |
Amangeldi_Abdibaitov_mo5_hw_1/app/src/main/java/com/example/amangeldi_abdibaitov_mo5_hw_1/mvp/Injector.kt | 902702587 | package com.example.amangeldi_abdibaitov_mo5_hw_1.mvp
class Injector {
companion object {
fun getPresenter() = Presenter()
fun getModel() = CounterModel()
}
} |
TableauApp/app/src/main/java/com/sunueric/tableauapp/ui/viewmodels/AuthViewModel.kt | 3382012860 | package com.sunueric.tableauapp.ui.viewmodels
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.sunueric.tableauapp.network.AuthService
import kotlinx.coroutines.launch
class AuthViewModel(private val authService: AuthService) : ViewModel() {
val accessToken = MutableLiveData("")
val isAuthenticated = MutableLiveData(false)
init {
isAuthenticated.value = false // Not authenticated by default
}
fun authenticateIfNeeded(url: String) {
if (requiresAuthentication(url)) {
if (accessToken.value.isNullOrEmpty()) {
signInAutomatically()
}
} else {
isAuthenticated.value = true // No authentication needed for public URLs
}
}
private fun requiresAuthentication(url: String): Boolean {
return url.contains("/private/") // placeholder condition
}
private fun signInAutomatically() {
viewModelScope.launch {
val response = authService.signIn("[email protected]", "password").execute()
if (response.isSuccessful && response.body() != null) {
accessToken.value = response.body()!!.accessToken
isAuthenticated.value = true
} else {
isAuthenticated.value = false
}
}
}
}
class AuthViewModelFactory(private val authService: AuthService) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(AuthViewModel::class.java)) {
@Suppress("UNCHECKED_CAST")
return AuthViewModel(authService) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
|
TableauApp/app/src/main/java/com/sunueric/tableauapp/ui/theme/Color.kt | 1442824813 | package com.sunueric.tableauapp.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260) |
TableauApp/app/src/main/java/com/sunueric/tableauapp/ui/theme/Theme.kt | 3450113258 | package com.sunueric.tableauapp.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.runtime.Composable
import androidx.tv.material3.ExperimentalTvMaterial3Api
import androidx.tv.material3.MaterialTheme
import androidx.tv.material3.darkColorScheme
import androidx.tv.material3.lightColorScheme
@OptIn(ExperimentalTvMaterial3Api::class)
@Composable
fun TableauAppTheme(
isInDarkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable () -> Unit,
) {
val colorScheme = if (isInDarkTheme) {
darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
} else {
lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
)
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} |
TableauApp/app/src/main/java/com/sunueric/tableauapp/ui/theme/Type.kt | 68522891 | package com.sunueric.tableauapp.ui.theme
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import androidx.tv.material3.ExperimentalTvMaterial3Api
import androidx.tv.material3.Typography
// Set of Material typography styles to start with
@OptIn(ExperimentalTvMaterial3Api::class)
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
) |
TableauApp/app/src/main/java/com/sunueric/tableauapp/MainActivity.kt | 581588108 | package com.sunueric.tableauapp
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.tooling.preview.Preview
import androidx.tv.material3.ExperimentalTvMaterial3Api
import androidx.tv.material3.Surface
import androidx.tv.material3.Text
import com.sunueric.tableauapp.network.provideAuthService
import com.sunueric.tableauapp.ui.theme.TableauAppTheme
import com.sunueric.tableauapp.ui.viewmodels.AuthViewModel
import com.sunueric.tableauapp.ui.viewmodels.AuthViewModelFactory
class MainActivity : ComponentActivity() {
@OptIn(ExperimentalTvMaterial3Api::class)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val authService = provideAuthService()
val authViewModel: AuthViewModel by viewModels { AuthViewModelFactory(authService) }
TableauAppTheme {
Surface(
modifier = Modifier.fillMaxSize(),
shape = RectangleShape
) {
TableauReportView(authViewModel)
}
}
}
}
}
@OptIn(ExperimentalTvMaterial3Api::class)
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
TableauAppTheme {
Greeting("Android")
}
} |
TableauApp/app/src/main/java/com/sunueric/tableauapp/network/AuthService.kt | 3657168732 | package com.sunueric.tableauapp.network
import okhttp3.OkHttpClient
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.POST
import retrofit2.http.Field
import retrofit2.http.FormUrlEncoded
interface AuthService {
@POST("/api/authenticate")
@FormUrlEncoded
fun signIn(@Field("email") email: String, @Field("password") password: String): Call<AuthResponse>
}
data class AuthResponse(val accessToken: String)
object RetrofitClient {
private const val BASE_URL = "https://your.api.base.url/" // Change this to your actual base URL
private fun provideOkHttpClient(): OkHttpClient {
return OkHttpClient.Builder()
.build()
}
val retrofit: Retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.client(provideOkHttpClient())
.addConverterFactory(GsonConverterFactory.create())
.build()
}
fun provideAuthService(): AuthService {
return RetrofitClient.retrofit.create(AuthService::class.java)
} |
TableauApp/app/src/main/java/com/sunueric/tableauapp/utils/SecureCredentials.kt | 2125208199 | package com.sunueric.tableauapp.utils
import android.content.Context
import androidx.security.crypto.EncryptedSharedPreferences
import androidx.security.crypto.MasterKey
fun saveCredentials(email: String, password: String, context: Context) {
val sharedPreferences = EncryptedSharedPreferences.create(
context,
"SecurePreferences",
MasterKey.Builder(context).setKeyScheme(MasterKey.KeyScheme.AES256_GCM).build(),
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
with(sharedPreferences.edit()) {
putString("email", email)
putString("password", password)
apply()
}
}
|
TableauApp/app/src/main/java/com/sunueric/tableauapp/ReportWebView.kt | 1814813893 | package com.sunueric.tableauapp
import android.view.ViewGroup
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import com.sunueric.tableauapp.ui.viewmodels.AuthViewModel
import kotlinx.coroutines.delay
@Composable
fun TableauReportView(authViewModel: AuthViewModel) {
val density = LocalDensity.current
val desiredWidthPx = remember(density) {
density.run { 1280.dp.toPx() }
}
val desiredHeightPx = remember(density) {
density.run { 720.dp.toPx() }
}
val webViewUrl = "https://public.tableau.com/views/TestBook_17133560147830/ExecutiveSummary?:embed=y&:tooltip=n&:toolbar=n&:showVizHome=no&:mobile=y&:showAppBanner=n"
val reloadTrigger = remember { mutableStateOf(false) }
val isAuthenticated = authViewModel.isAuthenticated.value
val accessToken = authViewModel.accessToken.value
// Example URL that needs to be dynamically set based on context
//val webViewUrl = "https://public.tableau.com/views/publicViz"
val urlToLoad = remember(isAuthenticated, accessToken) {
if (isAuthenticated == true && !accessToken.isNullOrEmpty()) {
"$webViewUrl?token=$accessToken" // Append the token for authenticated access
} else {
webViewUrl
}
}
AndroidView(
modifier = Modifier.fillMaxSize(),
factory = { context ->
WebView(context).apply {
layoutParams = ViewGroup.LayoutParams(
desiredWidthPx.toInt(),
desiredHeightPx.toInt()
)
webViewClient = object : WebViewClient() {
@Deprecated("Deprecated in Java")
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
view?.loadUrl(url ?: "")
return true
}
}
@Suppress("SetJavaScriptEnabled") // This is safe because the URL is a known constant...
settings.apply {
javaScriptEnabled = true
loadWithOverviewMode = true
useWideViewPort = true
builtInZoomControls = true
displayZoomControls = false
}
loadUrl(webViewUrl)
}
},
update = { webView ->
webView.apply {
layoutParams = ViewGroup.LayoutParams(
desiredWidthPx.toInt(),
desiredHeightPx.toInt()
)
if (reloadTrigger.value) {
webView.loadUrl(webViewUrl)
reloadTrigger.value = false
}
}
}
)
// Periodically reload the WebView
LaunchedEffect(key1 = Unit, urlToLoad) {
authViewModel.authenticateIfNeeded(webViewUrl)
while (true) {
delay(1800000) // wait for 30mins and reload
// Reload the WebView in a UI thread
reloadTrigger.value = true
}
}
}
|
protocol-e2e/src/test/kotlin/com/rarible/protocol/e2e/mint/ItemMintTest.kt | 2643044775 | package com.rarible.protocol.e2e.mint
import com.rarible.core.test.wait.Wait
import com.rarible.protocol.e2e.test.AbstractTest
import com.rarible.protocol.e2e.test.E2eTest
import kotlinx.coroutines.runBlocking
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.DynamicTest.dynamicTest
import org.junit.jupiter.api.TestFactory
import java.time.Duration
@E2eTest
class ItemMintTest : AbstractTest() {
@TestFactory
fun `mint item`() = properties.blockchains.map { blockchain ->
dynamicTest("mint item in $blockchain") {
runBlocking {
val content = contentPreparer.preparerImageContent()
val mintMeta = metaPreparer.prepare(blockchain, content)
val itemId = mintService.mintItem(blockchain, mintMeta)
Wait.waitAssert(Duration.ofSeconds(20)) {
val item = unionService.getItemById(itemId)
assertThat(item).isNotNull
}
}
}
}
}
|
protocol-e2e/src/test/kotlin/com/rarible/protocol/e2e/test/AbstractTest.kt | 2475930466 | package com.rarible.protocol.e2e.test
import com.rarible.protocol.e2e.configuration.E2eProperties
import com.rarible.protocol.e2e.service.api.UnionService
import com.rarible.protocol.e2e.service.content.ContentPreparer
import com.rarible.protocol.e2e.service.mint.CompositeMetaPreparer
import com.rarible.protocol.e2e.service.mint.CompositeMintService
import com.rarible.protocol.union.api.client.ItemControllerApi
import org.springframework.beans.factory.annotation.Autowired
abstract class AbstractTest {
@Autowired
protected lateinit var unionItemControllerApi: ItemControllerApi
@Autowired
protected lateinit var unionService: UnionService
@Autowired
protected lateinit var mintService: CompositeMintService
@Autowired
protected lateinit var metaPreparer: CompositeMetaPreparer
@Autowired
protected lateinit var contentPreparer: ContentPreparer
@Autowired
protected lateinit var properties: E2eProperties
}
|
protocol-e2e/src/test/kotlin/com/rarible/protocol/e2e/test/E2eTest.kt | 1748450099 | package com.rarible.protocol.e2e.test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = [
"logging.logstash.tcp-socket.enabled = false",
"logging.logjson.enabled = false",
]
)
annotation class E2eTest
|
protocol-e2e/src/test/kotlin/com/rarible/protocol/e2e/BasicTest.kt | 1121528110 | package com.rarible.protocol.e2e
import com.rarible.protocol.e2e.test.AbstractTest
import com.rarible.protocol.e2e.test.E2eTest
import com.rarible.protocol.union.dto.BlockchainDto
import com.rarible.protocol.union.dto.SearchEngineDto
import kotlinx.coroutines.reactor.awaitSingle
import kotlinx.coroutines.runBlocking
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.EnumSource
@E2eTest
class BasicTest : AbstractTest() {
@ParameterizedTest
@EnumSource(SearchEngineDto::class)
fun `fetch protocol items from union`(searchEngine: SearchEngineDto) = runBlocking<Unit> {
val blockchains = properties.blockchains
val continuation: String? = null
val size = 10
val showDeleted = false
val lastUpdatedFrom: Long? = null
val lastUpdatedTo: Long? = null
val items = unionItemControllerApi.getAllItems(
blockchains,
continuation,
size,
showDeleted,
lastUpdatedFrom,
lastUpdatedTo,
searchEngine
).awaitSingle()
assertThat(items.items).isNotEmpty
}
}
|
protocol-e2e/src/main/kotlin/com/rarible/protocol/e2e/misc/EthereumContractFactory.kt | 2581453237 | package com.rarible.protocol.e2e.misc
import com.rarible.contracts.test.erc721.TestERC721
import kotlinx.coroutines.reactive.awaitFirst
import scalether.transaction.MonoSigningTransactionSender
import scalether.transaction.MonoTransactionPoller
object EthereumContractFactory {
suspend fun deployToken(
sender: MonoSigningTransactionSender,
poller: MonoTransactionPoller,
name: String = "Test",
symbol: String = "TST"
): TestERC721 {
return TestERC721.deployAndWait(sender, poller, name, symbol).awaitFirst()
}
}
|
protocol-e2e/src/main/kotlin/com/rarible/protocol/e2e/misc/EthereumProvider.kt | 2402287204 | package com.rarible.protocol.e2e.misc
import io.daonomic.rpc.domain.Request
import io.daonomic.rpc.domain.Response
import io.netty.channel.ChannelException
import io.daonomic.rpc.mono.WebClientTransport
import org.springframework.web.reactive.function.client.WebClientException
import reactor.core.publisher.Mono
import reactor.util.retry.Retry
import scala.reflect.Manifest
import scalether.core.MonoEthereum
import scalether.transaction.MonoSigningTransactionSender
import scalether.transaction.MonoSimpleNonceProvider
import scalether.transaction.MonoTransactionPoller
import java.io.IOException
import java.math.BigInteger
import java.net.URL
import java.time.Duration
object EthereumProvider {
fun createEthereum(ethereumUri: URL): MonoEthereum {
val requestTimeoutMs = 10000
val readWriteTimeoutMs = 10000
val maxFrameSize = 1024 * 1024
val retryMaxAttempts = 5L
val retryBackoffDelay = 100L
val retry = Retry.backoff(retryMaxAttempts, Duration.ofMillis(retryBackoffDelay))
.filter { it is WebClientException || it is IOException || it is ChannelException }
val transport = object : WebClientTransport(
ethereumUri.toString(),
MonoEthereum.mapper(),
requestTimeoutMs,
readWriteTimeoutMs
) {
override fun maxInMemorySize(): Int = maxFrameSize
override fun <T : Any?> get(url: String?, manifest: Manifest<T>?): Mono<T> =
super.get(url, manifest).retryWhen(retry)
override fun <T : Any?> send(request: Request?, manifest: Manifest<T>?): Mono<Response<T>> {
return super.send(request, manifest).retryWhen(retry)
}
}
return MonoEthereum(transport)
}
fun createTransactionPoller(ethereum: MonoEthereum): MonoTransactionPoller {
return MonoTransactionPoller(ethereum)
}
fun createUserSender(
privateKey: BigInteger,
ethereum: MonoEthereum
): MonoSigningTransactionSender {
return MonoSigningTransactionSender(
ethereum,
MonoSimpleNonceProvider(ethereum),
privateKey,
BigInteger.valueOf(8000000)
) { Mono.just(BigInteger.valueOf(800000)) }
}
}
|
protocol-e2e/src/main/kotlin/com/rarible/protocol/e2e/misc/WebClientProvider.kt | 4091722024 | package com.rarible.protocol.e2e.misc
import io.netty.channel.ChannelOption
import io.netty.channel.epoll.EpollChannelOption
import org.springframework.http.client.reactive.ClientHttpConnector
import org.springframework.http.client.reactive.ReactorClientHttpConnector
import org.springframework.web.reactive.function.client.WebClient
import reactor.netty.http.client.HttpClient
import reactor.netty.resources.ConnectionProvider
object WebClientProvider {
fun initTransport(): WebClient {
return WebClient.builder().run {
clientConnector(clientConnector())
build()
}
}
private fun clientConnector(): ClientHttpConnector {
val provider = ConnectionProvider.builder("webclient-connection-provider")
.maxConnections(1000)
.pendingAcquireMaxCount(-1)
.lifo()
.build()
val client = HttpClient.create(provider)
.option(ChannelOption.SO_KEEPALIVE, true)
.option(EpollChannelOption.TCP_KEEPIDLE, 300)
.option(EpollChannelOption.TCP_KEEPINTVL, 60)
.option(EpollChannelOption.TCP_KEEPCNT, 8)
return ReactorClientHttpConnector(client)
}
}
|
protocol-e2e/src/main/kotlin/com/rarible/protocol/e2e/misc/Mapper.kt | 1333486517 | package com.rarible.protocol.e2e.misc
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.KotlinModule
import com.rarible.protocol.union.api.ApiClient
object Mapper {
val mapper = ObjectMapper().also {
it.setDateFormat(ApiClient.createDefaultDateFormat())
it.registerModule(JavaTimeModule())
it.registerModule(KotlinModule())
it.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
it.enable(SerializationFeature.INDENT_OUTPUT)
}
}
|
protocol-e2e/src/main/kotlin/com/rarible/protocol/e2e/configuration/ProtocolIndexerApiClientsConfiguration.kt | 1252221991 | package com.rarible.protocol.e2e.configuration
import com.rarible.protocol.e2e.service.provide.WebClientCustomizerFactory
import com.rarible.protocol.erc20.api.client.Erc20IndexerApiClientFactory
import com.rarible.protocol.erc20.api.client.Erc20IndexerApiServiceUriProvider
import com.rarible.protocol.erc20.api.client.FixedErc20IndexerApiServiceUriProvider
import com.rarible.protocol.nft.api.client.FixedNftIndexerApiServiceUriProvider
import com.rarible.protocol.nft.api.client.NftIndexerApiClientFactory
import com.rarible.protocol.nft.api.client.NftIndexerApiServiceUriProvider
import com.rarible.protocol.order.api.client.FixedOrderIndexerApiServiceUriProvider
import com.rarible.protocol.order.api.client.OrderIndexerApiServiceUriProvider
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
@EnableConfigurationProperties(E2eProperties::class)
class ProtocolIndexerApiClientsConfiguration(
private val e2eProperties: E2eProperties,
webClientCustomizerFactory: WebClientCustomizerFactory
) {
private val customizer = webClientCustomizerFactory.create(e2eProperties.protocol.getApiKey())
@Bean
fun nftIndexerApiServiceUriProvider(): NftIndexerApiServiceUriProvider {
return FixedNftIndexerApiServiceUriProvider(e2eProperties.protocol.indexerEndpoint)
}
@Bean
fun orderIndexerApiServiceUriProvider(): OrderIndexerApiServiceUriProvider {
return FixedOrderIndexerApiServiceUriProvider(e2eProperties.protocol.indexerEndpoint)
}
@Bean
fun erc20IndexerApiServiceUriProvider(): Erc20IndexerApiServiceUriProvider {
return FixedErc20IndexerApiServiceUriProvider(e2eProperties.protocol.indexerEndpoint)
}
@Bean
fun nftIndexerApiClientFactory(
nftIndexerApiServiceUriProvider: NftIndexerApiServiceUriProvider
): NftIndexerApiClientFactory {
return NftIndexerApiClientFactory(nftIndexerApiServiceUriProvider, customizer)
}
@Bean
fun orderIndexerApiClientFactory(
orderIndexerApiServiceUriProvider: OrderIndexerApiServiceUriProvider
): NftIndexerApiClientFactory {
return NftIndexerApiClientFactory(orderIndexerApiServiceUriProvider, customizer)
}
@Bean
fun erc20IndexerApiClientFactory(
erc20IndexerApiServiceUriProvider: Erc20IndexerApiServiceUriProvider
): Erc20IndexerApiClientFactory {
return Erc20IndexerApiClientFactory(erc20IndexerApiServiceUriProvider, customizer)
}
}
|
protocol-e2e/src/main/kotlin/com/rarible/protocol/e2e/configuration/E2eProperties.kt | 2028920296 | package com.rarible.protocol.e2e.configuration
import com.rarible.protocol.e2e.model.ApiKey
import com.rarible.protocol.union.dto.BlockchainDto
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.context.properties.ConstructorBinding
import org.springframework.boot.context.properties.NestedConfigurationProperty
import scalether.domain.Address
import java.math.BigInteger
import java.net.URI
import java.net.URL
import java.util.UUID
internal const val RARIBLE_E2E = "e2e"
@ConstructorBinding
@ConfigurationProperties(RARIBLE_E2E)
data class E2eProperties(
val environment: String,
val blockchains: List<BlockchainDto>,
@NestedConfigurationProperty
val protocol: ProtocolClientProperties,
@NestedConfigurationProperty
val contentStorage: ContentStorageProperties,
@NestedConfigurationProperty
val nodes: ChainNodeProperties,
@NestedConfigurationProperty
val account: AccountProperties,
)
data class AccountProperties(
val evm: EvmAccountProperties
)
data class EvmAccountProperties(
val privateKey: BigInteger
)
data class ChainNodeProperties(
@NestedConfigurationProperty
val evm: Map<BlockchainDto, URL>
)
data class ProtocolClientProperties(
val unionEndpoint: URI,
val indexerEndpoint: URI,
val apiKey: String = UUID.randomUUID().toString()
) {
fun getApiKey(): ApiKey {
return ApiKey.protocolApiKey(apiKey)
}
}
data class ContentStorageProperties(
val endpoint: URI,
)
|
protocol-e2e/src/main/kotlin/com/rarible/protocol/e2e/configuration/ProtocolUnionApiClientsConfiguration.kt | 2119074601 | package com.rarible.protocol.e2e.configuration
import com.rarible.protocol.e2e.service.provide.WebClientCustomizerFactory
import com.rarible.protocol.union.api.client.FixedUnionApiServiceUriProvider
import com.rarible.protocol.union.api.client.ItemControllerApi
import com.rarible.protocol.union.api.client.UnionApiClientFactory
import com.rarible.protocol.union.api.client.UnionApiServiceUriProvider
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@Configuration
@EnableConfigurationProperties(E2eProperties::class)
class ProtocolUnionApiClientsConfiguration(
private val e2eProperties: E2eProperties,
webClientCustomizerFactory: WebClientCustomizerFactory
) {
private val customizer = webClientCustomizerFactory.create(e2eProperties.protocol.getApiKey())
@Bean
fun unionApiServiceUriProvider(): UnionApiServiceUriProvider {
return FixedUnionApiServiceUriProvider(e2eProperties.protocol.unionEndpoint)
}
@Bean
fun unionApiClientFactory(
unionApiServiceUriProvider: UnionApiServiceUriProvider
): UnionApiClientFactory {
return UnionApiClientFactory(unionApiServiceUriProvider, customizer)
}
@Bean
fun unionItemControllerApi(
unionApiClientFactory: UnionApiClientFactory
): ItemControllerApi {
return unionApiClientFactory.createItemApiClient()
}
}
|
protocol-e2e/src/main/kotlin/com/rarible/protocol/e2e/model/Content.kt | 1915957708 | package com.rarible.protocol.e2e.model
@Suppress("ArrayInDataClass")
data class Content(val payload: ByteArray) {
constructor(payload: String) : this(payload.toByteArray())
}
|
protocol-e2e/src/main/kotlin/com/rarible/protocol/e2e/model/ApiKey.kt | 2735952617 | package com.rarible.protocol.e2e.model
data class ApiKey(
val header: String,
val apiKey: String
) {
companion object {
fun protocolApiKey(apiKey: String): ApiKey {
return ApiKey("x-api-key", apiKey)
}
}
}
|
protocol-e2e/src/main/kotlin/com/rarible/protocol/e2e/model/UploadedContent.kt | 4238659958 | package com.rarible.protocol.e2e.model
import java.net.URL
class UploadedContent(
val name: String,
val url: URL
)
|
protocol-e2e/src/main/kotlin/com/rarible/protocol/e2e/model/MintMeta.kt | 3368742157 | package com.rarible.protocol.e2e.model
import java.net.URL
data class MintMeta(
val raw: String,
val content: ContentMeta,
val attributes: List<Attribute>
)
data class Attribute(
val key: String,
val value: String
)
data class ContentMeta(
val content: URL,
val mimeType: String,
val width: Int?,
val height: Int?,
)
|
protocol-e2e/src/main/kotlin/com/rarible/protocol/e2e/service/mint/CompositeMetaPreparer.kt | 4155543328 | package com.rarible.protocol.e2e.service.mint
import com.rarible.protocol.e2e.model.ContentMeta
import com.rarible.protocol.e2e.model.MintMeta
import com.rarible.protocol.e2e.service.mint.blockchain.MetaPreparer
import com.rarible.protocol.union.dto.BlockchainDto
import org.springframework.stereotype.Component
@Component
class CompositeMetaPreparer(
metaPreparers: List<MetaPreparer>
) {
private val preparers = metaPreparers
.flatMap { minter -> minter.supportedBlockchain.map { it to minter } }
.toMap()
suspend fun prepare(blockchain: BlockchainDto, content: ContentMeta): MintMeta {
return getMinter(blockchain).prepare(blockchain, content)
}
private fun getMinter(blockchain: BlockchainDto): MetaPreparer {
return preparers[blockchain] ?: throw IllegalArgumentException("Unsupported blockchain: $blockchain")
}
}
|
protocol-e2e/src/main/kotlin/com/rarible/protocol/e2e/service/mint/blockchain/MetaPreparer.kt | 2284661511 | package com.rarible.protocol.e2e.service.mint.blockchain
import com.rarible.protocol.e2e.model.ContentMeta
import com.rarible.protocol.e2e.model.MintMeta
import com.rarible.protocol.union.dto.BlockchainDto
interface MetaPreparer {
val supportedBlockchain: List<BlockchainDto>
suspend fun prepare(blockchain: BlockchainDto, content: ContentMeta): MintMeta
}
|
protocol-e2e/src/main/kotlin/com/rarible/protocol/e2e/service/mint/blockchain/MintService.kt | 2358140865 | package com.rarible.protocol.e2e.service.mint.blockchain
import com.rarible.protocol.e2e.model.MintMeta
import com.rarible.protocol.union.dto.BlockchainDto
import com.rarible.protocol.union.dto.ItemIdDto
interface MintService {
val supportedBlockchain: List<BlockchainDto>
suspend fun mintItem(blockchain: BlockchainDto, mintMeta: MintMeta): ItemIdDto
}
|
protocol-e2e/src/main/kotlin/com/rarible/protocol/e2e/service/mint/blockchain/EvmMetaPreparer.kt | 27758808 | package com.rarible.protocol.e2e.service.mint.blockchain
import com.rarible.protocol.e2e.misc.Mapper
import com.rarible.protocol.e2e.model.Attribute
import com.rarible.protocol.e2e.model.Content
import com.rarible.protocol.e2e.model.ContentMeta
import com.rarible.protocol.e2e.model.MintMeta
import com.rarible.protocol.e2e.service.content.ContentUploader
import com.rarible.protocol.union.dto.BlockchainDto
import com.rarible.protocol.union.dto.BlockchainGroupDto
import com.rarible.protocol.union.dto.subchains
import org.springframework.stereotype.Component
import java.util.UUID
@Component
class EvmMetaPreparer(
private val uploader: ContentUploader,
) : MetaPreparer {
override val supportedBlockchain = BlockchainGroupDto.ETHEREUM.subchains()
override suspend fun prepare(
blockchain: BlockchainDto,
content: ContentMeta
): MintMeta {
val evmMeta = EvmMeta(
name = "name-${UUID.randomUUID()}",
description = "description-${UUID.randomUUID()}",
image = content.content.toString(),
attributes = (1..10).map {
Attribute(
key = "key-${UUID.randomUUID()}",
value = "value-${UUID.randomUUID()}"
)
}
)
val raw = Mapper.mapper.writeValueAsString(evmMeta)
val tokenUrl = uploader.uploadContent(Content(raw)).url
return MintMeta(
raw = tokenUrl.toString(),
content = content,
attributes = evmMeta.attributes
)
}
private data class EvmMeta(
val name: String,
val description: String,
val image: String,
val attributes: List<Attribute>
)
}
|
protocol-e2e/src/main/kotlin/com/rarible/protocol/e2e/service/mint/blockchain/EvmMintService.kt | 3178162226 | package com.rarible.protocol.e2e.service.mint.blockchain
import com.rarible.protocol.e2e.configuration.E2eProperties
import com.rarible.protocol.e2e.misc.EthereumContractFactory
import com.rarible.protocol.e2e.misc.EthereumProvider
import com.rarible.protocol.e2e.model.MintMeta
import com.rarible.protocol.union.dto.BlockchainDto
import com.rarible.protocol.union.dto.BlockchainGroupDto
import com.rarible.protocol.union.dto.ItemIdDto
import com.rarible.protocol.union.dto.subchains
import kotlinx.coroutines.reactive.awaitFirst
import org.springframework.stereotype.Component
import kotlin.random.Random
@Component
class EvmMintService(
properties: E2eProperties
) : MintService {
private val nodes = properties.nodes.evm
private val account = properties.account.evm
override val supportedBlockchain = BlockchainGroupDto.ETHEREUM.subchains()
override suspend fun mintItem(blockchain: BlockchainDto, mintMeta: MintMeta): ItemIdDto {
require(blockchain in supportedBlockchain) { "Unsupported blockchain: $blockchain" }
val node = nodes[blockchain] ?: throw IllegalArgumentException("Can't find node for blockchain: $blockchain")
val ethereum = EthereumProvider.createEthereum(node)
val sender = EthereumProvider.createUserSender(account.privateKey, ethereum)
val poller = EthereumProvider.createTransactionPoller(ethereum)
val token = EthereumContractFactory.deployToken(sender, poller)
val tokenId = Random.nextInt(1, 1000).toBigInteger()
token.mint(sender.from(), tokenId).execute().awaitFirst()
return ItemIdDto(blockchain = blockchain, value = "${token.address().prefixed()}:$tokenId")
}
}
|
protocol-e2e/src/main/kotlin/com/rarible/protocol/e2e/service/mint/CompositeMintService.kt | 263677192 | package com.rarible.protocol.e2e.service.mint
import com.rarible.protocol.e2e.model.MintMeta
import com.rarible.protocol.e2e.service.mint.blockchain.MintService
import com.rarible.protocol.union.dto.BlockchainDto
import com.rarible.protocol.union.dto.ItemIdDto
import org.springframework.stereotype.Component
@Component
class CompositeMintService(
minters: List<MintService>
) {
private val minters = minters
.flatMap { minter -> minter.supportedBlockchain.map { it to minter } }
.toMap()
suspend fun mintItem(blockchain: BlockchainDto, mintMeta: MintMeta): ItemIdDto {
return getMinter(blockchain).mintItem(blockchain, mintMeta)
}
private fun getMinter(blockchain: BlockchainDto): MintService {
return minters[blockchain] ?: throw IllegalArgumentException("Unsupported blockchain: $blockchain")
}
}
|
protocol-e2e/src/main/kotlin/com/rarible/protocol/e2e/service/content/ContentUploader.kt | 2731518908 | package com.rarible.protocol.e2e.service.content
import com.rarible.protocol.e2e.configuration.E2eProperties
import com.rarible.protocol.e2e.misc.WebClientProvider
import com.rarible.protocol.e2e.model.Content
import com.rarible.protocol.e2e.model.UploadedContent
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import org.springframework.web.reactive.function.client.awaitBodilessEntity
import java.net.URL
import java.util.UUID
@Component
class ContentUploader(e2eProperties: E2eProperties) {
private val properties = e2eProperties.contentStorage
private val transport = WebClientProvider.initTransport()
suspend fun uploadContent(content: Content): UploadedContent {
val name = UUID.randomUUID().toString()
val url = "${properties.endpoint}/$name"
transport.put().uri(url).bodyValue(content.payload).retrieve().awaitBodilessEntity()
val upload = UploadedContent(name = name, url = URL(url))
logger.info("Uploaded content: {}", upload)
return upload
}
private companion object {
private val logger = LoggerFactory.getLogger(ContentUploader::class.java)
}
}
|
protocol-e2e/src/main/kotlin/com/rarible/protocol/e2e/service/content/ContentPreparer.kt | 1639398917 | package com.rarible.protocol.e2e.service.content
import com.rarible.core.meta.resource.detector.ContentDetector
import com.rarible.core.meta.resource.model.ContentData
import com.rarible.protocol.e2e.model.Content
import com.rarible.protocol.e2e.model.ContentMeta
import org.springframework.core.io.ClassPathResource
import org.springframework.stereotype.Component
@Component
class ContentPreparer(
private val contentUploader: ContentUploader
) {
private val contentDetector = ContentDetector()
suspend fun preparerImageContent(): ContentMeta {
val image = ClassPathResource("content/image/sample1.png").inputStream.use { it.readAllBytes() }
val uploaded = contentUploader.uploadContent(Content(image))
val meta = contentDetector.detect(ContentData(image), uploaded.name) ?: throw IllegalStateException("Can't detect image meta")
return ContentMeta(
content = uploaded.url,
mimeType = meta.mimeType,
width = meta.width,
height = meta.height,
)
}
}
|
protocol-e2e/src/main/kotlin/com/rarible/protocol/e2e/service/api/UnionService.kt | 1670109748 | package com.rarible.protocol.e2e.service.api
import com.rarible.protocol.union.api.client.ItemControllerApi
import com.rarible.protocol.union.dto.ItemDto
import com.rarible.protocol.union.dto.ItemIdDto
import kotlinx.coroutines.reactive.awaitFirstOrNull
import org.springframework.stereotype.Component
@Component
class UnionService(
protected val itemControllerApi: ItemControllerApi
) : AbstractApiService() {
suspend fun getItemById(itemIdDto: ItemIdDto): ItemDto? {
return clientRequest {
itemControllerApi.getItemById(itemIdDto.fullId()).awaitFirstOrNull()
}
}
} |
protocol-e2e/src/main/kotlin/com/rarible/protocol/e2e/service/api/AbstractApiService.kt | 3524318914 | package com.rarible.protocol.e2e.service.api
import org.springframework.http.HttpStatus
import org.springframework.web.reactive.function.client.WebClientResponseException
abstract class AbstractApiService {
protected suspend fun <T> clientRequest(body: suspend () -> T): T? {
return try {
body()
} catch (ex: WebClientResponseException) {
if (ex.statusCode == HttpStatus.NOT_FOUND) {
null
} else {
throw ex
}
}
}
}
|
protocol-e2e/src/main/kotlin/com/rarible/protocol/e2e/service/provide/WebClientCustomizerFactory.kt | 2435568172 | package com.rarible.protocol.e2e.service.provide
import com.rarible.protocol.client.CompositeWebClientCustomizer
import com.rarible.protocol.client.DefaultProtocolWebClientCustomizer
import com.rarible.protocol.e2e.model.ApiKey
import org.springframework.boot.web.reactive.function.client.WebClientCustomizer
import org.springframework.stereotype.Component
@Component
class WebClientCustomizerFactory {
fun create(
apiKey: ApiKey? = null
): WebClientCustomizer {
val customizers = listOfNotNull(
DefaultProtocolWebClientCustomizer("protocol-e2e"),
apiKey?.let { createApiKeyWebClientCustomizer(it) }
)
return CompositeWebClientCustomizer(customizers)
}
private fun createApiKeyWebClientCustomizer(apiKey: ApiKey): WebClientCustomizer {
return WebClientCustomizer { builder ->
builder.defaultHeaders { headers ->
headers.set(apiKey.header, apiKey.apiKey)
}
}
}
}
|
protocol-e2e/src/main/kotlin/com/rarible/protocol/e2e/ProtocolE2eApplication.kt | 2877208447 | package com.rarible.protocol.e2e
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class ProtocolE2eApplication
fun main(args: Array<String>) {
runApplication<ProtocolE2eApplication>(*args)
}
|
kotlin_learning-stopWatchDemo/src/main/kotlin/StopWatch.kt | 2554739301 | import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import kotlinx.coroutines.*
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.*
class StopWatch {
var formattedTime by mutableStateOf("00:00:000")
private var coroutineScopt = CoroutineScope(Dispatchers.Default)
private var isActive = false
private var timeMillis = 0L
private var lastTimestamp = 0L
fun start() {
if (isActive) return
coroutineScopt.launch {
lastTimestamp = System.currentTimeMillis()
[email protected] = true
while ([email protected]) {
delay(10L)
timeMillis += System.currentTimeMillis() - lastTimestamp
lastTimestamp = System.currentTimeMillis()
formattedTime = formatTime(timeMillis)
}
}
}
fun pause() {
isActive = false
}
fun reset() {
coroutineScopt.cancel()
coroutineScopt = CoroutineScope(Dispatchers.Default)
timeMillis = 0L
lastTimestamp = 0L
formattedTime = ("00:00:000")
isActive = false
}
private fun formatTime(timeMillis: Long): String {
val localDataTime = LocalDateTime.ofInstant(
Instant.ofEpochMilli(timeMillis),
ZoneId.systemDefault()
)
val formatter = DateTimeFormatter.ofPattern(
"mm:ss:SSS",
Locale.getDefault()
)
return localDataTime.format(formatter)
}
} |
kotlin_learning-stopWatchDemo/src/main/kotlin/StopWatchDisplay.kt | 1659998809 | import androidx.compose.foundation.layout.*
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import androidx.compose.ui.unit.dp
@Composable
fun StopWatchDisplay(
formattedTime: String,
onStartClick: () -> Unit,
onPauseClick: () -> Unit,
onResetClick: () -> Unit,
modifier: Modifier = Modifier
) {
Column(
modifier = modifier,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
text = "简易计时器",
fontWeight = FontWeight.Bold,
fontSize = 15.sp,
color = Color.Gray,
)
Spacer(Modifier.height(16.dp))
Text(
text = formattedTime,
fontWeight = FontWeight.Bold,
fontSize = 30.sp,
color = Color.Black,
)
Spacer(Modifier.height(16.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically,
) {
// show 开始 button when not active
Button(onStartClick) {
Text("开始")
}
Spacer(Modifier.width(16.dp))
Button(onPauseClick) {
Text("暂停")
}
Spacer(Modifier.width(16.dp))
Button(onResetClick) {
Text("重置")
}
}
}
} |
kotlin_learning-stopWatchDemo/src/main/kotlin/Main.kt | 3304208759 | import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
@Composable
@Preview
fun App() {
MaterialTheme {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize()
) {
val stopWatch = remember { StopWatch() }
StopWatchDisplay(
formattedTime = stopWatch.formattedTime,
onStartClick = stopWatch::start,
onPauseClick = stopWatch::pause,
onResetClick = stopWatch::reset,
)
}
}
}
fun main() = application {
Window(onCloseRequest = ::exitApplication) {
App()
}
}
|
2do_Dep_Juego_Mario/Mario.kt | 1043662697 | package Clases
import kotlin.concurrent.schedule
import java.util.*
class Mario(var vidas: Int = 3) { //Setear el numero de vidas por defecto en el contructor
init {
println("It's a me! Mario!")
}
private var state = "small"
set(value){
val before = field
field = value
println("Tu estado ahora es $field")
if(value=="Star"){
Timer("SettingUp", false).schedule(10000){
field = before
println("tu estado ahora es $field")
}
}
}
private var lives = 3
set(value){
if(field == 1){
field = 0
gameOver()
}
else if (field == 0){
println("Necesitas volver a jugar")
}
else{
field = value
}
}
val isAlive: Boolean
get(){
return lives >=1
}
/*private fun die(){
lives--
println("Has perdido una vida!")
}*/
fun collision(collisionObj: String){
when (collisionObj){
"Goomba" -> lives--
"Super Mushroom" -> state = "Super Mario"
"Fire flower" -> state = "Fire Mario"
"Star" -> state = "Star"
else -> println("Objeto desconocido, ¡No pasa nada!")
}
}
fun getLives(): String{
return "$lives vidas"
}
private fun gameOver(){
println("Juego Terminado")
}
} |
2do_Dep_Juego_Mario/Enemy.kt | 3902848016 | package Clases
open class Enemy (val name: String, val strength:Int){
init {
println("Iniciando superclase")
}
protected var direction: String = "Left"
protected fun changeDirection(){
direction = if (direction=="Right") "Left" else "Right"
println("$name va en dirección $direction")
}
protected fun die(){
println("$name ha muerto")
}
open fun collision(collider: String){
when (collider){
"Weapon" -> die()
"Enemy" -> changeDirection()
}
}
}
|
2do_Dep_Juego_Mario/Goomba.kt | 2979133946 | package Clases
class Goomba: Enemy("Goomba", 1){
//(name: String, strength: Int):
//Enemy(name,strength) {
//Enemy("Goomba",1) {
init {
println("Iniciando subclase de $name")
}
} |
2do_Dep_Juego_Mario/Main.kt | 1485804590 |
import Clases.Goomba
import Clases.Koopa
import Clases.Mario
/*fun main(){
//Clase Telefono
val myPhone = Phone()
myPhone.getTurn()
myPhone.turnOn()
myPhone.getTurn()
//Clase Vehiculo
val miVehiculo = Vehiculos("Ford","2020","Verde")
miVehiculo.placas = "NNT3047"
println("El coche está encendido? ${miVehiculo.encendido}")
miVehiculo.encender()
println("El coche encendio? ${miVehiculo.encendido}")
println("El tanque tiene ${miVehiculo.gasolina}")
miVehiculo.recargar(20.07f)
println("El tanque ahora tiene ${miVehiculo.gasolina}")
val golNegro = Vehiculos("Volkswagen", "Gol")
val sonicAzul = Vehiculos(
marca = "Ford",
modelo = "Sonic",
color = "Azul",
placas = "ALS9763"
)
println(golNegro)
println(sonicAzul)
}*/
fun main(){
var mario = Mario()
/*for (i in 1..5){
if(mario.isAlive){
mario.collision("Goomba")
println("Te quedan ${mario.getLives()}")
}
println("Te quedan ${mario.getLives()}")
}*/
mario.collision("star")
/*val enemy = Enemy("Un enemigo",2)
enemy.collision("Enemy")
enemy.collision("Weapon")*/
val enemy = Goomba()
enemy.collision("Enemy")
enemy.collision("Weapon")
val koopa = Koopa()
koopa.collision("Weapon")
}
|
2do_Dep_Juego_Mario/Person.kt | 1641046203 | package Clases
class Person (val Nombre: String, val Apellidos: String, val Sexo: String, val Altura: String){
} |
2do_Dep_Juego_Mario/Phone.kt | 2769991600 | package Clases
class Phone {
//atributos
var isOn= false
lateinit var model:String
//metodos
fun turnOn(){
isOn = true
}
fun turnOff(){
isOn = true
}
fun getTurn(){
val turnMode = if(isOn) "Encedido" else "Apagado"
println("El teléfono esta $turnMode")
}
} |
2do_Dep_Juego_Mario/Koopa.kt | 2908339922 | package Clases
class Koopa:
Enemy("Koopa", 2){
override fun collision(collider: String) {
//super.collision(collider)
when(collider){
"Weapon" -> {
var state = "Shell"
println("El estado ahora es $state")
}
"Enemy" -> changeDirection()
}
println("Usando la colisión de la clase Enemy")
}
}
|
2do_Dep_Juego_Mario/Vehiculos.kt | 3771331790 | package Clases
class Vehiculos (val marca: String, val modelo: String, var color: String = "Negro"){
init {
println("""Los datos del coche son:
marca: $marca
modelo: $modelo
color: $color""")
}
constructor(marca: String, modelo: String, color: String, placas: String): this(marca,modelo,color){
this.placas = placas
println("Las placas son: ${this.placas}")
}
//atributos
var placas = ""
var gasolina = 0f
var encendido = false
//metodos
fun encender(){
encendido = true
}
fun apagar(){
encendido = false
}
fun recargar(litros:Float){
gasolina+=litros
}
}
|
kopring_graphql_querydsl/common/lib/src/main/kotlin/kr/co/anna/lib/config/MessageConfig.kt | 1848389810 | package kr.co.anna.lib.config
import kr.co.anna.lib.utils.MessageUtil
import org.springframework.context.MessageSource
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.support.MessageSourceAccessor
import org.springframework.context.support.ReloadableResourceBundleMessageSource
import org.springframework.web.servlet.LocaleResolver
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver
import java.util.*
@Configuration
class MessageConfig {
@Bean
fun localeResolver(): LocaleResolver {
val localeResolver = AcceptHeaderLocaleResolver()
localeResolver.defaultLocale = Locale.KOREA //언어&국가정보가 없는 경우 한국으로 인식
return localeResolver
}
@Bean
fun messageSource(): MessageSource {
val messageSource = ReloadableResourceBundleMessageSource()
messageSource.setBasenames("classpath:/messages/message")
messageSource.setDefaultEncoding("utf-8")
messageSource.setCacheSeconds(180) // 리로딩 간격
Locale.setDefault(Locale.KOREA) // 제공하지 않는 언어로 요청이 들어왔을 때 MessageSource에서 사용할 기본 언어정보.
return messageSource
}
@Bean
fun messageSourceAccessor(): MessageSourceAccessor {
return MessageSourceAccessor(messageSource()!!)
}
@Bean
fun messageUtils() {
MessageUtil.messageSourceAccessor = messageSourceAccessor()!!
}
}
|
kopring_graphql_querydsl/common/lib/src/main/kotlin/kr/co/anna/lib/security/jwt/JwtProcessor.kt | 3808581028 | package kr.co.anna.lib.security.jwt
import io.jsonwebtoken.Claims
import io.jsonwebtoken.Jws
import io.jsonwebtoken.Jwts
import io.jsonwebtoken.io.Decoders
import io.jsonwebtoken.security.Keys
import kr.co.anna.lib.error.JwtUnauthenticatedAccessException
import kr.co.anna.lib.security.AuthUser
import kr.co.anna.lib.security.SignInUser
import kr.co.anna.lib.security.UserDetailsServiceImpl
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.stereotype.Component
/**
* JWT 문자열을 처리하는 책임을 가진 객체
* JWT 토큰에서 인증 정보 조회
*/
@Component
class JwtProcessor(
private val jwtProperties: JwtProperties,
private val userDetailsServiceImpl: UserDetailsServiceImpl
) {
/**
* jwt 문자열을 파싱하고 사용자 정보를 UsernamePasswordAuthenticationToken 에 담아 반환
* UsernamePasswordAuthenticationToken 는 JwtFilter를 통해 Spring Security Context 에 저장되고,
* SecurityContextHolder.getContext().authentication 로 꺼내서 사용 가능
*/
fun extractAuthentication(jwt: String): UsernamePasswordAuthenticationToken {
val jws = parse(jwt)
val body = jws.body
val userId = body[JwtKeys.UID.keyName].toString()
val userOid = (body[JwtKeys.USER_OID.keyName] as Int).toLong()
val userDetails = userDetailsServiceImpl.loadUserByUsername(userId) as SignInUser //db에서 id확인
if (userDetails.userOid() != userOid) throw JwtUnauthenticatedAccessException()
return UsernamePasswordAuthenticationToken(AuthUser(userDetails), jws, userDetails.authorities)
}
private fun parse(token: String): Jws<Claims> {
return Jwts.parserBuilder()
.setSigningKey(Keys.hmacShaKeyFor(Decoders.BASE64.decode(jwtProperties.base64EncodedSecret)))
.build()
.parseClaimsJws(token)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.