81 lines
2.5 KiB
Dart
81 lines
2.5 KiB
Dart
// ignore_for_file: depend_on_referenced_packages
|
|
|
|
import 'dart:async';
|
|
import 'dart:convert';
|
|
import 'dart:io';
|
|
|
|
import 'package:didvan/services/storage/storage.dart';
|
|
import 'package:http/http.dart' as http;
|
|
import 'package:mime/mime.dart';
|
|
import 'package:path/path.dart' as p;
|
|
import 'package:http_parser/http_parser.dart' as parser;
|
|
|
|
class AiApiService {
|
|
static const String baseUrl = 'https://api.didvan.app/ai';
|
|
|
|
static Future<http.MultipartRequest> initial(
|
|
{required final String url,
|
|
required final String message,
|
|
final int? chatId,
|
|
final File? file,
|
|
final bool? edite}) async {
|
|
final headers = {
|
|
"Authorization": "Bearer ${await StorageService.getValue(key: 'token')}",
|
|
'Content-Type': 'multipart/form-data'
|
|
};
|
|
|
|
var request = http.MultipartRequest('POST', Uri.parse(baseUrl + url))
|
|
..headers.addAll(headers);
|
|
|
|
request.fields['prompt'] = message;
|
|
if (chatId != null) {
|
|
request.fields['chatId'] = chatId.toString();
|
|
}
|
|
if (edite != null) {
|
|
request.fields['edit'] = edite.toString().toLowerCase();
|
|
}
|
|
if (file != null) {
|
|
final length = await file.length();
|
|
String basename = p.basename(file.path);
|
|
String? mimeType =
|
|
lookupMimeType(file.path); // Use MIME type instead of file extension
|
|
mimeType ??= 'application/octet-stream';
|
|
if (mimeType.startsWith('audio')) {
|
|
mimeType = 'audio/${p.extension(file.path).replaceAll('.', '')}';
|
|
}
|
|
request.files.add(
|
|
http.MultipartFile('file', file.readAsBytes().asStream(), length,
|
|
filename: basename,
|
|
contentType: parser.MediaType.parse(
|
|
mimeType)), // Use MediaType.parse to parse the MIME type
|
|
);
|
|
}
|
|
|
|
// print("req: ${request.files}");
|
|
// print("req: ${request.fields}");
|
|
|
|
return request;
|
|
}
|
|
|
|
static Future<Stream<List<int>>> getResponse(
|
|
http.MultipartRequest req) async {
|
|
try {
|
|
final response = await http.Client().send(req);
|
|
if (response.statusCode == 400) {
|
|
// Handle 400 response
|
|
final errorResponse = await response.stream.bytesToString();
|
|
final errorJson = jsonDecode(errorResponse);
|
|
throw Exception(errorJson['error'] ?? 'Bad Request');
|
|
} else if (response.statusCode != 200) {
|
|
// Handle other non-200 responses
|
|
throw Exception('Failed to load data');
|
|
} else {
|
|
return response.stream;
|
|
}
|
|
} catch (e) {
|
|
// Handle any other errors
|
|
throw Exception('Failed to load data');
|
|
}
|
|
}
|
|
}
|