def is_nearby(self, listener, recording):
        if 'latitude' in listener and listener['latitude'] \
                and listener['longitude']:
            distance = gpsmixer.distance_in_meters(
                listener['latitude'], listener['longitude'],
                recording.latitude, recording.longitude)

            return distance <= self.radius
        else:
            return True
    def is_nearby(self, listener, recording):
        if 'latitude' in listener and listener['latitude'] \
                and listener['longitude']:
            distance = gpsmixer.distance_in_meters(listener['latitude'],
                                                   listener['longitude'],
                                                   recording.latitude,
                                                   recording.longitude)

            return distance <= self.radius
        else:
            return True
예제 #3
0
	def is_nearby (self, listener, recording):
		if listener.has_key('latitude') \
			and listener['latitude'] \
			and listener['longitude']:

			distance = gpsmixer.distance_in_meters(
				listener['latitude'], listener['longitude'],
				recording['latitude'], recording['longitude'])

			return distance <= VOICE_RADIUS
		else:
			return True
예제 #4
0
def is_listener_in_range_of_stream (form):
	if not form.get('latitude') or not form.get('latitude'):
		return True
	speakers = db.get_speakers(form['categoryid'])
	for speaker in speakers:
		distance = gpsmixer.distance_in_meters(
				float(form['latitude']),
				float(form['longitude']),
				speaker['latitude'],
				speaker['longitude'])
		if not distance > 3 * speaker['maxdistance']:
			return True
	return False
예제 #5
0
def is_listener_in_range_of_stream (form, proj):
	if not form.get('latitude') or not form.get('latitude'):
		return True
	speakers = models.Speaker.objects.filter(project=proj)
	
	for speaker in speakers:
		distance = gpsmixer.distance_in_meters(
				float(form['latitude']),
				float(form['longitude']),
				speaker.latitude,
				speaker.longitude)
		if not distance > 3 * speaker.maxdistance:
			return True
	return False
예제 #6
0
def is_listener_in_range_of_stream(form, proj):
    # If latitude and longitude is not specified assume True.
    if not ("latitude" in form and "longitude" in form) or not (form["latitude"] and form["longitude"]):
        return True
    # Get all active speakers
    speakers = models.Speaker.objects.filter(project=proj, activeyn=True)

    for speaker in speakers:
        distance = gpsmixer.distance_in_meters(
            float(form["latitude"]), float(form["longitude"]), speaker.latitude, speaker.longitude
        )
        if distance < 3 * speaker.maxdistance:
            return True
    return False
예제 #7
0
def is_listener_in_range_of_stream(form, proj):
    if not ('latitude' in form and 'longitude'
            in form) or not (form['latitude'] and form['longitude']):
        return True
    speakers = models.Speaker.objects.filter(project=proj, activeyn=True)

    for speaker in speakers:
        #only do this if latitude and longitude are included, return False otherwise
        distance = gpsmixer.distance_in_meters(float(form['latitude']),
                                               float(form['longitude']),
                                               speaker.latitude,
                                               speaker.longitude)
        if distance < 3 * speaker.maxdistance:
            return True
    return False
예제 #8
0
def is_listener_in_range_of_stream(form, proj):
    if not ('latitude' in form and 'longitude' in form) or not (form['latitude'] and form['longitude']):
        return True
    speakers = models.Speaker.objects.filter(project=proj, activeyn=True)

    for speaker in speakers:
        #only do this if latitude and longitude are included, return False otherwise
        distance = gpsmixer.distance_in_meters(
            float(form['latitude']),
            float(form['longitude']),
            speaker.latitude,
            speaker.longitude)
        if distance < 3 * speaker.maxdistance:
            return True
    return False
예제 #9
0
def is_listener_in_range_of_stream(form, proj):
    # If latitude and longitude is not specified assume True.
    if not ('latitude' in form and 'longitude'
            in form) or not (form['latitude'] and form['longitude']):
        return True
    # Get all active speakers
    speakers = models.Speaker.objects.filter(project=proj, activeyn=True)

    for speaker in speakers:
        distance = gpsmixer.distance_in_meters(float(form['latitude']),
                                               float(form['longitude']),
                                               speaker.latitude,
                                               speaker.longitude)
        if distance < 3 * speaker.maxdistance:
            return True
    return False
예제 #10
0
def get_available_assets(request):
    """Return JSON serializable dictionary with the number of matching assets
    by media type and a list of available assets based on filter criteria passed in
    request.  If asset_id is passed, ignore other filters and return single
    asset.  If multiple, comma-separated values for asset_id are passed, ignore
    other filters and return all those assets.  If envelope_id is passed, ignore
    other filters and return all assets in that envelope.  If multiple,
    comma-separated values for envelope_id are passed, ignore
    other filters and return all those assets.  Returns localized
    value for tag strings on asset by asset basis unless a specific language
    code is passed. Fall back to English if necessary."""
    def _get_best_localized_string(asset, tag, best_lang_id):
        """ Return localized string with specified language code.
            If that's not available, look for a language field on the model and
            use that.  If that's not available, fall back to English.
        """
        try:
            localization = tag.loc_msg.get(language=best_lang_id)
        except models.LocalizedString.DoesNotExist:
            # try object's specified language
            asset_lang = asset.language
            if asset_lang and retlng != asset_lang:
                localization = tag.loc_msg.get(language=asset_lang)
            else:
                # fall back to English
                eng_id = models.Language.objects.get(language_code='en')
                localization = tag.loc_msg.get(language=eng_id)
        return localization.localized_string

    form = request.GET
    kw = {}

    known_params = [
        'project_id', 'latitude', 'longitude', 'tag_ids', 'tagbool', 'radius',
        'language', 'asset_id', 'envelope_id'
    ]
    project_id = get_parameter_from_request(request, 'project_id')
    asset_id = get_parameter_from_request(request, 'asset_id')
    envelope_id = get_parameter_from_request(request, 'envelope_id')
    latitude = get_parameter_from_request(request, 'latitude')
    longitude = get_parameter_from_request(request, 'longitude')
    radius = get_parameter_from_request(request, 'radius')
    tag_ids = get_parameter_from_request(request, 'tagids')
    tagbool = get_parameter_from_request(request, 'tagbool')
    language = get_parameter_from_request(request, 'language')
    if (latitude and not longitude) or (longitude and not latitude):
        raise RoundException(
            "This operation requires that you pass both latitude and "
            "longitude, if you pass either one.")

    # accept other keyword parameters as long as the keys are fields on
    # Asset model
    asset_fields = models.get_field_names_from_model(models.Asset)
    asset_media_types = [tup[0] for tup in models.Asset.ASSET_MEDIA_TYPES]
    extraparams = [(param[0], param[1]) for param in form.items()
                   if param[0] not in known_params and param[0] in asset_fields
                   ]
    extras = {}
    for k, v in extraparams:
        extras[str(k)] = str(v)

    # if a language (code) is specified, use that
    # otherwise, return localized value specific to Asset
    qry_retlng = None
    if language:
        try:
            qry_retlng = models.Language.objects.get(language_code=language)
            lng_id = models.Language.objects.get(language_code=language)
        except models.Language.DoesNotExist:
            raise RoundException("Specified language code does not exist.")
    else:
        # default to English if no language parameter present
        lng_id = 1

    if asset_id:
        # ignore all other filter criteria
        assets = models.Asset.objects.filter(id__in=asset_id.split(','))

    elif envelope_id:
        assets = []
        envelopes = models.Envelope.objects.filter(
            id__in=envelope_id.split(','))
        for e in envelopes:
            e_assets = e.assets.all()
            for a in e_assets:
                if a not in assets:
                    assets.append(a)

    elif project_id:
        project = models.Project.objects.get(id=project_id)
        kw['project__exact'] = project

        assets = models.Asset.objects.filter(**kw)
        if tag_ids:
            if tagbool and str(tagbool).lower() == 'or':
                assets = assets.filter(tags__in=tag_ids.split(',')).distinct()
            else:
                # 'and'.  Asset must have all tags
                for tag_id in tag_ids.split(','):
                    assets = assets.filter(tags__id=tag_id)

        # filter by extra params. These are chained with an AND
        assets = assets.filter(**extras)

        if latitude and longitude:  # need both
            # return only assets within specified or default radius
            # by project
            latitude = float(latitude)
            longitude = float(longitude)
            if not radius:
                radius = project.recording_radius
                if not radius:
                    raise RoundException("Project does not specify a "
                                         "radius and no radius parameter "
                                         "passed to operation.")
            radius = float(radius)
            for asset in assets:
                distance = gpsmixer.distance_in_meters(latitude, longitude,
                                                       asset.latitude,
                                                       asset.longitude)
                if distance > radius:
                    assets = assets.exclude(id=asset.id)
    else:
        raise RoundException("This operation requires that you pass a "
                             "project_id, asset_id, or envelope_id")

    assets_info = {}
    assets_info['number_of_assets'] = {}
    for mtype in asset_media_types:
        assets_info['number_of_assets'][mtype] = 0
    assets_list = []

    for asset in assets:
        loc_desc = t("", asset.loc_description, lng_id)

        if asset.mediatype in asset_media_types:
            assets_info['number_of_assets'][asset.mediatype] += 1
        if not qry_retlng:
            retlng = asset.language  # can be None
        else:
            retlng = qry_retlng
        assets_list.append(
            dict(asset_id=asset.id,
                 asset_url='%s%s' % (settings.MEDIA_URL, asset.filename),
                 latitude=asset.latitude,
                 longitude=asset.longitude,
                 audio_length=asset.audiolength,
                 submitted=asset.submitted,
                 mediatype=asset.mediatype,
                 description=asset.description,
                 loc_description=loc_desc,
                 project=asset.project.name,
                 language=asset.language.language_code,
                 tags=[
                     dict(tag_category_name=tag.tag_category.name,
                          tag_id=tag.id,
                          localized_value=_get_best_localized_string(
                              asset, tag, retlng)) for tag in asset.tags.all()
                 ]), )
    assets_info['assets'] = assets_list
    return assets_info
예제 #11
0
 def distance(self, listener):
     return distance_in_meters(self.latitude, self.longitude,
                               listener['latitude'], listener['longitude'])
예제 #12
0
 def distance(self, listener):
     return distance_in_meters(self.latitude, self.longitude,
                               listener['latitude'], listener['longitude'])
예제 #13
0
def get_available_assets(request):
    """Return JSON serializable dictionary with the number of matching assets
    by media type and a list of available assets based on filter criteria passed in
    request.  If asset_id is passed, ignore other filters and return single
    asset.  If multiple, comma-separated values for asset_id are passed, ignore
    other filters and return all those assets.  If envelope_id is passed, ignore
    other filters and return all assets in that envelope.  If multiple, 
    comma-separated values for envelope_id are passed, ignore
    other filters and return all those assets.  Returns localized
    value for tag strings on asset by asset basis unless a specific language
    code is passed. Fall back to English if necessary."""
    

    def _get_best_localized_string(asset, tag, best_lang_id):
        """ Return localized string with specified language code.
            If that's not available, look for a language field on the model and
            use that.  If that's not available, fall back to English. 
        """
        try:
            localization = tag.loc_msg.get(language=best_lang_id)
        except models.LocalizedString.DoesNotExist:
            # try object's specified language
            asset_lang =  asset.language
            if asset_lang and retlng != asset_lang:
                localization = tag.loc_msg.get(language=asset_lang)
            else:
                # fall back to English
                eng_id = models.Language.objects.get(language_code='en')
                localization = tag.loc_msg.get(language=eng_id)
        return localization.localized_string

    form = request.GET
    kw = {}
    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. ")

    known_params = ['project_id', 'latitude', 'longitude',
                    'tag_ids', 'tagbool', 'radius', 'language', 'asset_id',
                    'envelope_id' ]
    project_id = get_parameter_from_request(request, 'project_id', None)
    asset_id = get_parameter_from_request(request, 'asset_id', None)
    envelope_id = get_parameter_from_request(request, 'envelope_id', None)
    latitude = get_parameter_from_request(request, 'latitude', None)
    longitude = get_parameter_from_request(request, 'longitude', None)
    radius = get_parameter_from_request(request, 'radius', None)
    tag_ids = get_parameter_from_request(request, 'tagids', None)
    tagbool = get_parameter_from_request(request, 'tagbool', None)
    language = get_parameter_from_request(request, 'language', None)
    if (latitude and not longitude) or (longitude and not latitude):
        raise roundexception.RoundException(
            "This operation requires that you pass both latitude and "
            "longitude, if you pass either one.")

    # accept other keyword parameters as long as the keys are fields on
    # Asset model
    asset_fields = models.get_field_names_from_model(models.Asset)
    asset_media_types = [tup[0] for tup in models.Asset.ASSET_MEDIA_TYPES]
    extraparams = [(param[0], param[1]) for param in form.items()
                if param[0] not in known_params and
                param[0] in asset_fields]
    extras = {}
    for k, v in extraparams:
        extras[str(k)] = str(v)

    # if a language (code) is specified, use that
    # otherwise, return localized value specific to Asset    
    qry_retlng = None
    if language:
        try:
            qry_retlng = models.Language.objects.get(language_code=language)
        except models.Language.DoesNotExist:
            raise roundexception.RoundException(
                "Specified language code does not exist."
            )

    if project_id or asset_id or envelope_id:
        
        # by asset
        if asset_id:
            # ignore all other filter criteria
            assets = models.Asset.objects.filter(id__in=asset_id.split(','))
        
        # by envelope    
        elif envelope_id:
            assets = []
            envelopes = models.Envelope.objects.filter(id__in=envelope_id.split(','))
            for e in envelopes:
                e_assets = e.assets.all()
                for a in e_assets:
                    if a not in assets:
                        assets.append(a)
        
        # by project
        elif project_id:
            project = models.Project.objects.get(id=project_id)
            kw['project__exact'] = project
            
            assets = models.Asset.objects.filter(**kw)
            if tag_ids:
                if tagbool and str(tagbool).lower() == 'or':
                    assets = assets.filter(tags__in=tag_ids.split(',')).distinct()
                else:
                    # 'and'.  Asset must have all tags
                    for tag_id in tag_ids.split(','):
                        assets = assets.filter(tags__id=tag_id)

            # filter by extra params. These are chained with an AND
            assets = assets.filter(**extras)

            if latitude and longitude:  # need both
                # return only assets within specified or default radius
                # by project
                latitude = float(latitude)
                longitude = float(longitude)
                if not radius:
                    radius = project.recording_radius
                    if not radius:
                        raise roundexception.RoundException("Project does not "
                            "specify a radius and no radius parameter passed to "
                            "operation.")
                radius = float(radius)
                for asset in assets:
                    distance = gpsmixer.distance_in_meters(
                        latitude, longitude,
                        asset.latitude, asset.longitude)
                    if distance > radius:
                        assets = assets.exclude(id=asset.id)

        assets_info = {}
        assets_info['number_of_assets'] = {}
        for mtype in asset_media_types:
            assets_info['number_of_assets'][mtype]= 0
        assets_list = []

        for asset in assets:
            if asset.mediatype in asset_media_types:
                assets_info['number_of_assets'][asset.mediatype] +=1
            if not qry_retlng:
                retlng = asset.language # can be None
            else:
                retlng = qry_retlng
            assets_list.append(
                dict(asset_id=asset.id,
                     asset_url='%s%s' % (
                         rw_settings.AUDIO_FILE_URI, asset.filename),
                     latitude=asset.latitude,
                     longitude=asset.longitude,
                     audio_length=asset.audiolength,
                     submitted=asset.submitted,
                     project=asset.project.name,
                     language=asset.language.language_code,
                     tags=[dict(
                         tag_category_name=tag.tag_category.name,
                         tag_id=tag.id,
                         localized_value=_get_best_localized_string(
                             asset, tag, retlng)
                     ) for tag in asset.tags.all()]),
            )
        assets_info['assets'] = assets_list
        return assets_info

    else:
        raise roundexception.RoundException("This operation requires that you "
            "pass a project_id, asset_id, or envelope_id")