Debian Codegraph @

autoradiod

raw
1 #!/usr/bin/env python3
2 # GPL. (C) 2007-2012 Paolo Patruno.
3
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 2 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 #
18
19 # ToDo:
20 # controllare altri conflitti in districa oltre ai jingles
21 # utilizzare mp3splt per spezzare i programmi per fare gli inserimenti pubblicitari
22 # alternare meglio i jingle tenendo in considerazione la priorita
23
24 import os
25 os.environ['DJANGO_SETTINGS_MODULE'] = 'autoradio.settings'
26 from django.conf import settings
27
28 import autoradio.settings
29 import autoradio.autoradio_config
30 from autoradio import daemon
31 from autoradio import _version_
32
33 autoradiod = daemon.Daemon(
34 stdin="/dev/null",
35 stdout=autoradio.autoradio_config.logfile,
36 stderr=autoradio.autoradio_config.errfile,
37 pidfile=autoradio.autoradio_config.lockfile,
38 user=autoradio.autoradio_config.user,
39 group=autoradio.autoradio_config.group,
40 env=autoradio.autoradio_config.env
41 )
42
43
44 def main():
45
46 import logging,os,sys,errno,signal,logging.handlers
47 import subprocess
48 try:
49 import thread
50 except:
51 import _thread as thread
52 import datetime
53 import time as timesleep
54 #from threading import *
55
56 import django
57 django.setup()
58
59 import autoradio.autoradio_core
60
61 formatter=logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s",datefmt="%Y-%m-%d %H:%M:%S")
62 handler = logging.handlers.RotatingFileHandler(autoradio.autoradio_config.logfile, maxBytes=5000000, backupCount=10)
63 handler.setFormatter(formatter)
64
65 # Add the log message handler to the root logger
66 logging.getLogger().addHandler(handler)
67 logging.getLogger().setLevel(logging.INFO)
68
69
70 logging.info('Starting up autoradiod version '+_version_)
71
72
73 if (autoradio.autoradio_config.player == "amarok1") :
74 import autoradio.manageamarok as manageplayer
75
76 elif (autoradio.autoradio_config.player == "xmms"):
77 # from managepytone import *
78 import autoradio.managexmms as manageplayer
79 import autoradio.xmmsweb as playerweb
80
81 elif (autoradio.autoradio_config.player == "audacious"
82 or autoradio.autoradio_config.player == "amarok"
83 or autoradio.autoradio_config.player == "vlc"
84 or autoradio.autoradio_config.player == "AutoPlayer"):
85
86 # import autoradio.manageaudacious as manageplayer
87 # import autoradio.audaciousweb as playerweb
88 import autoradio.managempris as manageplayer
89 import autoradio.mprisweb as playerweb
90
91 else:
92 logging.error('wrong player %s' % autoradio.autoradio_config.player)
93 raise Exception()
94
95 #def signalhandler(signum, frame):
96 # logging.info( 'Signal handler called with signal %d', signum)
97
98 #signal.signal(signal.SIGALRM, signalhandler)
99
100 f = open(autoradio.autoradio_config.timestampfile, "w")
101 f.write(str(datetime.datetime.now()))
102 f.close()
103
104 #we want to run a single process
105
106 try:
107
108 # now we can start to do our work
109 # time constant
110
111 # this is the first and last time that I set now with the current time
112 now=datetime.datetime.now(tz=None)
113
114 first = True
115
116 if (autoradio.autoradio_config.player == "amarok1") :
117 kapp=KdeInit()
118 function=manageplayer.ManageAmarok
119 ok=amarok_watchdog(kapp)
120
121 else:
122 # function=ManagePytone
123 session=0
124
125 # parte un thread pe monitorare via web il player
126 #t = Timer(5.0, xmmsweb.start_http_server)
127 #t.start()
128
129 #os.system("python xmmsweb.py&")
130 #p = subprocess.Popen("xmmsweb.py")
131
132
133 if (autoradio.autoradio_config.player == "amarok1"):
134 ok=manageplayer.amarok_watchdog(kapp)
135 elif (autoradio.autoradio_config.player == "xmms"):
136 t = thread.start_new_thread(playerweb.start_http_server,())
137 ok=manageplayeer.xmms_watchdog(session)
138 elif (autoradio.autoradio_config.player == "audacious"
139 or autoradio.autoradio_config.player == "amarok"
140 or autoradio.autoradio_config.player == "vlc"):
141 t = thread.start_new_thread(playerweb.start_http_server,())
142 ok=manageplayer.player_watchdog(autoradio.autoradio_config.player,session)
143 elif (autoradio.autoradio_config.player == "AutoPlayer"):
144 ok=manageplayer.player_watchdog(autoradio.autoradio_config.player,session)
145
146 while ( True):
147
148 scheds=autoradio.autoradio_core.schedules([])
149 scheds.get_all_refine(now)
150 for schedule in scheds:
151
152 scheduledatetime=schedule.scheduledatetime
153 filename=schedule.filename
154 type=schedule.type
155 emission_done=schedule.emission_done
156
157 if ( emission_done != None ):
158 if ( type == "program" ):
159 #la trasmissione ha una schedula con un'unica emissione prevista
160 logging.debug( " %s %s %s schedula already done; ignore it !",type,scheduledatetime,emission_done)
161 continue
162
163 if ( type == "spot" ):
164 # considero una emissione effettuata se e' avvenuta nell'intorno delle 3 ore
165 if ( abs(emission_done - scheduledatetime) < datetime.timedelta(minutes=180)):
166 logging.debug(" %s %s %s schedula already done; ignore it !", type,scheduledatetime,emission_done)
167 continue
168
169 if ( type == "playlist" ):
170 # I assume the emission is done if it happen around 3 hours
171 if ( abs(emission_done - scheduledatetime) < datetime.timedelta(minutes=180)):
172 logging.debug (" %s %s %s schedula already done; ignore it !",type,scheduledatetime,emission_done)
173 continue
174
175
176 delta=( scheduledatetime - now)
177 sec=manageplayer.secondi(delta)
178 #schedule for the nest minsched minutes starting from minsched minuti forward
179 #if it is the first time I start from minsched minuti in the past
180 if (first and ( type == "program" or type == "spot" or type == "playlist")):
181 #recovery programmi, playlist e pubblicita' not emitted in a ragionable past time range
182 startschedsec=-60 * autoradio.autoradio_config.minsched
183 elif (first and ( type == "jingle")):
184 startschedsec=0
185 else:
186 startschedsec=60*autoradio.autoradio_config.minsched
187
188
189 endschedsec = 60*autoradio.autoradio_config.minsched*2
190 if ( startschedsec < sec and sec <= endschedsec ):
191
192 #print "ora schedulata", scheduledatetime
193 #print "ora attuale", datetime.now()
194
195 if (autoradio.autoradio_config.player == "amarok1") :
196 threadschedule=manageplayer.ScheduleProgram(kapp,function,operation,filename,scheduledatetime,obj)
197 else:
198 #threadschedule=ScheduleProgram(session,function,operation,filename,scheduledatetime,obj,shuffle,length)
199 threadschedule=manageplayer.ScheduleProgram(autoradio.autoradio_config.player,session,schedule)
200
201 logging.debug (" %s %s programmed for %s seconds forward", type,filename,threadschedule.deltasec)
202 threadschedule.start()
203
204 first = False
205 sleepsec=autoradio.autoradio_config.minsched/5.*60.
206
207 #now I advance minsched and wait the right time to proced
208 now=now+datetime.timedelta(0,60*autoradio.autoradio_config.minsched)
209 while ( datetime.datetime.now(tz=None) < now):
210 if (autoradio.autoradio_config.player == "amarok1"):
211 ok=manageplayer.save_status(kapp)
212
213 else:
214 ok=manageplayer.save_status(session)
215
216 if ( ok ) :
217
218 f = open(autoradio.autoradio_config.timestampfile, "w")
219 f.write(str(datetime.datetime.now()))
220 f.close()
221
222 logging.debug ( "sleeping for %s seconds:%s %d",sleepsec,__name__,os.getpid())
223
224 #signal.alarm(0)
225 timesleep.sleep(sleepsec)
226
227 #os.system("sleep 60")
228 #target = time.time()
229 #while True:
230 # now = time.time()
231 # if now >= target+60: break
232 # os.sleep(target-now)
233
234 #logging.debug ( "wake up: %s %d",__name__,os.getpid() )
235
236 #sometime adjust playlist (will be deleted)
237 if (autoradio.autoradio_config.player == "amarok1"):
238 ok=manageplayer.amarok_watchdog(kapp)
239 elif (autoradio.autoradio_config.player == "xmms"):
240 ok=manageplayer.xmms_watchdog(session)
241 elif (autoradio.autoradio_config.player == "audacious"
242 or autoradio.autoradio_config.player == "amarok"
243 or autoradio.autoradio_config.player == "vlc"
244 or autoradio.autoradio_config.player == "AutoPlayer"):
245
246 ok=manageplayer.player_watchdog(autoradio.autoradio_config.player,session)
247
248
249 except KeyboardInterrupt :
250
251 logging.info('All threads terminated for keyboard interrupt' )
252 return 1
253
254 except SystemExit:
255
256 logging.info('Stopped OK')
257 return 0
258
259 except:
260 import traceback
261 msg = traceback.format_exc()
262 logging.error(msg)
263 logging.info('Stopping')
264
265 return 2
266
267 else:
268 msg = "error without traceback; what happens ?!?!"
269 logging.error(msg)
270 logging.info('Stopping')
271
272 return 3
273
274
275 if __name__ == '__main__':
276
277 import sys, os
278
279 # this is a triky for ubuntu and debian that remove /var/run every boot
280 # ATTENTION, this should be a security problem
281 path=os.path.dirname(autoradio.autoradio_config.lockfile)
282 if (not os.path.lexists(path) and path == "/var/run/autoradio" ):
283 os.mkdir(path)
284 if (os.getuid() == 0):
285
286 user=autoradio.autoradio_config.user
287 group=autoradio.autoradio_config.group
288 if user is not None and group is not None:
289 from pwd import getpwnam
290 from grp import getgrnam
291 uid = getpwnam(user)[2]
292 gid = getgrnam(group)[2]
293 os.chown(path,uid,gid)
294
295 if autoradiod.service():
296
297 sys.stdout.write("Autoradiod version "+_version_+"\n")
298 sys.stdout.write("Daemon started with pid %d\n" % os.getpid())
299 sys.stdout.write("Daemon stdout output\n")
300 sys.stderr.write("Daemon stderr output\n")
301
302 sys.exit(main()) # (this code was run as script)