Browse Source

amended kong realtime

Fares 10 months ago
parent
commit
07e25b5ef0
2 changed files with 72 additions and 71 deletions
  1. 0 5
      lib/handlers/realtime_handler.dart
  2. 72 66
      lib/handlers/upload_handler.dart

+ 0 - 5
lib/handlers/realtime_handler.dart

@@ -10,11 +10,6 @@ Future<Response> handleRealtime(Request request) async {
   }
   final token = authHeader.substring(7); // Remove 'Bearer ' prefix
 
-  final contentType = request.headers['content-type'];
-  if (contentType == null || !contentType.contains('multipart/form-data')) {
-    return Response(400, body: 'Unsupported content-type');
-  }
-
   // Initialize Supabase client with the bearer token
   final supabase = SupabaseClient(
     'http://baas.fares.cyou:8000',

+ 72 - 66
lib/handlers/upload_handler.dart

@@ -21,10 +21,11 @@ Future<Response> handleFileUpload(Request request) async {
     return Response(400, body: 'Unsupported content-type');
   }
 
+  final supabaseurl = request.headers['supabaseurl'] ?? "kong:8000";
   // Initialize Supabase client with the bearer token
   final supabase = SupabaseClient(
     // 'http://baas.fares.cyou:8000',
-    'http://kong:8000',
+    supabaseurl,
     token,
   );
 
@@ -42,71 +43,76 @@ Future<Response> handleFileUpload(Request request) async {
 
         if (name != null && name != "" && filename != null) {
           print("File Uploaded: $filename");
-          try {
-            // Create temporary file
-            final tempFile = File('uploads/$filename');
-            await tempFile.create(recursive: true);
-            await part.pipe(tempFile.openWrite());
-
-            // Upload to Supabase
-            final bytes = await tempFile.readAsBytes();
-            await supabase.storage.from('csvhich').uploadBinary(
-                  filename,
-                  bytes,
-                  fileOptions: FileOptions(
-                    upsert: true,
-                    contentType: part.headers['content-type'],
-                  ),
-                );
-
-            //insertline in csvhichupdates
-            //print("inserting incsvhichupdates");
-
-            await supabase.from('csvhichupdates').insert({
-              'filename': filename,
-              'updated_at': DateTime.now().toUtc().toIso8601String(),
-            });
-
-            //copy file to csvhich archive
-            final nowdt = DateTime.now().toUtc();
-            final now = nowdt.toIso8601String();
-            // final timestamp ='${nowdt.year}${nowdt.month.toString().padLeft(2, '0')}${nowdt.day.toString().padLeft(2, '0')}_${nowdt.hour.toString().padLeft(2, '0')}${nowdt.minute.toString().padLeft(2, '0')}';
-            final timestamp = nowdt.millisecondsSinceEpoch.toString();
-
-            //upload file to storage archive bucket
-            try {
-              final archiveFilename = 'upload/${timestamp}_$filename';
-              await supabase.storage.from('csvhich_archive').uploadBinary(
-                    archiveFilename,
-                    bytes,
-                    fileOptions: FileOptions(
-                      upsert: true,
-                      contentType: part.headers['content-type'],
-                    ),
-                  );
-            } catch (e) {
-              print('Error uploading to archive: $e');
-              // Continue execution even if archive upload fails
-            }
-
-            await processCsvData(tempFile, supabase);
-
-            //add filename ta list
-            uploadedFiles.add({
-              'filename': filename,
-              'updated_at': now,
-            });
-            final end = Jiffy.now();
-            print(
-                "                                        ${DTInterval(start, end).duration.inSeconds} seconds\n");
-            // Clean up temporary file
-            await tempFile.delete();
-          } catch (e) {
-            supabase.dispose();
-
-            print("Error processing file:\n $e");
-            return Response.internalServerError(body: e.toString());
-          }
+          // Create temporary file
+          final tempFile = File('uploads/$filename');
+          await tempFile.create(recursive: true);
+          await part.pipe(tempFile.openWrite());
+
+          // Upload to Supabase
+          final bytes = await tempFile.readAsBytes();
+          await supabase.storage.from('csvhich').uploadBinary(
+                filename,
+                bytes,
+                fileOptions: FileOptions(
+                  upsert: true,
+                  contentType: part.headers['content-type'],
+                ),
+              );
+
+          //insertline in csvhichupdates
+          //print("inserting incsvhichupdates");
+
+          await supabase.from('csvhichupdates').insert({
+            'filename': filename,
+            'updated_at': DateTime.now().toUtc().toIso8601String(),
+          });
+
+          //copy file to csvhich archive
+          final nowdt = DateTime.now().toUtc();
+          final now = nowdt.toIso8601String();
+          // final timestamp ='${nowdt.year}${nowdt.month.toString().padLeft(2, '0')}${nowdt.day.toString().padLeft(2, '0')}_${nowdt.hour.toString().padLeft(2, '0')}${nowdt.minute.toString().padLeft(2, '0')}';
+          final timestamp = nowdt.millisecondsSinceEpoch.toString();
+
+          //upload file to storage archive bucket
+          final archiveFilename = 'upload/${timestamp}_$filename';
+          await supabase.storage.from('csvhich_archive').uploadBinary(
+                archiveFilename,
+                bytes,
+                fileOptions: FileOptions(
+                  upsert: true,
+                  contentType: part.headers['content-type'],
+                ),
+              );
+
+          // No need to subscribe to channel
+          final supabaseRT = SupabaseClient(
+            // 'http://baas.fares.cyou:8000',
+            supabaseurl,
+            token,
+          );
+          final channel = supabaseRT.channel('csvhichstorage');
+          final res = await channel.sendBroadcastMessage(
+            event: "upload",
+            payload: {
+              "filename": filename,
+              "updated_at": now,
+            },
+          );
+          supabaseRT.dispose();
+          print("   realtime response: $res");
+
+          await processCsvData(tempFile, supabase);
+
+          //add filename ta list
+          uploadedFiles.add({
+            'filename': filename,
+            'updated_at': now,
+          });
+          final end = Jiffy.now();
+          print(
+              "                                        ${DTInterval(start, end).duration.inSeconds} seconds\n");
+          // Clean up temporary file
+          await tempFile.delete();
         }
       }
     }