import os
import mimetypes

import dropbox
from flask import Flask, request

app = Flask(__name__)
dbx = dropbox.Dropbox(os.environ.get('DROPBOX_TOKEN'))

CONTENTTYPE_CONFIG = {
    'image/jpeg': '.jpeg'
}


@app.route("/", methods=['GET', 'POST'])
def handle():
    """ Handle a Twilio SMS/MMS callback request by sending the contents to a Dropbox folder

    For information about the request: https://www.twilio.com/docs/api/twiml/sms/twilio_request
    Note: `MediaContentType{num}` and `MediaUrl{num}` where 'num' is a zero-based index derived from NumMedia
    """
    if request.method == 'POST':
        message_id = request.form.get('MessageSid')
        phone_number = request.form.get('From')[-10:]
        num_media = int(request.form.get('NumMedia', 0))
        for i in range(num_media):
            media_url = request.form.get('MediaUrl{}'.format(i))
            content_type = request.form.get('MediaContentType{}'.format(i))
            extension = CONTENTTYPE_CONFIG.get(content_type, mimetypes.guess_extension(content_type))
            upload_path = '/{}/{}-{}{}'.format(phone_number, message_id, str(i), extension)
            dbx.files_save_url(upload_path, media_url)
            # TODO: once ensured that DropBox received the file, delete it from Twilio
        file_contents = '{}\n\n'.format(request.form.get('Body'))
        for k, v in request.form.items():
            if k not in ['Body']:
                file_contents += '{}: {}\n'.format(k, str(v))
        dbx.files_upload(file_contents, '/{}/{}.txt'.format(phone_number, message_id))
    # TODO: return an HTTP response code and XML
    return ''

if __name__ == "__main__":
    app.run(debug=True)

@@ -45,165 +45,595 @@
 rom 
-flask import Flask, request%0A%0Aapp = Flask(__name__)%0Adbx = dropbox.Dropbox(os.environ.get('DROPBOX_TOKEN'))%0A%0ACONTENTTYPE_CONFIG = %7B%0A    'image/jpeg': '.jpeg'%0A%7D
+dropbox.files import SaveUrlError, UploadError%0Afrom flask import Flask, request%0Afrom twilio.rest import Client as TwilioRestClient%0A%0Aapp = Flask(__name__)%0Adbx = dropbox.Dropbox(os.environ.get('DROPBOX_TOKEN'))%0A%0ACONTENTTYPE_CONFIG = %7B%0A    'image/jpeg': '.jpeg'%0A%7D%0ATWILIO_ACCOUNT_SID = os.environ.get('TWILIO_ACCOUNT_SID', '')%0ATWILIO_AUTH_TOKEN = os.environ.get('TWILIO_AUTH_TOKEN', '')%0ATWILIO_DELETE_IMAGES = os.environ.get('TWILIO_DELETE_IMAGES', False)%0ATWILIO_DELETE_MESSAGES = os.environ.get('TWILIO_DELETE_MESSAGES', False)%0A%0Atwl = TwilioRestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
 %0A%0A%0A@
@@ -1043,16 +1043,17 @@
 message_
+s
 id = req
@@ -1133,16 +1133,81 @@
 ')%5B-10:%5D
+  # original is E.164 format: https://en.wikipedia.org/wiki/E.164
 %0A       
@@ -1603,16 +1603,17 @@
 message_
+s
 id, str(
@@ -1627,16 +1627,37 @@
 ension)%0A
+            try:%0A    
         
@@ -1719,82 +1719,353 @@
     
-# TODO: once ensured that DropBox received the file, delete it from Twilio
+except SaveUrlError:%0A                # TODO: log error%0A                pass%0A            else:%0A                if TWILIO_DELETE_IMAGES is True:%0A                    medium_sid = media_url.rsplit('/', 1)%5B-1%5D%0A                    media_instance = twl.account.messages(message_sid).media(medium_sid).fetch()%0A                    media_instance.delete()
 %0A   
@@ -2265,16 +2265,33 @@
 str(v))%0A
+        try:%0A    
         
@@ -2368,13 +2368,243 @@
 age_
+s
 id))%0A
+        except UploadError:%0A            # TODO: log error%0A            pass%0A        else:%0A            if TWILIO_DELETE_MESSAGES is True:%0A                message = twl.account.messages(message_sid)%0A                message.delete()%0A
     

handle deletion of media and/or images from Twilio (new env vars)