Browse Source

major refactor because of new endpoint supposed to bring runtime significantly (broke the opening of emails)

juan 2 months ago
parent
commit
9645db2fbe
1 changed files with 162 additions and 116 deletions
  1. 162 116
      lib/api_service.dart

+ 162 - 116
lib/api_service.dart

@@ -1,3 +1,5 @@
+import 'package:crab_ui/structs.dart';
+import 'package:english_words/english_words.dart';
 import 'package:flutter/material.dart';
 import 'package:http/http.dart' as http;
 import 'dart:convert';
@@ -26,57 +28,56 @@ class MailAddress {
   }
 }
 
-//data structure
-class SerializableMessage {
-  final String name;
-  final String from;
-  final List<MailAddress> to;
-  final List<MailAddress> cc;
-  final String hash;
+// //data structure
+// class SerializableMessage {
+//   final String name;
+//   final String from;
+//   final List<MailAddress> to;
+//   final List<MailAddress> cc;
+//   final String hash;
 
-  // final String path;
-  final String subject;
-  final String date;
-  final int uid;
-  final String list;
-  final String id;
-  final String in_reply_to;
+//   final String subject;
+//   final String date;
+//   final int uid;
+//   final String list;
+//   final String id;
+//   final String in_reply_to;
 
-  SerializableMessage({
-    required this.name,
-    required this.from,
-    required this.to,
-    required this.cc,
-    required this.hash,
-    required this.subject,
-    required this.date,
-    required this.uid,
-    required this.list,
-    required this.id,
-    required this.in_reply_to,
-  });
+//   SerializableMessage({
+//     required this.name,
+//     required this.from,
+//     required this.to,
+//     required this.cc,
+//     required this.hash,
+//     required this.subject,
+//     required this.date,
+//     required this.uid,
+//     required this.list,
+//     required this.id,
+//     required this.in_reply_to,
+//   });
 
-  factory SerializableMessage.fromJson(Map<String, dynamic> json) {
-    var toList = json['to'] as List;
-    var ccList = json['cc'] as List;
+//   factory SerializableMessage.fromJson(Map<String, dynamic> json) {
+//     var toList = json['to'] as List;
+//     var ccList = json['cc'] as List;
 
-    return SerializableMessage(
-      name: json['name'],
-      from: json['from'],
-      // to: json['name', 'address']
-      to: toList.map((i) => MailAddress.fromJson(i)).toList(),
-      cc: ccList.map((i) => MailAddress.fromJson(i)).toList(),
-      // path: json['path'],
-      hash: json['hash'],
-      subject: json['subject'],
-      date: json['date'],
-      uid: json['uid'],
-      list: json['list'],
-      id: json['id'],
-      in_reply_to: json['in_reply_to'],
-    );
-  }
-}
+//     return SerializableMessage(
+//       name: json['name'],
+//       from: json['from'],
+//       // to: json['name', 'address']
+//       to: toList.map((i) => MailAddress.fromJson(i)).toList(),
+//       cc: ccList.map((i) => MailAddress.fromJson(i)).toList(),
+//       // path: json['path'],
+//       hash: json['hash'],
+//       subject: json['subject'],
+//       date: json['date'],
+//       uid: json['uid'],
+//       list: json['list'],
+//       id: json['id'],
+//       in_reply_to: json['in_reply_to'],
+//     );
+//   }
+// }
 
 class EmailPage extends StatefulWidget {
   const EmailPage({super.key});
@@ -91,31 +92,23 @@ class _EmailPageState extends State<EmailPage> {
 
   void _displayEmailsFromFolder(String folder) async {
     // Map<String, List<SerializableMessage>> messagesMap = {};
-    List<SerializableMessage> allEmails = [];
+    List<GetThreadResponse> allEmails = []; //all the emails
 
     try {
       var url = Uri.http(
           '127.0.0.1:3001', 'sorted_threads_by_date', {'folder': folder});
       var response = await http.get(url);
-      print(response.body);
-      // Map<String, dynamic> json = jsonDecode(response.body); original
 
-      // json.forEach((key, value) {
-      //   List<SerializableMessage> messages = (value as List)
-      //       .map((item) => SerializableMessage.fromJson(item))
-      //       .toList();
-      //   messagesMap[key] = messages;
-      // });
-
-      // new shit
       if (response.statusCode == 200) {
-        List<dynamic> json = jsonDecode(response.body);
-        for (var item in json.take(1)) { //each item in the json is a date
+        List json = jsonDecode(response.body);
+        for (var item in json.take(1)) {
+          //each item in the json is a date
           if (item.length > 1 && item[0] is String && item[1] is List) {
             List<int> threadIDs = List<int>.from(item[1]);
             for (var threadId in threadIDs) {
-              print(threadId);
-              await fetchThreadMessages(threadId, allEmails);
+              // print(threadId);
+              // await fetchThreadMessages(threadId, allEmails);
+              await fetchThreads(threadId, allEmails);
             }
             //TODO: get exact thread with new api endpoint from chosen thread?
           }
@@ -127,30 +120,43 @@ class _EmailPageState extends State<EmailPage> {
       print('_displayEmailsFromFolder caught error: $e');
     }
     print("Done");
+
     setState(() {
-      emails.clear();
-      // emails = messagesMap.values.toList().expand((list) => list).toList();
-      emails.addAll(allEmails);
-      ;
+      emails = allEmails;
     });
+    print(emails[0]);
+    // Print allEmails to debug its structure
+    print("allEmails: ${allEmails[0].messages}");
+
+    // Convert allEmails to a list
   }
+// }
 
-  // Future<void> fetchThreads(AboutDialog){
-  // }
-
-  Future<void> fetchThreadMessages(
-      int threadId, List<SerializableMessage> allEmails) async {
+  Future<void> fetchThreads(
+      //complete
+      int threadId,
+      List<GetThreadResponse> allEmails) async {
     try {
-      var url = Uri.http(
-          '127.0.0.1:3001', 'get_thread_messages', {'id': threadId.toString()});
-
+      var url =
+          Uri.http('127.0.0.1:3001', 'get_thread', {'id': threadId.toString()});
       var response = await http.get(url);
-
+      // print(response.body);
       if (response.statusCode == 200) {
-        List<dynamic> messagesJson = jsonDecode(response.body);
-        List<SerializableMessage> messages =
-            messagesJson.map((mj) => SerializableMessage.fromJson(mj)).toList();
-        allEmails.addAll(messages);
+        Map<String, dynamic> messagesJson = jsonDecode(response.body);
+        // print(messagesJson);
+        // List<String> messagesofThread = messagesJson['messages'];
+        // messagesJson.map((mj) => GetThreadResponse.fromJson(mj)).toList();
+        // List<GetThreadResponse> messages = messagesJson.values.map((mj) {
+        //   return GetThreadResponse.fromJson(mj as Map<String, dynamic>);
+        // }).toList();
+        // List<GetThreadResponse> thread =
+        //     messagesJson.map((mj) => GetThreadResponse.fromJson(mj)).toList();
+        GetThreadResponse threadResponse =
+            GetThreadResponse.fromJson(messagesJson);
+
+        allEmails.add(
+            threadResponse); //adds all the messages of the thread into all emails
+        //perhaps should change
       } else {
         throw Exception(
             'Failed to fetch thread messages for thread ID: $threadId');
@@ -160,6 +166,28 @@ class _EmailPageState extends State<EmailPage> {
     }
   }
 
+  // Future<void> fetchThreadMessages(
+  //     int threadId, List<SerializableMessage> allEmails) async {
+  //   try {
+  //     var url = Uri.http(
+  //         '127.0.0.1:3001', 'get_thread_messages', {'id': threadId.toString()});
+
+  //     var response = await http.get(url);
+
+  //     if (response.statusCode == 200) {
+  //       List<dynamic> messagesJson = jsonDecode(response.body);
+  //       List<SerializableMessage> messages =
+  //           messagesJson.map((mj) => SerializableMessage.fromJson(mj)).toList();
+  //       allEmails.addAll(messages);
+  //     } else {
+  //       throw Exception(
+  //           'Failed to fetch thread messages for thread ID: $threadId');
+  //     }
+  //   } catch (e) {
+  //     print('Error fetching thread messages: $e');
+  //   }
+  // }
+
   Future<String> _getEmailContent(String id) async {
     String content = r"""
 
@@ -249,6 +277,8 @@ class _EmailPageState extends State<EmailPage> {
 }
 
 class EmailListScreen extends StatelessWidget {
+  //this is the bulding of the drawer with all emails
+  // try to only get the subject and id, date, sender to make it faster
   final List emails;
   final Future<String> Function(String) getEmailContent;
 
@@ -256,7 +286,7 @@ class EmailListScreen extends StatelessWidget {
     required this.emails,
     required this.getEmailContent,
   });
-
+  // instead of getting the entire email, just the from, text, subject, and id
   @override
   Widget build(BuildContext context) {
     return Scaffold(
@@ -267,7 +297,7 @@ class EmailListScreen extends StatelessWidget {
         itemCount: emails.length,
         itemBuilder: (context, index) {
           return ListTile(
-              title: Text(emails[index].from,
+              title: Text(emails[index].from_name,
                   style: TextStyle(fontWeight: FontWeight.bold)),
               subtitle: Column(
                 crossAxisAlignment: CrossAxisAlignment.start,
@@ -276,31 +306,42 @@ class EmailListScreen extends StatelessWidget {
                 ],
               ),
               trailing: Text(emails[index].date.toString()),
+              //here we assign each part of json to a var, this could be changed so it only happens,
+              // when clicking on email for modularity
               onTap: () async {
                 String emailContent = await getEmailContent(emails[index].id);
-                String from = emails[index].from.toString();
-                String name = emails[index].name.toString();
+                String messages = emails[index].messages.toString();
+                String fromName = emails[index].from_name.toString();
+                String fromAddress = emails[index].from_address.toString();
                 String to = emails[index].to.toString();
-                String cc = emails[index].cc.toString();
-                String hash = emails[index].hash.toString();
+                // String cc = emails[index].cc.toString();
+                // String hash = emails[index].hash.toString();
                 String subject = emails[index].subject.toString();
                 String date = emails[index].date.toString();
-                String uid = emails[index].uid.toString();
-                String list = emails[index].list.toString();
+                // String uid = emails[index].uid.toString();
+                // String list = emails[index].list.toString();
                 String id = emails[index].id.toString();
-                String in_reply_to = emails[index].in_reply_to.toString();
-                // String jsonbuilt =
+                // String in_reply_to = emails[index].in_reply_to.toString();
+
                 Navigator.push(
                   context,
                   MaterialPageRoute(
                       builder: (context) => EmailView(
                             emailContent: emailContent,
-                            // jsonEmail: jsonContent,
-                            from: from, name: name, to: to, cc: cc, hash: hash,
-                            subject: subject, date: date,
-                            uid: uid, list: list, id: id,
-                            in_reply_to: in_reply_to,
-                          )),
+                            from: fromAddress,
+                            name: fromName,
+                            to: to,
+                            // cc: cc,
+                            // hash: hash,
+                            subject: subject,
+                            date: date,
+                            // uid: uid,
+                            // list: list,
+                            id: id,
+                            // in_reply_to: in_reply_to,
+                          )
+                      //nada hpta
+                      ),
                 );
               });
         },
@@ -317,32 +358,37 @@ class EmailView extends StatefulWidget {
   // final String jsonEmail;
   final String from;
   final String name;
+
   final String to;
-  final String cc;
-  final String hash;
+
+  // final String to;
+  // final String cc;
+  // final String hash;
   final String subject;
   final String date;
-  final String uid;
-  final String list;
+  // final String uid;
+  // final String list;
   final String id;
-  final String in_reply_to;
+  // final String in_reply_to;
 
-  const EmailView(
-      {Key? key,
-      required this.emailContent,
-      //  required this.jsonEmail,
-      required this.from,
-      required this.name,
-      required this.to,
-      required this.cc,
-      required this.hash,
-      required this.subject,
-      required this.date,
-      required this.uid,
-      required this.list,
-      required this.id,
-      required this.in_reply_to})
-      : super(key: key);
+  const EmailView({
+    Key? key,
+    required this.emailContent,
+    //  required this.jsonEmail,
+    required this.from,
+    required this.name,
+    required this.to,
+
+    // required this.to,
+    // required this.cc,
+    // required this.hash,
+    required this.subject,
+    required this.date,
+    // required this.uid,
+    // required this.list,
+    required this.id,
+    // required this.in_reply_to
+  }) : super(key: key);
   @override
   _EmailViewState createState() => _EmailViewState();
 }