upload_handler.dart 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  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. final supabaseurl = request.headers['supabaseurl'] ?? "http://kong:8000";
  21. // Initialize Supabase client with the bearer token
  22. final supabase = SupabaseClient(
  23. // 'http://baas.fares.cyou:8000',
  24. supabaseurl,
  25. token,
  26. );
  27. if (request.multipart() case var multipart?) {
  28. List<Map<String, dynamic>> uploadedFiles = [];
  29. await for (final part in multipart.parts) {
  30. final contentDisposition = part.headers['content-disposition'];
  31. if (contentDisposition != null &&
  32. contentDisposition.contains('filename=')) {
  33. final name =
  34. RegExp(r'name="([^"]*)"').firstMatch(contentDisposition)?.group(1);
  35. final filename = RegExp(r'filename="([^"]*)"')
  36. .firstMatch(contentDisposition)
  37. ?.group(1);
  38. if (name != null && name != "" && filename != null) {
  39. print("File Uploaded: $filename");
  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. await supabase.storage.from('csvhich').uploadBinary(
  46. filename,
  47. await tempFile.readAsBytes(),
  48. fileOptions: FileOptions(
  49. upsert: true,
  50. contentType: part.headers['content-type'],
  51. ),
  52. );
  53. //insertline in csvhichupdates
  54. //print("inserting incsvhichupdates");
  55. await supabase.from('csvhichupdates').insert({
  56. 'filename': filename,
  57. 'updated_at': DateTime.now().toUtc().toIso8601String(),
  58. });
  59. //copy file to csvhich archive
  60. final nowdt = DateTime.now().toUtc();
  61. final now = nowdt.toIso8601String();
  62. // 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')}';
  63. final timestamp = nowdt.millisecondsSinceEpoch.toString();
  64. //upload file to storage archive bucket
  65. final archiveFilename = 'upload/${timestamp}_$filename';
  66. // await supabase.storage.from('csvhich_archive').uploadBinary(
  67. // archiveFilename,
  68. // await tempFile.readAsBytes(),
  69. // fileOptions: FileOptions(
  70. // upsert: true,
  71. // contentType: part.headers['content-type'],
  72. // ),
  73. // );
  74. await supabase.storage.from('csvhich').copy(
  75. filename,
  76. archiveFilename,
  77. destinationBucket: 'csvhich_archive',
  78. );
  79. await processCsvData(tempFile, supabase);
  80. //add filename ta list
  81. uploadedFiles.add({
  82. 'filename': filename,
  83. 'updated_at': now,
  84. });
  85. final end = Jiffy.now();
  86. print(
  87. " ${DTInterval(start, end).duration.inMilliseconds / 1000} seconds\n");
  88. // Clean up temporary file
  89. await tempFile.delete();
  90. }
  91. }
  92. }
  93. supabase.dispose();
  94. if (uploadedFiles.isNotEmpty) {
  95. return Response.ok(
  96. '{"status": "success", "files": ${uploadedFiles.toString()}}',
  97. headers: {'Content-Type': 'application/json'},
  98. );
  99. }
  100. return Response(400, body: 'No files were uploaded');
  101. } else {
  102. supabase.dispose();
  103. return Response(401, body: 'Not a multipart request');
  104. }
  105. }