fluffychat/lib/utils/matrix_file_extension.dart

65 lines
2.0 KiB
Dart
Raw Normal View History

2020-03-29 20:13:25 +02:00
import 'dart:io';
import 'package:famedlysdk/famedlysdk.dart';
2020-04-10 18:25:47 +02:00
import 'package:flutter/foundation.dart';
2020-03-29 20:13:25 +02:00
import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';
2020-04-10 18:25:47 +02:00
import 'package:universal_html/prefer_universal/html.dart' as html;
import 'package:mime_type/mime_type.dart';
2020-03-29 20:13:25 +02:00
extension MatrixFileExtension on MatrixFile {
void open() async {
2020-04-10 18:25:47 +02:00
if (kIsWeb) {
2020-07-02 11:30:59 +02:00
final fileName = name.split('/').last;
2020-04-10 18:25:47 +02:00
final mimeType = mime(fileName);
var element = html.document.createElement('a');
element.setAttribute(
'href', html.Url.createObjectUrlFromBlob(html.Blob([bytes])));
2020-05-13 15:58:59 +02:00
element.setAttribute('target', '_blank');
element.setAttribute('rel', 'noopener');
2020-04-10 18:52:40 +02:00
element.setAttribute('download', fileName);
2020-04-10 18:25:47 +02:00
element.setAttribute('type', mimeType);
element.style.display = 'none';
html.document.body.append(element);
element.click();
element.remove();
} else {
2020-05-13 15:58:59 +02:00
var tempDir = await getTemporaryDirectory();
2020-07-02 11:30:59 +02:00
final file = File(tempDir.path + '/' + name.split('/').last);
2020-05-07 11:19:57 +02:00
file.writeAsBytesSync(bytes);
2020-04-10 18:25:47 +02:00
await OpenFile.open(file.path);
}
2020-03-29 20:13:25 +02:00
return;
}
2020-09-04 12:56:25 +02: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 20:13:25 +02:00
}