email_util.dart 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. import 'dart:io';
  2. import 'package:archive/archive_io.dart';
  3. import 'package:email_validator/email_validator.dart';
  4. import 'package:ente_auth/core/configuration.dart';
  5. import 'package:ente_auth/core/logging/super_logging.dart';
  6. import 'package:ente_auth/ente_theme_data.dart';
  7. import 'package:ente_auth/l10n/l10n.dart';
  8. import 'package:ente_auth/ui/components/buttons/button_widget.dart';
  9. import 'package:ente_auth/ui/components/dialog_widget.dart';
  10. import 'package:ente_auth/ui/components/models/button_type.dart';
  11. import 'package:ente_auth/ui/tools/debug/log_file_viewer.dart';
  12. // import 'package:ente_auth/ui/tools/debug/log_file_viewer.dart';
  13. import 'package:ente_auth/utils/dialog_util.dart';
  14. import 'package:ente_auth/utils/toast_util.dart';
  15. import 'package:file_saver/file_saver.dart';
  16. import 'package:flutter/material.dart';
  17. import 'package:flutter/services.dart';
  18. import 'package:flutter_email_sender/flutter_email_sender.dart';
  19. import 'package:intl/intl.dart';
  20. import 'package:logging/logging.dart';
  21. // import 'package:open_mail_app/open_mail_app.dart';
  22. import 'package:package_info_plus/package_info_plus.dart';
  23. import 'package:path_provider/path_provider.dart';
  24. import 'package:share_plus/share_plus.dart';
  25. import 'package:url_launcher/url_launcher.dart';
  26. final Logger _logger = Logger('email_util');
  27. bool isValidEmail(String email) {
  28. return EmailValidator.validate(email);
  29. }
  30. Future<void> sendLogs(
  31. BuildContext context,
  32. String title,
  33. String toEmail, {
  34. Function? postShare,
  35. String? subject,
  36. String? body,
  37. }) async {
  38. final l10n = context.l10n;
  39. final List<Widget> actions = [
  40. TextButton(
  41. child: Row(
  42. mainAxisAlignment: MainAxisAlignment.start,
  43. children: [
  44. Icon(
  45. Icons.feed_outlined,
  46. color: Theme.of(context).iconTheme.color?.withOpacity(0.85),
  47. ),
  48. const Padding(padding: EdgeInsets.all(4)),
  49. Text(
  50. l10n.viewLogsAction,
  51. style: TextStyle(
  52. color: Theme.of(context)
  53. .colorScheme
  54. .defaultTextColor
  55. .withOpacity(0.85),
  56. ),
  57. ),
  58. ],
  59. ),
  60. onPressed: () async {
  61. showDialog(
  62. context: context,
  63. builder: (BuildContext context) {
  64. return LogFileViewer(SuperLogging.logFile!);
  65. },
  66. barrierColor: Colors.black87,
  67. barrierDismissible: false,
  68. );
  69. },
  70. ),
  71. TextButton(
  72. child: Text(
  73. title,
  74. style: TextStyle(
  75. color: Theme.of(context).colorScheme.alternativeColor,
  76. ),
  77. ),
  78. onPressed: () async {
  79. Navigator.of(context, rootNavigator: true).pop('dialog');
  80. await _sendLogs(context, toEmail, subject, body);
  81. if (postShare != null) {
  82. postShare();
  83. }
  84. },
  85. ),
  86. ];
  87. final List<Widget> content = [];
  88. content.addAll(
  89. [
  90. Text(
  91. l10n.sendLogsDescription,
  92. style: const TextStyle(
  93. height: 1.5,
  94. fontSize: 16,
  95. ),
  96. ),
  97. const Padding(padding: EdgeInsets.all(12)),
  98. Row(
  99. mainAxisAlignment: MainAxisAlignment.spaceBetween,
  100. children: actions,
  101. ),
  102. ],
  103. );
  104. final confirmation = AlertDialog(
  105. title: Text(
  106. title,
  107. style: const TextStyle(
  108. fontSize: 18,
  109. ),
  110. ),
  111. content: SingleChildScrollView(
  112. child: ListBody(
  113. children: content,
  114. ),
  115. ),
  116. );
  117. showDialog(
  118. context: context,
  119. builder: (_) {
  120. return confirmation;
  121. },
  122. );
  123. }
  124. Future<void> _sendLogs(
  125. BuildContext context,
  126. String toEmail,
  127. String? subject,
  128. String? body,
  129. ) async {
  130. final String zipFilePath = await getZippedLogsFile(context);
  131. final Email email = Email(
  132. recipients: [toEmail],
  133. subject: subject ?? '',
  134. body: body ?? '',
  135. attachmentPaths: [zipFilePath],
  136. isHTML: false,
  137. );
  138. try {
  139. await FlutterEmailSender.send(email);
  140. } catch (e, s) {
  141. _logger.severe('email sender failed', e, s);
  142. await shareLogs(context, toEmail, zipFilePath);
  143. }
  144. }
  145. Future<String> getZippedLogsFile(BuildContext context) async {
  146. final l10n = context.l10n;
  147. final dialog = createProgressDialog(context, l10n.preparingLogsTitle);
  148. await dialog.show();
  149. final logsPath = (await getApplicationSupportDirectory()).path;
  150. final logsDirectory = Directory(logsPath + "/logs");
  151. final tempPath = (await getTemporaryDirectory()).path;
  152. final zipFilePath =
  153. tempPath + "/logs-${Configuration.instance.getUserID() ?? 0}.zip";
  154. final encoder = ZipFileEncoder();
  155. encoder.create(zipFilePath);
  156. encoder.addDirectory(logsDirectory);
  157. encoder.close();
  158. await dialog.hide();
  159. return zipFilePath;
  160. }
  161. Future<void> shareLogs(
  162. BuildContext context,
  163. String toEmail,
  164. String zipFilePath,
  165. ) async {
  166. final result = await showDialogWidget(
  167. context: context,
  168. title: context.l10n.emailYourLogs,
  169. body: context.l10n.pleaseSendTheLogsTo(toEmail),
  170. buttons: [
  171. ButtonWidget(
  172. buttonType: ButtonType.neutral,
  173. labelText: context.l10n.copyEmailAddress,
  174. isInAlert: true,
  175. buttonAction: ButtonAction.first,
  176. onTap: () async {
  177. await Clipboard.setData(ClipboardData(text: toEmail));
  178. },
  179. shouldShowSuccessConfirmation: true,
  180. ),
  181. ButtonWidget(
  182. buttonType: ButtonType.neutral,
  183. labelText: context.l10n.exportLogs,
  184. isInAlert: true,
  185. buttonAction: ButtonAction.second,
  186. ),
  187. ButtonWidget(
  188. buttonType: ButtonType.secondary,
  189. labelText: context.l10n.cancel,
  190. isInAlert: true,
  191. buttonAction: ButtonAction.cancel,
  192. ),
  193. ],
  194. );
  195. if (result?.action != null && result!.action == ButtonAction.second) {
  196. final Size size = MediaQuery.of(context).size;
  197. if (Platform.isAndroid) {
  198. DateTime now = DateTime.now().toUtc();
  199. String shortMonthName = DateFormat('MMM').format(now); // Short month name
  200. String logFileName =
  201. 'ente-logs-${now.year}-$shortMonthName-${now.day}-${now.hour}-${now.minute}';
  202. await FileSaver.instance.saveAs(
  203. name: logFileName,
  204. filePath: zipFilePath,
  205. mimeType: MimeType.zip,
  206. ext: 'zip',
  207. );
  208. } else {
  209. await Share.shareXFiles(
  210. [XFile(zipFilePath, mimeType: 'application/zip')],
  211. sharePositionOrigin: Rect.fromLTWH(0, 0, size.width, size.height / 2),
  212. );
  213. }
  214. }
  215. }
  216. Future<void> sendEmail(
  217. BuildContext context, {
  218. required String to,
  219. String? subject,
  220. String? body,
  221. }) async {
  222. try {
  223. final String clientDebugInfo = await _clientInfo();
  224. final String _subject = subject ?? '[Support]';
  225. final String _body = (body ?? '') + clientDebugInfo;
  226. // final EmailContent email = EmailContent(
  227. // to: [
  228. // to,
  229. // ],
  230. // subject: subject ?? '[Support]',
  231. // body: (body ?? '') + clientDebugInfo,
  232. // );
  233. if (Platform.isAndroid) {
  234. // Special handling due to issue in proton mail android client
  235. // https://github.com/ente-io/frame/pull/253
  236. final Uri params = Uri(
  237. scheme: 'mailto',
  238. path: to,
  239. query: 'subject=$_subject&body=$_body',
  240. );
  241. if (await canLaunchUrl(params)) {
  242. await launchUrl(params);
  243. } else {
  244. // this will trigger _showNoMailAppsDialog
  245. throw Exception('Could not launch ${params.toString()}');
  246. }
  247. } else {
  248. _showNoMailAppsDialog(context, to);
  249. }
  250. } catch (e) {
  251. _logger.severe("Failed to send email to $to", e);
  252. _showNoMailAppsDialog(context, to);
  253. }
  254. }
  255. Future<String> _clientInfo() async {
  256. final packageInfo = await PackageInfo.fromPlatform();
  257. final String debugInfo =
  258. '\n\n\n\n ------------------- \nFollowing information can '
  259. 'help us in debugging if you are facing any issue '
  260. '\nRegistered email: ${Configuration.instance.getEmail()}'
  261. '\nClient: ${packageInfo.packageName}'
  262. '\nVersion : ${packageInfo.version}';
  263. return debugInfo;
  264. }
  265. void _showNoMailAppsDialog(BuildContext context, String toEmail) {
  266. final l10n = context.l10n;
  267. showDialog(
  268. context: context,
  269. builder: (context) {
  270. return AlertDialog(
  271. title: Text(l10n.emailUsMessage(toEmail)),
  272. actions: <Widget>[
  273. TextButton(
  274. child: Text(l10n.copyEmailAction),
  275. onPressed: () async {
  276. await Clipboard.setData(ClipboardData(text: toEmail));
  277. showShortToast(context, l10n.copied);
  278. },
  279. ),
  280. TextButton(
  281. child: Text(l10n.ok),
  282. onPressed: () {
  283. Navigator.pop(context);
  284. },
  285. ),
  286. ],
  287. );
  288. },
  289. );
  290. }