api_service.dart 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. import 'package:flutter/material.dart';
  2. import 'package:http/http.dart' as http;
  3. import 'dart:convert';
  4. import 'dart:ui_web' as ui;
  5. import 'dart:html' as html;
  6. class MailAddress {
  7. final String? name;
  8. final String address;
  9. MailAddress({this.name, required this.address});
  10. factory MailAddress.fromJson(Map<String, dynamic> json) {
  11. return MailAddress(
  12. name: json['name'],
  13. address: json['address'],
  14. );
  15. }
  16. }
  17. class SerializableMessage {
  18. final String name;
  19. final String from;
  20. final List<MailAddress> to;
  21. final List<MailAddress> cc;
  22. final String hash;
  23. // final String path;
  24. final String subject;
  25. final String date;
  26. final int uid;
  27. final String list;
  28. final String id;
  29. final String in_reply_to;
  30. SerializableMessage({
  31. required this.name,
  32. required this.from,
  33. required this.to,
  34. required this.cc,
  35. required this.hash,
  36. required this.subject,
  37. required this.date,
  38. required this.uid,
  39. required this.list,
  40. required this.id,
  41. required this.in_reply_to,
  42. });
  43. factory SerializableMessage.fromJson(Map<String, dynamic> json) {
  44. var toList = json['to'] as List;
  45. var ccList = json['cc'] as List;
  46. return SerializableMessage(
  47. name: json['name'],
  48. from: json['from'],
  49. // to: json['name', 'address']
  50. to: toList.map((i) => MailAddress.fromJson(i)).toList(),
  51. cc: ccList.map((i) => MailAddress.fromJson(i)).toList(),
  52. // path: json['path'],
  53. hash: json['hash'],
  54. subject: json['subject'],
  55. date: json['date'],
  56. uid: json['uid'],
  57. list: json['list'],
  58. id: json['id'],
  59. in_reply_to: json['in_reply_to'],
  60. );
  61. }
  62. }
  63. class EmailPage extends StatefulWidget {
  64. const EmailPage({super.key});
  65. final String title = 'Emails';
  66. @override
  67. State<EmailPage> createState() => _EmailPageState();
  68. }
  69. class _EmailPageState extends State<EmailPage> {
  70. List emails = [];
  71. void _displayEmailsFromFolder(String folder) async {
  72. // Map<String, List<SerializableMessage>> messagesMap = {};
  73. List<SerializableMessage> allEmails = [];
  74. try {
  75. var url = Uri.http(
  76. '127.0.0.1:3001', 'sorted_threads_by_date', {'folder': folder});
  77. var response = await http.get(url);
  78. // print(response.body);
  79. // Map<String, dynamic> json = jsonDecode(response.body); original
  80. // json.forEach((key, value) {
  81. // List<SerializableMessage> messages = (value as List)
  82. // .map((item) => SerializableMessage.fromJson(item))
  83. // .toList();
  84. // messagesMap[key] = messages;
  85. // });
  86. // new shit
  87. if (response.statusCode == 200) {
  88. List<dynamic> json = jsonDecode(response.body);
  89. for (var item in json) {
  90. if (item.length > 1 && item[0] is String && item[1] is List) {
  91. // print('Date: ${item[0]}, Threads: ${item[1]}');
  92. List<int> threadIDs = List<int>.from(item[1]);
  93. for (var threadId in threadIDs) {
  94. await fetchThreadMessages(threadId, allEmails);
  95. }
  96. }
  97. }
  98. } else {
  99. throw Exception('Failed to load threads');
  100. }
  101. } catch (e) {
  102. print('_displayEmailsFromFolder caught error: $e');
  103. }
  104. setState(() {
  105. emails.clear();
  106. // emails = messagesMap.values.toList().expand((list) => list).toList();
  107. emails.addAll(allEmails);
  108. // print(emails);
  109. ;
  110. });
  111. }
  112. Future<void> fetchThreadMessages(
  113. int threadId, List<SerializableMessage> allEmails) async {
  114. try {
  115. var url = Uri.http(
  116. '127.0.0.1:3001', 'get_thread_messages', {'id': threadId.toString()});
  117. // print(url);
  118. var response = await http.get(url);
  119. // print(response.body);
  120. if (response.statusCode == 200) {
  121. List<dynamic> messagesJson = jsonDecode(response.body);
  122. List<SerializableMessage> messages =
  123. messagesJson.map((mj) => SerializableMessage.fromJson(mj)).toList();
  124. allEmails.addAll(messages);
  125. } else {
  126. throw Exception(
  127. 'Failed to fetch thread messages for thread ID: $threadId');
  128. }
  129. } catch (e) {
  130. print('Error fetching thread messages: $e');
  131. }
  132. }
  133. Future<String> _getEmailContent(String id) async {
  134. String content = r"""
  135. """;
  136. // String restcontent = "";
  137. try {
  138. var url = Uri.http('127.0.0.1:3001', 'email', {'id': id});
  139. // print(url);
  140. var response = await http.get(url);
  141. // print(response.body);
  142. if (response.statusCode == 200) {
  143. print('ok');
  144. content = response.body;
  145. // try {
  146. // var restUrl =
  147. // Uri.http('127.0.0.1:3001', 'get_thread_messages', {'id': id});
  148. // // print(restUrl);
  149. // var restresponse = await http.get(restUrl);
  150. // // print(restresponse.statusCode);
  151. // if (restresponse.statusCode == 200) {
  152. // print("ok squared");
  153. // // restcontent = restresponse.body;
  154. // }
  155. // } catch (i) {
  156. // print('jsoncontent caught error: $i');
  157. // }
  158. }
  159. } catch (e) {
  160. print('_getEmailContent caught error: $e');
  161. }
  162. // print(content);
  163. // print(restcontent);
  164. return content;
  165. }
  166. Future<String> _getThreadMessagesJson(String threadId) async {
  167. String jsonResponse = "";
  168. try {
  169. var url =
  170. Uri.http('127.0.0.1:3001', 'get_thread_messages', {'id': threadId});
  171. // print(url);
  172. var response = await http.get(url);
  173. // print(response.statusCode);
  174. // print(response.body);
  175. if (response.statusCode == 200) {
  176. jsonResponse = response.body; // Here you get the JSON response
  177. } else {
  178. throw Exception('Failed to load thread messages');
  179. }
  180. } catch (e) {
  181. print('_getThreadMessagesJson caught error: $e');
  182. }
  183. return jsonResponse; // Returns the JSON string
  184. }
  185. Future<List<Widget>> _getDrawerItems() async {
  186. List<String> drawerItems = [];
  187. try {
  188. var url = Uri.http('127.0.0.1:3001', 'folders');
  189. var response = await http.get(url);
  190. drawerItems = List<String>.from(json.decode(response.body));
  191. } catch (e) {
  192. print('_getDrawerItems caught error: $e');
  193. }
  194. List<Widget> drawerWidgets = [];
  195. for (String item in drawerItems) {
  196. drawerWidgets.add(
  197. ListTile(
  198. leading: Icon(Icons.mail),
  199. title: Text(item),
  200. onTap: () {
  201. _displayEmailsFromFolder(item);
  202. Navigator.pop(context);
  203. },
  204. ),
  205. );
  206. }
  207. return drawerWidgets;
  208. }
  209. @override
  210. Widget build(BuildContext context) {
  211. return Scaffold(
  212. appBar: AppBar(
  213. backgroundColor: Theme.of(context).colorScheme.inversePrimary,
  214. title: Text(widget.title),
  215. ),
  216. drawer: Drawer(
  217. child: FutureBuilder<List<Widget>>(
  218. future:
  219. _getDrawerItems(), // call the async function to get the future
  220. builder:
  221. (BuildContext context, AsyncSnapshot<List<Widget>> snapshot) {
  222. if (snapshot.connectionState == ConnectionState.waiting) {
  223. // While data is loading, show a progress indicator
  224. return Center(child: CircularProgressIndicator());
  225. } else if (snapshot.hasError) {
  226. // If something went wrong, show an error message
  227. return Center(child: Text('Error: ${snapshot.error}'));
  228. } else {
  229. // When data is fetched successfully, display the items
  230. return ListView(
  231. padding: EdgeInsets.zero,
  232. children:
  233. snapshot.data!, // Unwrap the data once confirmed it's there
  234. );
  235. }
  236. },
  237. ),
  238. ),
  239. body: EmailListScreen(
  240. emails: emails,
  241. getEmailContent: _getEmailContent,
  242. getJsonEmail: _getThreadMessagesJson),
  243. );
  244. }
  245. }
  246. class EmailListScreen extends StatelessWidget {
  247. final List emails;
  248. final Future<String> Function(String) getEmailContent;
  249. final Future<String> Function(String) getJsonEmail;
  250. EmailListScreen(
  251. {required this.emails,
  252. required this.getEmailContent,
  253. required this.getJsonEmail});
  254. @override
  255. Widget build(BuildContext context) {
  256. // print(emails);
  257. return Scaffold(
  258. appBar: AppBar(
  259. title: Text('Emails'),
  260. ),
  261. body: ListView.separated(
  262. itemCount: emails.length,
  263. itemBuilder: (context, index) {
  264. return ListTile(
  265. title: Text(emails[index].from,
  266. style: TextStyle(fontWeight: FontWeight.bold)),
  267. subtitle: Column(
  268. crossAxisAlignment: CrossAxisAlignment.start,
  269. children: [
  270. Text(emails[index].subject),
  271. ],
  272. ),
  273. trailing: Text(emails[index].date.toString()),
  274. onTap: () async {
  275. String emailContent = await getEmailContent(emails[index].id);
  276. String jsonContent =
  277. await getJsonEmail(emails[index].uid.toString());
  278. // print(emails[index]);
  279. String from = emails[index].from;
  280. String name = emails[index].name;
  281. String to = emails[index].to;
  282. String cc = emails[index].cc;
  283. String hash = emails[index].hash;
  284. String subject = emails[index].subject;
  285. String date = emails[index].date;
  286. String uid = emails[index].uid;
  287. String list = emails[index].list;
  288. String id = emails[index].id;
  289. String in_reply_to = emails[index].in_reply_to;
  290. // String jsonbuilt =
  291. Navigator.push(
  292. context,
  293. MaterialPageRoute(
  294. builder: (context) => EmailView(
  295. emailContent: emailContent,
  296. jsonEmail: jsonContent,
  297. )),
  298. );
  299. });
  300. },
  301. separatorBuilder: (context, index) {
  302. return Divider();
  303. },
  304. ),
  305. );
  306. }
  307. }
  308. class EmailView extends StatefulWidget {
  309. final String emailContent;
  310. final String jsonEmail;
  311. const EmailView(
  312. {Key? key, required this.emailContent, required this.jsonEmail})
  313. : super(key: key);
  314. @override
  315. _EmailViewState createState() => _EmailViewState();
  316. }
  317. class _EmailViewState extends State<EmailView> {
  318. @override
  319. void initState() {
  320. super.initState();
  321. ui.platformViewRegistry.registerViewFactory(
  322. 'html-view33',
  323. (int viewId) => html.IFrameElement()
  324. ..width = '100%'
  325. ..height = '100%'
  326. ..srcdoc = widget.emailContent
  327. ..style.border = 'none',
  328. );
  329. }
  330. @override
  331. Widget build(BuildContext context) {
  332. return Scaffold(
  333. appBar: AppBar(
  334. title: Text(widget.name),
  335. ),
  336. body: Container(
  337. child: HtmlElementView(
  338. viewType: 'html-view33',
  339. ),
  340. ),
  341. );
  342. }
  343. }