diff --git a/app/src/main/java/com/example/util/GoogleSheetsSyncService.kt b/app/src/main/java/com/example/util/GoogleSheetsSyncService.kt index a4bb2ca..a5247d2 100644 --- a/app/src/main/java/com/example/util/GoogleSheetsSyncService.kt +++ b/app/src/main/java/com/example/util/GoogleSheetsSyncService.kt @@ -56,7 +56,7 @@ object GoogleSheetsSyncService { // 1. If we have a cached spreadsheetId, verify it still exists and ensure 2 tabs if (!cachedSpreadsheetId.isNullOrBlank()) { 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") .get() .build() @@ -70,7 +70,7 @@ object GoogleSheetsSyncService { val json = JSONObject(body) val id = json.getString("spreadsheetId") val url = json.optString("spreadsheetUrl", "https://docs.google.com/spreadsheets/d/$id/edit") - ensureCustomFoodsTabExists(accessToken, id, json) + ensureTabsExist(accessToken, id, json) if (parentFolderId != null) { GoogleDriveService.moveFileToFolder(accessToken, id, parentFolderId) } @@ -104,7 +104,7 @@ object GoogleSheetsSyncService { val firstFile = files.getJSONObject(0) val id = firstFile.getString("id") val link = firstFile.optString("webViewLink", "https://docs.google.com/spreadsheets/d/$id/edit") - ensureCustomFoodsTabExists(accessToken, id, null) + ensureTabsExist(accessToken, id, null) if (parentFolderId != null) { 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, spreadsheetId: String, - spreadsheetJson: JSONObject? + spreadsheetJson: JSONObject? = null ) = withContext(Dispatchers.IO) { try { val json = spreadsheetJson ?: run { 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") .get() .build() 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 } } ?: return@withContext val sheets = json.optJSONArray("sheets") ?: return@withContext + var hasMealsTab = false var hasFoodsTab = false + var legacySheetIdToRename: Int? = null + + val legacyTabNames = setOf("Journal", "Feuille 1", "Sheet1", "Sheet 1") + for (i in 0 until sheets.length()) { - val title = sheets.getJSONObject(i).optJSONObject("properties")?.optString("title") - if (title == SHEET_TAB_FOODS) { - hasFoodsTab = true - break + val props = sheets.getJSONObject(i).optJSONObject("properties") ?: continue + val title = props.optString("title") + val sId = props.optInt("sheetId", -1) + + 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 addSheetPayload = JSONObject().apply { - put("requests", JSONArray().apply { - put(JSONObject().apply { - put("addSheet", JSONObject().apply { - put("properties", JSONObject().apply { - put("title", SHEET_TAB_FOODS) - put("gridProperties", JSONObject().apply { - put("frozenRowCount", 1) - }) + val batchRequests = JSONArray() + + // 1. If "Journal des repas" does not exist: rename legacy sheet if present, else create it + if (!hasMealsTab) { + if (legacySheetIdToRename != null) { + batchRequests.put(JSONObject().apply { + put("updateSheetProperties", JSONObject().apply { + put("properties", JSONObject().apply { + 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") .header("Authorization", "Bearer $accessToken") - .post(addSheetPayload.toString().toRequestBody(jsonMediaType)) + .post(batchPayload.toString().toRequestBody(jsonMediaType)) .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) { - 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) { - 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 } ): Result = withContext(Dispatchers.IO) { try { + // Ensure both tabs exist and legacy tabs are migrated before writing + ensureTabsExist(accessToken, spreadsheetId) + // 1. Sync Meals on SHEET_TAB_MEALS val mealRows = GoogleSheetsDataFormatter.formatMealsToRows(meals = meals, photoLinkProvider = photoLinkProvider) writeRowsToSheet(accessToken, spreadsheetId, SHEET_TAB_MEALS, "A:Z", "A1", mealRows) @@ -279,8 +344,8 @@ object GoogleSheetsSyncService { startCell: String, rows: List> ) = withContext(Dispatchers.IO) { - // Clear previous range - val clearRange = URLEncoder.encode("'$sheetTitle'!$clearRangeColumns", "UTF-8") + // Clear previous range with RFC 3986 encoding (%20 instead of +) + val clearRange = encodePathRange("'$sheetTitle'!$clearRangeColumns") val clearUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/$clearRange:clear" val clearRequest = Request.Builder() .url(clearUrl) @@ -313,7 +378,7 @@ object GoogleSheetsSyncService { 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 writeRequest = Request.Builder() .url(writeUrl) @@ -336,8 +401,11 @@ object GoogleSheetsSyncService { spreadsheetId: String ): Result = withContext(Dispatchers.IO) { try { - // 1. Read Meals - val mealsRange = URLEncoder.encode("'$SHEET_TAB_MEALS'!A1:Z", "UTF-8") + // Ensure tabs exist and any legacy tab is renamed before attempting to read + 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 mealsReq = Request.Builder() .url(mealsUrl) @@ -347,7 +415,7 @@ object GoogleSheetsSyncService { val mealRows = mutableListOf>() 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) { val body = resp.body?.string().orEmpty() val values = JSONObject(body).optJSONArray("values") @@ -364,8 +432,8 @@ object GoogleSheetsSyncService { } } - // 2. Read Custom Foods - val foodsRange = URLEncoder.encode("'$SHEET_TAB_FOODS'!A1:C", "UTF-8") + // 2. Read Custom Foods with RFC 3986 encoding (%20) + val foodsRange = encodePathRange("'$SHEET_TAB_FOODS'!A1:C") val foodsUrl = "https://sheets.googleapis.com/v4/spreadsheets/$spreadsheetId/values/$foodsRange" val foodsReq = Request.Builder() .url(foodsUrl) @@ -375,6 +443,7 @@ object GoogleSheetsSyncService { val foodRows = mutableListOf>() okHttpClient.newCall(foodsReq).execute().use { resp -> + if (resp.code == 401) throw AuthExpiredException("Token expiré") if (resp.isSuccessful) { val body = resp.body?.string().orEmpty() val values = JSONObject(body).optJSONArray("values") diff --git a/app/src/test/java/com/example/GoogleSheetsDataFormatterTest.kt b/app/src/test/java/com/example/GoogleSheetsDataFormatterTest.kt index af27979..c784dd4 100644 --- a/app/src/test/java/com/example/GoogleSheetsDataFormatterTest.kt +++ b/app/src/test/java/com/example/GoogleSheetsDataFormatterTest.kt @@ -151,5 +151,16 @@ class GoogleSheetsDataFormatterTest { ) 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) + } }