api_service.dart 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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. import 'augment.dart';
  7. import 'dart:js' as js;
  8. // import 'dart:js_util';
  9. class MailAddress {
  10. final String? name;
  11. final String address;
  12. MailAddress({this.name, required this.address});
  13. factory MailAddress.fromJson(Map<String, dynamic> json) {
  14. return MailAddress(
  15. name: json['name'],
  16. address: json['address'],
  17. );
  18. }
  19. @override
  20. String toString() {
  21. // TODO: implement toString
  22. return '${name} <${address}>';
  23. }
  24. }
  25. class SerializableMessage {
  26. final String name;
  27. final String from;
  28. final List<MailAddress> to;
  29. final List<MailAddress> cc;
  30. final String hash;
  31. // final String path;
  32. final String subject;
  33. final String date;
  34. final int uid;
  35. final String list;
  36. final String id;
  37. final String in_reply_to;
  38. SerializableMessage({
  39. required this.name,
  40. required this.from,
  41. required this.to,
  42. required this.cc,
  43. required this.hash,
  44. required this.subject,
  45. required this.date,
  46. required this.uid,
  47. required this.list,
  48. required this.id,
  49. required this.in_reply_to,
  50. });
  51. factory SerializableMessage.fromJson(Map<String, dynamic> json) {
  52. var toList = json['to'] as List;
  53. var ccList = json['cc'] as List;
  54. return SerializableMessage(
  55. name: json['name'],
  56. from: json['from'],
  57. // to: json['name', 'address']
  58. to: toList.map((i) => MailAddress.fromJson(i)).toList(),
  59. cc: ccList.map((i) => MailAddress.fromJson(i)).toList(),
  60. // path: json['path'],
  61. hash: json['hash'],
  62. subject: json['subject'],
  63. date: json['date'],
  64. uid: json['uid'],
  65. list: json['list'],
  66. id: json['id'],
  67. in_reply_to: json['in_reply_to'],
  68. );
  69. }
  70. }
  71. class EmailPage extends StatefulWidget {
  72. const EmailPage({super.key});
  73. final String title = 'Emails';
  74. @override
  75. State<EmailPage> createState() => _EmailPageState();
  76. }
  77. class _EmailPageState extends State<EmailPage> {
  78. List emails = [];
  79. void _displayEmailsFromFolder(String folder) async {
  80. // Map<String, List<SerializableMessage>> messagesMap = {};
  81. List<SerializableMessage> allEmails = [];
  82. try {
  83. var url = Uri.http(
  84. '127.0.0.1:3001', 'sorted_threads_by_date', {'folder': folder});
  85. var response = await http.get(url);
  86. // print(response.body);
  87. // Map<String, dynamic> json = jsonDecode(response.body); original
  88. // json.forEach((key, value) {
  89. // List<SerializableMessage> messages = (value as List)
  90. // .map((item) => SerializableMessage.fromJson(item))
  91. // .toList();
  92. // messagesMap[key] = messages;
  93. // });
  94. // new shit
  95. if (response.statusCode == 200) {
  96. List<dynamic> json = jsonDecode(response.body);
  97. for (var item in json) {
  98. if (item.length > 1 && item[0] is String && item[1] is List) {
  99. List<int> threadIDs = List<int>.from(item[1]);
  100. for (var threadId in threadIDs) {
  101. await fetchThreadMessages(threadId, allEmails);
  102. }
  103. }
  104. }
  105. } else {
  106. throw Exception('Failed to load threads');
  107. }
  108. } catch (e) {
  109. print('_displayEmailsFromFolder caught error: $e');
  110. }
  111. setState(() {
  112. emails.clear();
  113. // emails = messagesMap.values.toList().expand((list) => list).toList();
  114. emails.addAll(allEmails);
  115. ;
  116. });
  117. }
  118. Future<void> fetchThreadMessages(
  119. int threadId, List<SerializableMessage> allEmails) async {
  120. try {
  121. var url = Uri.http(
  122. '127.0.0.1:3001', 'get_thread_messages', {'id': threadId.toString()});
  123. var response = await http.get(url);
  124. if (response.statusCode == 200) {
  125. List<dynamic> messagesJson = jsonDecode(response.body);
  126. List<SerializableMessage> messages =
  127. messagesJson.map((mj) => SerializableMessage.fromJson(mj)).toList();
  128. allEmails.addAll(messages);
  129. } else {
  130. throw Exception(
  131. 'Failed to fetch thread messages for thread ID: $threadId');
  132. }
  133. } catch (e) {
  134. print('Error fetching thread messages: $e');
  135. }
  136. }
  137. Future<String> _getEmailContent(String id) async {
  138. String content = r"""
  139. """;
  140. try {
  141. var url = Uri.http('127.0.0.1:3001', 'email', {'id': id});
  142. var response = await http.get(url);
  143. if (response.statusCode == 200) {
  144. content = response.body;
  145. }
  146. } catch (e) {
  147. print('_getEmailContent caught error: $e');
  148. }
  149. return content;
  150. }
  151. Future<List<Widget>> _getDrawerItems() async {
  152. List<String> drawerItems = [];
  153. try {
  154. var url = Uri.http('127.0.0.1:3001', 'folders');
  155. var response = await http.get(url);
  156. drawerItems = List<String>.from(json.decode(response.body));
  157. } catch (e) {
  158. print('_getDrawerItems caught error: $e');
  159. }
  160. List<Widget> drawerWidgets = [];
  161. for (String item in drawerItems) {
  162. drawerWidgets.add(
  163. ListTile(
  164. leading: Icon(Icons.mail),
  165. title: Text(item),
  166. onTap: () {
  167. _displayEmailsFromFolder(item);
  168. Navigator.pop(context);
  169. },
  170. ),
  171. );
  172. }
  173. return drawerWidgets;
  174. }
  175. @override
  176. Widget build(BuildContext context) {
  177. return Scaffold(
  178. appBar: AppBar(
  179. backgroundColor: Theme.of(context).colorScheme.inversePrimary,
  180. title: Text(widget.title),
  181. ),
  182. drawer: Drawer(
  183. child: FutureBuilder<List<Widget>>(
  184. future:
  185. _getDrawerItems(), // call the async function to get the future
  186. builder:
  187. (BuildContext context, AsyncSnapshot<List<Widget>> snapshot) {
  188. if (snapshot.connectionState == ConnectionState.waiting) {
  189. // While data is loading, show a progress indicator
  190. return Center(child: CircularProgressIndicator());
  191. } else if (snapshot.hasError) {
  192. // If something went wrong, show an error message
  193. return Center(child: Text('Error: ${snapshot.error}'));
  194. } else {
  195. // When data is fetched successfully, display the items
  196. return ListView(
  197. padding: EdgeInsets.zero,
  198. children:
  199. snapshot.data!, // Unwrap the data once confirmed it's there
  200. );
  201. }
  202. },
  203. ),
  204. ),
  205. body: EmailListScreen(
  206. emails: emails,
  207. getEmailContent: _getEmailContent,
  208. // getJsonEmail: _getThreadMessagesJson
  209. ),
  210. );
  211. }
  212. }
  213. class EmailListScreen extends StatelessWidget {
  214. final List emails;
  215. final Future<String> Function(String) getEmailContent;
  216. EmailListScreen({
  217. required this.emails,
  218. required this.getEmailContent,
  219. });
  220. @override
  221. Widget build(BuildContext context) {
  222. return Scaffold(
  223. appBar: AppBar(
  224. title: Text('Emails'),
  225. ),
  226. body: ListView.separated(
  227. itemCount: emails.length,
  228. itemBuilder: (context, index) {
  229. return ListTile(
  230. title: Text(emails[index].from,
  231. style: TextStyle(fontWeight: FontWeight.bold)),
  232. subtitle: Column(
  233. crossAxisAlignment: CrossAxisAlignment.start,
  234. children: [
  235. Text(emails[index].subject),
  236. ],
  237. ),
  238. trailing: Text(emails[index].date.toString()),
  239. onTap: () async {
  240. String emailContent = await getEmailContent(emails[index].id);
  241. String from = emails[index].from.toString();
  242. String name = emails[index].name.toString();
  243. String to = emails[index].to.toString();
  244. String cc = emails[index].cc.toString();
  245. String hash = emails[index].hash.toString();
  246. String subject = emails[index].subject.toString();
  247. String date = emails[index].date.toString();
  248. String uid = emails[index].uid.toString();
  249. String list = emails[index].list.toString();
  250. String id = emails[index].id.toString();
  251. String in_reply_to = emails[index].in_reply_to.toString();
  252. // String jsonbuilt =
  253. Navigator.push(
  254. context,
  255. MaterialPageRoute(
  256. builder: (context) => EmailView(
  257. emailContent: emailContent,
  258. // jsonEmail: jsonContent,
  259. from: from, name: name, to: to, cc: cc, hash: hash,
  260. subject: subject, date: date,
  261. uid: uid, list: list, id: id,
  262. in_reply_to: in_reply_to,
  263. )),
  264. );
  265. });
  266. },
  267. separatorBuilder: (context, index) {
  268. return Divider();
  269. },
  270. ),
  271. );
  272. }
  273. }
  274. class EmailView extends StatefulWidget {
  275. final String emailContent;
  276. // final String jsonEmail;
  277. final String from;
  278. final String name;
  279. final String to;
  280. final String cc;
  281. final String hash;
  282. final String subject;
  283. final String date;
  284. final String uid;
  285. final String list;
  286. final String id;
  287. final String in_reply_to;
  288. const EmailView(
  289. {Key? key,
  290. required this.emailContent,
  291. // required this.jsonEmail,
  292. required this.from,
  293. required this.name,
  294. required this.to,
  295. required this.cc,
  296. required this.hash,
  297. required this.subject,
  298. required this.date,
  299. required this.uid,
  300. required this.list,
  301. required this.id,
  302. required this.in_reply_to})
  303. : super(key: key);
  304. @override
  305. _EmailViewState createState() => _EmailViewState();
  306. }
  307. class _EmailViewState extends State<EmailView> {
  308. late Key iframeKey;
  309. late String currentContent;
  310. late String viewTypeId;
  311. TextEditingController _jumpController = TextEditingController();
  312. @override
  313. void initState() {
  314. super.initState();
  315. String currentContent = widget.emailContent;
  316. viewTypeId = "iframe-${DateTime.now().millisecondsSinceEpoch}";
  317. _registerViewFactory(currentContent);
  318. }
  319. void _registerViewFactory(String currentContent) {
  320. setState(() {
  321. viewTypeId = 'iframe-${DateTime.now().millisecondsSinceEpoch}';
  322. ui.platformViewRegistry.registerViewFactory(
  323. viewTypeId,
  324. (int viewId) => html.IFrameElement()
  325. ..width = '100%'
  326. ..height = '100%'
  327. ..srcdoc = currentContent
  328. ..style.border = 'none');
  329. });
  330. }
  331. void _scrollToNumber(String spanId) {
  332. AugmentClasses.handleJump(viewTypeId);
  333. }
  334. // void _invisibility(String )
  335. @override
  336. Widget build(BuildContext context) {
  337. // print(currentContent);
  338. return Scaffold(
  339. appBar: AppBar(
  340. title: Text(widget.name),
  341. ),
  342. body: Column(
  343. children: [
  344. EmailToolbar(
  345. onJumpToSpan: _scrollToNumber,
  346. onButtonPressed: () => {},
  347. // AugmentClasses.handleJump(viewTypeId, '1');
  348. // print("button got pressed?");
  349. // _registerViewFactory(r"""
  350. // <h1>Welcome to My Website</h1>
  351. // <p>This is a simple HTML page.</p>
  352. // <h2>What is HTML?</h2>
  353. // <p>HTML (HyperText Markup Language) is the most basic building block of the Web. It defines the meaning and structure of web content. Other technologies besides HTML are generally used to describe a web page's appearance/presentation (CSS) or functionality/behavior (JavaScript).</p>
  354. // <h3>Here's a simple list:</h3>
  355. // <ul>
  356. // <li>HTML elements are the building blocks of HTML pages</li>
  357. // <li>HTML uses tags like <code>&lt;tag&gt;</code> to organize and format content</li>
  358. // <li>CSS is used with HTML to style pages</li>
  359. // </ul>
  360. // <p>Copyright © 2023</p>
  361. // """);
  362. // print("change");
  363. // widget.emailContent = r"
  364. // "
  365. // },
  366. ),
  367. Row(
  368. // title of email
  369. children: [
  370. Text(
  371. widget.subject,
  372. style: TextStyle(fontSize: 30),
  373. ),
  374. ],
  375. ),
  376. Row(
  377. children: [
  378. Text(
  379. 'from ${widget.name}',
  380. style: TextStyle(fontSize: 18),
  381. ),
  382. Text(
  383. '<${widget.from}>',
  384. style: TextStyle(fontSize: 18),
  385. ),
  386. Spacer(),
  387. Text(
  388. '${widget.date}',
  389. textAlign: TextAlign.right,
  390. )
  391. ],
  392. ),
  393. // TODO: make a case where if one of these is the user's email it just says me :)))))
  394. Row(
  395. children: [
  396. Text(
  397. 'to ${widget.to.toString()}',
  398. style: TextStyle(fontSize: 15),
  399. )
  400. ],
  401. ),
  402. Expanded(
  403. child: HtmlElementView(
  404. key: UniqueKey(),
  405. viewType: viewTypeId,
  406. ),
  407. ),
  408. ],
  409. ));
  410. }
  411. }