api_service.dart 15 KB

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