FurryChat/lib/utils/matrix_file_extension.dart

75 lines
2.4 KiB
Dart
Raw Normal View History

2020-03-29 18:13:25 +00:00
import 'dart:io';
2020-10-29 09:53:36 +00:00
import 'package:downloads_path_provider_28/downloads_path_provider_28.dart';
2020-03-29 18:13:25 +00:00
import 'package:famedlysdk/famedlysdk.dart';
2020-04-10 16:25:47 +00:00
import 'package:flutter/foundation.dart';
2020-10-29 09:53:36 +00:00
import 'package:mime_type/mime_type.dart';
2020-03-29 18:13:25 +00:00
import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';
2020-10-28 07:05:10 +00:00
import 'package:permission_handler/permission_handler.dart';
2020-10-29 09:53:36 +00:00
import 'package:universal_html/prefer_universal/html.dart' as html;
import 'platform_infos.dart';
2020-03-29 18:13:25 +00:00
extension MatrixFileExtension on MatrixFile {
void open() async {
2020-04-10 16:25:47 +00:00
if (kIsWeb) {
2020-07-02 09:30:59 +00:00
final fileName = name.split('/').last;
2020-04-10 16:25:47 +00:00
final mimeType = mime(fileName);
var element = html.document.createElement('a');
element.setAttribute(
'href', html.Url.createObjectUrlFromBlob(html.Blob([bytes])));
2020-05-13 13:58:59 +00:00
element.setAttribute('target', '_blank');
element.setAttribute('rel', 'noopener');
2020-04-10 16:52:40 +00:00
element.setAttribute('download', fileName);
2020-04-10 16:25:47 +00:00
element.setAttribute('type', mimeType);
element.style.display = 'none';
html.document.body.append(element);
element.click();
element.remove();
} else {
2020-10-28 07:05:10 +00:00
if (!(await Permission.storage.request()).isGranted) return;
final downloadsDir = PlatformInfos.isDesktop
? (await getDownloadsDirectory())
: Platform.isAndroid
? (await DownloadsPathProvider.downloadsDirectory)
: (await getApplicationDocumentsDirectory());
2020-09-21 17:21:24 +00:00
final file = File(downloadsDir.path + '/' + name.split('/').last);
2020-05-07 09:19:57 +00:00
file.writeAsBytesSync(bytes);
2020-04-10 16:25:47 +00:00
await OpenFile.open(file.path);
}
2020-03-29 18:13:25 +00:00
return;
}
2020-09-04 10:56:25 +00:00
MatrixFile get detectFileType {
if (msgType == MessageTypes.Image) {
return MatrixImageFile(bytes: bytes, name: name);
}
if (msgType == MessageTypes.Video) {
return MatrixVideoFile(bytes: bytes, name: name);
}
if (msgType == MessageTypes.Audio) {
return MatrixAudioFile(bytes: bytes, name: name);
}
return this;
}
String get sizeString {
var size = this.size.toDouble();
if (size < 1000000) {
size = size / 1000;
size = (size * 10).round() / 10;
return '${size.toString()} KB';
} else if (size < 1000000000) {
size = size / 1000000;
size = (size * 10).round() / 10;
return '${size.toString()} MB';
} else {
size = size / 1000000000;
size = (size * 10).round() / 10;
return '${size.toString()} GB';
}
}
2020-03-29 18:13:25 +00:00
}