mirror of
https://github.com/bleackstorm/satiea.git
synced 2026-12-03 07:41:56 +01:00
refactor: improve Google Sheets sync and path encoding
Update spreadsheet tab verification to include full property data and implement RFC 3986-compliant path encoding for range parameters to ensure correct API interactions.
This commit is contained in:
1 parent
3397fc1c60
commit
3d1d0f43e7
2 files changed
+113
-33
No files matched your search
@@ -56,7 +56,7 @@ object GoogleSheetsSyncService {
|
|||||||
// 1. If we have a cached spreadsheetId, verify it still exists and ensure 2 tabs
|
// 1. If we have a cached spreadsheetId, verify it still exists and ensure 2 tabs
|
||||||
if (!cachedSpreadsheetId.isNullOrBlank()) {
|
if (!cachedSpreadsheetId.isNullOrBlank()) {
|
||||||
val checkRequest = Request.Builder()
|
val checkRequest = Request.Builder()
|
||||||
.url("https://sheets.googleapis.com/v4/spreadsheets/$cachedSpreadsheetId?fields=spreadsheetId,spreadsheetUrl,sheets.properties.title")
|
.url("https://sheets.googleapis.com/v4/spreadsheets/$cachedSpreadsheetId?fields=spreadsheetId,spreadsheetUrl,sheets.properties")
|
||||||
.header("Authorization", "Bearer $accessToken")
|
.header("Authorization", "Bearer $accessToken")
|
||||||
.get()
|
.get()
|
||||||
.build()
|
.build()
|
||||||
@@ -70,7 +70,7 @@ object GoogleSheetsSyncService {
|
|||||||
val json = JSONObject(body)
|
val json = JSONObject(body)
|
||||||
val id = json.getString("spreadsheetId")
|
val id = json.getString("spreadsheetId")
|
||||||
val url = json.optString("spreadsheetUrl", "https://docs.google.com/spreadsheets/d/$id/edit")
|
val url = json.optString("spreadsheetUrl", "https://docs.google.com/spreadsheets/d/$id/edit")
|
||||||
ensureCustomFoodsTabExists(accessToken, id, json)
|
ensureTabsExist(accessToken, id, json)
|
||||||
if (parentFolderId != null) {
|
if (parentFolderId != null) {
|
||||||
GoogleDriveService.moveFileToFolder(accessToken, id, parentFolderId)
|
GoogleDriveService.moveFileToFolder(accessToken, id, parentFolderId)
|
||||||
}
|
}
|
||||||
@@ -104,7 +104,7 @@ object GoogleSheetsSyncService {
|
|||||||
val firstFile = files.getJSONObject(0)
|
val firstFile = files.getJSONObject(0)
|
||||||
val id = firstFile.getString("id")
|
val id = firstFile.getString("id")
|
||||||
val link = firstFile.optString("webViewLink", "https://docs.google.com/spreadsheets/d/$id/edit")
|
val link = firstFile.optString("webViewLink", "https://docs.google.com/spreadsheets/d/$id/edit")
|
||||||
ensureCustomFoodsTabExists(accessToken, id, null)
|
ensureTabsExist(accessToken, id, null)
|
||||||
if (parentFolderId != null) {
|
if (parentFolderId != null) {
|
||||||
GoogleDriveService.moveFileToFolder(accessToken, id, parentFolderId)
|
GoogleDriveService.moveFileToFolder(accessToken, id, parentFolderId)
|
||||||
}
|
}
|
||||||
@@ -171,63 +171,125 @@ object GoogleSheetsSyncService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun ensureCustomFoodsTabExists(
|
/**
|
||||||
|
* Encodes a sheet range for use in REST URL path, compliant with RFC 3986 (spaces as %20, not +).
|
||||||
|
*/
|
||||||
|
fun encodePathRange(range: String): String {
|
||||||
|
return URLEncoder.encode(range, "UTF-8").replace("+", "%20")
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inspects spreadsheet tabs, migrates legacy/default sheet titles ("Journal", "Feuille 1", "Sheet1")
|
||||||
|
* to "Journal des repas", and creates "Mes plats et aliments" or "Journal des repas" if missing.
|
||||||
|
*/
|
||||||
|
suspend fun ensureTabsExist(
|
||||||
accessToken: String,
|
accessToken: String,
|
||||||
spreadsheetId: String,
|
spreadsheetId: String,
|
||||||
spreadsheetJson: JSONObject?
|
spreadsheetJson: JSONObject? = null
|
||||||
) = withContext(Dispatchers.IO) {
|
) = withContext(Dispatchers.IO) {
|
||||||
try {
|
try {
|
||||||
val json = spreadsheetJson ?: run {
|
val json = spreadsheetJson ?: run {
|
||||||
val req = Request.Builder()
|
val req = Request.Builder()
|
||||||
.url("https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId?fields=sheets.properties.title")
|
.url("https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId?fields=sheets.properties")
|
||||||
.header("Authorization", "Bearer $accessToken")
|
.header("Authorization", "Bearer $accessToken")
|
||||||
.get()
|
.get()
|
||||||
.build()
|
.build()
|
||||||
okHttpClient.newCall(req).execute().use { resp ->
|
okHttpClient.newCall(req).execute().use { resp ->
|
||||||
|
if (resp.code == 401) throw AuthExpiredException("Token Google expiré (401)")
|
||||||
if (resp.isSuccessful) JSONObject(resp.body?.string().orEmpty()) else null
|
if (resp.isSuccessful) JSONObject(resp.body?.string().orEmpty()) else null
|
||||||
}
|
}
|
||||||
} ?: return@withContext
|
} ?: return@withContext
|
||||||
|
|
||||||
val sheets = json.optJSONArray("sheets") ?: return@withContext
|
val sheets = json.optJSONArray("sheets") ?: return@withContext
|
||||||
|
var hasMealsTab = false
|
||||||
var hasFoodsTab = false
|
var hasFoodsTab = false
|
||||||
|
var legacySheetIdToRename: Int? = null
|
||||||
|
|
||||||
|
val legacyTabNames = setOf("Journal", "Feuille 1", "Sheet1", "Sheet 1")
|
||||||
|
|
||||||
for (i in 0 until sheets.length()) {
|
for (i in 0 until sheets.length()) {
|
||||||
val title = sheets.getJSONObject(i).optJSONObject("properties")?.optString("title")
|
val props = sheets.getJSONObject(i).optJSONObject("properties") ?: continue
|
||||||
if (title == SHEET_TAB_FOODS) {
|
val title = props.optString("title")
|
||||||
hasFoodsTab = true
|
val sId = props.optInt("sheetId", -1)
|
||||||
break
|
|
||||||
|
when {
|
||||||
|
title == SHEET_TAB_MEALS -> hasMealsTab = true
|
||||||
|
title == SHEET_TAB_FOODS -> hasFoodsTab = true
|
||||||
|
legacySheetIdToRename == null && legacyTabNames.contains(title) && sId != -1 -> {
|
||||||
|
legacySheetIdToRename = sId
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!hasFoodsTab) {
|
val batchRequests = JSONArray()
|
||||||
val addSheetPayload = JSONObject().apply {
|
|
||||||
put("requests", JSONArray().apply {
|
// 1. If "Journal des repas" does not exist: rename legacy sheet if present, else create it
|
||||||
put(JSONObject().apply {
|
if (!hasMealsTab) {
|
||||||
put("addSheet", JSONObject().apply {
|
if (legacySheetIdToRename != null) {
|
||||||
put("properties", JSONObject().apply {
|
batchRequests.put(JSONObject().apply {
|
||||||
put("title", SHEET_TAB_FOODS)
|
put("updateSheetProperties", JSONObject().apply {
|
||||||
put("gridProperties", JSONObject().apply {
|
put("properties", JSONObject().apply {
|
||||||
put("frozenRowCount", 1)
|
put("sheetId", legacySheetIdToRename)
|
||||||
})
|
put("title", SHEET_TAB_MEALS)
|
||||||
|
})
|
||||||
|
put("fields", "title")
|
||||||
|
})
|
||||||
|
})
|
||||||
|
hasMealsTab = true
|
||||||
|
} else {
|
||||||
|
batchRequests.put(JSONObject().apply {
|
||||||
|
put("addSheet", JSONObject().apply {
|
||||||
|
put("properties", JSONObject().apply {
|
||||||
|
put("index", 0)
|
||||||
|
put("title", SHEET_TAB_MEALS)
|
||||||
|
put("gridProperties", JSONObject().apply {
|
||||||
|
put("frozenRowCount", 1)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
hasMealsTab = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. If "Mes plats et aliments" does not exist: create it
|
||||||
|
if (!hasFoodsTab) {
|
||||||
|
batchRequests.put(JSONObject().apply {
|
||||||
|
put("addSheet", JSONObject().apply {
|
||||||
|
put("properties", JSONObject().apply {
|
||||||
|
put("title", SHEET_TAB_FOODS)
|
||||||
|
put("gridProperties", JSONObject().apply {
|
||||||
|
put("frozenRowCount", 1)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
if (batchRequests.length() > 0) {
|
||||||
|
val batchPayload = JSONObject().apply {
|
||||||
|
put("requests", batchRequests)
|
||||||
}
|
}
|
||||||
|
|
||||||
val addSheetReq = Request.Builder()
|
val batchReq = Request.Builder()
|
||||||
.url("https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId:batchUpdate")
|
.url("https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId:batchUpdate")
|
||||||
.header("Authorization", "Bearer $accessToken")
|
.header("Authorization", "Bearer $accessToken")
|
||||||
.post(addSheetPayload.toString().toRequestBody(jsonMediaType))
|
.post(batchPayload.toString().toRequestBody(jsonMediaType))
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
okHttpClient.newCall(addSheetReq).execute().use { resp ->
|
okHttpClient.newCall(batchReq).execute().use { resp ->
|
||||||
|
val body = resp.body?.string().orEmpty()
|
||||||
|
if (resp.code == 401) throw AuthExpiredException("Token Google expiré (401)")
|
||||||
if (!resp.isSuccessful) {
|
if (!resp.isSuccessful) {
|
||||||
Log.w(TAG, "Could not add sheet tab $SHEET_TAB_FOODS: ${resp.code}")
|
Log.w(TAG, "Batch update sheets properties error: ${resp.code} -> $body")
|
||||||
|
} else {
|
||||||
|
Log.i(TAG, "Successfully updated sheets structure on spreadsheet $spreadsheetId")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Log.w(TAG, "Error checking/adding $SHEET_TAB_FOODS tab: ${e.message}")
|
if (e is AuthExpiredException) throw e
|
||||||
|
Log.w(TAG, "Error checking/updating sheet tabs: ${e.message}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -239,6 +301,9 @@ object GoogleSheetsSyncService {
|
|||||||
photoLinkProvider: (String) -> String? = { null }
|
photoLinkProvider: (String) -> String? = { null }
|
||||||
): Result<GoogleSheetsSyncResult> = withContext(Dispatchers.IO) {
|
): Result<GoogleSheetsSyncResult> = withContext(Dispatchers.IO) {
|
||||||
try {
|
try {
|
||||||
|
// Ensure both tabs exist and legacy tabs are migrated before writing
|
||||||
|
ensureTabsExist(accessToken, spreadsheetId)
|
||||||
|
|
||||||
// 1. Sync Meals on SHEET_TAB_MEALS
|
// 1. Sync Meals on SHEET_TAB_MEALS
|
||||||
val mealRows = GoogleSheetsDataFormatter.formatMealsToRows(meals = meals, photoLinkProvider = photoLinkProvider)
|
val mealRows = GoogleSheetsDataFormatter.formatMealsToRows(meals = meals, photoLinkProvider = photoLinkProvider)
|
||||||
writeRowsToSheet(accessToken, spreadsheetId, SHEET_TAB_MEALS, "A:Z", "A1", mealRows)
|
writeRowsToSheet(accessToken, spreadsheetId, SHEET_TAB_MEALS, "A:Z", "A1", mealRows)
|
||||||
@@ -279,8 +344,8 @@ object GoogleSheetsSyncService {
|
|||||||
startCell: String,
|
startCell: String,
|
||||||
rows: List<List<Any>>
|
rows: List<List<Any>>
|
||||||
) = withContext(Dispatchers.IO) {
|
) = withContext(Dispatchers.IO) {
|
||||||
// Clear previous range
|
// Clear previous range with RFC 3986 encoding (%20 instead of +)
|
||||||
val clearRange = URLEncoder.encode("'$sheetTitle'!$clearRangeColumns", "UTF-8")
|
val clearRange = encodePathRange("'$sheetTitle'!$clearRangeColumns")
|
||||||
val clearUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/$clearRange:clear"
|
val clearUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/$clearRange:clear"
|
||||||
val clearRequest = Request.Builder()
|
val clearRequest = Request.Builder()
|
||||||
.url(clearUrl)
|
.url(clearUrl)
|
||||||
@@ -313,7 +378,7 @@ object GoogleSheetsSyncService {
|
|||||||
put("values", jsonValuesArray)
|
put("values", jsonValuesArray)
|
||||||
}
|
}
|
||||||
|
|
||||||
val writeRange = URLEncoder.encode("'$sheetTitle'!$startCell", "UTF-8")
|
val writeRange = encodePathRange("'$sheetTitle'!$startCell")
|
||||||
val writeUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/$writeRange?valueInputOption=RAW"
|
val writeUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/$writeRange?valueInputOption=RAW"
|
||||||
val writeRequest = Request.Builder()
|
val writeRequest = Request.Builder()
|
||||||
.url(writeUrl)
|
.url(writeUrl)
|
||||||
@@ -336,8 +401,11 @@ object GoogleSheetsSyncService {
|
|||||||
spreadsheetId: String
|
spreadsheetId: String
|
||||||
): Result<SpreadsheetRestoreData> = withContext(Dispatchers.IO) {
|
): Result<SpreadsheetRestoreData> = withContext(Dispatchers.IO) {
|
||||||
try {
|
try {
|
||||||
// 1. Read Meals
|
// Ensure tabs exist and any legacy tab is renamed before attempting to read
|
||||||
val mealsRange = URLEncoder.encode("'$SHEET_TAB_MEALS'!A1:Z", "UTF-8")
|
ensureTabsExist(accessToken, spreadsheetId)
|
||||||
|
|
||||||
|
// 1. Read Meals with RFC 3986 encoding (%20)
|
||||||
|
val mealsRange = encodePathRange("'$SHEET_TAB_MEALS'!A1:Z")
|
||||||
val mealsUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/$mealsRange"
|
val mealsUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/$mealsRange"
|
||||||
val mealsReq = Request.Builder()
|
val mealsReq = Request.Builder()
|
||||||
.url(mealsUrl)
|
.url(mealsUrl)
|
||||||
@@ -347,7 +415,7 @@ object GoogleSheetsSyncService {
|
|||||||
|
|
||||||
val mealRows = mutableListOf<List<Any>>()
|
val mealRows = mutableListOf<List<Any>>()
|
||||||
okHttpClient.newCall(mealsReq).execute().use { resp ->
|
okHttpClient.newCall(mealsReq).execute().use { resp ->
|
||||||
if (resp.code == 401) return@withContext Result.failure(AuthExpiredException("Token expiré"))
|
if (resp.code == 401) throw AuthExpiredException("Token expiré")
|
||||||
if (resp.isSuccessful) {
|
if (resp.isSuccessful) {
|
||||||
val body = resp.body?.string().orEmpty()
|
val body = resp.body?.string().orEmpty()
|
||||||
val values = JSONObject(body).optJSONArray("values")
|
val values = JSONObject(body).optJSONArray("values")
|
||||||
@@ -364,8 +432,8 @@ object GoogleSheetsSyncService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Read Custom Foods
|
// 2. Read Custom Foods with RFC 3986 encoding (%20)
|
||||||
val foodsRange = URLEncoder.encode("'$SHEET_TAB_FOODS'!A1:C", "UTF-8")
|
val foodsRange = encodePathRange("'$SHEET_TAB_FOODS'!A1:C")
|
||||||
val foodsUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/$foodsRange"
|
val foodsUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/$foodsRange"
|
||||||
val foodsReq = Request.Builder()
|
val foodsReq = Request.Builder()
|
||||||
.url(foodsUrl)
|
.url(foodsUrl)
|
||||||
@@ -375,6 +443,7 @@ object GoogleSheetsSyncService {
|
|||||||
|
|
||||||
val foodRows = mutableListOf<List<Any>>()
|
val foodRows = mutableListOf<List<Any>>()
|
||||||
okHttpClient.newCall(foodsReq).execute().use { resp ->
|
okHttpClient.newCall(foodsReq).execute().use { resp ->
|
||||||
|
if (resp.code == 401) throw AuthExpiredException("Token expiré")
|
||||||
if (resp.isSuccessful) {
|
if (resp.isSuccessful) {
|
||||||
val body = resp.body?.string().orEmpty()
|
val body = resp.body?.string().orEmpty()
|
||||||
val values = JSONObject(body).optJSONArray("values")
|
val values = JSONObject(body).optJSONArray("values")
|
||||||
|
|||||||
@@ -151,5 +151,16 @@ class GoogleSheetsDataFormatterTest {
|
|||||||
)
|
)
|
||||||
assertEquals("https://drive.google.com/file/1", rows[1][9])
|
assertEquals("https://drive.google.com/file/1", rows[1][9])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun `encodePathRange replaces plus signs with percent twenty according to RFC 3986`() {
|
||||||
|
val range = "'Journal des repas'!A1"
|
||||||
|
val encoded = com.example.util.GoogleSheetsSyncService.encodePathRange(range)
|
||||||
|
assertEquals("%27Journal%20des%20repas%27%21A1", encoded)
|
||||||
|
|
||||||
|
val foodRange = "'Mes plats et aliments'!A1:C"
|
||||||
|
val foodEncoded = com.example.util.GoogleSheetsSyncService.encodePathRange(foodRange)
|
||||||
|
assertEquals("%27Mes%20plats%20et%20aliments%27%21A1%3AC", foodEncoded)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Reference in new issue
Block a user