#! /usr/bin/python3 import os import subprocess import shutil import dbus import sys import json from datetime import datetime, date,timedelta class BellSchedulerPlayer: def __init__(self,bellId): self.bellId=bellId self.configDir=os.path.expanduser("/etc/bellScheduler/") self.configFile=os.path.join(self.configDir,"bell_list") self.tokenFolder="/tmp/.BellScheduler" self.tokenPath=os.path.join(self.tokenFolder,'bellscheduler-token') self.playBell() #def__init__ def playBell(self): self.fileToRemove="" abort=False bellInfo=self._readCurrentBell() if len(bellInfo)>0 and bellInfo[4]!="": if not self._checkBellValidity(bellInfo[4]): abort=True if abort: sys.exit(1) else: self._manageToken('create') user=self._getActiveUser() playCommand=self._getPlayCommand(bellInfo) if user!="": cmd="su -l %s -c '%s'"%(user,playCommand) else: cmd=playCommand pc=subprocess.run(cmd,shell=True,check=False) try: if os.path.exists(self.fileToRemove): os.remove(self.fileToRemove) except: pass self._manageToken('remove') sys.exit(0) #def playBell def _readCurrentBell(self): bellInfo=[] if os.path.exists(self.configFile): try: f=open(self.configFile) bellsConfig=json.load(f) for item in bellsConfig: if item==str(self.bellId): duration=bellsConfig[item]["play"]["duration"] bellInfo.append(duration) try: startTime=bellsConfig[item]["play"]["start"] except: startTime=0 bellInfo.append(startTime) soundOption=bellsConfig[item]["sound"]["option"] bellInfo.append(soundOption) soundPath=bellsConfig[item]["sound"]["path"] bellInfo.append(soundPath) try: if bellsConfig[item]["validity"]["active"]: validity=bellsConfig[item]["validity"]["value"] else: validity="" except: validity="" bellInfo.append(validity) break; except: pass return bellInfo #def _readCurrentBell def _checkBellValidity(self,validity): currentDay=date.today().strftime('%d/%m/%Y') listDays=[] tmp=validity.split("-") if len(tmp)>1: date1=datetime.strptime(tmp[0],'%d/%m/%Y') date2=datetime.strptime(tmp[1],'%d/%m/%Y') delta=date2-date1 for i in range(delta.days + 1): tmpDay=(date1 + timedelta(days=i)).strftime('%d/%m/%Y') listDays.append(tmpDay) else: listDays.append(tmp[0]) if currentDay in listDays: return True else: return False #def _checkBellValidity def _manageToken(self,action): if action=='create': if not os.path.exists(self.tokenFolder): os.mkdir(self.tokenFolder) with open(self.tokenPath,'w') as fd: fd.write(self.bellId) else: if os.path.exists(self.tokenPath): os.remove(self.tokenPath) #def _manageToken def _getActiveUser(self): user="" try: bellBus=dbus.SystemBus() bellProxy=bellBus.get_object('org.freedesktop.login1','/org/freedesktop/login1') dbusBell=dbus.Interface(bellProxy,dbus_interface='org.freedesktop.login1.Manager') currentSessions=dbusBell.ListSessions() if len(currentSessions)>0: for item in currentSessions: uid=int(item[0]) user=str(item[2]) cmd='loginctl session-status %s | grep "active" | grep -v "grep"'%uid p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE) pout=p.communicate()[0].decode() if len(pout)>0: break except Exception as e: pass if user=="sddm": user="" return user #def _getActiveUser def _getPlayCommand(self,bellInfo): playCommand="" if len(bellInfo)>0: duration=bellInfo[0] startTime=bellInfo[1] soundOption=bellInfo[2] soundPath=bellInfo[3] if duration>0: fadeOut=int(duration)+int(startTime)-2 fadeEffects='-af aformat=channel_layouts=mono -af afade=in:st=%s:d=3,afade=out:st=%s:d=2'%(str(startTime),str(fadeOut)) cmd=" ffplay -nodisp -autoexit " + "-ss %s -t %s"%(str(startTime),duration) else: fadeEffects='-af aformat=channel_layouts=mono ' cmd=" ffplay -nodisp -autoexit -ss %s"%str(startTime) if soundOption in ["directory","urlslist"]: soundPath=self._getSoundPath(soundOption,soundPath) if soundOption in ["file","directory"]: soundPath=soundPath.replace("'","'\\''") cmd=cmd+' "'+ soundPath +'" '+fadeEffects+';' elif sound_option in ["url","urlslist"]: soundPath=soundPath.replace("%","\%") cmd=cmd+ ' $(youtube-dl -g "'+soundPath+'" | sed -n 2p) '+fadeEffects+';' playCommand=cmd return playCommand #def _getPlayCommand def _getSoundPath(self,option,soundPath): playPath="" cmd='randomaudiofile "%s"'%soundPath p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE) pout=p.communicate()[0].decode().strip() if pout!="": if option=="directory": extensionFile=pout.split(".")[-1] tmpFile="bellSelected.%s"%extensionFile playPath=os.path.join("/tmp",tmpFile) try: shutil.copy(pout,playPath) except : pass self.fileToRemove=playPath else: playPath=pout return playPath #def _getSoundPath #class BellSchedulerPlayer if __name__=="__main__": bellId=sys.argv[1] bp=BellSchedulerPlayer(bellId)