upload_handler.dart 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. import 'dart:io';
  2. import 'package:jiffy/jiffy.dart';
  3. import 'package:myshelf/models/data.dart';
  4. import 'package:myshelf/models/dtinterval.dart';
  5. import 'package:shelf/shelf.dart';
  6. import 'package:shelf_multipart/shelf_multipart.dart';
  7. import 'package:supabase/supabase.dart';
  8. Future<Response> handleFileUpload(Request request) async {
  9. final start = Jiffy.now();
  10. // Check authorization
  11. final authHeader = request.headers['authorization'];
  12. if (authHeader == null || !authHeader.startsWith('Bearer ')) {
  13. return Response.forbidden('Authorization header missing or invalid');
  14. }
  15. final token = authHeader.substring(7); // Remove 'Bearer ' prefix
  16. final contentType = request.headers['content-type'];
  17. if (contentType == null || !contentType.contains('multipart/form-data')) {
  18. return Response(400, body: 'Unsupported content-type');
  19. }
  20. // Initialize Supabase client with the bearer token
  21. final supabase = SupabaseClient(
  22. // 'http://baas.fares.cyou:8000',
  23. 'http://kong:8000',
  24. token,
  25. );
  26. if (request.multipart() case var multipart?) {
  27. List<Map<String, dynamic>> uploadedFiles = [];
  28. await for (final part in multipart.parts) {
  29. final contentDisposition = part.headers['content-disposition'];
  30. if (contentDisposition != null &&
  31. contentDisposition.contains('filename=')) {
  32. final name =
  33. RegExp(r'name="([^"]*)"').firstMatch(contentDisposition)?.group(1);
  34. final filename = RegExp(r'filename="([^"]*)"')
  35. .firstMatch(contentDisposition)
  36. ?.group(1);
  37. if (name != null && name != "" && filename != null) {
  38. print("File Uploaded: $filename");
  39. try {
  40. // Create temporary file
  41. final tempFile = File('uploads/$filename');
  42. await tempFile.create(recursive: true);
  43. await part.pipe(tempFile.openWrite());
  44. // Upload to Supabase
  45. final bytes = await tempFile.readAsBytes();
  46. await supabase.storage.from('csvhich').uploadBinary(
  47. filename,
  48. bytes,
  49. fileOptions: FileOptions(
  50. upsert: true,
  51. contentType: part.headers['content-type'],
  52. ),
  53. );
  54. //insertline in csvhichupdates
  55. //print("inserting incsvhichupdates");
  56. await supabase.from('csvhichupdates').insert({
  57. 'filename': filename,
  58. 'updated_at': DateTime.now().toUtc().toIso8601String(),
  59. });
  60. //copy file to csvhich archive
  61. final nowdt = DateTime.now().toUtc();
  62. final now = nowdt.toIso8601String();
  63. // 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')}';
  64. final timestamp = nowdt.millisecondsSinceEpoch.toString();
  65. //upload file to storage archive bucket
  66. try {
  67. final archiveFilename = 'upload/${timestamp}_$filename';
  68. await supabase.storage.from('csvhich_archive').uploadBinary(
  69. archiveFilename,
  70. bytes,
  71. fileOptions: FileOptions(
  72. upsert: true,
  73. contentType: part.headers['content-type'],
  74. ),
  75. );
  76. } catch (e) {
  77. print('Error uploading to archive: $e');
  78. // Continue execution even if archive upload fails
  79. }
  80. // No need to subscribe to channel
  81. final channel = supabase.channel('csvhichstorage');
  82. final res = await channel.sendBroadcastMessage(
  83. event: "upload",
  84. payload: {
  85. "filename": filename,
  86. "updated_at": now,
  87. },
  88. );
  89. print(" realtime response: $res");
  90. await processCsvData(tempFile, supabase);
  91. //add filename ta list
  92. uploadedFiles.add({
  93. 'filename': filename,
  94. 'updated_at': now,
  95. });
  96. final end = Jiffy.now();
  97. print(
  98. " ${DTInterval(start, end).duration.inSeconds} seconds\n");
  99. // Clean up temporary file
  100. await tempFile.delete();
  101. } catch (e) {
  102. supabase.dispose();
  103. print("Error processing file:\n $e");
  104. return Response.internalServerError(body: e.toString());
  105. }
  106. }
  107. }
  108. }
  109. supabase.dispose();
  110. if (uploadedFiles.isNotEmpty) {
  111. return Response.ok(
  112. '{"status": "success", "files": ${uploadedFiles.toString()}}',
  113. headers: {'Content-Type': 'application/json'},
  114. );
  115. }
  116. return Response(400, body: 'No files were uploaded');
  117. } else {
  118. supabase.dispose();
  119. return Response(401, body: 'Not a multipart request');
  120. }
  121. }