Esempio n. 1
0
    def test_finish_spot(self):
        self.assertEqual(list(models.TrafficLogEntry.all().fetch(5)), [])

        author = User(email='test')
        author.save()
        spot = models.Spot(
                        title='Legal ID',
                        type='Station ID',
                        author=author)
        spot.put()

        # make a constraint closest to now:
        now = time_util.chicago_now()
        today = now.date()
        current_hour = now.hour
        constraint = models.SpotConstraint(
            dow=today.isoweekday(), hour=current_hour, slot=0, spots=[spot.key()])
        constraint.put()

        spot_copy = models.SpotCopy(
                        body='You are listening to chirpradio.org',
                        spot=spot,
                        author=author)
        spot_copy.put()

        spot.random_spot_copies = [spot_copy.key()]
        spot.save()

        resp = self.client.get(reverse('traffic_log.index'))
        # unfinished spot should have been marked in static HTML:
        assert '<tr class="new">' in resp.content

        resp = self.client.get(reverse('traffic_log.finishReadingSpotCopy', args=(spot_copy.key(),)), {
            'hour': constraint.hour,
            'dow': constraint.dow,
            'slot': constraint.slot
        })
        logged = models.TrafficLogEntry.all().fetch(1)[0]
        self.assertEqual(logged.reader.email, "*****@*****.**")
        self.assertEqual(logged.readtime.timetuple()[0:5], datetime.datetime.now().timetuple()[0:5])
        self.assertEqual(logged.log_date, time_util.chicago_now().date())
        self.assertEqual(logged.spot.key(), spot.key())
        self.assertEqual(logged.spot_copy.key(), spot_copy.key())
        self.assertEqual(logged.scheduled.key(), constraint.key())
        self.assertEqual(logged.hour, constraint.hour)
        self.assertEqual(logged.dow, constraint.dow)

        resp = self.client.get(reverse('traffic_log.index'))
        # finished spot should have been marked in static HTML:
        assert '<tr class="finished">' in resp.content

        resp = self.client.get(reverse('traffic_log.spotTextForReading', args=(spot.key(),)), {
            'hour': constraint.hour,
            'dow': constraint.dow,
            'slot': constraint.slot
        })
        context = resp.context
        # already finished, no need for finish URL:
        self.assertEqual(context['url_to_finish_spot'], None)
        assert '(already finished)' in resp.content
Esempio n. 2
0
    def setUp(self):
        assert self.client.login(email="*****@*****.**",
                                 roles=[roles.TRAFFIC_LOG_ADMIN])

        author = User(email='test')
        author.save()
        self.author = author
        spot = models.Spot(title='Legal ID', type='Station ID', author=author)
        self.spot = spot
        spot.put()

        self.now = time_util.chicago_now()
        self.today = self.now.date()
        self.dow = self.today.isoweekday()

        constraint = self.add_spot_to_constraint(spot)
        self.constraint = constraint
        spot_copy = models.SpotCopy(body='You are listening to chirpradio.org',
                                    spot=spot,
                                    author=author)
        self.spot_copy = spot_copy
        spot_copy.put()
        spot.random_spot_copies = [spot_copy.key()]
        spot.save()

        logged_spot = models.TrafficLogEntry(log_date=self.today,
                                             spot=spot_copy.spot,
                                             spot_copy=spot_copy,
                                             dow=self.dow,
                                             hour=self.now.hour,
                                             slot=0,
                                             scheduled=constraint,
                                             readtime=time_util.chicago_now(),
                                             reader=author)
        logged_spot.put()
Esempio n. 3
0
    def setUp(self):
        assert self.client.login(email="*****@*****.**", roles=[roles.TRAFFIC_LOG_ADMIN])

        author = User(email="test")
        author.save()
        self.author = author
        spot = models.Spot(title="Legal ID", type="Station ID", author=author)
        self.spot = spot
        spot.put()

        self.now = time_util.chicago_now()
        self.today = self.now.date()
        self.dow = self.today.isoweekday()

        constraint = self.add_spot_to_constraint(spot)
        self.constraint = constraint
        spot_copy = models.SpotCopy(body="You are listening to chirpradio.org", spot=spot, author=author)
        self.spot_copy = spot_copy
        spot_copy.put()
        spot.random_spot_copies = [spot_copy.key()]
        spot.save()

        logged_spot = models.TrafficLogEntry(
            log_date=self.today,
            spot=spot_copy.spot,
            spot_copy=spot_copy,
            dow=self.dow,
            hour=self.now.hour,
            slot=0,
            scheduled=constraint,
            readtime=time_util.chicago_now(),
            reader=author,
        )
        logged_spot.put()
Esempio n. 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())
    }
Esempio n. 5
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())
    }
Esempio n. 6
0
    def test_create_edit_spot_copy_expiry(self):
        dow = 1
        hour = 0
        slot = 0
        spot = models.Spot(
                        title='Legal ID',
                        type='Station ID')
        spot.put()
        constraint = models.SpotConstraint(dow=dow, hour=hour, slot=slot, spots=[spot.key()])
        constraint.put()

        now = time_util.chicago_now() + datetime.timedelta(hours=2)
        resp = self.client.post(reverse('traffic_log.views.addCopyForSpot', args=(spot.key(),)), {
            'spot_key': spot.key(),
            'body': 'You are listening to chirprario.odg',
            'underwriter': 'pretend this is an underwriter',
            'expire_on': now.strftime("%m/%d/%Y %H:%M:%S") # no timezone info
        })
        self.assertNoFormErrors(resp)

        spot_copy, is_logged = spot.get_spot_copy(dow, hour, slot)
        converted_expire_on = time_util.convert_utc_to_chicago(spot_copy.expire_on)
        self.assertEqual(converted_expire_on.timetuple(), now.timetuple())

        resp = self.client.post(reverse('traffic_log.editSpotCopy', args=(spot_copy.key(),)), {
            'spot_key': spot.key(),
            'body': 'You are listening to chirprario.odg',
            'underwriter': 'pretend this is an underwriter',
            'expire_on': spot_copy.expire_on.strftime("%m/%d/%Y %H:%M:%S") # no timezone info
        })
        self.assertNoFormErrors(resp)

        spot_copy, is_logged = spot.get_spot_copy(dow, hour, slot)
        converted_expire_on = time_util.convert_utc_to_chicago(spot_copy.expire_on)
        self.assertEqual(converted_expire_on.timetuple(), now.timetuple())
Esempio n. 7
0
    def test_landing_page_shows_spots(self):
        user = User(email='test')
        user.save()
        spot = models.Spot(title='Legal ID', type='Station ID')
        spot_key = spot.put()
        # assign it to every day of the week at the top of the hour:
        constraint_keys = views.saveConstraint(
            dict(hour_list=range(0, 24), dow_list=range(1, 8), slot=0))
        views.connectConstraintsAndSpot(constraint_keys, spot_key)

        spot_copy = models.SpotCopy(body='body', spot=spot, author=user)
        spot_copy.put()

        resp = self.client.get(reverse('traffic_log.index'))
        context = resp.context[0]
        spot_map = {}
        constraint_map = {}
        for c in context['slotted_spots']:
            spot_map[c.hour] = list(c.iter_spots())[0]
            constraint_map[c.hour] = c

        now = time_util.chicago_now()

        # first hour:
        self.assertEqual(spot_map[now.hour].title, 'Legal ID')
        # second hour:
        self.assertEqual(
            spot_map[(now + datetime.timedelta(hours=1)).hour].title,
            'Legal ID')
Esempio n. 8
0
def get_quotas(playlist):
    quotas = {
        'heavy_rotation_played': 0,
        'heavy_rotation_target': TRACKS_HEAVY_ROTATION_TARGET,
        'light_rotation_played': 0,
        'light_rotation_target': TRACKS_LIGHT_ROTATION_TARGET,
        'local_current_played': 0,
        'local_current_target': TRACKS_LOCAL_CURRENT_TARGET,
        'local_classic_played': 0,
        'local_classic_target': TRACKS_LOCAL_CLASSIC_TARGET
    }
    pl = PlaylistEvent.all().filter('playlist =', playlist)
    now = chicago_now()
    now.replace(second=0, microsecond=0)
    pl.filter('established >=', now - timedelta(seconds=60 * now.minute))
    pl.filter('established <', now + timedelta(seconds=60 * (60 - now.minute)))
    for event in iter_playlist_events_for_view(pl):
        if not event.is_break:
            if 'heavy_rotation' in event.categories:
                quotas['heavy_rotation_played'] += 1
            if 'light_rotation' in event.categories:
                quotas['light_rotation_played'] += 1
            if 'local_current' in event.categories:
                quotas['local_current_played'] += 1
            if 'local_classic' in event.categories:
                quotas['local_classic_played'] += 1

    return quotas
Esempio n. 9
0
def get_quotas(playlist):
    quotas = {'heavy_rotation_played': 0,
              'heavy_rotation_target': TRACKS_HEAVY_ROTATION_TARGET,
              'light_rotation_played': 0,
              'light_rotation_target': TRACKS_LIGHT_ROTATION_TARGET,
              'local_current_played': 0,
              'local_current_target': TRACKS_LOCAL_CURRENT_TARGET,
              'local_classic_played': 0,
              'local_classic_target': TRACKS_LOCAL_CLASSIC_TARGET}
    pl = PlaylistEvent.all().filter('playlist =', playlist)
    now = chicago_now()
    now.replace(second=0, microsecond=0)
    pl.filter('established >=', now - timedelta(seconds=60 * now.minute))
    pl.filter('established <', now + timedelta(seconds=60 * (60 - now.minute)))
    for event in iter_playlist_events_for_view(pl):
        if not event.is_break:
            if 'heavy_rotation' in event.categories:
                quotas['heavy_rotation_played'] += 1
            if 'light_rotation' in event.categories:
                quotas['light_rotation_played'] += 1
            if 'local_current' in event.categories:
                quotas['local_current_played'] += 1
            if 'local_classic' in event.categories:
                quotas['local_classic_played'] += 1

    return quotas
Esempio n. 10
0
def get_quotas(playlist):
    quotas = {
        "heavy_rotation_played": 0,
        "heavy_rotation_target": TRACKS_HEAVY_ROTATION_TARGET,
        "light_rotation_played": 0,
        "light_rotation_target": TRACKS_LIGHT_ROTATION_TARGET,
        "local_current_played": 0,
        "local_current_target": TRACKS_LOCAL_CURRENT_TARGET,
        "local_classic_played": 0,
        "local_classic_target": TRACKS_LOCAL_CLASSIC_TARGET,
    }
    pl = PlaylistEvent.all().filter("playlist =", playlist)
    now = chicago_now()
    now.replace(second=0, microsecond=0)
    pl.filter("established >=", now - timedelta(seconds=60 * now.minute))
    pl.filter("established <", now + timedelta(seconds=60 * (60 - now.minute)))
    for event in iter_playlist_events_for_view(pl):
        if not event.is_break:
            if "heavy_rotation" in event.categories:
                quotas["heavy_rotation_played"] += 1
            if "light_rotation" in event.categories:
                quotas["light_rotation_played"] += 1
            if "local_current" in event.categories:
                quotas["local_current_played"] += 1
            if "local_classic" in event.categories:
                quotas["local_classic_played"] += 1

    return quotas
Esempio n. 11
0
    def test_landing_page_shows_spots(self):
        user = User(email='test')
        user.save()
        spot = models.Spot(
                        title='Legal ID',
                        type='Station ID')
        spot_key = spot.put()
        # assign it to every day of the week at the top of the hour:
        constraint_keys = views.saveConstraint(dict(hour_list=range(0,24), dow_list=range(1,8), slot=0))
        views.connectConstraintsAndSpot(constraint_keys, spot_key)

        spot_copy = models.SpotCopy(body='body',
                                    spot=spot,
                                    author=user)
        spot_copy.put()

        resp = self.client.get(reverse('traffic_log.index'))
        context = resp.context[0]
        spot_map = {}
        constraint_map = {}
        for c in context['slotted_spots']:
            spot_map[c.hour] = list(c.iter_spots())[0]
            constraint_map[c.hour] = c

        now = time_util.chicago_now()

        # first hour:
        self.assertEqual(spot_map[now.hour].title, 'Legal ID')
        # second hour:
        self.assertEqual(spot_map[(now + datetime.timedelta(hours=1)).hour].title,
                'Legal ID')
Esempio n. 12
0
 def __init__(self, spot_constraint, spot):
     self.spot = spot
     
     q = (TrafficLogEntry.all()
             .filter("log_date =", time_util.chicago_now().date())
             .filter("spot =", spot)
             .filter("hour =", spot_constraint.hour)
             .filter("slot =", spot_constraint.slot)
             .filter("dow =", spot_constraint.dow))
     if AutoRetry(q).count(1):
         self.finished = True
     else:
         self.finished = False
Esempio n. 13
0
def base(request):
    # logout should always redirect to the current page to
    # make it easier to switch users (like on the playlist tracker)
    logout_url = "%s?redirect=%s" % (auth.LOGOUT_URL, request.path)
    return {
        'user': hasattr(request, 'user') and request.user or None,
        'login_url': auth.create_login_url('/'),
        'logout_url': logout_url,
        'settings': settings,
        'MEDIA_URL': settings.MEDIA_URL,
        'chicago_now': time_util.chicago_now(),
        'request': request,
    }
Esempio n. 14
0
def landing_page(request, vars=None):
    if vars is None:
        vars = get_vars(request)

    # Load quotas for tracks played.
    vars["quotas"] = get_quotas(vars["playlist"])
    now = chicago_now()
    vars["last_dt"] = datetime(now.year, now.month, now.day, now.hour)

    # load the playlist history
    vars["playlist_events"] = get_playlist_history(vars["playlist"])

    return render_to_response("playlists/landing_page.html", vars, context_instance=RequestContext(request))
def base(request):
    # logout should always redirect to the current page to 
    # make it easier to switch users (like on the playlist tracker)
    logout_url = "%s?redirect=%s" % (auth.LOGOUT_URL, request.path)
    return {
        'user': hasattr(request, 'user') and request.user or None,
        'login_url': auth.create_login_url('/'),
        'logout_url': logout_url,
        'settings': settings,
        'MEDIA_URL': settings.MEDIA_URL,
        'chicago_now': time_util.chicago_now(),
        'request': request,
        }
Esempio n. 16
0
 def __init__(self, spot_constraint, spot):
     self.spot = spot
     
     q = (TrafficLogEntry.all()
             .filter("log_date =", time_util.chicago_now().date())
             .filter("spot =", spot)
             .filter("hour =", spot_constraint.hour)
             .filter("slot =", spot_constraint.slot)
             .filter("dow =", spot_constraint.dow))
     if AutoRetry(q).count(1):
         self.finished = True
     else:
         self.finished = False
Esempio n. 17
0
def landing_page(request, vars=None):
    if vars is None:
        vars = get_vars(request)

    # Load quotas for tracks played.
    vars['quotas'] = get_quotas(vars['playlist'])
    now = chicago_now()
    vars['last_dt'] = datetime(now.year, now.month, now.day, now.hour)

    # load the playlist history
    vars['playlist_events'] = get_playlist_history(vars['playlist'])

    return render_to_response('playlists/landing_page.html',
                              vars,
                              context_instance=RequestContext(request))
Esempio n. 18
0
    def test_filter_by_type(self):
        # Make another type of spot:
        spot = models.Spot(
                        title='PSA',
                        type='Live Read PSA',
                        author=self.author)
        spot.put()
        constraint = self.add_spot_to_constraint(spot)
        spot_copy = models.SpotCopy(
                    body='Save the children from bad music. Listen to CHIRP',
                    spot=spot,
                    author=self.author)
        spot_copy.put()

        today = self.now.date()
        current_hour = self.now.hour
        hour = current_hour

        logged_spot = models.TrafficLogEntry(
            log_date = self.today,
            spot = spot_copy.spot,
            spot_copy = spot_copy,
            dow = self.dow,
            hour = self.now.hour,
            slot = 0,
            scheduled = constraint,
            readtime = time_util.chicago_now(),
            reader = self.author
        )
        logged_spot.put()

        from_date = datetime.date.today() - timedelta(days=1)
        to_date = datetime.date.today() + timedelta(days=1)

        params = {'start_date': from_date.strftime("%Y-%m-%d"),
                  'end_date': to_date.strftime("%Y-%m-%d"),
                  # Live Read PSA:
                  'type': constants.SPOT_TYPE_CHOICES[3],
                  'underwriter': '',
                  'download': 'Download'}
        response = self.get_job_product('build-trafficlog-report', params)
        report = csv.reader(StringIO(response.content))
        header = report.next()
        row = report.next()
        self.assertEquals(row[4], spot.title)
        self.assertEquals(row[5], spot.type)
        self.assertEquals(row[6], spot_copy.body)
Esempio n. 19
0
    def test_filter_by_underwriter(self):
        # Make another type of spot:
        spot = models.Spot(
                        title='PSA',
                        type='Live Read PSA',
                        author=self.author)
        spot.put()
        constraint = self.add_spot_to_constraint(spot)
        spot_copy = models.SpotCopy(
            body='Pst, Reckless Records has killer hip hop in the cutout bin',
            spot=spot,
            author=self.author,
            underwriter='reckless')
        spot_copy.put()

        today = self.now.date()
        current_hour = self.now.hour
        hour = current_hour

        logged_spot = models.TrafficLogEntry(
            log_date = self.today,
            spot = spot_copy.spot,
            spot_copy = spot_copy,
            dow = self.dow,
            hour = self.now.hour,
            slot = 0,
            scheduled = constraint,
            readtime = time_util.chicago_now(),
            reader = self.author
        )
        logged_spot.put()

        from_date = datetime.date.today() - timedelta(days=1)
        to_date = datetime.date.today() + timedelta(days=1)

        params = {'start_date': from_date.strftime("%Y-%m-%d"),
                  'end_date': to_date.strftime("%Y-%m-%d"),
                  # All:
                  'type': constants.SPOT_TYPE_CHOICES[0],
                  'underwriter': 'reckless',
                  'download': 'Download'}
        response = self.get_job_product('build-trafficlog-report', params)
        report = csv.reader(StringIO(response.content))
        header = report.next()
        underwriters = set([row[3] for row in report])
        self.assertEquals(underwriters, set(['reckless']))
Esempio n. 20
0
    def test_filter_by_type(self):
        # Make another type of spot:
        spot = models.Spot(title='PSA',
                           type='Live Read PSA',
                           author=self.author)
        spot.put()
        constraint = self.add_spot_to_constraint(spot)
        spot_copy = models.SpotCopy(
            body='Save the children from bad music. Listen to CHIRP',
            spot=spot,
            author=self.author)
        spot_copy.put()

        today = self.now.date()
        current_hour = self.now.hour
        hour = current_hour

        logged_spot = models.TrafficLogEntry(log_date=self.today,
                                             spot=spot_copy.spot,
                                             spot_copy=spot_copy,
                                             dow=self.dow,
                                             hour=self.now.hour,
                                             slot=0,
                                             scheduled=constraint,
                                             readtime=time_util.chicago_now(),
                                             reader=self.author)
        logged_spot.put()

        from_date = datetime.date.today() - timedelta(days=1)
        to_date = datetime.date.today() + timedelta(days=1)

        params = {
            'start_date': from_date.strftime("%Y-%m-%d"),
            'end_date': to_date.strftime("%Y-%m-%d"),
            # Live Read PSA:
            'type': constants.SPOT_TYPE_CHOICES[3],
            'underwriter': '',
            'download': 'Download'
        }
        response = self.get_job_product('build-trafficlog-report', params)
        report = csv.reader(StringIO(response.content))
        header = report.next()
        row = report.next()
        self.assertEquals(row[4], spot.title)
        self.assertEquals(row[5], spot.type)
        self.assertEquals(row[6], spot_copy.body)
Esempio n. 21
0
    def test_filter_by_underwriter(self):
        # Make another type of spot:
        spot = models.Spot(title='PSA',
                           type='Live Read PSA',
                           author=self.author)
        spot.put()
        constraint = self.add_spot_to_constraint(spot)
        spot_copy = models.SpotCopy(
            body='Pst, Reckless Records has killer hip hop in the cutout bin',
            spot=spot,
            author=self.author,
            underwriter='reckless')
        spot_copy.put()

        today = self.now.date()
        current_hour = self.now.hour
        hour = current_hour

        logged_spot = models.TrafficLogEntry(log_date=self.today,
                                             spot=spot_copy.spot,
                                             spot_copy=spot_copy,
                                             dow=self.dow,
                                             hour=self.now.hour,
                                             slot=0,
                                             scheduled=constraint,
                                             readtime=time_util.chicago_now(),
                                             reader=self.author)
        logged_spot.put()

        from_date = datetime.date.today() - timedelta(days=1)
        to_date = datetime.date.today() + timedelta(days=1)

        params = {
            'start_date': from_date.strftime("%Y-%m-%d"),
            'end_date': to_date.strftime("%Y-%m-%d"),
            # All:
            'type': constants.SPOT_TYPE_CHOICES[0],
            'underwriter': 'reckless',
            'download': 'Download'
        }
        response = self.get_job_product('build-trafficlog-report', params)
        report = csv.reader(StringIO(response.content))
        header = report.next()
        underwriters = set([row[3] for row in report])
        self.assertEquals(underwriters, set(['reckless']))
Esempio n. 22
0
    def test_create_edit_spot_copy_expiry(self):
        dow = 1
        hour = 0
        slot = 0
        spot = models.Spot(title='Legal ID', type='Station ID')
        spot.put()
        constraint = models.SpotConstraint(dow=dow,
                                           hour=hour,
                                           slot=slot,
                                           spots=[spot.key()])
        constraint.put()

        now = time_util.chicago_now() + datetime.timedelta(hours=2)
        resp = self.client.post(
            reverse('traffic_log.views.addCopyForSpot', args=(spot.key(), )),
            {
                'spot_key': spot.key(),
                'body': 'You are listening to chirprario.odg',
                'underwriter': 'pretend this is an underwriter',
                'expire_on': now.strftime(
                    "%m/%d/%Y %H:%M:%S")  # no timezone info
            })
        self.assertNoFormErrors(resp)

        spot_copy, is_logged = spot.get_spot_copy(dow, hour, slot)
        converted_expire_on = time_util.convert_utc_to_chicago(
            spot_copy.expire_on)
        self.assertEqual(converted_expire_on.timetuple(), now.timetuple())

        resp = self.client.post(
            reverse('traffic_log.editSpotCopy', args=(spot_copy.key(), )),
            {
                'spot_key': spot.key(),
                'body': 'You are listening to chirprario.odg',
                'underwriter': 'pretend this is an underwriter',
                'expire_on': spot_copy.expire_on.strftime(
                    "%m/%d/%Y %H:%M:%S")  # no timezone info
            })
        self.assertNoFormErrors(resp)

        spot_copy, is_logged = spot.get_spot_copy(dow, hour, slot)
        converted_expire_on = time_util.convert_utc_to_chicago(
            spot_copy.expire_on)
        self.assertEqual(converted_expire_on.timetuple(), now.timetuple())
Esempio n. 23
0
def index(request):
    now = time_util.chicago_now()
    # now = now.replace(hour=23)
    today = now.date()

    hours_by_day = defaultdict(lambda: [])
    current_hour = now.hour
    current_dow = today.isoweekday()
    hours_by_day[current_dow].append(current_hour)

    hour_plus1, dow_for_hour = add_hour(current_hour, current_dow)
    hours_by_day[dow_for_hour].append(hour_plus1)

    ## it seems that showing more than 2 hours was
    ## consistently causing datastore timeouts during a
    ## period when datastore status was reported as normal

    # hour_plus2, dow_for_hour = add_hour(hour_plus1, dow_for_hour)
    # hours_by_day[dow_for_hour].append(hour_plus2)
    #
    # hour_plus3, dow_for_hour = add_hour(hour_plus2, dow_for_hour)
    # hours_by_day[dow_for_hour].append(hour_plus3)
    #
    # hours_to_show = [current_hour, hour_plus1, hour_plus2, hour_plus3]

    hours_to_show = [current_hour, hour_plus1]

    slotted_spots = []
    for dow in hours_by_day:
        q = models.SpotConstraint.all().filter("dow =", dow).filter(
            "hour IN", hours_by_day[dow])
        for s in AutoRetry(q):
            slotted_spots.append(s)

    def hour_position(s):
        return hours_to_show.index(s.hour)

    slotted_spots.sort(key=hour_position)
    return render_to_response('traffic_log/index.html',
                              context(date=today, slotted_spots=slotted_spots),
                              context_instance=RequestContext(request))
Esempio n. 24
0
def index(request):
    now = time_util.chicago_now()
    # now = now.replace(hour=23)
    today = now.date()
    
    hours_by_day = defaultdict(lambda: [])
    current_hour = now.hour
    current_dow = today.isoweekday()
    hours_by_day[current_dow].append(current_hour)
    
    hour_plus1, dow_for_hour = add_hour(current_hour, current_dow)
    hours_by_day[dow_for_hour].append(hour_plus1)
    
    ## it seems that showing more than 2 hours was 
    ## consistently causing datastore timeouts during a 
    ## period when datastore status was reported as normal
    
    # hour_plus2, dow_for_hour = add_hour(hour_plus1, dow_for_hour)
    # hours_by_day[dow_for_hour].append(hour_plus2)
    # 
    # hour_plus3, dow_for_hour = add_hour(hour_plus2, dow_for_hour)
    # hours_by_day[dow_for_hour].append(hour_plus3)
    # 
    # hours_to_show = [current_hour, hour_plus1, hour_plus2, hour_plus3]
    
    hours_to_show = [current_hour, hour_plus1]
    
    slotted_spots = []
    for dow in hours_by_day:
        q = models.SpotConstraint.all().filter("dow =", dow).filter("hour IN", hours_by_day[dow])
        for s in AutoRetry(q):
            slotted_spots.append(s)
    
    def hour_position(s):
        return hours_to_show.index(s.hour)
        
    slotted_spots.sort(key=hour_position)
    return render_to_response('traffic_log/index.html', context(
            date=today,
            slotted_spots=slotted_spots
        ), context_instance=RequestContext(request))
Esempio n. 25
0
    def test_many_spots(self):
        raise SkipTest('Something in DB sorting probably broke this test')
        copy = []
        for i in range(65):
            txt = 'PSA %s' % i
            copy.append(txt)
            spot_copy = models.SpotCopy(
                    body=txt,
                    spot=self.spot,
                    author=self.author)
            spot_copy.put()
            logged_spot = models.TrafficLogEntry(
                log_date = self.today,
                spot = spot_copy.spot,
                spot_copy = spot_copy,
                dow = self.dow,
                hour = self.now.hour,
                slot = 0,
                scheduled = self.constraint,
                readtime = time_util.chicago_now() - timedelta(days=1),
                reader = self.author
            )
            logged_spot.put()

        from_date = datetime.date.today() - timedelta(days=30)
        to_date = datetime.date.today()

        params = {'start_date': from_date.strftime("%Y-%m-%d"),
                  'end_date': to_date.strftime("%Y-%m-%d"),
                  # All:
                  'type': constants.SPOT_TYPE_CHOICES[0],
                  'underwriter': '',
                  'download': 'Download'}
        response = self.get_job_product('build-trafficlog-report', params)
        report = csv.reader(StringIO(response.content))
        header = report.next()
        self.assertEquals([r[6] for r in report],
                          ['You are listening to chirpradio.org'] + copy)
Esempio n. 26
0
    def test_many_spots(self):
        raise SkipTest('Something in DB sorting probably broke this test')
        copy = []
        for i in range(65):
            txt = 'PSA %s' % i
            copy.append(txt)
            spot_copy = models.SpotCopy(body=txt,
                                        spot=self.spot,
                                        author=self.author)
            spot_copy.put()
            logged_spot = models.TrafficLogEntry(
                log_date=self.today,
                spot=spot_copy.spot,
                spot_copy=spot_copy,
                dow=self.dow,
                hour=self.now.hour,
                slot=0,
                scheduled=self.constraint,
                readtime=time_util.chicago_now() - timedelta(days=1),
                reader=self.author)
            logged_spot.put()

        from_date = datetime.date.today() - timedelta(days=30)
        to_date = datetime.date.today()

        params = {
            'start_date': from_date.strftime("%Y-%m-%d"),
            'end_date': to_date.strftime("%Y-%m-%d"),
            # All:
            'type': constants.SPOT_TYPE_CHOICES[0],
            'underwriter': '',
            'download': 'Download'
        }
        response = self.get_job_product('build-trafficlog-report', params)
        report = csv.reader(StringIO(response.content))
        header = report.next()
        self.assertEquals([r[6] for r in report],
                          ['You are listening to chirpradio.org'] + copy)
Esempio n. 27
0
    def get_spot_copy(self, dow, hour, slot):
        spot_copy = None
        is_logged = False
        
        # If random spot copy list for this spot is empty, fill and shuffle.
        if len(self.random_spot_copies) == 0:
            self.shuffle_spot_copies()
            AutoRetry(self).save()
        
        self._expunge_expired_spot_copies(self.random_spot_copies)
        self._expunge_unstarted_spot_copies(self.random_spot_copies)
        
        # if spot copies exist and none have expired...
        if len(self.random_spot_copies) > 0:
            # Return the spot copy that a DJ just read (even though the 
            # finish link will be disabled)
            # or return the next random one for reading

            today = time_util.chicago_now().date()
            q = (TrafficLogEntry.all()
                    .filter("log_date =", today)
                    .filter("spot =", self)
                    .filter("dow =", dow)
                    .filter("hour =", hour)
                    .filter("slot =", slot))
                
            # Spot copy exists for dow, hour, and slot. Return it.
            if AutoRetry(q).count(1):
                existing_logged_spot = AutoRetry(q).fetch(1)[0]
                spot_copy = existing_logged_spot.spot_copy
                is_logged = True
            
            # Return next random spot copy.
            else:
                spot_copy = AutoRetry(db).get(self.random_spot_copies[0])
        
        return spot_copy, is_logged
Esempio n. 28
0
    def get_spot_copy(self, dow, hour, slot):
        spot_copy = None
        is_logged = False
        
        # If random spot copy list for this spot is empty, fill and shuffle.
        if len(self.random_spot_copies) == 0:
            self.shuffle_spot_copies()
            AutoRetry(self).save()
        
        self._expunge_expired_spot_copies(self.random_spot_copies)
        self._expunge_unstarted_spot_copies(self.random_spot_copies)
        
        # if spot copies exist and none have expired...
        if len(self.random_spot_copies) > 0:
            # Return the spot copy that a DJ just read (even though the 
            # finish link will be disabled)
            # or return the next random one for reading

            today = time_util.chicago_now().date()
            q = (TrafficLogEntry.all()
                    .filter("log_date =", today)
                    .filter("spot =", self)
                    .filter("dow =", dow)
                    .filter("hour =", hour)
                    .filter("slot =", slot))
                
            # Spot copy exists for dow, hour, and slot. Return it.
            if AutoRetry(q).count(1):
                existing_logged_spot = AutoRetry(q).fetch(1)[0]
                spot_copy = existing_logged_spot.spot_copy
                is_logged = True
            
            # Return next random spot copy.
            else:
                spot_copy = AutoRetry(db).get(self.random_spot_copies[0])
        
        return spot_copy, is_logged
Esempio n. 29
0
def deleteSpotCopy(request, spot_copy_key=None):
    spot_copy = AutoRetry(models.SpotCopy).get(spot_copy_key)
    spot_copy.expire_on = time_util.chicago_now()
    AutoRetry(spot_copy).put()
    return HttpResponseRedirect(reverse('traffic_log.views.listSpots'))
Esempio n. 30
0
    def test_finish_spot(self):
        self.assertEqual(list(models.TrafficLogEntry.all().fetch(5)), [])

        author = User(email='test')
        author.save()
        spot = models.Spot(title='Legal ID', type='Station ID', author=author)
        spot.put()

        # make a constraint closest to now:
        now = time_util.chicago_now()
        today = now.date()
        current_hour = now.hour
        constraint = models.SpotConstraint(dow=today.isoweekday(),
                                           hour=current_hour,
                                           slot=0,
                                           spots=[spot.key()])
        constraint.put()

        spot_copy = models.SpotCopy(body='You are listening to chirpradio.org',
                                    spot=spot,
                                    author=author)
        spot_copy.put()

        spot.random_spot_copies = [spot_copy.key()]
        spot.save()

        resp = self.client.get(reverse('traffic_log.index'))
        # unfinished spot should have been marked in static HTML:
        assert '<tr class="new">' in resp.content

        resp = self.client.get(
            reverse('traffic_log.finishReadingSpotCopy',
                    args=(spot_copy.key(), )), {
                        'hour': constraint.hour,
                        'dow': constraint.dow,
                        'slot': constraint.slot
                    })
        logged = models.TrafficLogEntry.all().fetch(1)[0]
        self.assertEqual(logged.reader.email, "*****@*****.**")
        self.assertEqual(logged.readtime.timetuple()[0:5],
                         datetime.datetime.now().timetuple()[0:5])
        self.assertEqual(logged.log_date, time_util.chicago_now().date())
        self.assertEqual(logged.spot.key(), spot.key())
        self.assertEqual(logged.spot_copy.key(), spot_copy.key())
        self.assertEqual(logged.scheduled.key(), constraint.key())
        self.assertEqual(logged.hour, constraint.hour)
        self.assertEqual(logged.dow, constraint.dow)

        resp = self.client.get(reverse('traffic_log.index'))
        # finished spot should have been marked in static HTML:
        assert '<tr class="finished">' in resp.content

        resp = self.client.get(
            reverse('traffic_log.spotTextForReading', args=(spot.key(), )), {
                'hour': constraint.hour,
                'dow': constraint.dow,
                'slot': constraint.slot
            })
        context = resp.context
        # already finished, no need for finish URL:
        self.assertEqual(context['url_to_finish_spot'], None)
        assert '(already finished)' in resp.content
Esempio n. 31
0
def deleteSpotCopy(request, spot_copy_key=None):
    spot_copy = AutoRetry(models.SpotCopy).get(spot_copy_key)
    spot_copy.expire_on = time_util.chicago_now()
    AutoRetry(spot_copy).put()
    return HttpResponseRedirect(reverse('traffic_log.views.listSpots'))