def editSpot(request, spot_key=None):
    spot = AutoRetry(models.Spot).get(spot_key)
    user = auth.get_current_user(request)
    if request.method ==  'POST':
        spot_form = forms.SpotForm(request.POST)
        constraint_form = forms.SpotConstraintForm(request.POST)
        # check if spot is changed
        # check if new constraint to be added
        if spot_form.is_valid():
            for field in spot_form.fields.keys():
                setattr(spot,field,spot_form.cleaned_data[field])
                spot.author = user
                AutoRetry(models.Spot).put(spot)

        if constraint_form.is_valid():
            connectConstraintsAndSpot(
                saveConstraint(constraint_form.cleaned_data), spot.key()
                )
            
        return HttpResponseRedirect('/traffic_log/spot/%s'%spot.key())
    else:
        return render_to_response('traffic_log/create_edit_spot.html', 
                      context(spot=forms.SpotForm(instance=spot),
                              spot_key=spot_key,
                              constraints=spot.constraints,
                              constraint_form=forms.SpotConstraintForm(),
                              edit=True,
                              dow_dict=constants.DOW_DICT,
                              formaction="/traffic_log/spot/edit/%s"%spot.key()
                              ), context_instance=RequestContext(request))
Exemple #2
0
def editSpot(request, spot_key=None):
    spot = AutoRetry(models.Spot).get(spot_key)
    user = auth.get_current_user(request)
    if request.method == 'POST':
        spot_form = forms.SpotForm(request.POST)
        constraint_form = forms.SpotConstraintForm(request.POST)
        # check if spot is changed
        # check if new constraint to be added
        if spot_form.is_valid():
            for field in spot_form.fields.keys():
                setattr(spot, field, spot_form.cleaned_data[field])
                spot.author = user
                AutoRetry(models.Spot).put(spot)

        if constraint_form.is_valid():
            connectConstraintsAndSpot(
                saveConstraint(constraint_form.cleaned_data), spot.key())

        return HttpResponseRedirect('/traffic_log/spot/%s' % spot.key())
    else:
        return render_to_response(
            'traffic_log/create_edit_spot.html',
            context(spot=forms.SpotForm(instance=spot),
                    spot_key=spot_key,
                    constraints=spot.constraints,
                    constraint_form=forms.SpotConstraintForm(),
                    edit=True,
                    dow_dict=constants.DOW_DICT,
                    formaction="/traffic_log/spot/edit/%s" % spot.key()),
            context_instance=RequestContext(request))
def finishReadingSpotCopy(request, spot_copy_key=None):
    dow, hour, slot = _get_slot_from_request(request)
    
    # Check if a single spot constraint exists for the dow, hour, slot.
    q = (models.SpotConstraint.all()
                    .filter("dow =", dow)
                    .filter("hour =", hour)
                    .filter("slot =", slot))
    count = AutoRetry(q).count(1) 
    if count == 0:
        raise ValueError("No spot constraint found for dow=%r, hour=%r, slot=%r" % (
                                                                    dow, hour, slot))
    elif count > 1:
        # kumar: not sure if this will actually happen
        raise ValueError("Multiple spot constraints found for dow=%r, hour=%r, slot=%r" % (
                                                                    dow, hour, slot))
    
    constraint = AutoRetry(q).fetch(1)[0]

    spot_copy = AutoRetry(models.SpotCopy).get(spot_copy_key)

    # Check if spot has already been read (i.e., logged).
    today = time_util.chicago_now().date()
    q = (models.TrafficLogEntry.all()
                    .filter("log_date =", today)
                    .filter("spot =", spot_copy.spot)
                    .filter("dow =", dow)
                    .filter("hour =", hour)
                    .filter("slot =", slot))
    if AutoRetry(q).count(1):
        existing_logged_spot = AutoRetry(q).fetch(1)[0]
        raise RuntimeError("This spot %r at %r has already been read %s" % (
                    spot_copy.spot, constraint, existing_logged_spot.reader))

    # Remove spot copy from the spot's list.
    spot_copy.spot.finish_spot_copy()
	
    # Log spot read.
    logged_spot = models.TrafficLogEntry(
        log_date = today,
        spot = spot_copy.spot,
        spot_copy = spot_copy,
        dow = dow,
        hour = hour,
        slot = slot,
        scheduled = constraint,
        readtime = time_util.chicago_now(), 
        reader = auth.get_current_user(request)
    )
    AutoRetry(logged_spot).put()
    
    return {
        'spot_copy_key': str(spot_copy.key()), 
        'spot_constraint_key': str(constraint.key()),
        'logged_spot': str(logged_spot.key())
    }
Exemple #4
0
def finishReadingSpotCopy(request, spot_copy_key=None):
    dow, hour, slot = _get_slot_from_request(request)

    # Check if a single spot constraint exists for the dow, hour, slot.
    q = (models.SpotConstraint.all().filter("dow =", dow).filter(
        "hour =", hour).filter("slot =", slot))
    count = AutoRetry(q).count(1)
    if count == 0:
        raise ValueError(
            "No spot constraint found for dow=%r, hour=%r, slot=%r" %
            (dow, hour, slot))
    elif count > 1:
        # kumar: not sure if this will actually happen
        raise ValueError(
            "Multiple spot constraints found for dow=%r, hour=%r, slot=%r" %
            (dow, hour, slot))

    constraint = AutoRetry(q).fetch(1)[0]

    spot_copy = AutoRetry(models.SpotCopy).get(spot_copy_key)

    # Check if spot has already been read (i.e., logged).
    today = time_util.chicago_now().date()
    q = (models.TrafficLogEntry.all().filter("log_date =", today).filter(
        "spot =",
        spot_copy.spot).filter("dow =",
                               dow).filter("hour =",
                                           hour).filter("slot =", slot))
    if AutoRetry(q).count(1):
        existing_logged_spot = AutoRetry(q).fetch(1)[0]
        raise RuntimeError(
            "This spot %r at %r has already been read %s" %
            (spot_copy.spot, constraint, existing_logged_spot.reader))

    # Remove spot copy from the spot's list.
    spot_copy.spot.finish_spot_copy()

    # Log spot read.
    logged_spot = models.TrafficLogEntry(log_date=today,
                                         spot=spot_copy.spot,
                                         spot_copy=spot_copy,
                                         dow=dow,
                                         hour=hour,
                                         slot=slot,
                                         scheduled=constraint,
                                         readtime=time_util.chicago_now(),
                                         reader=auth.get_current_user(request))
    AutoRetry(logged_spot).put()

    return {
        'spot_copy_key': str(spot_copy.key()),
        'spot_constraint_key': str(constraint.key()),
        'logged_spot': str(logged_spot.key())
    }
def deleteSpot(request, spot_key=None):
    spot = AutoRetry(models.Spot).get(spot_key)
    spot.active = False
    AutoRetry(spot).save()
    
    # remove the spot from its constraints:
    for constraint in AutoRetry(models.SpotConstraint.all().filter("spots IN", [spot.key()])):
        active_spots = []
        for spot_key in constraint.spots:
            if spot_key != spot.key():
                active_spots.append(spot_key)
        constraint.spots = active_spots
        AutoRetry(constraint).save()
        
    return HttpResponseRedirect('/traffic_log/spot')
Exemple #6
0
def deleteSpot(request, spot_key=None):
    spot = AutoRetry(models.Spot).get(spot_key)
    spot.active = False
    AutoRetry(spot).save()

    # remove the spot from its constraints:
    for constraint in AutoRetry(models.SpotConstraint.all().filter(
            "spots IN", [spot.key()])):
        active_spots = []
        for spot_key in constraint.spots:
            if spot_key != spot.key():
                active_spots.append(spot_key)
        constraint.spots = active_spots
        AutoRetry(constraint).save()

    return HttpResponseRedirect('/traffic_log/spot')
def saveConstraint(constraint):
    dows = [ int(x) for x in constraint['dow_list'] ]
    hours = constraint['hour_list']
    keys = []
    slot = int(constraint['slot'])
    for d in dows:
        for h in hours:
            name = ":".join([constants.DOW_DICT[d],str(h), str(slot)])
            obj  = AutoRetry(models.SpotConstraint).get_or_insert(name,dow=d,hour=int(h),slot=slot)
            if not obj.is_saved():
                AutoRetry(obj).put()
            keys.append(obj.key())
    return keys
Exemple #8
0
def saveConstraint(constraint):
    dows = [int(x) for x in constraint['dow_list']]
    hours = constraint['hour_list']
    keys = []
    slot = int(constraint['slot'])
    for d in dows:
        for h in hours:
            name = ":".join([constants.DOW_DICT[d], str(h), str(slot)])
            obj = AutoRetry(models.SpotConstraint).get_or_insert(name,
                                                                 dow=d,
                                                                 hour=int(h),
                                                                 slot=slot)
            if not obj.is_saved():
                AutoRetry(obj).put()
            keys.append(obj.key())
    return keys
Exemple #9
0
def send_track_to_live365(request):
    """
    Background Task URL to send playlist to Live 365 service.

    This view expects POST parameters:

    **id**
    The Datastore key of the playlist entry

    When POSTing to Live 365 here are the parameters:

    **member_name**
    Live365 member name

    **password**
    Live365 password

    **sessionid**
    Unused.  This is an alternative to user password and looks like
    membername:sessionkey as returned by api_login.cgi

    **version**
    Version of API request.  Currently this must be 2

    **filename**
    I think we can leave this blank because Live365 docs say they
    will use it to guess song and artist info if none was sent.

    **seconds**
    Length of the track in seconds.  Live365 uses this to refresh its
    popup player window thing.  So really we should probably set this to 60 or 120
    because DJs might be submitting playlist entries out of sync with when
    they are actually playing the songs.

    **title**
    Song title

    **artist**
    Artist name

    **album**
    Album title
    """
    track = AutoRetry(PlaylistEvent).get(request.POST['id'])
    if not track:
        log.warning("Requested to create a non-existant track of ID %r" % request.POST['id'])
        # this is not an error (malicious POST, etc), so make sure the task succeeds:
        return task_response({'success':True})

    log.info("Live365 create track %s" % track.key())

    qs = {
        'member_name': dbconfig['live365.member_name'],
        'password': dbconfig['live365.password'],
        'version': 2,
        'seconds': 30,
        'title': as_encoded_str(track.track_title, encoding='latin-1', errors="ignore"),
        'artist': as_encoded_str(track.artist_name, encoding='latin-1', errors="ignore"),
        'album': as_encoded_str(track.album_title, encoding='latin-1', errors="ignore")
    }
    data = urllib.urlencode(qs)
    headers = {"Content-type": "application/x-www-form-urlencoded"}
    # in prod: http://www.live365.com/cgi-bin/add_song.cgi
    service_url = dbconfig['live365.service_url']
    result = _fetch_url(url=service_url, method='POST', data=data, headers=headers)
    return task_response(result)
Exemple #10
0
def send_track_to_live365(request):
    """
    Background Task URL to send playlist to Live 365 service.

    This view expects POST parameters:

    **id**
    The Datastore key of the playlist entry

    When POSTing to Live 365 here are the parameters:

    **member_name**
    Live365 member name

    **password**
    Live365 password

    **sessionid**
    Unused.  This is an alternative to user password and looks like
    membername:sessionkey as returned by api_login.cgi

    **version**
    Version of API request.  Currently this must be 2

    **filename**
    I think we can leave this blank because Live365 docs say they
    will use it to guess song and artist info if none was sent.

    **seconds**
    Length of the track in seconds.  Live365 uses this to refresh its
    popup player window thing.  So really we should probably set this to 60 or 120
    because DJs might be submitting playlist entries out of sync with when
    they are actually playing the songs.

    **title**
    Song title

    **artist**
    Artist name

    **album**
    Album title
    """
    track = AutoRetry(PlaylistEvent).get(request.POST['id'])
    if not track:
        log.warning("Requested to create a non-existant track of ID %r" %
                    request.POST['id'])
        # this is not an error (malicious POST, etc), so make sure the task succeeds:
        return task_response({'success': True})

    log.info("Live365 create track %s" % track.key())

    qs = {
        'member_name':
        dbconfig['live365.member_name'],
        'password':
        dbconfig['live365.password'],
        'version':
        2,
        'seconds':
        30,
        'title':
        as_encoded_str(track.track_title, encoding='latin-1', errors="ignore"),
        'artist':
        as_encoded_str(track.artist_name, encoding='latin-1', errors="ignore"),
        'album':
        as_encoded_str(track.album_title, encoding='latin-1', errors="ignore")
    }
    data = urllib.urlencode(qs)
    headers = {"Content-type": "application/x-www-form-urlencoded"}
    # in prod: http://www.live365.com/cgi-bin/add_song.cgi
    service_url = dbconfig['live365.service_url']
    result = _fetch_url(url=service_url,
                        method='POST',
                        data=data,
                        headers=headers)
    return task_response(result)