From 4286c231c404dc60dadb5fe858766e9fe0d91705 Mon Sep 17 00:00:00 2001
From: fabiovandewaeter <vandewaeter.fabio@gmail.com>
Date: Sun, 23 Mar 2025 12:23:57 +0100
Subject: [PATCH] =?UTF-8?q?recherche=20de=20ressources=20sur=20tous=20diff?=
 =?UTF-8?q?=C3=A9rents=20serveurs=20FTP?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 README.md                                     |  5 ++
 .../java/fil/sr2/flopbox/FTPResource.java     | 61 +++++++++++++++++++
 2 files changed, 66 insertions(+)

diff --git a/README.md b/README.md
index 4a74bc5..f4d8f74 100644
--- a/README.md
+++ b/README.md
@@ -175,3 +175,8 @@ curl -X DELETE -H "Authorization: Bearer valid-token-1" -H "X-FTP-User: user" -H
 ```
 
 **Note comprise entre 15 et 16 si—en plus—le proxy FlopBox, permet de chercher des fichiers/répertoires stockés dans plusieurs serveurs FTP (le proxy retourne la liste des URLs pour chaque fichier trouvé):**
+
+- rechercher une ressource :
+```shell
+curl -X GET -H "Authorization: Bearer valid-token-1" -H "X-FTP-User: user" -H "X-FTP-Pass: password" http://localhost:8080/ftps/search/fichier1
+```
diff --git a/src/main/java/fil/sr2/flopbox/FTPResource.java b/src/main/java/fil/sr2/flopbox/FTPResource.java
index e3385d6..eb95dc0 100644
--- a/src/main/java/fil/sr2/flopbox/FTPResource.java
+++ b/src/main/java/fil/sr2/flopbox/FTPResource.java
@@ -6,6 +6,9 @@ import java.io.IOException;
 import java.io.InputStream;
 import java.net.URI;
 import java.util.List;
+import java.util.Map;
+import java.util.HashMap;
+import java.util.ArrayList;
 
 @Path("/ftps")
 public class FTPResource {
@@ -44,6 +47,64 @@ public class FTPResource {
         return Response.created(builder.build()).build();
     }
 
+    @GET
+    @Path("/search/{path: .+}")
+    @Produces(MediaType.APPLICATION_JSON)
+    public Response searchFiles(
+            @PathParam("path") String searchTerm,
+            @HeaderParam("X-FTP-User") String user,
+            @HeaderParam("X-FTP-Pass") String pass) {
+        System.out.println("searchFiles()");
+        List<FTPServerConfig> servers = FTPServerRepository.getInstance().getAllServers();
+        Map<String, List<String>> results = new HashMap<>();
+        // Pour chaque serveur FTP configuré
+        for (FTPServerConfig config : servers) {
+            try {
+                // On récupère l’arborescence racine du serveur
+                FTPService.FtpNode tree = ftpService.getResourceTree(config.getAlias(), "", user, pass);
+                List<String> urls = new ArrayList<>();
+                // Parcourir récursivement l’arborescence pour chercher le fichier (ou
+                // répertoire) recherché
+                searchInTree(tree, searchTerm, "", config, urls);
+                if (!urls.isEmpty()) {
+                    results.put(config.getAlias(), urls);
+                }
+            } catch (Exception e) {
+                System.err.println(
+                        "Erreur lors de la recherche sur le serveur " + config.getAlias() + " : " + e.getMessage());
+            }
+        }
+        return Response.ok(results).build();
+    }
+
+    /**
+     * Recherche récursive dans l’arborescence FTP.
+     *
+     * @param node        l’arborescence à parcourir
+     * @param searchTerm  la chaîne à rechercher
+     * @param currentPath le chemin courant dans l’arborescence
+     * @param config      la configuration du serveur FTP (pour construire l’URL)
+     * @param urls        la liste des URLs trouvées
+     */
+    private void searchInTree(FTPService.FtpNode node, String searchTerm, String currentPath, FTPServerConfig config,
+            List<String> urls) {
+        // Concaténation du chemin
+        String newPath = currentPath.isEmpty() ? node.name : currentPath + "/" + node.name;
+        // Si le nom contient le terme recherché (fichier ou dossier)
+        if (node.name.toLowerCase().contains(searchTerm.toLowerCase())) {
+            // Construction de l’URL FTP. On suppose que FTPServerConfig possède une méthode
+            // getHost().
+            String ftpUrl = "ftp://" + config.getHost() + "/" + newPath;
+            urls.add(ftpUrl);
+        }
+        // Parcours des enfants si le nœud est un répertoire
+        if (node.isDirectory && node.children != null) {
+            for (FTPService.FtpNode child : node.children) {
+                searchInTree(child, searchTerm, newPath, config, urls);
+            }
+        }
+    }
+
     @DELETE
     @Path("/{alias}")
     public Response removeFTPServer(@PathParam("alias") String alias) {
-- 
GitLab