Browse Source

Change the code to Python3

Shendan JIN 8 years ago
parent
commit
72479a8e4e
5 changed files with 108 additions and 92 deletions
  1. 16 0
      analyse_event.py
  2. 22 20
      event.py
  3. 4 2
      gcal.py
  4. 3 4
      gmail.py
  5. 63 66
      gmail_msg.py

+ 16 - 0
analyse_event.py

@@ -0,0 +1,16 @@
+from gmail import *
+from gcal import *
+
+def main():
+
+    mc = input('Please enter m(for gmail) or c (for google calendar) to start the events finder: ').lower()
+    if (mc == 'm'):
+        list_event = get_list_event_gmail()
+    else:
+        list_event = get_list_event_gcal()
+  
+    for event in list_event:
+        event.affiche()
+    
+if __name__ == '__main__':
+    main()

+ 22 - 20
event.py

@@ -1,25 +1,27 @@
-import heapq
+from gmail import *
 
-class Event():
-    def __init__(self, date, location, description):
-        self.date = date
-        self.location = location
-        self.description = description
-
-
-class HeapEvent():
-    """Heap for event : sort event according to their dates"""
+class event:
     def __init__(self):
-        self.data = []
+        pass
 
-    def push(self, event):
-        heapq.heappush(self.data, (event.date, event))
-
-    def pop(self):
-        return heapq.heappop(self.data)[1]
+class Event(event):
+    def __init__(self, date, location, body, eid):
+        self.date = date
+        self.location = location
+        self.body = body
+        self.eid = eid
+        
+    def affiche(self):
+        print('<Date>: %s' % self.date)
+        print('<Location>: %s' % self.location)
 
-    def top(self):
-        return self.data[0][1]
+        if (self.eid == "m"):
+            print('<Body>: %s' % self.body.decode())
+        elif (self.eid == "c"):
+            print('<Body>: %s' % self.body)       
+              
+    def problem(self):
+        #TODO: Call the function of RATP
+        return "TODO"
+    
 
-    def empty(self):
-        return not self.data

+ 4 - 2
gcal.py

@@ -20,7 +20,7 @@ except ImportError:
 # at ~/.credentials/calendar-python-quickstart.json
 SCOPES = 'https://www.googleapis.com/auth/calendar.readonly'
 CLIENT_SECRET_FILE = 'client_secret.json'
-APPLICATION_NAME = 'Google Calendar API Python Quickstart'
+APPLICATION_NAME = 'Google Calendar API Python'
 
 
 def get_credentials():
@@ -93,6 +93,8 @@ def find_list_event_gcal(events):
         location = ""
         if ('location' in event):
             location = event['location']
+            if (type(location) == 'bytes'):
+                location = location.decode()
             #print('  Location:', event['location'])
 
         #print("  Organizer's name:", event['organizer'].get('displayName', 'unknown'))
@@ -105,7 +107,7 @@ def find_list_event_gcal(events):
         #print(start, event['summary']);
 
 
-        list_event.append(Event(start,location,subject,body,status, withwho, withwhomail))
+        list_event.append(Event(start,location,body,"c"))
         return list_event
  
 def get_list_event_gcal():

+ 3 - 4
gmail.py

@@ -20,7 +20,7 @@ except ImportError:
 # at ~/.credentials/gmail-python-quickstart.json
 SCOPES = 'https://www.googleapis.com/auth/gmail.readonly'
 CLIENT_SECRET_FILE = 'client_secret.json'
-APPLICATION_NAME = 'Gmail API Python Quickstart111'
+APPLICATION_NAME = 'Gmail API Python'
 
 
 def get_credentials():
@@ -72,7 +72,7 @@ def get_list_event_gmail():
 
 
 
-    keyword = raw_input('Please enter a keyword to start searching the related messages in the mailbox(ctrl+c for quit) : ').lower()
+    keyword = input('Please enter a keyword to start searching the related messages in the mailbox(ctrl+c for quit) : ').lower()
 
     for i in range(3):
         print()
@@ -111,8 +111,7 @@ def get_list_event_gmail():
                 mime_msg = GetMimeMessage(service,"me",msg['id'])
                 body = get_message_body(mime_msg)
                 
-                
-                list_event.append(Event(date,location,subject,body,status, withwho, withwhomail))
+                list_event.append(Event(date,location,body,"m"))
     return list_event
                 #print('Body:')
                 #print('%s' % msg_body)

+ 63 - 66
gmail_msg.py

@@ -1,73 +1,68 @@
-"""Get a list of Messages from the user's mailbox.
-"""
 
 from apiclient import errors
 
-
 def ListMessagesMatchingQuery(service, user_id, query=''):
-  """List all Messages of the user's mailbox matching the query.
-
-  Args:
-    service: Authorized Gmail API service instance.
-    user_id: User's email address. The special value "me"
-    can be used to indicate the authenticated user.
-    query: String used to filter messages returned.
-    Eg.- 'from:user@some_domain.com' for Messages from a particular sender.
-
-  Returns:
-    List of Messages that match the criteria of the query. Note that the
-    returned list contains Message IDs, you must use get with the
-    appropriate ID to get the details of a Message.
-  """
-  try:
-    response = service.users().messages().list(userId=user_id,
-                                               q=query).execute()
-    messages = []
-    if 'messages' in response:
-      messages.extend(response['messages'])
-
-    while 'nextPageToken' in response:
-      page_token = response['nextPageToken']
-      response = service.users().messages().list(userId=user_id, q=query,
-                                         pageToken=page_token).execute()
-      messages.extend(response['messages'])
-
-    return messages
-  except errors.HttpError, error:
-    print 'An error occurred: %s' % error
+    """List all Messages of the user's mailbox matching the query.
+
+    Args:
+        service: Authorized Gmail API service instance.
+        user_id: User's email address. The special value "me"
+        can be used to indicate the authenticated user.
+        query: String used to filter messages returned.
+        Eg.- 'from:user@some_domain.com' for Messages from a particular sender.
+
+        Returns:
+            List of Messages that match the criteria of the query. Note that the
+            returned list contains Message IDs, you must use get with the
+            appropriate ID to get the details of a Message.
+    """
+    try:
+        response = service.users().messages().list(userId=user_id, q=query).execute()
+        messages = []
+        if 'messages' in response:
+            messages.extend(response['messages'])
+
+        while 'nextPageToken' in response:
+            page_token = response['nextPageToken']
+            response = service.users().messages().list(userId=user_id, q=query, pageToken=page_token).execute()
+            messages.extend(response['messages'])
+
+        return messages
+
+    except errors.HttpError:
+        print('An error occurred: %s' % error)
 
 
 def ListMessagesWithLabels(service, user_id, label_ids=[]):
-  """List all Messages of the user's mailbox with label_ids applied.
-
-  Args:
-    service: Authorized Gmail API service instance.
-    user_id: User's email address. The special value "me"
-    can be used to indicate the authenticated user.
-    label_ids: Only return Messages with these labelIds applied.
-
-  Returns:
-    List of Messages that have all required Labels applied. Note that the
-    returned list contains Message IDs, you must use get with the
-    appropriate id to get the details of a Message.
-  """
-  try:
-    response = service.users().messages().list(userId=user_id,
-                                               labelIds=label_ids).execute()
-    messages = []
-    if 'messages' in response:
-      messages.extend(response['messages'])
-
-    while 'nextPageToken' in response:
-      page_token = response['nextPageToken']
-      response = service.users().messages().list(userId=user_id,
+    """List all Messages of the user's mailbox with label_ids applied.
+
+    Args:
+        service: Authorized Gmail API service instance.
+        user_id: User's email address. The special value "me"
+        can be used to indicate the authenticated user.
+        label_ids: Only return Messages with these labelIds applied.
+
+    Returns:
+        List of Messages that have all required Labels applied. Note that the
+        returned list contains Message IDs, you must use get with the
+        appropriate id to get the details of a Message.
+    """
+    try:
+        response = service.users().messages().list(userId=user_id, labelIds=label_ids).execute()
+        messages = []
+        if 'messages' in response:
+            messages.extend(response['messages'])
+
+        while 'nextPageToken' in response:
+            page_token = response['nextPageToken']
+            response = service.users().messages().list(userId=user_id,
                                                  labelIds=label_ids,
                                                  pageToken=page_token).execute()
-      messages.extend(response['messages'])
+            messages.extend(response['messages'])
 
-    return messages
-  except errors.HttpError, error:
-    print 'An error occurred: %s' % error
+        return messages
+    except errors.HttpError:
+        print('An error occurred: %s' % error)
 
 
 
@@ -95,8 +90,8 @@ def GetMessage(service, user_id, msg_id):
       
             
         return message
-    except errors.HttpError, error:
-        print 'An error occurred: %s' % error
+    except errors.HttpError:
+        print('An error occurred: %s' % error)
 
 def get_message_header(message):
    
@@ -134,11 +129,13 @@ def GetMimeMessage(service, user_id, msg_id):
 
         msg_str = base64.urlsafe_b64decode(message['raw'].encode('ASCII'))
 
-        mime_msg = email.message_from_string(msg_str)
-
+        print()
+        print(type(msg_str))
+        mime_msg = email.message_from_string(msg_str.decode())
+      
         return mime_msg
-    except errors.HttpError, error:
-        print 'An error occurred: %s' % error
+    except errors.HttpError:
+        print('An error occurred: %s' % error)
 
 
 def get_message_body(mime_msg):