浏览代码

implement python calling

Noah Vogt 3 年之前
父节点
当前提交
80af7f773a

+ 1 - 1
.gitignore

@@ -16,4 +16,4 @@
 .cxx
 local.properties
 app/release/
-*__pycache__/*
+*__pycache__*

+ 5 - 1
app/build.gradle

@@ -21,7 +21,11 @@ android {
             abiFilters "armeabi-v7a", "arm64-v8a", "x86", "x86_64"
         }
         python {
-            buildPython "/usr/bin/python3"
+            pip {
+                //install "email"
+                //install "imaplib"
+            }
+            buildPython "/usr/bin/python3.8"
         }
     packagingOptions {
         exclude 'META-INF/NOTICE.md'

+ 10 - 4
app/src/main/java/com/noahvogt/miniprojekt/MainActivity.java

@@ -20,6 +20,7 @@ import androidx.navigation.ui.NavigationUI;
 import androidx.recyclerview.widget.LinearLayoutManager;
 import androidx.recyclerview.widget.RecyclerView;
 
+import com.chaquo.python.PyObject;
 import com.chaquo.python.Python;
 import com.chaquo.python.android.AndroidPlatform;
 import com.google.android.material.navigation.NavigationView;
@@ -144,16 +145,16 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
         /* may not be private */
         Button newemail_cancel_button = (Button) emailPopupView.findViewById(R.id.cancelButton);
 
-        if (! Python.isStarted()) {
-            Python.start(new AndroidPlatform(this));
-        }
-
 
         /* open View window */
             dialogBuilder.setView(emailPopupView);
         dialog = dialogBuilder.create();
         dialog.show();
 
+        if (! Python.isStarted()) {
+            Python.start(new AndroidPlatform(this));
+        }
+
         /* store user input */
         newemail_save_button.setOnClickListener(new View.OnClickListener() {
             @Override
@@ -167,6 +168,11 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
                     return;
                 }
 
+                Python python = Python.getInstance();
+                PyObject helloWorld = python.getModule("helloworldscript");
+                String stringFromPy = helloWorld.callAttr("hi").toString();
+                showToast(stringFromPy);
+
                 /* show all strings the user gave, this will later be stored to a secure database and checked for validation */
                 showToast(name);
                 showToast(email);

+ 2 - 0
app/src/main/python/helloworldscript.py

@@ -0,0 +1,2 @@
+def hi():
+    return "python says hi"

+ 110 - 0
app/src/main/python/mailFunctions.py

@@ -0,0 +1,110 @@
+import imaplib, email, os
+
+def errorMsgExit(error_msg):
+    print("Error: " + error_msg)
+
+def checkConnection(host, username, password, port):
+    try:
+        connection = imaplib.IMAP4_SSL(host, port)
+        connection.login(username, password)
+        connection.logout()
+        return True
+    except Exception as e:
+        print(str(e))
+        return False
+
+def connect(host, username, password, port):
+    connect = imaplib.IMAP4_SSL(host, port)
+    connect.login(username, password)
+    connect.enable("UTF8=ACCEPT")
+    return connect
+
+def listMailboxes(connection):
+    mailboxes = connection.list()
+    formatted_mailbox_list = []
+
+    for items in mailboxes:
+        if type(items) == list:
+            for raw_box_string in items:
+                box_string = str(raw_box_string)
+                # TODO: handle cases when folder contains subfolders
+                modified_box_string = (box_string[box_string.find('"/" ')+4:-1])
+
+                # strip unneeded "'s surrounding the folder name
+                if modified_box_string.startswith('"') and modified_box_string.endswith('"'):
+                    modified_box_string = modified_box_string[1:-1]
+
+                formatted_mailbox_list.append(modified_box_string)
+
+    connection.logout()
+    return formatted_mailbox_list
+
+def fetchMails(connection, inbox):
+    status, messages = connection.select(inbox)
+    print("status-------\n" + status)
+    print("messages-------\n" + str(messages))
+    # number of top emails to fetch
+    N = 3
+    # total number of emails
+    messages_int = int(messages[0])
+    print("message_int------\n" + str(messages_int))
+
+    typ, data = connection.search(None, 'ALL')
+    output_list = []
+    for num in data[0].split():
+        typ, data = connection.fetch(num, '(RFC822)')
+        msg = email.message_from_bytes(data[0][1])
+        #print(type(msg))
+        #print(msg)
+        raw_subject = email.header.decode_header(msg['Subject'])[0]
+        #raw_body = email.header.decode_header(msg['Body'])[0][0]
+        '''
+        if decode[1] == 'utf-8':
+            subject = decode[0].decode('utf-8')
+        else:
+            subject = decode[0]
+        '''
+        #print("subject: {}".format(subject))
+        #input()
+        #print('Message %s\n%s\n' % (num, data[0][1]))
+        #print('Message %s\n%s\n' % (num, data[0][1].split()))
+        #print('%s\n' % (len(data[0][1].split())))
+        '''
+        j = 0
+        for i in range(len(str(msg))):
+            if str(msg)[i] == "\n":
+                print(str(msg)[j:i])
+                j = int(i)
+        '''
+
+
+        output_list.append(str(raw_subject))
+
+    connection.close()
+    connection.logout()
+
+    return output_list
+
+def afetchMails(con):
+    con.select("Sent")
+    status, email_ids = con.search(None, "ALL")
+    if status != 'OK':
+        raise Exception("Error running imap search for spinvox messages: "
+                        "%s" % status)
+
+    print(email_ids[0])
+    fetch_ids = ','.join(str(email_ids[0]).split())
+    status, data = con.fetch(3, '(RFC822)')
+    if status != 'OK':
+        raise Exception("Error running imap fetch for spinvox message: "
+                        "%s" % status)
+    for i in range(3,4):
+        header_msg = email.message_from_string(data[i * 3 + 0][1])
+        subject = header_msg['Subject'],
+        print(subject)
+        date = header_msg['Date'],
+        print(date)
+        body = data[i * 3 + 1][1]
+        print(body)
+    connection.close()
+    connection.logout()

+ 1 - 1
build.gradle

@@ -6,7 +6,7 @@ buildscript {
         maven { url "https://chaquo.com/maven" }
     }
     dependencies {
-        classpath 'com.android.tools.build:gradle:4.0.2'
+        classpath 'com.android.tools.build:gradle:4.2.0'
         classpath "com.chaquo.python:gradle:9.1.0"
     }
 }

+ 2 - 2
gradle/wrapper/gradle-wrapper.properties

@@ -1,6 +1,6 @@
-#Wed Aug 25 19:12:25 CEST 2021
+#Tue Aug 31 15:54:45 CEST 2021
 distributionBase=GRADLE_USER_HOME
-distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-6.7.1-bin.zip
 distributionPath=wrapper/dists
 zipStorePath=wrapper/dists
 zipStoreBase=GRADLE_USER_HOME