content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package com.dtks.quickmuseum.ui.overview import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier @OptIn(ExperimentalMaterial3Api::class) @Composable fun OverviewTopBar(title: String) { TopAppBar( title = { Text(text = title) }, modifier = Modifier.fillMaxWidth() ) }
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/overview/OverviewTopBar.kt
1669009789
package com.dtks.quickmuseum.ui.overview data class OverviewUiState( val userMessage: Int? = null, val isEmpty: Boolean = false, val isLoading: Boolean = false, val items: List<ArtObjectListItem> = emptyList(), )
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/ui/overview/OverviewUiState.kt
3505635252
package com.dtks.quickmuseum.di import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import javax.inject.Qualifier import javax.inject.Singleton @Qualifier @Retention(AnnotationRetention.RUNTIME) annotation class IoDispatcher @Retention(AnnotationRetention.RUNTIME) @Qualifier annotation class DefaultDispatcher @Retention(AnnotationRetention.RUNTIME) @Qualifier annotation class ApplicationScope @Module @InstallIn(SingletonComponent::class) object CoroutinesModule { @Provides @IoDispatcher fun providesIODispatcher(): CoroutineDispatcher = Dispatchers.IO @Provides @DefaultDispatcher fun providesDefaultDispatcher(): CoroutineDispatcher = Dispatchers.Default @Provides @Singleton @ApplicationScope fun providesCoroutineScope( @DefaultDispatcher dispatcher: CoroutineDispatcher ): CoroutineScope = CoroutineScope(SupervisorJob() + dispatcher) }
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/di/CoroutinesModule.kt
761507023
package com.dtks.quickmuseum.di import com.dtks.quickmuseum.data.api.RijksMuseumApi import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object NetworkModule { private const val BASE_URL = "https://www.rijksmuseum.nl/api/" @Singleton @Provides fun provideHttpClient(): OkHttpClient { val interceptor = HttpLoggingInterceptor() interceptor.setLevel(HttpLoggingInterceptor.Level.BODY) return OkHttpClient.Builder() .addInterceptor(interceptor) .readTimeout(15, TimeUnit.SECONDS) .connectTimeout(15, TimeUnit.SECONDS) .build() } @Singleton @Provides fun provideConverterFactory(): GsonConverterFactory { return GsonConverterFactory.create() } @Singleton @Provides fun provideRetrofitInstance( okHttpClient: OkHttpClient, gsonConverterFactory: GsonConverterFactory ): Retrofit { return Retrofit.Builder() .baseUrl(BASE_URL) .client(okHttpClient) .addConverterFactory(gsonConverterFactory) .build() } @Provides @Singleton fun provideRijksMuseumApi(retrofit: Retrofit): RijksMuseumApi = retrofit.create(RijksMuseumApi::class.java) }
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/di/NetworkModule.kt
1216945480
package com.dtks.quickmuseum import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.material3.MaterialTheme import com.dtks.quickmuseum.ui.navigation.QuickMuseumNavGraph import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class QuickMuseumActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MaterialTheme { QuickMuseumNavGraph() } } } }
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/QuickMuseumActivity.kt
1403567693
package com.dtks.quickmuseum.utils sealed class AsyncResource<out T> { object Loading : AsyncResource<Nothing>() data class Error(val errorMessage: Int) : AsyncResource<Nothing>() data class Success<out T>(val data: T) : AsyncResource<T>() }
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/utils/AsyncResource.kt
38044972
package com.dtks.quickmuseum.utils import kotlinx.coroutines.flow.SharingStarted private const val StopTimeoutMillis: Long = 5000 val WhileUiSubscribed: SharingStarted = SharingStarted.WhileSubscribed(StopTimeoutMillis)
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/utils/CoroutinesUtils.kt
752373781
package com.dtks.quickmuseum import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class QuickMuseumApplication : Application()
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/QuickMuseumApplication.kt
2033835346
package com.dtks.quickmuseum.data.repository import com.dtks.quickmuseum.data.RemoteDataSource import com.dtks.quickmuseum.data.model.ArtDetailsRequest import com.dtks.quickmuseum.di.DefaultDispatcher import com.dtks.quickmuseum.ui.details.ArtDetails import com.dtks.quickmuseum.ui.details.ArtDetailsImage import dagger.hilt.android.scopes.ViewModelScoped import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.withContext import javax.inject.Inject @ViewModelScoped class ArtDetailsRepository @Inject constructor( private val remoteDataSource: RemoteDataSource, @DefaultDispatcher private val dispatcher: CoroutineDispatcher, ) { suspend fun getArtDetails(artDetailsRequest: ArtDetailsRequest): ArtDetails { return withContext(dispatcher) { val artDetailsResponse = remoteDataSource.getArtDetails(artDetailsRequest) val artDetails = artDetailsResponse.artObject ArtDetails( id = artDetails.id, objectNumber = artDetails.objectNumber, title = artDetails.title, creators = artDetails.principalMakers.map { it.name }, materials = artDetails.materials, techniques = artDetails.techniques, dating = artDetails.dating?.presentingDate, image = artDetails.webImage?.let { ArtDetailsImage( url = it.url, width = it.width, height = it.height ) } ) } } fun getArtDetailsFlow(artDetailsRequest: ArtDetailsRequest): Flow<ArtDetails> = flow { emit(getArtDetails(artDetailsRequest)) } }
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/data/repository/ArtDetailsRepository.kt
187020808
package com.dtks.quickmuseum.data.repository import com.dtks.quickmuseum.data.RemoteDataSource import com.dtks.quickmuseum.data.model.CollectionRequest import com.dtks.quickmuseum.di.DefaultDispatcher import com.dtks.quickmuseum.ui.overview.ArtObjectListItem import dagger.hilt.android.scopes.ViewModelScoped import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.withContext import javax.inject.Inject @ViewModelScoped class OverviewRepository @Inject constructor( private val remoteDataSource: RemoteDataSource, @DefaultDispatcher private val dispatcher: CoroutineDispatcher, ){ suspend fun getOverviewArtObjects(collectionRequest: CollectionRequest): List<ArtObjectListItem> { return withContext(dispatcher) { remoteDataSource.getCollection(collectionRequest).artObjects.filter { it.hasImage }.map { ArtObjectListItem( id = it.id, title = it.title, creator = it.principalOrFirstMaker, imageUrl = it.webImage?.url, objectNumber = it.objectNumber ) } } } fun getCollectionFlow(collectionRequest: CollectionRequest): Flow<List<ArtObjectListItem>> = flow { emit(getOverviewArtObjects(collectionRequest)) } }
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/data/repository/OverviewRepository.kt
1472904778
package com.dtks.quickmuseum.data import com.dtks.quickmuseum.data.api.RijksMuseumApi import com.dtks.quickmuseum.data.model.ArtDetailsRequest import com.dtks.quickmuseum.data.model.ArtDetailsResponse import com.dtks.quickmuseum.data.model.CollectionRequest import com.dtks.quickmuseum.data.model.CollectionResponse import javax.inject.Inject class RemoteDataSource @Inject constructor( private val rijksMuseumApi: RijksMuseumApi ) { suspend fun getCollection(collectionRequest: CollectionRequest): CollectionResponse { return rijksMuseumApi.getCollection( searchType = collectionRequest.searchType, page = collectionRequest.page, pageSize = collectionRequest.pageSize, language = collectionRequest.language ) } suspend fun getArtDetails(artDetailsRequest: ArtDetailsRequest): ArtDetailsResponse { return rijksMuseumApi.getArtDetails( artObjectNumber = artDetailsRequest.artObjectNumber, language = artDetailsRequest.language ) } }
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/data/RemoteDataSource.kt
3940395843
package com.dtks.quickmuseum.data.model data class ArtDetailsRequest( val artObjectNumber: String, val language: String = "en", )
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/data/model/ArtDetailsRequest.kt
428892768
package com.dtks.quickmuseum.data.model data class ArtObjectDao( val id: String, val objectNumber: String, val title: String, val hasImage: Boolean, val principalOrFirstMaker: String, val webImage: WebImage? )
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/data/model/ArtObjectDao.kt
2536135750
package com.dtks.quickmuseum.data.model data class CollectionResponse( val count: Long, val artObjects: List<ArtObjectDao>, )
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/data/model/CollectionResponse.kt
2467439500
package com.dtks.quickmuseum.data.model data class ArtDetailsResponse( val artObject: ArtDetailsDao )
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/data/model/ArtDetailsResponse.kt
4257592535
package com.dtks.quickmuseum.data.model data class ArtDetailsDao( val id: String, val objectNumber: String, val title: String, val principalMakers: List<ArtCreator>, val materials: List<String>?, val techniques: List<String>?, val dating: Dating?, val webImage: WebImage? )
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/data/model/ArtDetailsDao.kt
2963975366
package com.dtks.quickmuseum.data.model data class WebImage( val guid: String, val width: Int, val height: Int, val url: String? = null )
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/data/model/WebImage.kt
59438240
package com.dtks.quickmuseum.data.model data class ArtCreator( val name: String, val nationality: String?, val occupation: List<String>?, val roles: List<String>?, )
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/data/model/ArtCreator.kt
709518188
package com.dtks.quickmuseum.data.model data class Dating( val presentingDate: String )
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/data/model/Dating.kt
3450308172
package com.dtks.quickmuseum.data.model data class CollectionRequest( val searchType: String = "relevance", val page: Int = 1, val pageSize: Int = 50, val language: String = "en", )
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/data/model/CollectionRequest.kt
3653824033
package com.dtks.quickmuseum.data.api import com.dtks.quickmuseum.data.model.ArtDetailsResponse import com.dtks.quickmuseum.data.model.CollectionResponse import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query interface RijksMuseumApi { @GET("{culture}/collection") suspend fun getCollection( @Path("culture") language: String = "en", @Query("s") searchType: String = "relevance", @Query("p") page: Int = 0, @Query("ps") pageSize: Int = 10, @Query("key") apiKey: String = API_KEY ): CollectionResponse @GET("{culture}/collection/{artObjectNumber}") suspend fun getArtDetails( @Path("culture") language: String = "en", @Path("artObjectNumber") artObjectNumber: String, @Query("key") apiKey: String = API_KEY ): ArtDetailsResponse companion object { private const val API_KEY = "0fiuZFh4" } }
QuickMuseum/app/src/main/java/com/dtks/quickmuseum/data/api/RijksMuseumApi.kt
4219232049
package br.com.devcapu.nestedscrollexample 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("br.com.devcapu.nestedscrollexample", appContext.packageName) } }
NestedScrollExample/app/src/androidTest/java/br/com/devcapu/nestedscrollexample/ExampleInstrumentedTest.kt
1462851345
package br.com.devcapu.nestedscrollexample 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) } }
NestedScrollExample/app/src/test/java/br/com/devcapu/nestedscrollexample/ExampleUnitTest.kt
3750543286
package br.com.devcapu.nestedscrollexample.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)
NestedScrollExample/app/src/main/java/br/com/devcapu/nestedscrollexample/ui/theme/Color.kt
3811189157
package br.com.devcapu.nestedscrollexample.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun NestedScrollExampleTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
NestedScrollExample/app/src/main/java/br/com/devcapu/nestedscrollexample/ui/theme/Theme.kt
2319342368
package br.com.devcapu.nestedscrollexample.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
NestedScrollExample/app/src/main/java/br/com/devcapu/nestedscrollexample/ui/theme/Type.kt
3084803422
package br.com.devcapu.nestedscrollexample import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import br.com.devcapu.nestedscrollexample.ui.theme.NestedScrollExampleTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { NestedScrollExampleTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Greeting("Android") } } } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Text( text = "Hello $name!", modifier = modifier ) } @Preview(showBackground = true) @Composable fun GreetingPreview() { NestedScrollExampleTheme { Greeting("Android") } }
NestedScrollExample/app/src/main/java/br/com/devcapu/nestedscrollexample/MainActivity.kt
2325333046
package be.helmo.planivacances 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("be.helmo.planivancances", appContext.packageName) } }
mobile-planivacances/app/src/androidTest/java/be/helmo/planivacances/ExampleInstrumentedTest.kt
1802419454
package be.helmo.planivacances 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) } }
mobile-planivacances/app/src/test/java/be/helmo/planivacances/ExampleUnitTest.kt
3697766357
package be.helmo.planivacances.util import be.helmo.planivacances.domain.Group import be.helmo.planivacances.domain.Place import be.helmo.planivacances.presenter.viewmodel.* import be.helmo.planivacances.service.dto.ActivityDTO import be.helmo.planivacances.service.dto.GroupDTO import be.helmo.planivacances.service.dto.GroupInviteDTO import be.helmo.planivacances.service.dto.PlaceDTO import com.google.android.gms.maps.model.LatLng object DTOMapper { fun groupToGroupDTO(group: Group) : GroupDTO { return GroupDTO( "null", group.groupName, group.description, group.startDate, group.endDate, placeToPlaceDTO(group.place) ) } fun groupDtoToGroup(groupDTO: GroupDTO) : Group { return Group( groupDTO.groupName, groupDTO.description, groupDTO.startDate, groupDTO.endDate, placeDtoToPlace(groupDTO.place), groupDTO.owner!! ) } fun groupToGroupListItem(gid: String, group: Group) : GroupListItemVM { return GroupListItemVM( gid, group.groupName, group.description, group.startDate, group.endDate ) } fun groupToGroupVM(group: Group) : GroupVM { val placeVM : PlaceVM = placeToPlaceVM(group.place) return GroupVM(group.groupName,group.description,group.startDate,group.endDate,placeVM) } fun groupVMToGroupDTO(groupVM: GroupVM,owner: String,gid:String) : GroupDTO { val placeDTO = placeVMToPlaceDTO(groupVM.place) return GroupDTO(gid,groupVM.name,groupVM.description,groupVM.startDate,groupVM.endDate,placeDTO,owner) } fun placeToPlaceDTO(place: Place) : PlaceDTO { return PlaceDTO( place.country, place.city, place.street, place.number, place.postalCode, place.latLng.latitude, place.latLng.longitude ) } fun placeDtoToPlace(placeDTO: PlaceDTO) : Place { return Place( placeDTO.country, placeDTO.city, if (placeDTO.street != null) placeDTO.street else "", if (placeDTO.number != null) placeDTO.number else "", placeDTO.postalCode, LatLng(placeDTO.lat, placeDTO.lon) ) } fun placeToPlaceVM(place: Place) : PlaceVM { return PlaceVM(place.street,place.number,place.postalCode,place.city,place.country, LatLng(place.latLng.latitude,place.latLng.longitude) ) } fun placeVMToPlaceDTO(placeVM: PlaceVM) : PlaceDTO { return PlaceDTO(placeVM.country,placeVM.city,placeVM.street,placeVM.number,placeVM.postalCode,placeVM.latLng.latitude,placeVM.latLng.longitude) } fun placeDTOToPlaceVM(placeDTO: PlaceDTO) : PlaceVM { return PlaceVM(placeDTO.street,placeDTO.number,placeDTO.postalCode,placeDTO.city,placeDTO.country, LatLng(placeDTO.lat,placeDTO.lon) ) } fun activityVMToActivityDTO(activityVM: ActivityVM) : ActivityDTO { val placeDTO : PlaceDTO = placeVMToPlaceDTO(activityVM.place) return ActivityDTO(activityVM.title,activityVM.description,activityVM.startDate,activityVM.duration,placeDTO) } fun activityDTOToActivityVM(activityDTO: ActivityDTO) : ActivityVM { val placeVM : PlaceVM = placeDTOToPlaceVM(activityDTO.place) return ActivityVM(activityDTO.title,activityDTO.description,activityDTO.startDate,activityDTO.duration,placeVM) } fun groupInviteDTOToGroupInvitationVM(groupInviteDTO: GroupInviteDTO) : GroupInvitationVM { return GroupInvitationVM(groupInviteDTO.gid,groupInviteDTO.groupName,"Rejoindre le groupe") } }
mobile-planivacances/app/src/main/java/be/helmo/planivacances/util/DTOMapper.kt
3214316675
package be.helmo.planivacances.util import java.text.SimpleDateFormat import java.util.* object DateFormatter { fun formatTimestampForDisplay(timestamp: Long): String { val date = Date(timestamp) val format = SimpleDateFormat("dd/MM/yyyy - HH'h'mm", Locale.getDefault()) return format.format(date) } }
mobile-planivacances/app/src/main/java/be/helmo/planivacances/util/DateFormatter.kt
53178976
package be.helmo.planivacances.presenter.viewmodel data class GroupDetailVM(val groupName: String, val description: String, val period : String, val address: String)
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/viewmodel/GroupDetailVM.kt
428815704
package be.helmo.planivacances.presenter.viewmodel import java.util.* data class GroupListItemVM( var gid: String? = null, val groupName: String, val description: String, val startDate: Date, val endDate: Date)
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/viewmodel/GroupListItemVM.kt
3543483726
package be.helmo.planivacances.presenter.viewmodel data class WeatherForecastVM(val imageUrl: String, val temperature: String, val date: String, val infos: String)
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/viewmodel/WeatherForecastVM.kt
4788105
package be.helmo.planivacances.presenter.viewmodel import com.google.android.gms.maps.model.LatLng data class PlaceVM(val street : String, val number : String, val postalCode : String, val city : String, val country: String, val latLng: LatLng )
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/viewmodel/PlaceVM.kt
4270062884
package be.helmo.planivacances.presenter.viewmodel data class ActivityDetailVM( val activityTitle:String, val activityPeriod: String, val activityPlace: String, val activityDescription: String )
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/viewmodel/ActivityDetailVM.kt
1391650138
package be.helmo.planivacances.presenter.viewmodel import java.util.* data class GroupVM( val name:String, val description: String, val startDate: Date, val endDate: Date, val place: PlaceVM )
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/viewmodel/GroupVM.kt
2320907291
package be.helmo.planivacances.presenter.viewmodel data class ActivityListItemVM( val aid: String, val title: String, val startHour: String, val duration: String )
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/viewmodel/ActivityListItemVM.kt
107657653
package be.helmo.planivacances.presenter.viewmodel import java.util.* data class ActivityVM( val title: String, val description: String, val startDate: Date, val duration: Int, val place: PlaceVM )
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/viewmodel/ActivityVM.kt
1129489815
package be.helmo.planivacances.presenter.viewmodel data class GroupInvitationVM( val gid:String, val groupName: String, val content: String )
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/viewmodel/GroupInvitationVM.kt
2136865911
package be.helmo.planivacances.presenter import android.util.Log import be.helmo.planivacances.presenter.interfaces.ITchatView import be.helmo.planivacances.service.ApiClient import be.helmo.planivacances.service.dto.MessageDTO import be.helmo.planivacances.view.interfaces.IAuthPresenter import be.helmo.planivacances.view.interfaces.IGroupPresenter import be.helmo.planivacances.view.interfaces.ITchatPresenter import com.pusher.client.Pusher import com.pusher.client.channel.PrivateChannel import com.pusher.client.channel.PrivateChannelEventListener import com.pusher.client.channel.PusherEvent import com.pusher.client.connection.ConnectionState import com.pusher.client.connection.ConnectionStateChange import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import java.lang.Exception class TchatPresenter(val groupPresenter: IGroupPresenter, val authPresenter: IAuthPresenter) : ITchatPresenter { lateinit var tchatView : ITchatView lateinit var tchatService : Pusher lateinit var channel: PrivateChannel var previousMessageLoaded : Boolean = false override fun setITchatView(tchatView: ITchatView) { this.tchatView = tchatView } override suspend fun connectToTchat() { tchatService = ApiClient.getTchatInstance() tchatService.connect(object:com.pusher.client.connection.ConnectionEventListener { override fun onConnectionStateChange(change: ConnectionStateChange?) { if (change != null) { Log.d("Tchat Presenter : ", "Etat de la connexion : ${change.currentState}") if(change.currentState == ConnectionState.CONNECTED) { subscribeToGroupChannel() } } } override fun onError(message: String?, code: String?, e: Exception?) { Log.d("Tchat presenter : ", "Erreur durant la connexion au tchat : $message") } }) } fun subscribeToGroupChannel() { channel = tchatService.subscribePrivate( "private-${groupPresenter.getCurrentGroupId()}", object:PrivateChannelEventListener { override fun onEvent(event: PusherEvent?) {} override fun onSubscriptionSucceeded(channelName: String?) { Log.d("Tchat presenter : ","Suscription ok => $channelName") bindToEvents() CoroutineScope(Dispatchers.Main).launch { loadPreviousMessages() } } override fun onAuthenticationFailure(message: String?, e: Exception?) { Log.d("Tchat presenter","Suscription failed : $message") } }) } fun bindToEvents() { channel.bind("new_messages",object:PrivateChannelEventListener { override fun onEvent(event: PusherEvent?) { if(previousMessageLoaded) { Log.d("Tchat presenter : ", "${event?.eventName} => ${event?.data}") if (event?.data != null) { val messageDTO : MessageDTO? = ApiClient.formatMessageToDisplay(event.data) if(messageDTO != null) { sendMessageToView(messageDTO) } } } } override fun onSubscriptionSucceeded(channelName: String?) { } override fun onAuthenticationFailure(message: String?, e: Exception?) { } }) } suspend fun loadPreviousMessages() { val response = ApiClient .tchatService .getPreviousMessages(groupPresenter.getCurrentGroupId()) if(response.isSuccessful && response.body() != null) { val messages : List<MessageDTO> = response.body()!! for(message in messages) { sendMessageToView(message) } previousMessageLoaded = true } tchatView.stopLoading() } fun sendMessageToView(message: MessageDTO) { if(message.sender == authPresenter.getUid()) { message.sender = "me" } else { message.sender = "other" } tchatView.addMessageToView(message) } override fun sendMessage(message: String) { if(message.isNotEmpty()) { val messageDTO = MessageDTO( authPresenter.getUid(), authPresenter.getDisplayName(), groupPresenter.getCurrentGroupId(), message, System.currentTimeMillis() ) CoroutineScope(Dispatchers.Default).launch { ApiClient.tchatService.sendMessage(messageDTO) } } } override fun disconnectToTchat() { channel.unbind("new_messages",object:PrivateChannelEventListener { override fun onEvent(event: PusherEvent?) {} override fun onSubscriptionSucceeded(channelName: String?) {} override fun onAuthenticationFailure(message: String?, e: Exception?) {} }) tchatService.unsubscribe("private-${groupPresenter.getCurrentGroupId()}") tchatService.disconnect() } }
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/TchatPresenter.kt
2424026119
package be.helmo.planivacances.presenter import android.util.Log import be.helmo.planivacances.domain.Group import be.helmo.planivacances.presenter.viewmodel.GroupListItemVM 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.GroupDetailVM import be.helmo.planivacances.presenter.viewmodel.GroupInvitationVM import be.helmo.planivacances.presenter.viewmodel.GroupVM import be.helmo.planivacances.service.ApiClient import be.helmo.planivacances.service.dto.GroupDTO import be.helmo.planivacances.util.DTOMapper import be.helmo.planivacances.view.interfaces.IGroupPresenter import com.google.firebase.auth.FirebaseAuth import java.text.SimpleDateFormat class GroupPresenter : IGroupPresenter { lateinit var groupView: IGroupView lateinit var createGroupView: ICreateGroupView lateinit var updateGroupView: IUpdateGroupView lateinit var homeView: IHomeView var groups : HashMap<String, Group> = HashMap() lateinit var currentGid : String /** * Crée un groupe * @param groupVM (GroupVM) */ override suspend fun createGroup(groupVM: GroupVM) { val groupDto = DTOMapper.groupVMToGroupDTO(groupVM, "null", "null") val group = DTOMapper.groupDtoToGroup(groupDto) try { val response = ApiClient.groupService.create(groupDto) if (response.isSuccessful && response.body() != null) { val gid = response.body()!! currentGid = gid group.owner = FirebaseAuth.getInstance().uid!! groups[gid] = group Log.d("CreateGroupFragment", "Group created : $gid") createGroupView.onGroupCreated() } else { Log.d("CreateGroupFragment", "${response.message()}, ${response.isSuccessful}") createGroupView.showToast( "Erreur lors de la création du groupe ${response.message()}", 1 ) } } catch (e: Exception) { createGroupView.showToast("Erreur durant la création du groupe", 1) } } /** * Charge les groupes de l'utilisateur */ override suspend fun loadUserGroups() { try { groups.clear() currentGid = "" val response = ApiClient.groupService.getList() if (response.isSuccessful && response.body() != null) { val groupsDto = response.body()!! Log.d("ag", response.body().toString()) for(groupDto in groupsDto) { Log.d("gg", groupDto.place.city) groups[groupDto.gid!!] = DTOMapper.groupDtoToGroup(groupDto) } Log.d("GroupFragment", "Groups retrieved : ${groups.size}") homeView.setGroupList(getGroupListItems()) } else { Log.d("GroupFragment", "${response.message()}, ${response.isSuccessful}") homeView.showToast( "Erreur lors de la récupération des groupes ${response.message()}", 1 ) } } catch (e: Exception) { Log.d("GroupFragment", "Erreur durant la récupération des groupes : ${e.message}") homeView.showToast("Erreur durant la récupération des groupes", 1) } } /** * Charge les données nécessaires à l'affichage de l'itinéraire */ override fun loadItinerary() { val place = groups[currentGid]?.place val latitude = place?.latLng?.latitude.toString() val longitude = place?.latLng?.longitude.toString() groupView.buildItinerary(latitude,longitude) } override fun showGroupInfos() { val group = getCurrentGroup()!! val formatter = SimpleDateFormat("dd/MM/yyyy") val startDate = formatter.format(group.startDate) val endDate = formatter.format(group.endDate) val groupDetailVM = GroupDetailVM(group.groupName, group.description, "Du $startDate au $endDate", getCurrentGroupPlace().address) groupView.setGroupInfos(groupDetailVM) } /** * Récupère la liste des groupes * @return (List<GroupDTO>) */ fun getGroupListItems(): List<GroupListItemVM> { return groups.entries.map { (gid, group) -> DTOMapper.groupToGroupListItem(gid, group) } } /** * Récupère le groupe courant * @return (GroupDTO) */ override fun getCurrentGroup(): Group? { return groups[currentGid] } /** * Récupère le lieu du groupe courant * @return (Place) */ override fun getCurrentGroupPlace(): Place { return groups[currentGid]?.place!! } /** * Récupère l'id du groupe courant * @return (String) */ override fun getCurrentGroupId(): String { return currentGid } /** * Assigne l'id du groupe séléctionné * @param gid (String) */ override fun setCurrentGroupId(gid: String) { currentGid = gid } /** * Assigne la GroupView Interface */ override fun setIGroupView(groupView: IGroupView) { this.groupView = groupView } /** * Assigne la CreateGroupView Interface */ override fun setICreateGroupView(createGroupView: ICreateGroupView) { this.createGroupView = createGroupView } override fun setIUpdateGroupView(updateGroupView: IUpdateGroupView) { this.updateGroupView = updateGroupView } /** * Assigne la HomeView Interface */ override fun setIHomeView(homeView: IHomeView) { this.homeView = homeView } override fun loadCurrentGroup() { val currentGroupVM : GroupVM = DTOMapper.groupToGroupVM(getCurrentGroup()!!) updateGroupView.setCurrentGroup(currentGroupVM) } override suspend fun updateCurrentGroup(groupVM: GroupVM) { val group = getCurrentGroup() val groupDTO : GroupDTO = DTOMapper.groupVMToGroupDTO(groupVM,group?.owner!!,currentGid) val response = ApiClient.groupService.update(currentGid,groupDTO) if(response.isSuccessful) { updateGroupView.onGroupUpdated() } else { updateGroupView.showToast("Erreur lors de la mise à jour du groupe",1) } } override suspend fun deleteCurrentGroup() { val response = ApiClient.groupService.delete(currentGid) if(response.isSuccessful) { groupView.onGroupDeleted() } else { groupView.showToast("Erreur durant la suppression du groupe",1) } } override suspend fun loadUserGroupInvites() { val response = ApiClient.groupService.getUserGroupInvites() if(response.isSuccessful && response.body() != null) { val groupInvitationsList : ArrayList<GroupInvitationVM> = ArrayList() for(invitation in response.body()!!) { groupInvitationsList.add(DTOMapper.groupInviteDTOToGroupInvitationVM(invitation)) } homeView.onGroupInvitationsLoaded(groupInvitationsList) } else { homeView.showToast("Erreur durant le chargement des invitations",1) } } override suspend fun sendGroupInvite(email:String) { val currentUserMail = FirebaseAuth.getInstance().currentUser?.email if(currentUserMail != null && currentUserMail != email) { val response = ApiClient.groupService.inviteUser(currentGid!!,email) if(response.isSuccessful && response.body() == true) { groupView.showToast("Invitation envoyée avec succès",1) } else { groupView.showToast("Erreur lors de l'envoi de l'invitation",1) } } else { groupView.showToast("Impossible de s'inviter soi-même à rejoindre un groupe",1) } } override suspend fun acceptGroupInvite(gid: String) { val response = ApiClient.groupService.acceptGroupInvite(gid) if(response.isSuccessful && response.body() == true) { homeView.onGroupInvitationAccepted() } else { homeView.showToast("Erreur durant l'acceptation de l'invitation",1) } } override suspend fun declineGroupInvite(gid: String) { val response = ApiClient.groupService.declineGroupInvite(gid) if(response.isSuccessful && response.body() != null) { homeView.onGroupInvitationDeclined() } else { homeView.showToast("Erreur durant le refus de l'invitation",1) } } }
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/GroupPresenter.kt
3556818092
package be.helmo.planivacances.presenter import android.content.SharedPreferences import android.util.Log import be.helmo.planivacances.presenter.interfaces.IAuthView import be.helmo.planivacances.service.ApiClient import be.helmo.planivacances.service.TokenAuthenticator import be.helmo.planivacances.service.dto.LoginUserDTO import be.helmo.planivacances.service.dto.RegisterUserDTO import be.helmo.planivacances.view.interfaces.IAuthPresenter import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException import kotlinx.coroutines.tasks.await /** * Authentification Presenter */ class AuthPresenter : IAuthPresenter { val mAuth: FirebaseAuth = FirebaseAuth.getInstance() lateinit var sharedPreferences : SharedPreferences lateinit var authView: IAuthView val tokenAuthenticator: TokenAuthenticator = TokenAuthenticator.instance!! /** * Enregistrement asycnhrone d'un profil utilisateur * @param username (String) nom * @param mail (String) email * @param password (String) mot de passe * mail et mot de passe utilisateur */ override suspend fun register(username: String, mail: String, password: String) { try { val response = ApiClient.authService.register(RegisterUserDTO(username, mail, password)) if (!response.isSuccessful || response.body() == null) { authView.showToast( "Erreur lors de l'enregistrement : ${response.message()}", 1 ) return } val customToken = response.body() Log.d("AuthFragment", "Register Response: $customToken") auth(customToken!!, false) } catch (e: Exception) { Log.w("Erreur lors de l'enregistrement", "${e.message}") authView.showToast( "Une erreur est survenue lors de l'enregistrement", 1 ) } } /** * Connexion asycnhrone à un profil utilisateur * @param mail (String) email * @param password (String) mot de passe * @param keepConnected (Boolean) stocker le token en local ? */ override suspend fun login(mail: String, password: String, keepConnected: Boolean) { try { val response = ApiClient.authService.login(LoginUserDTO(mail, password)) if (!response.isSuccessful || response.body() == null) { authView.showToast("Erreur lors de la connexion\n&${response.message()}", 1) return } val customToken = response.body() Log.d("AuthFragment", "Login Response : $customToken") auth(customToken!!, keepConnected) } catch (e: Exception) { Log.w("Erreur lors de la connexion", "${e.message}") authView.showToast("Une erreur est survenue lors de la connexion", 1) } } /** * Connexion asynchrone automatique sur base du potentiel token d'identification sauvegardé */ override suspend fun autoAuth() { val customToken = sharedPreferences.getString("CustomToken", null) if(customToken == null) { authView.stopLoading() return } auth(customToken, true) } /** * Sauvegarde le resfresh token si demandé et précise le token au TokenAuthenticator * @param customToken (String) customToken * @param keepConnected (Boolean) stocker le token en local ? */ suspend fun auth(customToken: String, keepConnected: Boolean) { if(keepConnected) { val editor = sharedPreferences.edit() editor.putString("CustomToken", customToken) editor.apply() } try { val authResult = mAuth.signInWithCustomToken(customToken).await() if (authResult != null) { initAuthenticator() authView.goToHome() return } } catch (_: FirebaseAuthInvalidCredentialsException) {} authView.showToast("Erreur lors de l'authentification", 1) } /** * load a new idToken in the TokenAuthenticator * @return (Boolean) */ override suspend fun loadIdToken(): Boolean { val tokenTask = mAuth.currentUser?.getIdToken(false)?.await() return if (tokenTask != null) { val token = "Bearer ${tokenTask.token}" tokenAuthenticator.idToken = token Log.i("AuthFragment.TAG", "Successfully retrieved new account token: $token") true } else { val errorMessage = "Erreur lors de récupération d'un nouveau jeton d'identification" Log.w("AuthFragment.TAG", errorMessage) false } } /** * initialize the authenticator * @return (Boolean) */ override suspend fun initAuthenticator(): Boolean { tokenAuthenticator.authPresenter = this //todo setters ou pas en kotlin ? return loadIdToken() } /** * Get user id * @return (String) */ override fun getUid(): String { return mAuth.uid!! } /** * get the name of the user * @return (String) */ override fun getDisplayName(): String { return mAuth.currentUser!!.displayName!! } /** * assigne le sharedPreferences à la variable locale du presenter * @param sharedPreferences (SharedPreferences) */ override fun setSharedPreference(sharedPreferences: SharedPreferences) { this.sharedPreferences = sharedPreferences } /** * Assigne la AuthView Interface */ override fun setIAuthView(authView : IAuthView) { this.authView = authView } }
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/AuthPresenter.kt
2344298179
package be.helmo.planivacances.presenter import be.helmo.planivacances.domain.Place 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.ActivityDetailVM import be.helmo.planivacances.presenter.viewmodel.ActivityListItemVM import be.helmo.planivacances.presenter.viewmodel.ActivityVM import be.helmo.planivacances.presenter.viewmodel.PlaceVM import be.helmo.planivacances.service.ApiClient import be.helmo.planivacances.service.dto.ActivitiesDTO import be.helmo.planivacances.service.dto.ActivityDTO import be.helmo.planivacances.service.dto.PlaceDTO import be.helmo.planivacances.util.DTOMapper import be.helmo.planivacances.view.interfaces.IActivityPresenter import be.helmo.planivacances.view.interfaces.IGroupPresenter import java.text.SimpleDateFormat import java.util.* import kotlin.collections.ArrayList import kotlin.collections.HashMap class ActivityPresenter(private val groupPresenter: IGroupPresenter) : IActivityPresenter { lateinit var calendarView : ICalendarView lateinit var activityView: IActivityView lateinit var createActivityView: ICreateActivityView lateinit var updateActivityView: IUpdateActivityView var activitiesDTO: ActivitiesDTO = ActivitiesDTO(HashMap()) lateinit var currentActivityDTO : Pair<String,ActivityDTO> override fun setICalendarView(calendarView: ICalendarView) { this.calendarView = calendarView } override fun setIActivityView(activityView: IActivityView) { this.activityView = activityView } override fun setICreateActivityView(createIActivityView: ICreateActivityView) { this.createActivityView = createIActivityView } override fun setIUpdateActivityView(updateActivityView: IUpdateActivityView) { this.updateActivityView = updateActivityView } override fun setCurrentActivity(activityId: String) { if(activitiesDTO.activitiesMap.contains(activityId)) { currentActivityDTO = Pair(activityId,activitiesDTO.activitiesMap[activityId]!!) } } override suspend fun getCalendarFile() { try { val response = ApiClient.calendarService.getICS(groupPresenter.getCurrentGroupId()) if(response.isSuccessful && response.body() != null) { val currentGroup = groupPresenter.getCurrentGroup()!! calendarView.downloadCalendar(response.body()!!,"Calendrier-${currentGroup.groupName}.ics") } } catch(e:Exception) { e.printStackTrace() calendarView.showToast("Erreur lors du téléchargement du calendrier",1) } } override suspend fun loadActivities() { val response = ApiClient.activityService.loadActivities(groupPresenter.getCurrentGroupId()) if(response.isSuccessful && response.body() != null) { activitiesDTO.activitiesMap.clear() response.body()!!.forEach { entry -> run { activitiesDTO.activitiesMap[entry.key] = entry.value } } onActivitiesLoaded() } } override suspend fun deleteCurrentActivity() { val response = ApiClient.activityService.deleteActivity(groupPresenter.getCurrentGroupId(),currentActivityDTO.first) if(response.isSuccessful) { activityView.onActivityDeleted() } else { activityView.showToast("Erreur durant la suppression de l'activité",1) } } override fun getCurrentActivity() { val currentActivityVM : ActivityVM = DTOMapper.activityDTOToActivityVM(currentActivityDTO.second) updateActivityView.setCurrentActivity(currentActivityVM) } override fun loadCurrentActivity() { val currentActivity = currentActivityDTO.second activityView.loadActivity(ActivityDetailVM(currentActivity.title,formatPeriod(currentActivity.startDate,currentActivity.duration),formatPlace(currentActivity.place),currentActivity.description)) } override fun loadItinerary() { val currentActivity = currentActivityDTO.second activityView.buildItinerary(currentActivity.place.lat.toString(),currentActivity.place.lon.toString()) } override suspend fun createActivity(activityVM: ActivityVM) { val activityDTO : ActivityDTO = DTOMapper.activityVMToActivityDTO(activityVM) val response = ApiClient.activityService.createActivity(groupPresenter.getCurrentGroupId(),activityDTO) if(response.isSuccessful) { createActivityView.onActivityCreated() } else { createActivityView.showToast("Erreur durant la création de l'activité",1) } } override suspend fun updateCurrentActivity(activityVM: ActivityVM) { val activityDTO : ActivityDTO = DTOMapper.activityVMToActivityDTO(activityVM) val response = ApiClient.activityService.updateActivity(groupPresenter.getCurrentGroupId(),currentActivityDTO.first,activityDTO) if(response.isSuccessful) { updateActivityView.onActivityUpdated() } else { updateActivityView.showToast("Erreur lors de la mise à jour de l'activité",1) } } fun onActivitiesLoaded() { val activityDates : ArrayList<Date> = ArrayList() activitiesDTO.activitiesMap.forEach { entry -> activityDates.add(entry.value.startDate) } calendarView.onActivitiesLoaded(activityDates) } override fun onActivityDateChanged(dayOfMonth: Int, month: Int, year: Int) { val date = Calendar.getInstance() date.set(year, month, dayOfMonth) val activities : ArrayList<ActivityListItemVM> = ArrayList() val dateFormat = SimpleDateFormat("dd/MM/YYYY") val formattedDate = dateFormat.format(date.timeInMillis) activitiesDTO.activitiesMap.forEach { entry -> val currentActivity = entry.value if(formattedDate == dateFormat.format(currentActivity.startDate)) { activities.add(ActivityListItemVM(entry.key,currentActivity.title,formatStartDate(currentActivity.startDate),formatDuration(currentActivity.duration))) } } calendarView.setDisplayedActivities(activities) } fun formatStartDate(startDate:Date) : String { val startDateFormat : SimpleDateFormat = SimpleDateFormat("HH'h'mm") return startDateFormat.format(startDate) } fun formatPeriod(startDate: Date,duration: Int) : String { val startDateFormat : SimpleDateFormat = SimpleDateFormat("dd/MM/yyyy") return "Le ${startDateFormat.format(startDate)} à ${formatStartDate(startDate)} - Durée : ${formatDuration(duration)}" } fun formatPlace(placeDTO: PlaceDTO) : String { return "${placeDTO.street},${placeDTO.number},${placeDTO.city} ${placeDTO.postalCode},${placeDTO.country}" } fun formatDuration(duration: Int) : String { val hours = duration / 3600 val minutes = (duration % 3600) / 60 return String.format("%dh%02d",hours,minutes) } }
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/ActivityPresenter.kt
11759843
package be.helmo.planivacances.presenter import android.util.Log import be.helmo.planivacances.presenter.viewmodel.WeatherForecastVM import be.helmo.planivacances.presenter.interfaces.IWeatherView import be.helmo.planivacances.service.ApiClient import be.helmo.planivacances.view.interfaces.IGroupPresenter import be.helmo.planivacances.view.interfaces.IWeatherPresenter class WeatherPresenter(val groupPresenter: IGroupPresenter) : IWeatherPresenter { lateinit var weatherView: IWeatherView /** * get the weather forecast for the current group place */ override suspend fun getForecast() { try { val latLng = groupPresenter.getCurrentGroupPlace()?.latLngString if(latLng == null) { weatherView.showToast( "Erreur lors de la récupération du lieu de météo", 1 ) return } val response = ApiClient.weatherService.getForecast(latLng) if (!response.isSuccessful || response.body() == null) { Log.e("WeatherFragment","${response.message()}, ${response.isSuccessful}") weatherView.showToast("Erreur lors de la récupération " + "des données météo ${response.message()}", 1) } val weatherData = response.body() val forecastList = weatherData?.forecast?.forecastday?.map { it -> WeatherForecastVM( "https:${it.day.condition.icon}", "${it.day.avgtemp_c}° C", it.date, "Humidité : ${it.day.avghumidity}%, " + "Pluie : ${it.day.daily_chance_of_rain}%, " + "Vent : ${it.day.maxwind_kph}km/h" ) } ?: emptyList() Log.d("WeatherFragment", "Weather retrieved") weatherView.onForecastLoaded(forecastList) } catch (e: Exception) { Log.e("WeatherFragment", "Error while retrieving weather : ${e.message}") weatherView.showToast( "Erreur durant la récupération des données météo", 1 ) } } /** * Assigne la WeatherView Interface */ override fun setIWeatherView(weatherView: IWeatherView) { this.weatherView = weatherView } }
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/WeatherPresenter.kt
225867197
package be.helmo.planivacances.presenter.interfaces import be.helmo.planivacances.presenter.viewmodel.GroupDetailVM interface IGroupView : IShowToast { fun buildItinerary(latitude:String,longitude:String) fun setGroupInfos(group: GroupDetailVM) fun onGroupDeleted() }
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/interfaces/IGroupView.kt
981022186
package be.helmo.planivacances.presenter.interfaces import be.helmo.planivacances.presenter.viewmodel.ActivityDetailVM interface IActivityView : IShowToast { fun loadActivity(activity:ActivityDetailVM) fun buildItinerary(latitude: String, longitude: String) fun onActivityDeleted() }
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/interfaces/IActivityView.kt
868751211
package be.helmo.planivacances.presenter.interfaces import be.helmo.planivacances.presenter.viewmodel.ActivityVM interface IUpdateActivityView : IShowToast { fun setCurrentActivity(activityVM: ActivityVM) fun onActivityUpdated() }
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/interfaces/IUpdateActivityView.kt
3978029636
package be.helmo.planivacances.presenter.interfaces interface IShowToast { fun showToast(message : String, length: Int) }
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/interfaces/IShowToast.kt
4292816971
package be.helmo.planivacances.presenter.interfaces import be.helmo.planivacances.service.dto.MessageDTO interface ITchatView { fun addMessageToView(message: MessageDTO) fun stopLoading() }
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/interfaces/ITchatView.kt
116630499
package be.helmo.planivacances.presenter.interfaces interface ICreateGroupView : IShowToast { fun onGroupCreated() }
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/interfaces/ICreateGroupView.kt
618525246
package be.helmo.planivacances.presenter.interfaces interface ICreateActivityView : IShowToast { fun onActivityCreated() }
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/interfaces/ICreateActivityView.kt
2123830959
package be.helmo.planivacances.presenter.interfaces import be.helmo.planivacances.presenter.viewmodel.GroupVM interface IUpdateGroupView : IShowToast { fun onGroupUpdated() fun setCurrentGroup(groupVM: GroupVM) }
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/interfaces/IUpdateGroupView.kt
2576536124
package be.helmo.planivacances.presenter.interfaces import be.helmo.planivacances.presenter.viewmodel.GroupInvitationVM import be.helmo.planivacances.presenter.viewmodel.GroupListItemVM interface IHomeView : IShowToast { fun setGroupList(groups: List<GroupListItemVM>) fun onGroupInvitationsLoaded(invitations: List<GroupInvitationVM>) fun onGroupInvitationAccepted() fun onGroupInvitationDeclined() }
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/interfaces/IHomeView.kt
763258560
package be.helmo.planivacances.presenter.interfaces import be.helmo.planivacances.presenter.viewmodel.ActivityListItemVM import java.util.* interface ICalendarView : IShowToast { fun downloadCalendar(calendarContent:String,fileName:String) fun onActivitiesLoaded(activityDates: List<Date>) fun setDisplayedActivities(activities: List<ActivityListItemVM>) }
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/interfaces/ICalendarView.kt
3401566593
package be.helmo.planivacances.presenter.interfaces interface IAuthView : IShowToast { fun goToHome() fun stopLoading() }
mobile-planivacances/app/src/main/java/be/helmo/planivacances/presenter/interfaces/IAuthView.kt
2595702684
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/presenter/interfaces/IWeatherView.kt
3402014688
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/MainActivity.kt
3236137920
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/GroupAdapter.kt
2749820384
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/GroupInviteAdapter.kt
122081815
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/home/HomeFragment.kt
2787075420
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/AuthFragment.kt
903007799
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/CreateGroupFragment.kt
1484559517
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/GroupFragment.kt
1455692541
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/group/UpdateGroupFragment.kt
178195900
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/CalendarFragment.kt
3262013934
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/UpdateActivityFragment.kt
2337178274
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/CalendarAdapter.kt
837387627
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/CreateActivityFragment.kt
277164909
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/activity/ActivityFragment.kt
1614630531
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/TchatAdapter.kt
1346828268
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/tchat/TchatFragment.kt
767451286
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/WeatherFragment.kt
2716934954
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/fragments/weather/WeatherAdapter.kt
1239923056
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/IGroupPresenter.kt
2032799998
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/IActivityPresenter.kt
2055172236
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/ITchatPresenter.kt
1788054134
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/IAuthPresenter.kt
3806182375
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/view/interfaces/IWeatherPresenter.kt
4033760169
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/LoginUserDTO.kt
2114454019
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/PlaceDTO.kt
2660271804
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/MessageDTO.kt
3852202589
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/GroupInviteDTO.kt
173532709
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/GroupDTO.kt
3959535480
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/CreateGroupDTO.kt
1305424804
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/RegisterUserDTO.kt
4111510833
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/ActivityDTO.kt
1231858590
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/ActivitiesDTO.kt
976572635
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/dto/WeatherDTOs.kt
2564388064
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/IPlaceService.kt
4258499378
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/IGroupService.kt
911077402
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/IActivityService.kt
323497755
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/ICalendarService.kt
4013081758
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/ITchatService.kt
3135314967
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/IWeatherService.kt
1207584352
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/ApiClient.kt
3478559398
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/TokenAuthenticator.kt
616123181
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/service/IAuthService.kt
104691591
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/Group.kt
3391998362
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/domain/Place.kt
3492634135