Skip to content

Commit

Permalink
Merge pull request #75 from papercups-io/lighten-sendMessage
Browse files Browse the repository at this point in the history
Attchment Improvements & Better Maintainability
  • Loading branch information
aguilaair authored Oct 17, 2021
2 parents c9b2a6e + be1699c commit 1360acf
Show file tree
Hide file tree
Showing 32 changed files with 959 additions and 668 deletions.
15 changes: 11 additions & 4 deletions example/pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ packages:
name: ffi
url: "https://pub.dartlang.org"
source: hosted
version: "1.0.0"
version: "1.1.2"
file:
dependency: transitive
description:
Expand All @@ -98,7 +98,7 @@ packages:
name: file_picker
url: "https://pub.dartlang.org"
source: hosted
version: "3.0.1"
version: "4.1.4"
flex_color_picker:
dependency: "direct main"
description:
Expand All @@ -124,7 +124,7 @@ packages:
name: flutter_plugin_android_lifecycle
url: "https://pub.dartlang.org"
source: hosted
version: "2.0.1"
version: "2.0.3"
flutter_test:
dependency: "direct dev"
description: flutter
Expand Down Expand Up @@ -191,6 +191,13 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "1.7.0"
open_file:
dependency: transitive
description:
name: open_file
url: "https://pub.dartlang.org"
source: hosted
version: "3.2.1"
papercups_flutter:
dependency: "direct main"
description:
Expand Down Expand Up @@ -438,4 +445,4 @@ packages:
version: "0.2.0"
sdks:
dart: ">=2.12.0 <3.0.0"
flutter: ">=1.22.0"
flutter: ">=2.0.0"
2 changes: 2 additions & 0 deletions lib/models/attachment.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'package:universal_io/io.dart';

class PapercupsAttachment {
String? id;
String? fileName;
Expand Down
1 change: 0 additions & 1 deletion lib/models/models.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,5 @@ export 'classes.dart';
export 'conversation.dart';
export 'customer.dart';
export 'message.dart';
export 'message.dart';
export 'user.dart';
export 'attachment.dart';
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import 'dart:convert';

import 'package:http/http.dart';
import '../models/models.dart';
import '../../models/models.dart';

/// This function will get the conversation details that we need in order to join the room.
/// The most important detail is the ID, and this will return a **new** conversation.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import 'dart:convert';

import 'package:http/http.dart';
import '../models/models.dart';
import 'utils.dart';
import '../../models/models.dart';
import '../utils.dart';

Future<PapercupsCustomer> getCustomerDetails(
Props p,
Expand All @@ -18,7 +18,9 @@ Future<PapercupsCustomer> getCustomerDetails(
}
try {
var timeNow = DateTime.now().toUtc().toIso8601String();
var metadata = p.customer != null && p.customer!.otherMetadata != null ? p.customer!.otherMetadata! : {};
var metadata = p.customer != null && p.customer!.otherMetadata != null
? p.customer!.otherMetadata!
: {};
var jsonString = jsonEncode(
{
"customer": {
Expand All @@ -41,10 +43,14 @@ Future<PapercupsCustomer> getCustomerDetails(
);
var data = jsonDecode(res.body)["data"];
c = PapercupsCustomer(
createdAt: data["created_at"] != null ? parseDateFromUTC(data["created_at"]) : null,
createdAt: data["created_at"] != null
? parseDateFromUTC(data["created_at"])
: null,
email: data["email"],
externalId: data["external_id"],
firstSeen: data["first_seen"] != null ? parseDateFromUTC(data["first_seen"]) : null,
firstSeen: data["first_seen"] != null
? parseDateFromUTC(data["first_seen"])
: null,
id: data["id"],
lastSeenAt: data["last_seen_at"] != null
? parseDateFromUTC(data["last_seen_at"])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import 'dart:convert';

import 'package:http/http.dart';
import '../models/models.dart';
import '../../models/models.dart';

/// This funtction is used to get the customer details from Papercups.
/// This is the function responsible for finding the Customer's ID.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
//Imports
import 'updateUserMetadata.dart';

import '../models/models.dart';
import '../papercups_flutter.dart';
import '../../models/models.dart';
import '../../papercups_flutter.dart';
import 'package:phoenix_socket/phoenix_socket.dart';
import 'dart:async';

import 'getCustomerDetailsFromMetadata.dart';
import 'getPastCustomerMessages.dart';
import 'joinConversation.dart';
import '../socket/joinConversation.dart';

/// This function is used to get the history.
/// It also initializes the necessary funtions if the customer is known.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
import 'dart:convert';

import 'package:http/http.dart';
import '../models/models.dart';
import 'utils.dart';
import '../../models/models.dart';
import '../utils.dart';

/// This function is used to get the past messages from the customer.
Future<Map<String, dynamic>> getPastCustomerMessages(
Expand Down Expand Up @@ -38,7 +38,7 @@ Future<Map<String, dynamic>> getPastCustomerMessages(
};
}

data[0]["messages"].forEach((val) {
data["messages"].forEach((val) {
rMsgs.add(
PapercupsMessage(
accountId: val["account_id"],
Expand All @@ -55,10 +55,29 @@ Future<Map<String, dynamic>> getPastCustomerMessages(
email: val["user"]["email"],
id: val["user"]["id"],
role: val["user"]["role"],
fullName: (val["user"]["full_name"] != null) ? val["user"]["full_name"] : null,
profilePhotoUrl: (val["user"]["profile_photo_url"] != null) ? val["user"]["profile_photo_url"] : null,
fullName: (val["user"]["full_name"] != null)
? val["user"]["full_name"]
: null,
profilePhotoUrl: (val["user"]["profile_photo_url"] != null)
? val["user"]["profile_photo_url"]
: null,
)
: null,
attachments: (val["attachments"] != null)
? (val["attachments"] as List<dynamic>).map((attachment) {
return PapercupsAttachment(
contentType: attachment["content_type"],
fileName: attachment["filename"],
fileUrl: attachment["file_url"],
id: attachment["id"],
);
}).toList()
: null,
fileIds: (val["attachments"] != null)
? (val["attachments"] as List<dynamic>).map((attachment) {
return attachment["id"] as String;
}).toList()
: null,
),
);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
import 'dart:convert';

import 'package:http/http.dart';
import '../papercups_flutter.dart';
import '../../papercups_flutter.dart';

import '../models/models.dart';
import 'utils.dart';
import '../../models/models.dart';
import '../utils.dart';

/// This function is used to update customer details on the Papercups server.
Future<PapercupsCustomer?> updateUserMetadata(
Expand Down
File renamed without changes.
57 changes: 57 additions & 0 deletions lib/utils/fileInteraction/handleDownloads.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import 'dart:typed_data';

import 'package:http/http.dart';
import 'package:open_file/open_file.dart';
import 'package:papercups_flutter/models/models.dart';
import 'package:path_provider/path_provider.dart';
import 'package:universal_io/io.dart';

Future<void> handleDownloadStream(Stream<StreamedResponse> resp,
{required File file,
Function? onDownloading,
Function? onDownloaded}) async {
List<List<int>> chunks = [];

if (onDownloading != null) {
onDownloading();
}

resp.listen((StreamedResponse r) {
r.stream.listen((List<int> chunk) {
if (r.contentLength == null) {
print("Error");
}

chunks.add(chunk);
}, onDone: () async {
final Uint8List bytes = Uint8List(r.contentLength ?? 0);
int offset = 0;
for (List<int> chunk in chunks) {
bytes.setRange(offset, offset + chunk.length, chunk);
offset += chunk.length;
}
await file.writeAsBytes(bytes);
OpenFile.open(file.absolute.path);
if (onDownloaded != null) {
onDownloaded();
}
});
});
}

Future<File> getAttachment(PapercupsAttachment attachment) async {
String dir = (await getApplicationDocumentsDirectory()).path;
File? file = File(dir +
Platform.pathSeparator +
(attachment.id ?? "noId") +
(attachment.fileName ?? "noName"));
return file;
}

Future<bool> checkCachedFiles(PapercupsAttachment attachment) async {
var file = await getAttachment(attachment);
if (await file.exists()) {
return true;
}
return false;
}
65 changes: 65 additions & 0 deletions lib/utils/fileInteraction/nativeFilePicker.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:papercups_flutter/models/models.dart';
import 'package:papercups_flutter/utils/fileInteraction/uploadFile.dart';
import 'package:papercups_flutter/widgets/alert.dart';

void nativeFilePicker(
{required FileType type,
required BuildContext context,
required widget,
required Function onUploadSuccess}) async {
try {
final _paths = (await FilePicker.platform.pickFiles(
type: type,
))
?.files;
if (_paths != null && _paths.first.path != null) {
Alert.show(
"Uploading...",
context,
textStyle: Theme.of(context).textTheme.bodyText2,
backgroundColor: Theme.of(context).bottomAppBarColor,
gravity: Alert.bottom,
duration: Alert.lengthLong,
);
List<PapercupsAttachment> attachments = await uploadFile(
widget.props,
filePath: _paths.first.path,
onUploadProgress: (sentBytes, totalBytes) {
Alert.show(
"${(sentBytes * 100 / totalBytes).toStringAsFixed(2)}% uploaded",
context,
textStyle: Theme.of(context).textTheme.bodyText2,
backgroundColor: Theme.of(context).bottomAppBarColor,
gravity: Alert.bottom,
duration: Alert.lengthLong,
);
},
);

onUploadSuccess(attachments);
}
} on PlatformException catch (_) {
Alert.show(
"Failed to upload attachment",
context,
textStyle: Theme.of(context).textTheme.bodyText2,
backgroundColor: Theme.of(context).bottomAppBarColor,
gravity: Alert.bottom,
duration: Alert.lengthLong,
);
throw _;
} catch (_) {
Alert.show(
"Failed to upload attachment",
context,
textStyle: Theme.of(context).textTheme.bodyText2,
backgroundColor: Theme.of(context).bottomAppBarColor,
gravity: Alert.bottom,
duration: Alert.lengthLong,
);
throw _;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import 'dart:convert';
import 'dart:typed_data';

import 'package:http/http.dart';
import '../models/models.dart';
import '../../models/models.dart';

typedef void OnUploadProgressCallback(int sentBytes, int totalBytes);

Expand All @@ -23,7 +23,11 @@ Future<List<PapercupsAttachment>> uploadFile(
var client = MultipartRequest("POST", uri)
..fields['account_id'] = p.accountId;

if (Platform.isAndroid || Platform.isIOS) {
if (Platform.isAndroid ||
Platform.isIOS ||
Platform.isLinux ||
Platform.isMacOS ||
Platform.isWindows) {
client.files.add(await MultipartFile.fromPath('file', filePath ?? ''));
var msStream = client.finalize();
var totalByteLength = client.contentLength;
Expand Down
41 changes: 41 additions & 0 deletions lib/utils/fileInteraction/webFilePicker.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:papercups_flutter/models/attachment.dart';
import 'package:papercups_flutter/utils/fileInteraction/uploadFile.dart';
import 'package:papercups_flutter/widgets/alert.dart';

Future<void> webFilePicker(
{required BuildContext context,
required Function onUploadSuccess,
required widget}) async {
try {
var picked = await FilePicker.platform.pickFiles();

if (picked != null && picked.files.first.bytes != null) {
Alert.show(
"Uploading...",
context,
textStyle: Theme.of(context).textTheme.bodyText2,
backgroundColor: Theme.of(context).bottomAppBarColor,
gravity: Alert.bottom,
duration: Alert.lengthLong,
);
List<PapercupsAttachment> attachments = await uploadFile(
widget.props,
fileBytes: picked.files.first.bytes,
fileName: picked.files.first.name,
);
onUploadSuccess(attachments);
}
} on Exception catch (_) {
Alert.show(
"Failed to upload attachment",
context,
textStyle: Theme.of(context).textTheme.bodyText2,
backgroundColor: Theme.of(context).bottomAppBarColor,
gravity: Alert.bottom,
duration: Alert.lengthLong,
);
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Imports
import '../models/models.dart';
import '../papercups_flutter.dart';
import '../../models/models.dart';
import '../../papercups_flutter.dart';
import 'package:phoenix_socket/phoenix_socket.dart';

/// This function creates the necessary channels, sockets and rooms for papercups to communicate.
Expand Down
Loading

0 comments on commit 1360acf

Please sign in to comment.