Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ability to attach files in chat - app side #1629

Open
wants to merge 21 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 42 additions & 4 deletions app/lib/backend/http/api/messages.dart
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ Future<List<ServerMessage>> clearChatServer({String? pluginId}) async {
}
}

Future<ServerMessage> sendMessageServer(String text, {String? appId}) {
Future<ServerMessage> sendMessageServer(String text, {String? appId, List<String>? fileIds}) {
var url = '${Env.apiBaseUrl}v1/messages?plugin_id=$appId';
if (appId == null || appId.isEmpty || appId == 'null' || appId == 'no_selected') {
url = '${Env.apiBaseUrl}v1/messages';
Expand All @@ -63,7 +63,7 @@ Future<ServerMessage> sendMessageServer(String text, {String? appId}) {
url: url,
headers: {},
method: 'POST',
body: jsonEncode({'text': text}),
body: jsonEncode({'text': text, 'file_ids': fileIds}),
).then((response) {
if (response == null) throw Exception('Failed to send message');
if (response.statusCode == 200) {
Expand Down Expand Up @@ -104,7 +104,7 @@ ServerMessageChunk? parseMessageChunk(String line, String messageId) {
return null;
}

Stream<ServerMessageChunk> sendMessageStreamServer(String text, {String? appId}) async* {
Stream<ServerMessageChunk> sendMessageStreamServer(String text, {String? appId, List<String>? filesId}) async* {
var url = '${Env.apiBaseUrl}v2/messages?plugin_id=$appId';
if (appId == null || appId.isEmpty || appId == 'null' || appId == 'no_selected') {
url = '${Env.apiBaseUrl}v2/messages';
Expand All @@ -114,7 +114,7 @@ Stream<ServerMessageChunk> sendMessageStreamServer(String text, {String? appId})
final request = await HttpClient().postUrl(Uri.parse(url));
request.headers.set('Authorization', await getAuthHeader());
request.headers.contentType = ContentType.json;
request.write(jsonEncode({'text': text}));
request.write(jsonEncode({'text': text, 'file_ids': filesId}));

final response = await request.close();

Expand Down Expand Up @@ -262,6 +262,44 @@ Future<List<ServerMessage>> sendVoiceMessageServer(List<File> files) async {
}
}

Future<List<MessageFile>?> uploadFilesServer(List<File> files, {String? appId}) async {
var url = '${Env.apiBaseUrl}v1/files?plugin_id=$appId';
if (appId == null || appId.isEmpty || appId == 'null' || appId == 'no_selected') {
url = '${Env.apiBaseUrl}v1/files';
}
var request = http.MultipartRequest(
'POST',
Uri.parse(url),
);
request.headers.addAll({'Authorization': await getAuthHeader()});
for (var file in files) {
var stream = http.ByteStream(file.openRead());
var length = await file.length();
var multipartFile = http.MultipartFile(
'files',
stream,
length,
filename: basename(file.path),
);
request.files.add(multipartFile);
}

try {
var streamedResponse = await request.send();
var response = await http.Response.fromStream(streamedResponse);
if (response.statusCode == 200) {
debugPrint('uploadFileServer response body: ${jsonDecode(response.body)}');
return MessageFile.fromJsonList(jsonDecode(response.body));
} else {
debugPrint('Failed to upload file. Status code: ${response.statusCode} ${response.body}');
throw Exception('Failed to upload file. Status code: ${response.statusCode}');
}
} catch (e) {
debugPrint('An error occurred uploadFileServer: $e');
throw Exception('An error occurred uploadFileServer: $e');
}
}

Future reportMessageServer(String messageId) async {
var response = await makeApiCall(
url: '${Env.apiBaseUrl}v1/messages/$messageId/report',
Expand Down
69 changes: 69 additions & 0 deletions app/lib/backend/schema/message.dart
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,54 @@ class MessageConversation {
}
}

class MessageFile {
String id;
String openaiFileId;
String? thumbnail;
String? thumbnailName;
String name;
String mimeType;
DateTime createdAt;

MessageFile(this.openaiFileId, this.thumbnail, this.name, this.mimeType, this.id, this.createdAt, this.thumbnailName);

static MessageFile fromJson(Map<String, dynamic> json) {
return MessageFile(
json['openai_file_id'],
json['thumbnail'],
json['name'],
json['mime_type'],
json['id'],
DateTime.parse(json['created_at']).toLocal(),
json['thumb_name'],
);
}

static List<MessageFile> fromJsonList(List<dynamic> json) {
return json.map((e) => MessageFile.fromJson(e)).toList();
}

Map<String, dynamic> toJson() {
return {
'openai_file_id': openaiFileId,
'thumbnail': thumbnail,
'name': name,
'mime_type': mimeType,
'id': id,
'created_at': createdAt.toUtc().toIso8601String(),
'thumb_name': thumbnailName,
};
}

String mimeTypeToFileType() {
if (mimeType.contains('image')) {
return 'image';
} else {
return 'file';
}
}
}

class ServerMessage {
String id;
DateTime createdAt;
Expand All @@ -69,6 +117,9 @@ class ServerMessage {
String? appId;
bool fromIntegration;

List<MessageFile> files;
List filesId;

List<MessageConversation> memories;
bool askForNps = false;

Expand All @@ -82,6 +133,8 @@ class ServerMessage {
this.type,
this.appId,
this.fromIntegration,
this.files,
this.filesId,
this.memories, {
this.askForNps = false,
});
Expand All @@ -95,6 +148,8 @@ class ServerMessage {
MessageType.valuesFromString(json['type']),
json['plugin_id'],
json['from_integration'] ?? false,
((json['files'] ?? []) as List<dynamic>).map((m) => MessageFile.fromJson(m)).toList(),
(json['files_id'] ?? []).map((m) => m.toString()).toList(),
((json['memories'] ?? []) as List<dynamic>).map((m) => MessageConversation.fromJson(m)).toList(),
askForNps: json['ask_for_nps'] ?? false,
);
Expand All @@ -111,9 +166,19 @@ class ServerMessage {
'from_integration': fromIntegration,
'memories': memories.map((m) => m.toJson()).toList(),
'ask_for_nps': askForNps,
'files': files.map((m) => m.toJson()).toList(),
};
}

bool areFilesOfSameType() {
if (files.isEmpty) {
return true;
}

final firstType = files.first.mimeTypeToFileType();
return files.every((element) => element.mimeTypeToFileType() == firstType);
}

static ServerMessage empty({String? appId}) {
return ServerMessage(
'0000',
Expand All @@ -124,6 +189,8 @@ class ServerMessage {
appId,
false,
[],
[],
[],
);
}

Expand All @@ -137,6 +204,8 @@ class ServerMessage {
null,
false,
[],
[],
[],
);
}

Expand Down
Loading