Skip to content

Commit

Permalink
Merge pull request #84 from anrouxel/DownloadFromApi
Browse files Browse the repository at this point in the history
Download from api
  • Loading branch information
gueguefun authored Feb 29, 2024
2 parents 17c722e + 2ef59cd commit 02b430e
Show file tree
Hide file tree
Showing 13 changed files with 260 additions and 20 deletions.
4 changes: 3 additions & 1 deletion app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,10 @@ dependencies {
implementation("androidx.room:room-runtime:2.5.2")
ksp("androidx.room:room-compiler:2.5.2")

// Gson
// Gson / Moshi
implementation("com.google.code.gson:gson:2.10.1")
implementation("com.squareup.moshi:moshi-kotlin:1.12.0")


// QRcode
implementation("com.journeyapps:zxing-android-embedded:4.3.0")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,7 @@ interface ApiServiceGuewen {
fun getLittleDocByNom(
@Path("name") name: String
): Call<String>

@GET("get_relations")
fun getRelations(): Call<String>
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package fr.medicapp.medicapp.api.address.apiInteractions

import android.content.Context
import android.content.SharedPreferences
import android.os.Handler
import android.os.HandlerThread
import android.util.Log
Expand All @@ -10,19 +11,22 @@ import com.google.gson.reflect.TypeToken
import fr.medicapp.medicapp.api.address.APIAddressClient
import fr.medicapp.medicapp.database.converter.LocalDateTypeAdapter
import fr.medicapp.medicapp.database.repositories.medication.MedicationRepository
import fr.medicapp.medicapp.database.repositories.relations.RelationRepository
import fr.medicapp.medicapp.model.gson.MedicationGSON
import fr.medicapp.medicapp.model.gson.RelationGSON
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.lang.reflect.Type
import java.time.LocalDate

@OptIn(DelicateCoroutinesApi::class)
class MedicationDownload(
private val context: Context
) {
/**
* Thread en background pour le téléchargement des données
*/
private lateinit var gBackgroundThread: HandlerThread
private var gBackgroundThread: HandlerThread = HandlerThread("MedicationDownload")

/**
* Gestionnaire des tâches en background
Expand All @@ -32,13 +36,12 @@ class MedicationDownload(
/**
* Accès aux donnés sauvegardées dans le téléphone
*/
val sharedPreferences = context.getSharedPreferences("medicapp", Context.MODE_PRIVATE)
private val sharedPreferences: SharedPreferences = context.getSharedPreferences("medicapp", Context.MODE_PRIVATE)

/**
* Initialisation du thread en background
*/
init {
gBackgroundThread = HandlerThread("MedicationDownload")
gBackgroundThread.start()
gHandler = Handler(gBackgroundThread.looper)

Expand All @@ -47,10 +50,12 @@ class MedicationDownload(
if (sharedPreferences.getInt("totalMedication", 0) == 0) {
getTotalData()
}
downloadRelations()
download()
}
}

@OptIn(DelicateCoroutinesApi::class)
@WorkerThread
fun download() {
val medicationRepository = MedicationRepository(context)
Expand All @@ -64,23 +69,25 @@ class MedicationDownload(
if (response.isSuccessful) {
val allMedsJsonArray = response.body()!!

val gson = GsonBuilder()
.registerTypeAdapter(LocalDate::class.java, LocalDateTypeAdapter())
.create()
GlobalScope.launch {
val gson = GsonBuilder()
.registerTypeAdapter(LocalDate::class.java, LocalDateTypeAdapter())
.create()

val listType: Type = object : TypeToken<List<MedicationGSON>>() {}.type
val listType: Type = object : TypeToken<List<MedicationGSON>>() {}.type

val medications: List<MedicationGSON> =
gson.fromJson(allMedsJsonArray, listType)
val medications: List<MedicationGSON> =
gson.fromJson(allMedsJsonArray, listType)

// Mapper et convertir les données en MedicationEntity
val medicationEntities = medications.map { it.toMedication() }
MedicationRepository(context).getAll().count().let {
updateDownloadCountInSharedPreferences(it)
// Mapper et convertir les données en MedicationEntity
val medicationEntities = medications.map { it.toMedication() }
MedicationRepository(context).getAll().count().let {
updateDownloadCountInSharedPreferences(it)
}
// Enregistrer les MedicationEntity
medicationRepository.insert(medicationEntities)
sharedPreferences.edit().putInt("medicationPage", page).apply()
}
// Enregistrer les MedicationEntity
medicationRepository.insert(medicationEntities)
sharedPreferences.edit().putInt("medicationPage", page).apply()

page += 1
} else if (response.code() == 409) {
Expand All @@ -97,6 +104,39 @@ class MedicationDownload(
gBackgroundThread.quitSafely()
}

@WorkerThread
fun downloadRelations() {

val dl = sharedPreferences.getBoolean("isRelationDownloaded", false)
if (!dl) {
Log.d("GuegueApi", "On télécharge les relations")
val apiService = APIAddressClient().apiServiceGuewen
val response = apiService.getRelations().execute()
if (response.isSuccessful) {
val allRelJsonArray = response.body()!!
Log.d("GuegueApi", "Les données sont téléchargées")
val gson = GsonBuilder()
.registerTypeAdapter(LocalDate::class.java, LocalDateTypeAdapter())
.create()

val listType: Type = object : TypeToken<List<RelationGSON>>() {}.type

val relations: List<RelationGSON> =
gson.fromJson(allRelJsonArray, listType)

// Mapper et convertir les données en MedicationEntity
val relationsEntities = relations.map { it.toRelations() }

// Enregistrer les RelationsEntity
RelationRepository(context).insert(relationsEntities)
Log.d("GuegueApi", "Les relations sont enregistrées")
sharedPreferences.edit().putBoolean("isRelationDownloaded", true).apply()
} else {
Log.e("ObjectBox", "Error while fetching relations")
}
}
}

@WorkerThread
fun getTotalData() {
val sharedPreferences = context.getSharedPreferences("medicapp", Context.MODE_PRIVATE)
Expand All @@ -109,7 +149,7 @@ class MedicationDownload(
}
}

fun updateDownloadCountInSharedPreferences(countDownload: Int) {
private fun updateDownloadCountInSharedPreferences(countDownload: Int) {
sharedPreferences.edit().putInt("downloadCount", countDownload).apply()
}
}
12 changes: 11 additions & 1 deletion app/src/main/java/fr/medicapp/medicapp/database/AppDatabase.kt
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ import fr.medicapp.medicapp.database.dao.prescription.NotificationDAO
import fr.medicapp.medicapp.database.dao.prescription.PrescriptionDAO
import fr.medicapp.medicapp.database.dao.prescription.SideEffectDAO
import fr.medicapp.medicapp.database.dao.prescription.crossRef.NotificationAlarmCrossRefDAO
import fr.medicapp.medicapp.database.dao.relations.InteractionsDAO
import fr.medicapp.medicapp.database.dao.relations.RelationsDAO
import fr.medicapp.medicapp.model.User
import fr.medicapp.medicapp.model.medication.GenericGroup
import fr.medicapp.medicapp.model.medication.HasAsmrOpinionInformation
Expand All @@ -51,6 +53,8 @@ import fr.medicapp.medicapp.model.prescription.NotificationInformation
import fr.medicapp.medicapp.model.prescription.PrescriptionInformation
import fr.medicapp.medicapp.model.prescription.SideEffectInformation
import fr.medicapp.medicapp.model.prescription.relationship.crossRef.NotificationAlarmCrossRef
import fr.medicapp.medicapp.model.relations.Interactions
import fr.medicapp.medicapp.model.relations.RelationInfo

/**
* Cette classe représente la base de données de l'application.
Expand All @@ -76,7 +80,9 @@ import fr.medicapp.medicapp.model.prescription.relationship.crossRef.Notificatio
HasAsmrOpinionTransparencyCommissionOpinionLinksCrossRef::class,
HasSmrOpinionTransparencyCommissionOpinionLinksCrossRef::class,
NotificationAlarmCrossRef::class,
User::class
User::class,
RelationInfo::class,
Interactions::class
],
version = 1,
exportSchema = false
Expand Down Expand Up @@ -130,6 +136,10 @@ abstract class AppDatabase : RoomDatabase() {

abstract fun userDAO(): UserDAO

abstract fun RelationsDAO(): RelationsDAO

abstract fun InteractionsDAO(): InteractionsDAO

companion object {

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package fr.medicapp.medicapp.database.dao.relations

import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Transaction
import fr.medicapp.medicapp.model.relations.Interactions

@Dao
interface InteractionsDAO {

@Transaction
@Query("SELECT * FROM Interactions")
fun getAll(): List<Interactions>

@Insert
fun insert(interactions: Interactions) : Long

@Insert
fun insert(interactions: List<Interactions>) : List<Long>

@Delete
fun delete(interactions: Interactions)

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package fr.medicapp.medicapp.database.dao.relations

import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Transaction
import fr.medicapp.medicapp.model.relations.RelationInfo
import fr.medicapp.medicapp.model.relations.crossRef.Relations

@Dao
interface RelationsDAO {

@Transaction
@Query("SELECT * FROM RelationInfo")
fun getAll() : List<Relations>

@Insert
fun insert(relation: RelationInfo): Long

@Insert
fun insert(relations: List<RelationInfo>): List<Long>

@Delete
fun delete(relation: RelationInfo)

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package fr.medicapp.medicapp.database.repositories.relations

import android.content.Context
import fr.medicapp.medicapp.database.repositories.Repository
import fr.medicapp.medicapp.model.relations.Interactions

class InteractionRepository(contexte : Context) : Repository(contexte) {
fun getAll(): List<Interactions> {
return db.InteractionsDAO().getAll()
}

fun insert(interactions: Interactions): Long {
return db.InteractionsDAO().insert(interactions)
}

fun insert(interactions: List<Interactions>): List<Long> {
return db.InteractionsDAO().insert(interactions)
}

fun delete(interactions : Interactions) {
db.InteractionsDAO().delete(interactions)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package fr.medicapp.medicapp.database.repositories.relations

import android.content.Context
import androidx.room.Relation
import fr.medicapp.medicapp.database.repositories.Repository
import fr.medicapp.medicapp.model.relations.Interactions
import fr.medicapp.medicapp.model.relations.crossRef.Relations

class RelationRepository(contexte : Context) : Repository(contexte) {
fun getAll(): List<Relations> {
return db.RelationsDAO().getAll()
}

fun insert(relation: Relations): Long {
val id = db.RelationsDAO().insert(relation.relationInfo)

relation.interactions.forEach {
it.relationInfoId = id
}

return id
}

fun insert(relations: List<Relations>): List<Long> {
relations.forEach {
insert(it)
}
return relations.map { it.relationInfo.id }
}

fun delete(relation : Relations) {
relation.interactions.forEach {
db.InteractionsDAO().delete(it)
}
db.RelationsDAO().delete(relation.relationInfo)
}
}
21 changes: 21 additions & 0 deletions app/src/main/java/fr/medicapp/medicapp/model/gson/RelationGSON.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package fr.medicapp.medicapp.model.gson

import fr.medicapp.medicapp.model.relations.Interactions
import fr.medicapp.medicapp.model.relations.RelationInfo
import fr.medicapp.medicapp.model.relations.crossRef.Relations

data class RelationGSON(
var substance: String = "",
var com: String = "",
var interactions: List<Interactions> = emptyList()
) {
fun toRelations(): Relations {
return Relations(
relationInfo = RelationInfo(
substance = substance,
com = com
),
interactions = interactions
)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package fr.medicapp.medicapp.model.relations
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey

@Entity
data class Interactions(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "interaction_id")
val id: Long = 0L,
val substance: String = "",
val com1: String = "",
val com2: String = "",

@ColumnInfo(name = "relation_info_id")
var relationInfoId: Long = 0L
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package fr.medicapp.medicapp.model.relations

import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey

@Entity
data class RelationInfo(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "relation_info_id")
val id: Long = 0L,
val substance: String = "",
val com: String = ""
)
Loading

0 comments on commit 02b430e

Please sign in to comment.