#!/usr/bin/python3

# ## {R2D2919B742E} ##
# ###########################################################################
# What if magic existed?
# What if a place existed where your every thought and dream come to life.
# There is only one catch: it has to be written down.
# Such a place exists, it is called programming.
#    - Scott Taylor Reph, RightThumb.com
# ###########################################################################
# ## {C3P0D40fAe8B} ##
##################################################
import os, sys, time
##################################################
import _rightThumb._construct as __
appDBA = __.clearFocus( __name__, __file__ )
__.appReg = appDBA
def focus( parentApp='', childApp='', reg=True ):
    global appDBA
    f = __.appName( appDBA, parentApp, childApp )
    if reg:
        __.appReg = f
    return f
__.registeredApps.append( focus() )
import _rightThumb._base3 as _
_.load()
##################################################
import _rightThumb._vars as _v
import _rightThumb._string as _str
##################################################

def appSwitches():
    pass

_.autoBackupData = __.setting('receipt-log')
__.releaseAcquiredData = __.setting('receipt-file')
__.myFileLocations_SKIP_VALIDATION = False
__.isRequired_Pipe = False
__.isRequired_Pipe_or_File = False
__.pre_error = False
__.switch_raw = []
# __.switch_raw = [ 'Delim' ]
# __.isRequired_or_List = ['Pipe','Files','Plus']
# __.setting( 'app-switches-raw', [ 'Delim' ] )


_.appInfo[focus()] = {
    'file': 'vps-srv-7facG-twilio-mms.py',
    'liveAppName': __.thisApp( __file__ ),
    'description': 'web server to capture texted images',
    'categories': [
                        'twilio',
                        'mms',
                        'sms',
                ],
    'usage': [
                        # 'epy another',
                        # 'e nmap',
                        # '',
    ],
    'relatedapps': [
                        # 'p another -file file.txt',
                        # '',
    ],
    'prerequisite': [
                        # 'p another -file file.txt',
                        # '',
    ],
    'examples': [
                        _.hp('p vps-srv-7facG-twilio-mms '),
                        '',
    ],
    'columns': [
                       # { 'name': 'name', 'abbreviation': 'n' },
                       # { 'name': '{1}', 'abbreviation': '{0}', 'sort': '{2}' },
    ],
    'aliases': [
                       # 'this',
                       # 'app',
    ],
    'notes': [
                       # {},
    ],
}

_.appData[focus()] = {
        'start': __.startTime,
        'uuid': '',
        'audit': [],
        'pipe': False,
        'data': {
                    'field': {'sent': [], 'received': [] }, # { 'label': '', 'context': [],  }
                    'table': {'sent': [], 'received': [] }, 
        },
    }



def registerSwitches( argvProcessForce=False ):
    global appDBA
    if not __.appReg == appDBA and appDBA in __.appReg:

        if not __name__ == '__main__':
            _.argvProcess = argvProcessForce
        else:
            _.argvProcess = True

        _.load()
        _.appInfo[__.appReg] = _.appInfo[appDBA]
        _.appData[__.appReg] = _.appData[appDBA]
    __.constructRegistration( _.appInfo[__.appReg]['file'],__.appReg )
    appSwitches()

    _.myFileLocation_Print = False
    _.switches.trigger( 'Files', _.myFileLocations, vs=True )
    _.switches.trigger( 'Folder', _.myFolderLocations )
    _.switches.trigger( 'URL', _.urlTrigger )
    _.switches.trigger( 'Ago', _.timeAgo )
    _.switches.trigger( 'Duration', _.timeFuture )
    
    _.defaultScriptTriggers()
    _.switches.process()


if not __name__ == '__main__':
    _.argvProcess = False
else:
    _.argvProcess = True

registerSwitches()


def fieldSet( switchName, switchField, switchValue, theFocus=False ):
    if not type( theFocus ) == bool:
        theFocus = theFocus
    _.switches.fieldSet( switchName, switchField, switchValue, theFocus )


if __name__ == '__main__':
    if not sys.stdin.isatty():
        _.setPipeData( sys.stdin.readlines(), __.appReg, clean=True )


_.postLoad( __file__ )

########################################################################################
# START

mime_ext = _.getTableDB('mime-ext.index')
# _.pv(mime_ext)
# sys.exit()
import requests
from flask import Flask, request, redirect
from twilio.twiml.messaging_response import MessagingResponse
app = Flask(__name__)

notifications = {
                    'photo': {
                        '8136901260':'endearing',

                        '7279023028':'endearing',
                        # '8132308620':'endearing',
                        # '8135458526':'endearing',
                        # '8139095297':'endearing',
                        # '8138384321':'endearing',
                    }
}

notifications['photo']
DOWNLOAD_DIRECTORY = '/home/admin/domains/eyeformeta.com/private_html/apps/mms'


names = {
                '8136901260': 'Scott',
                '8139095297': 'Alexandria',
                '8138384321': 'Taylor',
                '8134695709': 'Beth',
                '8136101963': 'Jon',
                '8132449301': 'Mema',
                '8136245009': 'Grandpa',
                '8137354872': 'Jessica',
                '7275121425': 'Kevin',
                '8139573524': 'Lorraine',
                '8135035938': 'Frank',

                '7279023028': 'Karla',
                '8132308620': 'Karen',
                '8135458526': 'Mandy',
}

folders = {
                '8139095297': '/home/admin/domains/eyeformeta.com/private_html/apps/gallery/family/albums',
                '8138384321': '/home/admin/domains/eyeformeta.com/private_html/apps/gallery/family/albums',
                '8134695709': '/home/admin/domains/eyeformeta.com/private_html/apps/gallery/family/albums',
                '8136101963': '/home/admin/domains/eyeformeta.com/private_html/apps/gallery/family/albums',
                '8132449301': '/home/admin/domains/eyeformeta.com/private_html/apps/gallery/family/albums',
                '8136245009': '/home/admin/domains/eyeformeta.com/private_html/apps/gallery/family/albums',
                '8137354872': '/home/admin/domains/eyeformeta.com/private_html/apps/gallery/family/albums',
                '7275121425': '/home/admin/domains/eyeformeta.com/private_html/apps/gallery/family/albums',

                '8136901260': '/home/admin/domains/eyeformeta.com/private_html/apps/gallery/cats/albums',
                '7279023028': '/home/admin/domains/eyeformeta.com/private_html/apps/gallery/cats/albums',
                '8132308620': '/home/admin/domains/eyeformeta.com/private_html/apps/gallery/cats/albums',
                '8135458526': '/home/admin/domains/eyeformeta.com/private_html/apps/gallery/cats/albums',
}
_send =  _.regImp( __.appReg, 'vps-srv-7facG-twilio-send' )
_greeting =  _.regImp( __.appReg, 'greeting' )
_send.switch( 'Type', 'endearing' )
_greeting.switch( 'Type', 'endearing' )
@app.route("/sms", methods=['GET', 'POST'])
def sms_reply():
    global notifications
    global mime_ext
    global names
    global folders
    global _greeting
    global _send
    message_sent=False
    """Respond to incoming with a simple text message."""

    resp = MessagingResponse()
    if request.values['NumMedia'] != '0':
        try:
            from_ = request.values['From'].replace('+1','')
            if from_ in names:
                body = request.values['Body']
                ti = _.isDate(time.time())['sdate'].replace(':','.')
                # Use the message SID as a filename.
                filename = request.values['MessageSid']
                if from_ in folders:
                    DOWNLOAD_DIRECTORY = folders[from_]
                if from_ in names:
                    if not names[from_] in 'Karla Karen Mandy Scott'.split(' '):
                        DOWNLOAD_DIRECTORY += os.sep+ names[from_]
                    else:
                        DOWNLOAD_DIRECTORY += os.sep+ 'fur-babies'

                if len(body):
                    body = body.replace('&',' and ')
                    body = body.lower()
                    body = body.replace('\r','')
                    body = body.replace('\n','/')
                    body = body.replace('\t',' ')
                    body = body.replace('\\',os.sep)
                    body = body.replace('/',os.sep)
                    body = _str.replaceDuplicate(body,' ')
                    parts = body.split(os.sep)
                    for i,par in enumerate(parts):
                        parts[i] = _str.cleanBE(par,' ')
                    parts.reverse()
                    filename = parts.pop(0)  +' - '+  ti
                    parts.reverse()
                    # DOWNLOAD_DIRECTORY +=  os.sep + os.sep.join(parts)


                pass
                _v.mkdir(DOWNLOAD_DIRECTORY)
                ext = ''
                if request.values['MediaContentType0'] in mime_ext:
                    ext = mime_ext[ request.values['MediaContentType0'] ]
                _.pr(request.values['MediaContentType0'],ext)
                path = DOWNLOAD_DIRECTORY +os.sep+ filename+ext




                
                for n in notifications:
                    if from_ in notifications[n]:
                        for nn in notifications[n]:
                            t = nn
                            greet = 'endearing'
                            # greet = notifications[n][nn]
                            if t in names:
                                to = names[t]

                            to = _greeting.imp.action( greet )
                            fr = ''
                            if from_ in names:
                                fr = names[from_]
                            pass
                            # url = __.path(path,pop=True).replace('/home/admin/domains/eyeformeta.com/private_html','https://eyeformeta.com')
                            # url+='/?'
                            url='https://eyeformeta.com/apps/gallery/cats/index.php?album=fur-babies'
                            print('url:',url)
                            # url = 'https://eyeformeta.com/apps/gallery/family/index.php?album='+fr
                            print(__.path(path,file=True))
                            try:
                                _send.imp.action( to=t, from_=fr,body=to+',\n'+fr+' posted a picture\n'+url+'\n\n" '+__.path(path,file=True)+' "' )
                            except Exception as err1:
                                print('err1:',err1)
                                pass




                path = _str.replaceDuplicate(path,os.sep)
                # _.saveText( str(request.values), DOWNLOAD_DIRECTORY +os.sep+ filename +'.txt' )
                with open(path, 'wb') as f:
                   image_url = request.values['MediaUrl0']
                   f.write(requests.get(image_url).content)

                # if from_ in names:
                #     message_sent=True
                #     resp.message('Thanks for the image '+names[from_]+'!')
                # else:
                #     message_sent=True
                #     resp.message("Thanks for the image!")
            else:
                message_sent=True
                resp.message("Try sending a picture message.")
        except Exception as err0:
            print('err0:',err0)
    # if not message_sent:
    #     resp.message("error")
    #     print('error-eof')

    return str(resp)

if __name__ == "__main__":
    # app.run(host='0.0.0.0', port=80, debug=True)
    app.run(host='0.0.0.0', port=5000, debug=False)



def action():
    pass



########################################################################################
if __name__ == '__main__':
    action()
    # __.isExit()





