upload_handler.dart 4.4 KB

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