upload_handler.dart 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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. token,
  24. );
  25. if (request.multipart() case var multipart?) {
  26. List<Map<String, dynamic>> uploadedFiles = [];
  27. await for (final part in multipart.parts) {
  28. final contentDisposition = part.headers['content-disposition'];
  29. if (contentDisposition != null &&
  30. contentDisposition.contains('filename=')) {
  31. final name =
  32. RegExp(r'name="([^"]*)"').firstMatch(contentDisposition)?.group(1);
  33. final filename = RegExp(r'filename="([^"]*)"')
  34. .firstMatch(contentDisposition)
  35. ?.group(1);
  36. if (name != null && name != "" && filename != null) {
  37. print("File Uploaded: $filename");
  38. try {
  39. // Create temporary file
  40. final tempFile = File('uploads/$filename');
  41. await tempFile.create(recursive: true);
  42. await part.pipe(tempFile.openWrite());
  43. // Upload to Supabase
  44. final bytes = await tempFile.readAsBytes();
  45. await supabase.storage.from('csvhich').uploadBinary(
  46. filename,
  47. bytes,
  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. try {
  66. final archiveFilename = 'upload/${timestamp}_$filename';
  67. await supabase.storage.from('csvhich_archive').uploadBinary(
  68. archiveFilename,
  69. bytes,
  70. fileOptions: FileOptions(
  71. upsert: true,
  72. contentType: part.headers['content-type'],
  73. ),
  74. );
  75. } catch (e) {
  76. print('Error uploading to archive: $e');
  77. // Continue execution even if archive upload fails
  78. }
  79. await processCsvData(tempFile, supabase);
  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. //add filename ta list
  91. uploadedFiles.add({
  92. 'filename': filename,
  93. 'updated_at': now,
  94. });
  95. final end = Jiffy.now();
  96. print(
  97. " ${DTInterval(start, end).duration.inSeconds} seconds\n");
  98. // Clean up temporary file
  99. await tempFile.delete();
  100. } catch (e) {
  101. supabase.dispose();
  102. print("Error processing file:\n $e");
  103. return Response.internalServerError(body: e.toString());
  104. }
  105. }
  106. }
  107. }
  108. supabase.dispose();
  109. if (uploadedFiles.isNotEmpty) {
  110. return Response.ok(
  111. '{"status": "success", "files": ${uploadedFiles.toString()}}',
  112. headers: {'Content-Type': 'application/json'},
  113. );
  114. }
  115. return Response(400, body: 'No files were uploaded');
  116. } else {
  117. supabase.dispose();
  118. return Response(401, body: 'Not a multipart request');
  119. }
  120. }