gonzopi

git clone https://git.tarina.org/gonzopi
Log | Files | Refs | README | LICENSE

gonzopiserver.py (17771B)


      1 #!/usr/bin/env python3
      2 
      3 import web
      4 import os
      5 import socket
      6 import ifaddr
      7 import sys
      8 import time
      9 import random
     10 import hashlib
     11 import configparser
     12 
     13 # Get path of the current dir, then use it as working directory:
     14 rundir = os.path.dirname(__file__)
     15 if rundir != '':
     16     os.chdir(rundir)
     17 
     18 urls = (
     19     '/','intro',   
     20     '/c/?', 'index',
     21     '/f/(.*)?', 'films',
     22     '/api','api'
     23 )
     24 
     25 #--------------USB filmfolder-------------------
     26 
     27 def usbfilmfolder():
     28     usbmount = 0
     29     while True:
     30         usbconnected = os.path.ismount('/media/usb'+str(usbmount))
     31         time.sleep(0.02)
     32         if usbconnected == True:
     33             try:
     34                 os.makedirs('/media/usb'+str(usbmount)+'/gonzopifilms/')
     35             except:
     36                 pass
     37             try:
     38                 p = subprocess.check_output('stat -f -c %T /media/usb'+str(usbmount), shell=True)
     39                 filesystem = p.decode()
     40                 print('filesystem info: ' + filesystem)
     41             except:
     42                 print('Oh-no! dont know your filesystem')
     43             filmfolder = '/media/usb'+str(usbmount)+'/gonzopifilms/'
     44             return filmfolder
     45         else:
     46             usbmount = usbmount + 1
     47         if usbmount > 20:
     48             break
     49 
     50 home = os.path.expanduser('~')
     51 menuold = []
     52 vumeterold = ''
     53 #configfile = home + '/.gonzopi/config.ini'
     54 #configdir = os.path.dirname(configfile)
     55 #config = configparser.ConfigParser()
     56 #if config.read(configfile):
     57 #    filmfolder = config['USER']['filmfolder']+'/'
     58 filmfolder = '/home/pi/gonzopifilms/'
     59 
     60 os.system("unlink static/*")
     61 #CHECK IF FILMING TO USB STORAGE
     62 filmfolderusb=usbfilmfolder()
     63 if filmfolderusb:
     64     filmfolder=filmfolderusb
     65     # Link video directory to static dir
     66     os.system("ln -s -t static/ " + filmfolder)
     67     filmfolder='static/gonzopifilms/'
     68 else:
     69     os.system("ln -s -t static/ " + filmfolder)
     70     filmfolder='static/gonzopifilms/'
     71     #fix filmfolder root to Videos/gonzopifilms
     72 
     73 basedir = os.path.dirname(os.path.realpath(__file__))
     74 sys.path.append(basedir)
     75 
     76 films = []
     77 
     78 #NETWORKS
     79 
     80 networks=[]
     81 adapters = ifaddr.get_adapters()
     82 for adapter in adapters:
     83     print("IPs of network adapter " + adapter.nice_name)
     84     for ip in adapter.ips:
     85         if '::' not in ip.ip[0] and '127.0.0.1' != ip.ip:
     86             print(ip.ip)
     87             networks.append(ip.ip)
     88 network=networks[0]
     89 
     90 app = web.application(urls, globals())
     91 render = web.template.render('templates/', base="base")
     92 web.config.debug=False
     93 os.system('rm '+basedir+'/sessions/*')
     94 store = web.session.DiskStore(basedir + '/sessions/')
     95 session = web.session.Session(app,store,initializer={'login': 0, 'user': '', 'backurl': '', 'bildsida': 0, 'cameras': [], 'reload': 0, 'randhash':'', 'menu':[]})
     96 
     97 port=55555
     98 ip='0.0.0.0'
     99 cameras=[]
    100 recording = False
    101 
    102 session.randhash = hashlib.md5(str(random.getrandbits(256)).encode('utf-8')).hexdigest()
    103 
    104 ##---------------Connection----------------------------------------------
    105 
    106 def pingtocamera(host, port, data):
    107     print("Sending to "+host+" on port "+str(port)+" DATA:"+data)
    108     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    109     s.settimeout(0.01)
    110     try:
    111         while True:
    112             s.connect((host, port))
    113             s.send(str.encode(data))
    114             if host not in cameras and host not in networks:
    115                 session.cameras.append(host)
    116                 print("Found camera! "+host)
    117             print("Sent to server..")
    118             break
    119     except:
    120         ('did not connect')
    121     s.close()
    122 
    123 def sendtocamera(host, port, data):
    124     print("Sending to "+host+" on port "+str(port)+" DATA:"+data)
    125     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    126     s.settimeout(0.1)
    127     try:
    128         while True:
    129             s.connect((host, port))
    130             s.send(str.encode(data))
    131             print("Sent to server..")
    132             break
    133     except:
    134         ('did not connect')
    135     s.close()
    136 
    137 
    138 def getfilms(filmfolder):
    139     #get a list of films, in order of settings.p file last modified
    140     films_sorted = []
    141     print(filmfolder)
    142     films = next(os.walk(filmfolder))[1]
    143     for i in films:
    144         if os.path.isfile(filmfolder + i + '/settings.p') == True:
    145             lastupdate = os.path.getmtime(filmfolder + i + '/' + 'settings.p')
    146             films_sorted.append((i,lastupdate))
    147     films_sorted = sorted(films_sorted, key=lambda tup: tup[1], reverse=True)
    148     print(films_sorted)
    149     return films_sorted
    150 
    151 #------------Count scenes--------
    152 
    153 def countscenes(filmfolder, filmname):
    154     scenes = 0
    155     try:
    156         allfiles = os.listdir(filmfolder + filmname)
    157     except:
    158         allfiles = []
    159         scenes = 0
    160     for a in allfiles:
    161         if 'scene' in a:
    162             scenes = scenes + 1
    163     return scenes
    164 
    165 #------------Count shots--------
    166 
    167 def countshots(filmname, filmfolder, scene):
    168     shots = 0
    169     try:
    170         allfiles = os.listdir(filmfolder + filmname + '/scene' + str(scene).zfill(3))
    171     except:
    172         allfiles = []
    173         shots = 0
    174     for a in allfiles:
    175         if 'shot' in a:
    176             shots = shots + 1
    177     return shots
    178 
    179 #------------Count takes--------
    180 
    181 def counttakes(filmname, filmfolder, scene, shot):
    182     takes = 0
    183     try:
    184         allfiles = os.listdir(filmfolder + filmname + '/scene' + str(scene).zfill(3) + '/shot' + str(shot).zfill(3))
    185     except:
    186         allfiles = []
    187         return takes
    188     for a in allfiles:
    189         if '.mp4' in a or '.h264' in a:
    190             takes = takes + 1
    191     return takes
    192 
    193 def checkpicture(thumbdir,scene,shot,take):
    194     if os.path.isfile(thumbdir) == False:
    195         return "/"+filmfolder+name+"/scene"+str(scene).zfill(3)+"/shot"+str(shot).zfill(3)+"/picture"+str(take).zfill(3)+".jpeg"
    196     else:
    197         return ''
    198 
    199 def countsize(filename):
    200     size = 0
    201     if type(filename) is str:
    202         size = os.stat(filename).st_size
    203     else:
    204         return 0
    205     return size/1024
    206 
    207 def checkvideo(video,filmfolder,film,scene,shot,take):
    208     if take==None:
    209         take=1
    210     print(basedir+video)
    211     p = "/"+filmfolder+film+"/scene"+str(scene).zfill(3)+"/shot"+str(shot).zfill(3)+ "/picture"+str(take).zfill(3)+".jpeg"
    212     print(p)
    213     v = ''
    214     if video != '':
    215         try:
    216             if os.stat(basedir+video).st_size == 0:
    217                 v = ''
    218             else:
    219                 v='video'
    220         except:
    221             v = ''
    222     if os.path.isfile(basedir+p) == True:
    223         return p, v
    224     return '', v
    225 
    226 class intro:
    227     def GET(self):
    228         return render.intro()
    229 
    230 class index:
    231     def GET(self):
    232         global recording
    233         films = getfilms(filmfolder)
    234         renderedfilms = []
    235         unrenderedfilms = []
    236         allfilms = []
    237         for f in films:
    238             if os.path.isfile(filmfolder + f[0] + '/' + f[0] + '.mp4') == True:
    239                 renderedfilms.append(f[0])
    240                 allfilms.append(f[0])
    241             else:
    242                 unrenderedfilms.append(f[0])
    243                 allfilms.append(f[0])
    244         i=web.input(func=None,selected=None)
    245         if i.selected != None:
    246             sendtocamera(ip,port,'SELECTED:'+i.selected)
    247         if i.func == 'search':
    248             session.cameras=[]
    249             # ping ip every 10 sec while not recording to connect cameras
    250             pingip=0
    251             while pingip < 255 :
    252                 pingip+=1
    253                 pingtocamera(network[:-3]+str(pingip),port,'PING')
    254         elif i.func == 'record':
    255             sendtocamera(ip,port,'RECORD')
    256         elif i.func == 'retake':
    257             print('retake')
    258         elif i.func == 'up':
    259             sendtocamera(ip,port,'UP')
    260         elif i.func == 'down':
    261             sendtocamera(ip,port,'DOWN')
    262         elif i.func == 'left':
    263             sendtocamera(ip,port,'LEFT')
    264         elif i.func == 'right':
    265             sendtocamera(ip,port,'RIGHT')
    266         elif i.func == 'view':
    267             sendtocamera(ip,port,'VIEW')
    268         elif i.func == 'middle':
    269             sendtocamera(ip,port,'MIDDLE')
    270         elif i.func == 'delete':
    271             sendtocamera(ip,port,'DELETE')
    272         elif i.func == 'picture':
    273             sendtocamera(ip,port,'PICTURE')
    274             session.randhash = hashlib.md5(str(random.getrandbits(256)).encode('utf-8')).hexdigest()
    275             session.reload = 1
    276         elif i.func == 'camera0':
    277             sendtocamera(ip,port,'CAMERA:0')
    278         elif i.func == 'camera1':
    279             sendtocamera(ip,port,'CAMERA:1')
    280         elif i.func == 'camera2':
    281             sendtocamera(ip,port,'CAMERA:2')
    282         elif i.func == 'camera3':
    283             sendtocamera(ip,port,'CAMERA:3')
    284         elif i.func == 'camera4':
    285             sendtocamera(ip,port,'CAMERA:4')
    286         elif i.func == 'camera5':
    287             sendtocamera(ip,port,'CAMERA:5')
    288         elif i.func == 'camera6':
    289             sendtocamera(ip,port,'CAMERA:6')
    290         elif i.func == 'camera7':
    291             sendtocamera(ip,port,'CAMERA:7')
    292         elif i.func == 'camera8':
    293             sendtocamera(ip,port,'CAMERA:8')
    294         elif i.func == 'move':
    295             sendtocamera(ip,port,'move')
    296         elif i.func == 'copy':
    297             sendtocamera(ip,port,'copy')
    298         elif i.func == 'paste':
    299             sendtocamera(ip,port,'paste')
    300         interface=open('/dev/shm/interface','r')
    301         vumeter=open('/dev/shm/vumeter','r')
    302         menu=interface.readlines()
    303         vumetermessage=vumeter.readlines()[0].rstrip('\n')
    304         try:
    305             selected=int(menu[0])
    306         except:
    307             selected=0
    308         try:
    309             name=menu[3].split(':')[1]
    310             name=name.rstrip('\n')
    311         except:
    312             name=''
    313         try:
    314             scene=menu[4].split(':')[1].split('/')[0]
    315         except:
    316             scene=1
    317         try:
    318             shot=menu[5].split(':')[1].split('/')[0]
    319         except:
    320             shot=1
    321         try:
    322             take=menu[6].split(':')[1].split('/')[0]
    323         except:
    324             take=1
    325             session.reload = 0
    326         if i.func == 'retake': 
    327             print(i.func)
    328             if recording == False:
    329                 sendtocamera(ip,port,'RETAKE:'+shot)
    330                 recording = True
    331             else:
    332                 sendtocamera(ip,port,'STOPRETAKE')
    333                 recording = False
    334         if i.func != None:
    335             time.sleep(1)
    336             session.reload = 1
    337             raise web.seeother('/c/')
    338         thumb="/"+filmfolder+name+"/scene"+str(scene).zfill(3)+"/shot"+str(shot).zfill(3)+"/picture"+str(take).zfill(3)+".jpeg"
    339         print(thumb)
    340         if os.path.isfile(basedir+thumb) == False:
    341             print(basedir+thumb)
    342             thumb=''
    343         return render.index(allfilms, session.cameras, menu, selected,name,scene,shot,take,str,session.randhash,thumb,vumetermessage,i.func,filmfolder)
    344 
    345 class films:
    346     def GET(self, film):
    347         shots = 0
    348         takes = 0
    349         gonzopifilms = getfilms(filmfolder)
    350         renderedfilms = []
    351         unrenderedfilms = []
    352         allfilms = []
    353         for f in gonzopifilms:
    354             if os.path.isfile(filmfolder + f[0] + '/' + f[0] + '.mp4') == True:
    355                 renderedfilms.append(f[0])
    356                 allfilms.append(f[0])
    357             else:
    358                 unrenderedfilms.append(f[0])
    359                 allfilms.append(f[0])
    360         i = web.input(page=None, scene=None, shot=None, take=None, film=None, randhash=None)
    361         if i.scene != None:
    362             shots = countshots(film, filmfolder, i.scene)
    363             takes = counttakes(film, filmfolder, i.scene, i.shot)
    364         if i.scene != None and i.shot != None:
    365             shots = countshots(film, filmfolder, i.scene)
    366         if i.randhash == None:
    367             randhash = hashlib.md5(str(random.getrandbits(256)).encode('utf-8')).hexdigest()
    368         scenes = countscenes(filmfolder, film)
    369         return render.filmpage(allfilms, film, scenes, str, filmfolder, counttakes, countshots, shots, i.scene, takes, i.shot, i.take, checkvideo, randhash)
    370 
    371 
    372 class api:
    373     def GET(self):
    374         global menuold, vumeterold
    375         i=web.input(func=None,selected=None)
    376         if i.func == 'record':
    377             sendtocamera(ip,port,'RECORD')
    378         elif i.func == 'retake':
    379             sendtocamera(ip,port,'RETAKE')
    380         elif i.func == 'up':
    381             sendtocamera(ip,port,'UP')
    382         elif i.func == 'down':
    383             sendtocamera(ip,port,'DOWN')
    384         elif i.func == 'left':
    385             sendtocamera(ip,port,'LEFT')
    386         elif i.func == 'right':
    387             sendtocamera(ip,port,'RIGHT')
    388         elif i.func == 'view':
    389             sendtocamera(ip,port,'VIEW')
    390         elif i.func == 'middle':
    391             sendtocamera(ip,port,'MIDDLE')
    392         elif i.func == 'delete':
    393             sendtocamera(ip,port,'DELETE')
    394         elif i.func == 'picture':
    395             sendtocamera(ip,port,'PICTURE')
    396         elif i.func == 'camera0':
    397             sendtocamera(ip,port,'CAMERA:0')
    398         elif i.func == 'camera1':
    399             sendtocamera(ip,port,'CAMERA:1')
    400         elif i.func == 'camera2':
    401             sendtocamera(ip,port,'CAMERA:2')
    402         elif i.func == 'camera3':
    403             sendtocamera(ip,port,'CAMERA:3')
    404         elif i.func == 'camera4':
    405             sendtocamera(ip,port,'CAMERA:4')
    406         elif i.func == 'camera5':
    407             sendtocamera(ip,port,'CAMERA:5')
    408         elif i.func == 'camera6':
    409             sendtocamera(ip,port,'CAMERA:6')
    410         elif i.func == 'camera7':
    411             sendtocamera(ip,port,'CAMERA:7')
    412         elif i.func == 'camera8':
    413             sendtocamera(ip,port,'CAMERA:8')
    414         elif i.func == 'move':
    415             sendtocamera(ip,port,'move')
    416         elif i.func == 'copy':
    417             sendtocamera(ip,port,'copy')
    418         elif i.func == 'paste':
    419             sendtocamera(ip,port,'paste')
    420         interface=open('/dev/shm/interface','r')
    421         menu=interface.readlines()
    422         vumeter=open('/dev/shm/vumeter','r')
    423         vumetermessage=vumeter.readlines()[0].rstrip('\n')
    424         if menu != menuold or vumetermessage != vumeterold:
    425             menuold=menu
    426             vumeterold=vumetermessage
    427             print(menu)
    428             menudone=''
    429             p=0
    430             film=None
    431             if menu != '':
    432                 scene=1
    433                 shot=1
    434                 take=1
    435                 for i in menu:
    436                     if p == 0:
    437                         selected=int(i)+3
    438                     if p > 1:
    439                         if selected == p:
    440                             #menudone=menudone+'<b> '+i.rstrip('\n')+' </b> | '
    441                             menudone=menudone+'<ka style="text-decoration:none; font-size:20px;" color:fff;" href="">'+i+'</ka>'
    442                         else:
    443                             #menudone=menudone+i.rstrip('\n')+' | '
    444                             menudone=menudone+'<a style="text-decoration:none; font-size:20px;" href="?selected='+str(p-3)+'"> '+i+' </a>'
    445                         #if p == 7:
    446                         #    menudone=menudone+'<br>'
    447                         #if p == 13:
    448                         #    menudone=menudone+'<br>'
    449                         #if p == 21:
    450                         #    menudone=menudone+'<br>'
    451                         #if p == 30:
    452                         #    menudone=menudone+'<br>'
    453                     if p == 4:
    454                         try:
    455                             film=i.split(':')[1].rstrip('\n')
    456                         except:
    457                             film=None
    458                     if p == 5 and film != None:
    459                         try:
    460                             scene=int(i.split(':')[1].split('/')[0])
    461                         except:
    462                             scene=1
    463                     if p == 6 and film != None:
    464                         try:
    465                             shot=int(i.split(':')[1].split('/')[0])
    466                         except:
    467                             shot=1
    468                     if p == 7 and film != None:
    469                         try:
    470                             take=int(i.split(':')[1].split('/')[0])
    471                         except:
    472                             take=1
    473                     if p > 0 and selected == 423:
    474                         menudone=menudone+'<ka style="text-decoration:none; font-size:20px;" color:fff;" href="">'+i+'</ka>'
    475                     #if p > 2 and film == None:
    476                         #menudone=menudone+'<ka style="text-decoration:none; font-size:20px;" color:fff;" href="">'+i+'</ka>'
    477                     p = p + 1
    478             thumb = ''
    479             video = ''
    480             if film != None:
    481                 if selected == 4:
    482                     video = '/'+filmfolder + film +'/'+ film+'.mp4'
    483                 elif selected == 5:
    484                     video = '/'+filmfolder + film + '/scene' + str(scene).zfill(3) + '/scene.mp4'
    485                 elif selected == 6:
    486                     video = '/'+filmfolder + film + '/scene' + str(scene).zfill(3) + '/shot' + str(shot).zfill(3) + '/take' + str(take).zfill(3) + '.mp4'
    487                 elif selected == 7:
    488                     video = '/'+filmfolder + film + '/scene' + str(scene).zfill(3) + '/shot' + str(shot).zfill(3) + '/take' + str(take).zfill(3) + '.mp4'
    489                 else:
    490                     video = '/'+filmfolder + film + '/scene' + str(scene).zfill(3) + '/shot' + str(shot).zfill(3) + '/take' + str(take).zfill(3) + '.mp4'
    491                 thumb = '/'+filmfolder + film + "/scene" + str(scene).zfill(3) + "/shot" + str(shot).zfill(3) + "/take" + str(take).zfill(3) + ".jpeg" 
    492             if os.path.isfile(basedir+thumb) == True:
    493                 randhashimg = '?'+hashlib.md5(str(random.getrandbits(256)).encode('utf-8')).hexdigest()
    494                 writemenu=menudone+'<br><br>'+vumetermessage+'<br><a href="'+video+'"><img src="'+thumb+randhashimg+'"></a>'
    495             else:
    496                 writemenu=menudone+'<br><br>'+vumetermessage+'<br>'
    497             f = open(basedir+'/static/menu.html', 'w')
    498             f.write(writemenu)
    499             f.close()
    500 
    501 application = app.wsgifunc()
    502