def modify_stream(request): success = False msg = "" form = request.GET request = form_to_request(form) arg_hack = json.dumps(request) db.log_event("modify_stream", int(form['session_id']), form) if form.has_key('session_id'): session = models.Session.objects.select_related('project').get(id=form['session_id']) project = session.project if form.has_key('language'): try: logging.debug("modify_stream: language: " + form['language']) l = models.Language.objects.filter(language_code=form['language'])[0] session.language = l session.save() except: raise roundexception.RoundException("language not supported") audio_format = project.audio_format.upper() if stream_exists(int(form['session_id']), audio_format): rounddbus.emit_stream_signal(int(form['session_id']), "modify_stream", arg_hack) success = True else: msg = "no stream available for session: " + form['session_id'] else: msg = "a session_id is required for this operation" if success: return {"success": success} else: return {"success": success, }
def upload_recording (form): logging.debug("upload_recording") db.log_event(7, form) user = form_to_user(form) request = form_to_recording_request(form) fileitem = form['file'] id_to_update = form['recordingid'] if id_to_update != None: if fileitem.filename: logging.debug("Processing " + fileitem.filename) (filename_prefix, filename_extension) = \ os.path.splitext(fileitem.filename) fn = time.strftime("%Y%m%d-%H%M%S") + filename_extension fileout = open(os.path.join(settings.config["upload_dir"], fn), 'wb') fileout.write(fileitem.file.read()) fileout.close() retval = update_recorded_file_helper (user, request, fn, id_to_update) refresh_recordings() return retval else: raise RoundException("Uploaded file has no filename") else: raise RoundException("No recordingid provided for update")
def vote_asset(request): form = request.GET db.log_event("vote_asset", int(form['session_id']), form) if not form.has_key('session_id'): raise roundexception.RoundException("a session_id is required for this operation") if not form.has_key('asset_id'): raise roundexception.RoundException("an asset_id is required for this operation") if not form.has_key('vote_type'): raise roundexception.RoundException("a vote_type is required for this operation") if check_for_single_audiotrack(form.get('session_id')) != True: raise roundexception.RoundException("this operation is only valid for projects with 1 audiotrack") try: session = models.Session.objects.get(id=int(form.get('session_id'))) except: raise roundexception.RoundException("Session not found.") try: asset = models.Asset.objects.get(id=int(form.get('asset_id'))) except: raise roundexception.RoundException("asset not found.") if not form.has_key('value'): v = models.Vote(asset=asset, session=session, type=form.get('vote_type')) else: v = models.Vote(asset=asset, session=session, value=int(form.get('value')), type=form.get('vote_type')) v.save() return {"success": True}
def skip_ahead(request): form = request.GET db.log_event("skip_ahead", int(form['session_id']), form) if not form.has_key('session_id'): raise roundexception.RoundException("a session_id is required for this operation") if check_for_single_audiotrack(form.get('session_id')) != True: raise roundexception.RoundException("this operation is only valid for projects with 1 audiotrack") rounddbus.emit_stream_signal(int(form['session_id']), "skip_ahead", "") return {"success": True}
def log_event (request): form = request.GET if not form.has_key('session_id'): raise roundexception.RoundException("a session_id is required for this operation") if not form.has_key('event_type'): raise roundexception.RoundException("an event_type is required for this operation") db.log_event(form.get('event_type'),form.get('session_id'), form) return {"success":True}
def cleanup(self): db.log_event("cleanup_session", self.sessionid,None) logging.debug("Cleaning up" + str(self.sessionid)) if self.pipeline: if self.watch_id: self.pipeline.get_bus().remove_signal_watch() self.pipeline.get_bus().disconnect(self.watch_id) self.watch_id = None self.pipeline.set_state(gst.STATE_NULL) self.main_loop.quit()
def skip_ahead(request): form = request.GET db.log_event("skip_ahead", int(form['session_id']), form) if not form.has_key('session_id'): raise roundexception.RoundException( "a session_id is required for this operation") if check_for_single_audiotrack(form.get('session_id')) != True: raise roundexception.RoundException( "this operation is only valid for projects with 1 audiotrack") rounddbus.emit_stream_signal(int(form['session_id']), "skip_ahead", "") return {"success": True}
def cleanup(self): db.log_event("cleanup_session", self.sessionid, None) logging.debug("Cleaning up" + str(self.sessionid)) #db.cleanup_history_for_session(self.sessionid) if self.pipeline: if self.watch_id: self.pipeline.get_bus().remove_signal_watch() self.pipeline.get_bus().disconnect(self.watch_id) self.watch_id = None self.pipeline.set_state(gst.STATE_NULL) self.main_loop.quit()
def log_event(request): form = request.GET if not form.has_key('session_id'): raise roundexception.RoundException( "a session_id is required for this operation") if not form.has_key('event_type'): raise roundexception.RoundException( "an event_type is required for this operation") db.log_event(form.get('event_type'), form.get('session_id'), form) return {"success": True}
def request_stream (form): logging.debug("request") #FIXME: next line is a hack. os.envrion is not available from fastcgi db.log_event(10, form) hostname_without_port = str(settings.config["external_host_name_without_port"]) if is_listener_in_range_of_stream(form): udid = "" if form.has_key('udid'): udid = form['udid'] sessionid = db.create_session(udid) command = ['/usr/local/bin/streamscript', '--sessionid', str(sessionid)] for p in ['categoryid', 'subcategoryid', 'questionid', 'usertypeid', 'genderid', 'demographicid', 'ageid', 'latitude', 'longitude', 'audioformat']: if form.has_key(p) and form[p]: command.extend(['--' + p, form[p].replace("\t", ",")]) if form.has_key('config'): command.extend(['--configfile', os.path.join(settings.configdir, form['config'])]) audio_format = 'MP3' if form.has_key('audioformat'): audio_format = form['audioformat'].upper() apache_safe_daemon_subprocess(command) wait_for_stream(sessionid, audio_format) #TODO: must return streamurl and sessionid here # do NOT brake scapes.py return { "SESSIONID" : sessionid, "STREAM_URL" : "http://" + hostname_without_port + ":" + \ str(settings.config["icecast_port"]) + \ icecast_mount_point(sessionid, audio_format), } else: msg = "This application is designed to be used in specific geographic locations. Apparently your phone thinks you are not at one of those locations, so you will hear a sample audio stream instead of the real deal. If you think your phone is incorrect, please restart Scapes and it will probably work. Thanks for checking it out!" if form.has_key('out_of_range_message'): msg = form['out_of_range_message'] url = "http://" + hostname_without_port + ":" + \ str(settings.config["icecast_port"]) + \ "/outofrange.mp3" if form.has_key('categoryid'): dburl = db.get_out_of_range_url_for_categoryid(form["categoryid"]) if(dburl): url = dburl return { "SESSIONID" : "-1", 'STREAM_URL' : url , 'USER_ERROR_MESSAGE' : msg }
def add_asset_to_envelope(request): envelope_id = get_parameter_from_request(request, 'envelope_id', True) latitude = get_parameter_from_request(request, 'latitude', False) longitude = get_parameter_from_request(request, 'longitude', False) if latitude == None: latitude = 0.0 if longitude == None: longitude = 0.0 tagset = [] tags = get_parameter_from_request(request, 'tags', False) if tags != None: ids = tags.split(',') tagset = models.Tag.objects.filter(id__in=ids) envelope = models.Envelope.objects.get(id=envelope_id) session = envelope.session submitted = get_parameter_from_request(request, 'submitted', False) if submitted == None: submitted=session.project.auto_submit db.log_event("start_upload", session.id,request.GET) fileitem = request.FILES.get('file') if fileitem.name: logging.debug("Processing " + fileitem.name) (filename_prefix, filename_extension) = \ os.path.splitext(fileitem.name) fn = time.strftime("%Y%m%d-%H%M%S") + filename_extension fileout = open(os.path.join(settings.config["upload_dir"], fn), 'wb') fileout.write(fileitem.file.read()) fileout.close() newfilename = convertaudio.convert_uploaded_file(fn) if newfilename: asset = models.Asset(latitude=latitude,longitude=longitude, filename=newfilename, session=session, submitted=submitted, volume=1.0) asset.project = session.project asset.save() for t in tagset: asset.tags.add(t) discover_audiolength.discover_and_set_audiolength(asset, newfilename) asset.save() envelope.assets.add(asset) envelope.save() else: raise RoundException("File not converted successfully: " + newfilename) else: raise RoundException("No file in request") rounddbus.emit_stream_signal(0, "refresh_recordings", "") return {"success":True}
def enter_recording (form): response = {} logging.debug("enter_recording") db.log_event(7, form) user = form_to_user(form) request = form_to_recording_request(form) recordingid = db.store_recording(user, request, '') response['RESULT'] = recordingid msg = db.get_sharing_message_for_categoryid(form['categoryid']) msg = msg + str(recordingid) response['SHARING_MESSAGE'] = msg return response
def play_asset_in_stream(request): form = request.GET # add skipped asset_id to form in order to track which asset is played #assetid = form[asset_id] #form[data] = form["asset_id"] request = form_to_request(form) arg_hack = json.dumps(request) db.log_event("play_asset_in_stream", int(form['session_id']), form) if not form.has_key('session_id'): raise roundexception.RoundException("a session_id is required for this operation") if check_for_single_audiotrack(form.get('session_id')) != True: raise roundexception.RoundException("this operation is only valid for projects with 1 audiotrack") if not form.has_key('asset_id'): raise roundexception.RoundException("an asset_id is required for this operation") rounddbus.emit_stream_signal(int(form['session_id']), "play_asset", arg_hack) return {"success": True}
def upload_and_process_file (form): logging.debug("upload_and_process_file") db.log_event(7, form) user = form_to_user(form) request = form_to_recording_request(form) submityn = form['submittedyn'] fileitem = form['file'] if fileitem.filename: logging.debug("Processing " + fileitem.filename) (filename_prefix, filename_extension) = \ os.path.splitext(fileitem.filename) fn = time.strftime("%Y%m%d-%H%M%S") + filename_extension fileout = open(os.path.join(settings.config["upload_dir"], fn), 'wb') fileout.write(fileitem.file.read()) fileout.close() retval = process_recorded_file_helper (user, request, fn, submityn) refresh_recordings() return retval else: raise RoundException("Uploaded file has no filename")
def play_asset_in_stream(request): form = request.GET # add skipped asset_id to form in order to track which asset is played #assetid = form[asset_id] #form[data] = form["asset_id"] request = form_to_request(form) arg_hack = json.dumps(request) db.log_event("play_asset_in_stream", int(form['session_id']), form) if not form.has_key('session_id'): raise roundexception.RoundException( "a session_id is required for this operation") if check_for_single_audiotrack(form.get('session_id')) != True: raise roundexception.RoundException( "this operation is only valid for projects with 1 audiotrack") if not form.has_key('asset_id'): raise roundexception.RoundException( "an asset_id is required for this operation") rounddbus.emit_stream_signal(int(form['session_id']), "play_asset", arg_hack) return {"success": True}
def get_config(request): form = request.GET try: hostname_without_port = str(settings.config["external_host_name_without_port"]) except KeyError: raise roundexception.RoundException("Roundware configuration file is missing 'external_host_name_without_port' key. ") #check params if not form.has_key('project_id'): raise roundexception.RoundException("a project_id is required for this operation") project = models.Project.objects.get(id=form.get('project_id')) if not form.has_key('device_id') or (form.has_key('device_id') and form['device_id']==""): device_id = str(uuid.uuid4()) else: device_id = form.get('device_id') session_id = db.create_session(device_id,project) sharing_url = str.format("http://{0}/roundware/?operation=view_envelope&envelopeid=[id]", hostname_without_port) response = [ { "device":{"device_id":device_id}}, { "session":{"session_id":session_id}}, { "project":{ "project_id":project.id, "project_name":project.name, "audio_format":project.audio_format, "max_recording_length":project.max_recording_length, "sharing_message":project.sharing_message, "sharing_url":sharing_url, "listen_questions_dynamic":project.listen_questions_dynamic, "speak_questions_dynamic":project.speak_questions_dynamic, }}, { "server":{ "version": "2.0"}} ] db.log_event('start_session',session_id,None) return response
def modify_stream(request): success = False msg = "" form = request.GET request = form_to_request(form) arg_hack = json.dumps(request) db.log_event("modify_stream", int(form['session_id']), form) if form.has_key('session_id'): session = models.Session.objects.select_related('project').get( id=form['session_id']) project = session.project if form.has_key('language'): try: logging.debug("modify_stream: language: " + form['language']) l = models.Language.objects.filter( language_code=form['language'])[0] session.language = l session.save() except: raise roundexception.RoundException("language not supported") audio_format = project.audio_format.upper() if stream_exists(int(form['session_id']), audio_format): rounddbus.emit_stream_signal(int(form['session_id']), "modify_stream", arg_hack) success = True else: msg = "no stream available for session: " + form['session_id'] else: msg = "a session_id is required for this operation" if success: return {"success": success} else: return { "success": success, }
def modify_stream (request): success = False msg = "" form = request.GET request = form_to_request(form) arg_hack = json.dumps(request) db.log_event("modify_stream", int(form['session_id']),form) if form.has_key('session_id'): session = models.Session.objects.get(id=form['session_id']) project = session.project audio_format = project.audio_format.upper() if stream_exists(int(form['session_id']), audio_format): rounddbus.emit_stream_signal(int(form['session_id']), "modify_stream", arg_hack) success = True else: msg = "no stream available for session: " + form['session_id'] else: msg = "a session_id is required for this operation" if success: return {"success":success} else: return {"success":success,"user_error_message":msg}
def vote_asset(request): form = request.GET db.log_event("vote_asset", int(form['session_id']), form) if not form.has_key('session_id'): raise roundexception.RoundException( "a session_id is required for this operation") if not form.has_key('asset_id'): raise roundexception.RoundException( "an asset_id is required for this operation") if not form.has_key('vote_type'): raise roundexception.RoundException( "a vote_type is required for this operation") if check_for_single_audiotrack(form.get('session_id')) != True: raise roundexception.RoundException( "this operation is only valid for projects with 1 audiotrack") try: session = models.Session.objects.get(id=int(form.get('session_id'))) except: raise roundexception.RoundException("Session not found.") try: asset = models.Asset.objects.get(id=int(form.get('asset_id'))) except: raise roundexception.RoundException("asset not found.") if not form.has_key('value'): v = models.Vote(asset=asset, session=session, type=form.get('vote_type')) else: v = models.Vote(asset=asset, session=session, value=int(form.get('value')), type=form.get('vote_type')) v.save() return {"success": True}
def add_asset_to_envelope(request): #get asset_id from the GET request asset_id = get_parameter_from_request(request, 'asset_id', False) asset = None #grab the Asset from the database, if an asset_id has been passed in if asset_id: try: asset = models.Asset.objects.get(pk=asset_id) except models.Asset.DoesNotExist: raise roundexception.RoundException( "Invalid Asset ID Provided. No Asset exists with ID %s" % asset_id) envelope_id = get_parameter_from_request(request, 'envelope_id', True) envelope = models.Envelope.objects.select_related('session').get( id=envelope_id) session = envelope.session db.log_event("start_upload", session.id, request.GET) fileitem = request.FILES.get('file') if not asset else asset.file #get mediatype from the GET request mediatype = get_parameter_from_request( request, 'mediatype', False) if not asset else asset.mediatype #if mediatype parameter not passed, set to 'audio' #this ensures backwards compatibility if mediatype is None: mediatype = "audio" if fileitem.name: #copy the file to a unique name (current time and date) logging.debug("Processing " + fileitem.name) (filename_prefix, filename_extension) = \ os.path.splitext(fileitem.name) fn = time.strftime("%Y%m%d-%H%M%S") + filename_extension fileout = open(os.path.join(settings.config["upload_dir"], fn), 'wb') fileout.write(fileitem.file.read()) fileout.close() #delete the uploaded original after the copy has been made if asset: asset.file.delete() # re-assign file to asset asset.file.name = fn asset.filename = fn asset.save() #make sure everything is in wav form only if mediatype is audio if mediatype == "audio": newfilename = convertaudio.convert_uploaded_file(fn) else: newfilename = fn if newfilename: #create the new asset if request comes in from a source other #than the django admin interface if not asset: #get location data from request latitude = get_parameter_from_request(request, 'latitude', False) longitude = get_parameter_from_request(request, 'longitude', False) #if no location data in request, default to project latitude and longitude if not latitude: latitude = session.project.latitude if not longitude: longitude = session.project.longitude tagset = [] tags = get_parameter_from_request(request, 'tags', False) if tags is not None: ids = tags.split(',') tagset = models.Tag.objects.filter(id__in=ids) # get optional submitted parameter from request (Y, N or blank string are only acceptable values) submitted = get_parameter_from_request(request, 'submitted', False) # set submitted variable to proper boolean value if it is passed as parameter if submitted == "N": submitted = False elif submitted == "Y": submitted = True # if blank string or not included as parameter, check if in range of project and if so # set asset.submitted based on project.auto_submit boolean value elif submitted is None or len(submitted) == 0: submitted = False if is_listener_in_range_of_stream(request.GET, session.project): submitted = session.project.auto_submit asset = models.Asset(latitude=latitude, longitude=longitude, filename=newfilename, session=session, submitted=submitted, mediatype=mediatype, volume=1.0, language=session.language, project=session.project) asset.file.name = fn asset.save() for t in tagset: asset.tags.add(t) #if the request comes from the django admin interface #update the Asset with the right information else: #update asset with session asset.session = session asset.filename = newfilename #get the audiolength of the file only if mediatype is audio and update the Asset if mediatype == "audio": discover_audiolength.discover_and_set_audiolength( asset, newfilename) asset.save() envelope.assets.add(asset) envelope.save() else: raise roundexception.RoundException( "File not converted successfully: " + newfilename) else: raise roundexception.RoundException("No file in request") rounddbus.emit_stream_signal(0, "refresh_recordings", "") return {"success": True, "asset_id": asset.id}
def request_stream(request): request_form = request.GET try: hostname_without_port = str(settings.config["external_host_name_without_port"]) except KeyError: raise roundexception.RoundException("Roundware configuration file is missing 'external_host_name_without_port' key. ") db.log_event("request_stream", int(request_form['session_id']), request_form) if not request_form.get('session_id'): raise roundexception.RoundException("Must supply session_id.") session = models.Session.objects.select_related('project').get(id=request_form.get('session_id')) project = session.project if session.demo_stream_enabled: msg = "demo_stream_message" try: msg = project.demo_stream_message_loc.filter(language=session.language)[0].localized_string except: pass if project.demo_stream_url: url = project.demo_stream_url else: url = "http://" + hostname_without_port + ":" + \ str(settings.config["icecast_port"]) + \ "/demo_stream.mp3" return { 'stream_url': url, 'demo_stream_message': msg } elif is_listener_in_range_of_stream(request_form, project): command = ['/usr/local/bin/streamscript', '--session_id', str(session.id), '--project_id', str(project.id)] for p in ['latitude', 'longitude', 'audio_format']: if request_form.has_key(p) and request_form[p]: command.extend(['--' + p, request_form[p].replace("\t", ",")]) if request_form.has_key('config'): command.extend(['--configfile', os.path.join(settings.configdir, request_form['config'])]) else: command.extend(['--configfile', os.path.join(settings.configdir, 'rw')]) if request_form.has_key('audio_stream_bitrate'): command.extend(['--audio_stream_bitrate', str(request_form['audio_stream_bitrate'])]) audio_format = project.audio_format.upper() apache_safe_daemon_subprocess(command) wait_for_stream(session.id, audio_format) return { "stream_url": "http://" + hostname_without_port + ":" + \ str(settings.config["icecast_port"]) + \ icecast_mount_point(session.id, audio_format), } else: msg = "This application is designed to be used in specific geographic locations. Apparently your phone thinks you are not at one of those locations, so you will hear a sample audio stream instead of the real deal. If you think your phone is incorrect, please restart Scapes and it will probably work. Thanks for checking it out!" try: msg = project.out_of_range_message_loc.filter(language=session.language)[0].localized_string except: pass if project.out_of_range_url: url = project.out_of_range_url else: url = "http://" + hostname_without_port + ":" + \ str(settings.config["icecast_port"]) + \ "/outofrange.mp3" return { 'stream_url': url, 'user_message': msg }
def heartbeat (request): form = request.GET rounddbus.emit_stream_signal(int(form['session_id']), "heartbeat", "") db.log_event("heartbeat", int(form['session_id']),form) return {"success":True}
def get_config(request): form = request.GET try: hostname_without_port = str( settings.config["external_host_name_without_port"]) except KeyError: raise roundexception.RoundException( "Roundware configuration file is missing 'external_host_name_without_port' key. " ) #check params if not form.has_key('project_id'): raise roundexception.RoundException( "a project_id is required for this operation") project = models.Project.objects.get(id=form.get('project_id')) speakers = models.Speaker.objects.filter( project=form.get('project_id')).values() audiotracks = models.Audiotrack.objects.filter( project=form.get('project_id')).values() if not form.has_key('device_id') or (form.has_key('device_id') and form['device_id'] == ""): device_id = str(uuid.uuid4()) else: device_id = form.get('device_id') l = models.Language.objects.filter(language_code='en')[0] if form.has_key('language') or (form.has_key('language') and form['language'] == ""): try: l = models.Language.objects.filter( language_code=form.get('language'))[0] except: pass s = models.Session(device_id=device_id, starttime=datetime.datetime.now(), project=project, language=l) if form.has_key('client_type'): s.client_type = form.get('client_type') if form.has_key('client_system'): s.client_system = form.get('client_system') sharing_url = str.format( "http://{0}/roundware/?operation=view_envelope&envelopeid=[id]", hostname_without_port) sharing_message = "none set" out_of_range_message = "none set" legal_agreement = "none set" demo_stream_message = "none set" try: sharing_message = project.sharing_message_loc.filter( language=l)[0].localized_string except: pass try: out_of_range_message = project.out_of_range_message_loc.filter( language=l)[0].localized_string except: pass try: legal_agreement = project.legal_agreement_loc.filter( language=l)[0].localized_string except: pass try: demo_stream_message = project.demo_stream_message_loc.filter( language=l)[0].localized_string except: pass cpu_idle = psutil.cpu_times_percent().idle s.demo_stream_enabled = project.demo_stream_enabled or cpu_idle < float( settings.config["demo_stream_cpu_limit"]) s.save() session_id = s.id response = [ { "device": { "device_id": device_id } }, { "session": { "session_id": session_id } }, { "project": { "project_id": project.id, "project_name": project.name, "audio_format": project.audio_format, "max_recording_length": project.max_recording_length, "recording_radius": project.recording_radius, "sharing_message": sharing_message, "out_of_range_message": out_of_range_message, "sharing_url": project.sharing_url, "listen_questions_dynamic": project.listen_questions_dynamic, "speak_questions_dynamic": project.speak_questions_dynamic, "listen_enabled": project.listen_enabled, "geo_listen_enabled": project.geo_listen_enabled, "speak_enabled": project.speak_enabled, "geo_speak_enabled": project.geo_speak_enabled, "reset_tag_defaults_on_startup": project.reset_tag_defaults_on_startup, "legal_agreement": legal_agreement, "files_url": project.files_url, "files_version": project.files_version, "audio_stream_bitrate": project.audio_stream_bitrate, # TODO: following attribute 'demo_stream_enabled' has be moved to the 'session' object "demo_stream_enabled": s.demo_stream_enabled, "demo_stream_url": project.demo_stream_url, "demo_stream_message": demo_stream_message, } }, { "server": { "version": "2.0" } }, { "speakers": [dict(d) for d in speakers] }, { "audiotracks": [dict(d) for d in audiotracks] } ] db.log_event('start_session', session_id, None) return response
def move_listener (form): db.log_event(1, form) request = form_to_request(form) arg_hack = json.dumps(request) rounddbus.emit_stream_signal(int(form['sessionid']), "move_listener", arg_hack) return True
def add_asset_to_envelope(request): #get asset_id from the GET request asset_id = get_parameter_from_request(request, 'asset_id', False) asset = None #grab the Asset from the database, if an asset_id has been passed in if asset_id: try: asset = models.Asset.objects.get(pk=asset_id) except models.Asset.DoesNotExist: raise roundexception.RoundException("Invalid Asset ID Provided. No Asset exists with ID %s" % asset_id) envelope_id = get_parameter_from_request(request, 'envelope_id', True) envelope = models.Envelope.objects.select_related('session').get(id=envelope_id) session = envelope.session db.log_event("start_upload", session.id, request.GET) fileitem = request.FILES.get('file') if not asset else asset.file #get mediatype from the GET request mediatype = get_parameter_from_request(request, 'mediatype', False) if not asset else asset.mediatype #if mediatype parameter not passed, set to 'audio' #this ensures backwards compatibility if mediatype is None: mediatype = "audio" if fileitem.name: #copy the file to a unique name (current time and date) logging.debug("Processing " + fileitem.name) (filename_prefix, filename_extension) = \ os.path.splitext(fileitem.name) fn = time.strftime("%Y%m%d-%H%M%S") + filename_extension fileout = open(os.path.join(settings.config["upload_dir"], fn), 'wb') fileout.write(fileitem.file.read()) fileout.close() #delete the uploaded original after the copy has been made if asset: asset.file.delete() # re-assign file to asset asset.file.name = fn asset.filename = fn asset.save() #make sure everything is in wav form only if mediatype is audio if mediatype == "audio": newfilename = convertaudio.convert_uploaded_file(fn) else: newfilename = fn if newfilename: #create the new asset if request comes in from a source other #than the django admin interface if not asset: #get location data from request latitude = get_parameter_from_request(request, 'latitude', False) longitude = get_parameter_from_request(request, 'longitude', False) #if no location data in request, default to project latitude and longitude if not latitude: latitude = session.project.latitude if not longitude: longitude = session.project.longitude tagset = [] tags = get_parameter_from_request(request, 'tags', False) if tags is not None: ids = tags.split(',') tagset = models.Tag.objects.filter(id__in=ids) # get optional submitted parameter from request (Y, N or blank string are only acceptable values) submitted = get_parameter_from_request(request, 'submitted', False) # set submitted variable to proper boolean value if it is passed as parameter if submitted == "N": submitted = False elif submitted == "Y": submitted = True # if blank string or not included as parameter, check if in range of project and if so # set asset.submitted based on project.auto_submit boolean value elif submitted is None or len(submitted) == 0: submitted = False if is_listener_in_range_of_stream(request.GET, session.project): submitted = session.project.auto_submit asset = models.Asset(latitude=latitude, longitude=longitude, filename=newfilename, session=session, submitted=submitted, mediatype=mediatype, volume=1.0, language=session.language, project = session.project) asset.file.name = fn asset.save() for t in tagset: asset.tags.add(t) #if the request comes from the django admin interface #update the Asset with the right information else: #update asset with session asset.session = session asset.filename = newfilename #get the audiolength of the file only if mediatype is audio and update the Asset if mediatype == "audio": discover_audiolength.discover_and_set_audiolength(asset, newfilename) asset.save() envelope.assets.add(asset) envelope.save() else: raise roundexception.RoundException("File not converted successfully: " + newfilename) else: raise roundexception.RoundException("No file in request") rounddbus.emit_stream_signal(0, "refresh_recordings", "") return {"success": True, "asset_id": asset.id}
def heartbeat(request): form = request.GET rounddbus.emit_stream_signal(int(form['session_id']), "heartbeat", "") db.log_event("heartbeat", int(form['session_id']), form) return {"success": True}
def heartbeat (form): db.log_event(2, form) rounddbus.emit_stream_signal(int(form['sessionid']), "heartbeat", "") return True #FIXME: return false if it failed. don't always return true
def request_stream(request): request_form = request.GET try: hostname_without_port = str( settings.config["external_host_name_without_port"]) except KeyError: raise roundexception.RoundException( "Roundware configuration file is missing 'external_host_name_without_port' key. " ) db.log_event("request_stream", int(request_form['session_id']), request_form) if not request_form.get('session_id'): raise roundexception.RoundException("Must supply session_id.") session = models.Session.objects.select_related('project').get( id=request_form.get('session_id')) project = session.project if session.demo_stream_enabled: msg = "demo_stream_message" try: msg = project.demo_stream_message_loc.filter( language=session.language)[0].localized_string except: pass if project.demo_stream_url: url = project.demo_stream_url else: url = "http://" + hostname_without_port + ":" + \ str(settings.config["icecast_port"]) + \ "/demo_stream.mp3" return {'stream_url': url, 'demo_stream_message': msg} elif is_listener_in_range_of_stream(request_form, project): command = [ '/usr/local/bin/streamscript', '--session_id', str(session.id), '--project_id', str(project.id) ] for p in ['latitude', 'longitude', 'audio_format']: if request_form.has_key(p) and request_form[p]: command.extend(['--' + p, request_form[p].replace("\t", ",")]) if request_form.has_key('config'): command.extend([ '--configfile', os.path.join(settings.configdir, request_form['config']) ]) else: command.extend( ['--configfile', os.path.join(settings.configdir, 'rw')]) if request_form.has_key('audio_stream_bitrate'): command.extend([ '--audio_stream_bitrate', str(request_form['audio_stream_bitrate']) ]) audio_format = project.audio_format.upper() apache_safe_daemon_subprocess(command) wait_for_stream(session.id, audio_format) return { "stream_url": "http://" + hostname_without_port + ":" + \ str(settings.config["icecast_port"]) + \ icecast_mount_point(session.id, audio_format), } else: msg = "This application is designed to be used in specific geographic locations. Apparently your phone thinks you are not at one of those locations, so you will hear a sample audio stream instead of the real deal. If you think your phone is incorrect, please restart Scapes and it will probably work. Thanks for checking it out!" try: msg = project.out_of_range_message_loc.filter( language=session.language)[0].localized_string except: pass if project.out_of_range_url: url = project.out_of_range_url else: url = "http://" + hostname_without_port + ":" + \ str(settings.config["icecast_port"]) + \ "/outofrange.mp3" return {'stream_url': url, 'user_message': msg}
def log_event (form): if form.has_key('eventtypeid'): eventtypeid = int(form['eventtypeid']) return db.log_event(eventtypeid, form) else: raise roundexception.RoundException("An eventtypeid is required for the log_event operation")
def get_config(request): form = request.GET try: hostname_without_port = str(settings.config["external_host_name_without_port"]) except KeyError: raise roundexception.RoundException("Roundware configuration file is missing 'external_host_name_without_port' key. ") #check params if not form.has_key('project_id'): raise roundexception.RoundException("a project_id is required for this operation") project = models.Project.objects.get(id=form.get('project_id')) speakers = models.Speaker.objects.filter(project=form.get('project_id')).values() audiotracks = models.Audiotrack.objects.filter(project=form.get('project_id')).values() if not form.has_key('device_id') or (form.has_key('device_id') and form['device_id'] == ""): device_id = str(uuid.uuid4()) else: device_id = form.get('device_id') l = models.Language.objects.filter(language_code='en')[0] if form.has_key('language') or (form.has_key('language') and form['language'] == ""): try: l = models.Language.objects.filter(language_code=form.get('language'))[0] except: pass s = models.Session(device_id=device_id, starttime=datetime.datetime.now(), project=project, language=l) if form.has_key('client_type'): s.client_type = form.get('client_type') if form.has_key('client_system'): s.client_system = form.get('client_system') sharing_url = str.format("http://{0}/roundware/?operation=view_envelope&envelopeid=[id]", hostname_without_port) sharing_message = "none set" out_of_range_message = "none set" legal_agreement = "none set" demo_stream_message = "none set" try: sharing_message = project.sharing_message_loc.filter(language=l)[0].localized_string except: pass try: out_of_range_message = project.out_of_range_message_loc.filter(language=l)[0].localized_string except: pass try: legal_agreement = project.legal_agreement_loc.filter(language=l)[0].localized_string except: pass try: demo_stream_message = project.demo_stream_message_loc.filter(language=l)[0].localized_string except: pass cpu_idle = psutil.cpu_times_percent().idle s.demo_stream_enabled = project.demo_stream_enabled or cpu_idle < float(settings.config["demo_stream_cpu_limit"]) s.save() session_id = s.id response = [ {"device":{"device_id": device_id}}, {"session":{"session_id": session_id}}, {"project":{ "project_id":project.id, "project_name":project.name, "audio_format":project.audio_format, "max_recording_length":project.max_recording_length, "recording_radius":project.recording_radius, "sharing_message":sharing_message, "out_of_range_message":out_of_range_message, "sharing_url":project.sharing_url, "listen_questions_dynamic":project.listen_questions_dynamic, "speak_questions_dynamic":project.speak_questions_dynamic, "listen_enabled":project.listen_enabled, "geo_listen_enabled":project.geo_listen_enabled, "speak_enabled":project.speak_enabled, "geo_speak_enabled":project.geo_speak_enabled, "reset_tag_defaults_on_startup":project.reset_tag_defaults_on_startup, "legal_agreement":legal_agreement, "files_url":project.files_url, "files_version":project.files_version, "audio_stream_bitrate":project.audio_stream_bitrate, # TODO: following attribute 'demo_stream_enabled' has be moved to the 'session' object "demo_stream_enabled":s.demo_stream_enabled, "demo_stream_url":project.demo_stream_url, "demo_stream_message":demo_stream_message, }}, {"server":{ "version": "2.0"}}, {"speakers":[dict(d) for d in speakers]}, {"audiotracks":[dict(d) for d in audiotracks]} ] db.log_event('start_session', session_id, None) return response