示例#1
0
    def merge_episode(episode_info):

        # Split the name
        path, info = episode_info
        show_name = info['series'].lower()
        parsed_season = info['season']
        parsed_episode = info['episodeNumber']

        try:
            show = Show.get(Show.name == show_name)
        except DoesNotExist:
            # Show does not exist yet
            show = Show.create(name=show_name)
            season = Season.create(show=show, season_number=parsed_season)
            Episode.create(season=season, episode_number=parsed_episode, path=path, added_time=datetime.datetime.now())
            print('Merged "' + show.name + '" season ' + str(parsed_season) + ' episode ' + str(parsed_episode))
        else:
            try:
                season = Season.get(Season.show == show, Season.season_number == parsed_season)
            except DoesNotExist:
                # Season did not exist yet
                season = Season.create(show=show, season_number=parsed_season)
                Episode.create(season=season, episode_number=parsed_episode, path=path,
                               added_time=datetime.datetime.now())
                print('Merged "' + show.name + '" season ' + str(parsed_season) + ' episode ' + str(parsed_episode))
            else:
                try:
                    Episode.get(Episode.season == season, Episode.episode_number == parsed_episode)
                except DoesNotExist:
                    Episode.create(season=season, episode_number=parsed_episode, path=path,
                                   added_time=datetime.datetime.now())
                    print('Merged "' + show.name + '" season ' + str(parsed_season) + ' episode ' + str(parsed_episode))
示例#2
0
    def test_subscriptions(self):
        ''' Tests responses on subscriptions request. '''

        configure_for_unittest()
        from command import subscriptions
        from model import Show, Chat

        show1 = Show(title=u'House of Cards').save()
        show2 = Show(title=u'Teacher Gym').save()
        chat = Chat(id=1).save()

        bot = FakeBot()
        upd = FakeUpdate(message=FakeMessage(chat=FakeChat(id=1)))

        # if there is at least one subscription
        chat.subscriptions.connect(show1)
        subscriptions(bot, upd)

        lines = (u'Active subscriptions:\n', u'▪ House of Cards')

        self.assertEqual(bot.sended_message['text'], '\n'.join(lines))
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardHide)

        # if no subscriptions
        chat.subscriptions.disconnect(show1)
        subscriptions(bot, upd)

        self.assertEqual(bot.sended_message['text'],
                         _('You are not subscribed to any of the series.'))
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardHide)
示例#3
0
    def test_showlist(self):
        ''' Tests response on showlist request. '''

        configure_for_unittest()
        from command import showlist
        from model import Show, Chat

        show1 = Show(title=u'House of Cards').save()
        show2 = Show(title=u'Физрук').save()
        chat = Chat(id=1).save()

        chat.subscriptions.connect(show1)

        bot = FakeBot()
        upd = FakeUpdate(message=FakeMessage(chat=FakeChat(id=1)))

        showlist(bot, upd)

        lines = (u'Available TV shows:\n', u'▪ House of Cards', u'▫ Физрук')

        print bot.sended_message['text']

        self.assertEqual(bot.sended_message['text'], u'\n'.join(lines))
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardHide)
示例#4
0
    def test_create_duplicates(self):
        ''' Tests raise exception with trying to create duplicates. '''

        configure_for_unittest()
        from model import Show
        from neomodel import UniqueProperty

        show1 = Show(title='House of Cards').save()
        show2 = Show(title='House of Cards')

        with self.assertRaises(UniqueProperty):
            show2.save()
示例#5
0
    def test_create_duplicates(self):
        ''' Tests raise exception with trying to create duplicates. '''

        configure_for_unittest()
        from model import Show
        from neomodel import UniqueProperty

        show1 = Show(title='House of Cards').save()
        show2 = Show(title='House of Cards')

        with self.assertRaises(UniqueProperty):
            show2.save()
示例#6
0
    def test_multiple_returned(self):
        ''' Tests raise exception with trying to access multiple returned objects
            with .get().
        '''

        configure_for_unittest()
        from model import Show
        from neomodel import MultipleNodesReturned

        Show(title='House of Cards').save()
        Show(title='Teacher Gym').save()

        with self.assertRaises(MultipleNodesReturned):
            Show.nodes.get(title__ne='Kitchen')
示例#7
0
def create_show_submission():
    # called to create new shows in the db, upon submitting new show listing form
    # TODO: insert form data as a new Show record in the db, instead
    error = False
    try:

        artist_id = request.form['artist_id']
        venue_id = request.form['venue_id']
        start_time = request.form['start_time']

        if Show.query.filter_by(artist_id=artist_id).filter_by(
                venue_id=venue_id).filter_by(
                    start_time=start_time).count() != 0:
            flash("This show" + " is already in the database")
            return render_template('pages/home.html')

        show = Show(artist_id=artist_id,
                    venue_id=venue_id,
                    start_time=start_time)
        db.session.add(show)
        db.session.commit()
    except:
        error = True
        db.session.rollback()
        print(sys.exc_info())
    finally:
        db.session.close()
    if error:
        flash('An error occurred. Show could not be listed.')
    if not error:
        flash('Show was successfully listed')
    return render_template('pages/home.html')
示例#8
0
def create_show_submission():
    data = request.form

    venue_id = data['venue_id']
    artist_id = data['artist_id']
    start_time = data['start_time']

    if Show.query.first() != None and Show.query.filter_by(
            start_time=start_time).first() != None:
        flash('this Show cannot be listed because this time is booked before!')

    else:
        try:
            new_show = Show(venue_id=venue_id,
                            artist_id=artist_id,
                            start_time=start_time)
            db.session.add(new_show)
            db.session.commit()
            # on successful db insert, flash success
            flash('Show was successfully listed!')
        except:
            db.session.rollback()
            # TODO: on unsuccessful db insert, flash an error instead.
            flash('Something went wrong :( Show could not be listed')
        finally:
            db.session.close()

    return render_template('pages/home.html')
示例#9
0
def create_show_submission():
    # called to create new shows in the db, upon submitting new show listing form
    # DONE: insert form data as a new Show record in the db, instead
    form = ShowForm()
    error = False

    artist_id = form.artist_id.data
    venue_id = form.venue_id.data
    start_time = form.start_time.data
    print(venue_id)

    try:
        show = Show(start_time=start_time,
                    artist_id=artist_id,
                    venue_id=venue_id)
        db.session.add(show)
        db.session.commit()
    except:
        db.session.rollback()
        print(sys.exc_info())
        error = True
    finally:
        db.session.close()

    if error:
        flash('An error occurred. Show could not be listed.')
    else:
        flash('Show was successfully listed!')

    # on successful db insert, flash success

    # DONE: on unsuccessful db insert, flash an error instead.
    # e.g., flash('An error occurred. Show could not be listed.')
    # see: http://flask.pocoo.org/docs/1.0/patterns/flashing/
    return render_template('pages/home.html')
示例#10
0
def create_show_submission():
  form = ShowForm(request.form) # Initialize form instance with values from the request
  flashType = 'danger' # Initialize flashType to fail. Either it will be changed to "success" on successfully db insert, or in all other cases it should be equal to "fail"
  if form.validate():
    try:
      newShow = Show.insert().values(
        Venue_id = request.form['venue_id'],
        Artist_id = request.form['artist_id'],
        start_time = request.form['start_time']
      )
      db.session.execute(newShow) 
      db.session.commit()
      # on successful db insert, flash success
      flashType = 'success'
      flash('Show was successfully listed!')
    except : 
      # TODO DONE: on unsuccessful db insert, flash an error instead.
      flash('An error occurred due to database insertion error. Show could not be listed.')
    finally:
      # Always close session
      db.session.close()
  else:
    flash(form.errors) # Flashes reason, why form is unsuccessful (not really pretty)
    flash('An error occurred due to form validation. Show could not be listed.')
  return render_template('pages/home.html', flashType = flashType)
示例#11
0
def create_show_submission():
    try:
        showData = request.form
        showVenueId = showData.get('venue_id')
        showArtistId = showData.get('artist_id')
        showStartTime = showData.get('start_time')
        if not Venue.query.filter_by(id=showVenueId).first():
            flash(
                'The venue does not exist. Please find the venue id from the venues page.'
            )
        elif not Artist.query.filter_by(id=showArtistId).first():
            flash(
                'The artist does not exist. Please find the artist id from the venues page.'
            )
        else:
            show = Show(venue_id=showVenueId,
                        artist_id=showArtistId,
                        start_time=showStartTime)
            db.session.add(show)
            db.session.commit()
            flash('Show was successfully listed!')
    except:
        db.session.rollback()
        flash('Show could not be listed!')
    finally:
        db.session.close()

    return render_template('pages/home.html')
示例#12
0
    def test_get_episode(self):
        ''' Tests getting episode from video's field. '''

        configure_for_unittest()
        from model import Video, Show, Season, Episode

        show = Show(title='House of Cards').save()
        season1 = Season(show=show, number=1).save()
        season2 = Season(show=show, number=2).save()
        episode1 = Episode(season=season1,
                           number=1,
                           release_date=dt(2010, 1, 1)).save()
        episode2 = Episode(season=season1, number=2).save()
        episode3 = Episode(season=season2, number=1).save()
        video = Video(link='vk.com').save()

        show.seasons.connect(season1)
        show.seasons.connect(season2)
        season1.episodes.connect(episode1)
        season1.episodes.connect(episode2)
        season2.episodes.connect(episode3)
        episode1.videos.connect(video)

        video.refresh()

        self.assertEqual(video.episode.get().number, 1)
示例#13
0
def create_show_submission():
    '''
    called to create new shows in the db,
    upon submitting new show listing form
    TODO: insert form data as a new Show record in the db, instead
    '''
    form = ShowForm()
    if request.method == 'POST':
        try:
            show = Show(
                venue=form.venue_id.data,
                artist=form.artist_id.data,
                start_time=form.start_time.data
            )

            db.session.add(show)
            db.session.commit()
            # on successful db insert, flash success
            flash('Show was successfully listed!')

        except:
            db.session.rollback()
            # DONE: on unsuccessful db insert, flash an error instead.
            # e.g., flash('An error occurred. Show could not be listed.')
            # see: http://flask.pocoo.org/docs/1.0/patterns/flashing/
            flash('An error occurred. Show could not be listed.')

        finally:
            db.session.close()
            return render_template('pages/home.html')
示例#14
0
def create_show_submission():
    # called to create new shows in the db, upon submitting new show listing form
    # TODO: insert form data as a new Show record in the db, instead
    error = False
    try:
        venue_id = request.form.get('venue_id')
        artist_id = request.form.get('artist_id')
        start_time = request.form.get('start_time')
        show = Show(venue_id=venue_id,
                    artist_id=artist_id,
                    start_time=start_time)
        db.session.add(show)
        db.session.commit()
    except:
        error = True
        db.session.rollback()
        print(sys.exc_info())
    finally:
        db.session.close()
    if error:
        flash('An error occurred. Show could not be listed.')
    else:
        # on successful db insert, flash success
        flash('Show was successfully listed!')
    return render_template('pages/home.html')
示例#15
0
def load_shows(file_user):

    for row in (open(file_user)):
        row = row.strip()

        user_id, show_name, show_type, show_url, show_amount_people, show_dressing_room, show_length, location_id, time_id, show_ticket_price, show_rent, show_ranking = row.split(
            ",")

        # IF YOU ADD THE ACT PREFERRED: ADD THE show_venue_preferred TO THE UMPAKING

        new_show = Show(user_id=user_id,
                        show_name=show_name,
                        show_type=show_type,
                        show_url=show_url,
                        show_amount_people=show_amount_people,
                        show_dressing_room=show_dressing_room,
                        show_length=show_length,
                        location_id=location_id,
                        time_id=time_id,
                        show_ticket_price=show_ticket_price,
                        show_rent=show_rent,
                        show_ranking=show_ranking)

        db.session.add(new_show)
        db.session.commit()
示例#16
0
    def test_unsubscribe(self):
        ''' Tests responses on unsubscirbe request. '''

        configure_for_unittest()
        from command import unsubscribe
        from model import Show, Chat

        show1 = Show(title='House of Cards').save()
        show2 = Show(title='Teacher Gym').save()
        chat = Chat(id=1).save()

        chat.subscriptions.connect(show1)

        bot = FakeBot()
        upd = FakeUpdate(message=FakeMessage(chat=FakeChat(id=1)))

        # valid request
        upd.message.text = '/unsubscribe house of cards'
        unsubscribe(bot, upd)

        self.assertFalse(chat in show1.subscribers.all())
        self.assertEqual(bot.sended_message['text'],
                         _('You have unsubscribed from the show.'))
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardHide)

        # trying to cancel non-existent subscription
        upd.message.text = '/unsubscribe house of cards'
        unsubscribe(bot, upd)

        self.assertEqual(bot.sended_message['text'],
                         _('You are not subscribed to the show.'))
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardHide)

        # trying to unsubscript for non-existent TV show
        upd.message.text = '/unsubscribe kitchen'
        unsubscribe(bot, upd)

        self.assertEqual(bot.sended_message['text'],
                         _('Specified series is not on my list.'))
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardHide)
示例#17
0
def create_show_submission():
    """
  Called to create new shows in the db, upon submitting new show listing form
  """

    try:
        request.get_data()
        show_dict = request.form.to_dict()
        show = Show(venue_id=show_dict["venue_id"],
                    artist_id=show_dict["artist_id"],
                    start_time=show_dict["start_time"])
        show.create()
        flash('Show was successfully listed!')
        return render_template('pages/home.html')
    except Exception as e:
        print("Error in creating new show: ", e)
        print(traceback.format_exc())
        flash('An error occurred. Show could not be listed.')
        abort(500)
示例#18
0
文件: app.py 项目: AmmarMousa17/Fyyur
def create_show_submission():
    error = False
    try:
        show = Show()
        show.artist_id = request.form['artist_id']
        show.venue_id = request.form['venue_id']
        show.start_time = request.form['start_time']
        db.session.add(show)
        db.session.commit()
    except:
        error = True
        db.session.rollback()
        print(sys.exc_info())

    if error:
        flash('An error occurred.')
    else:
        flash(' show was successfully added')
    return render_template('pages/home.html')
示例#19
0
    def __parse_single_attraction(li):
        """
        下記の形式のHTMLをParseする。

        <li>
          <a href='****' title='****'>
            <ul>
              <li class='photo'><img data-src='****' width='64' height='64' class='lozad' alt='***'></li>
              <li class='desc'>
                <h4>ショー名称</h4>
                <p>11:15 12:40 <span class='cur'>14:40</span> 16:05</p>
              </li>
              <li class='time'>
                <p><span>開始</span>14:40</p>
              </li>
            </ul>
          </a>
        </li>
        """

        show = Show()
        if elem_desc := li.find(class_='desc'):
            # ショー名称
            show.name = elem_desc.find('h4').text
            for child in elem_desc.children:
                if not child:
                    continue
                if not child.text:
                    continue
                # 中止フラグ
                if "中止" in child.text:
                    show.disable_flag = True
                # ショー開始時間一覧
                show.start_time_list = []
                start_time_list = child.text.split(" ")
                for start_time in start_time_list:
                    if ":" in start_time:
                        show.start_time_list.append(start_time)
示例#20
0
def query_shows_list_with_state():
    shows = (Show.select(Show.id, Show.name, fn.Count(fn.Distinct(Episode.episode_state)).alias('state_count'),
                         Episode.episode_state.alias('state'))
             .join(Season)
             .join(Episode)
             .order_by(Show.name)
             .group_by(Show.id)
             .dicts())

    res = list()
    for show in shows:
        if show['state_count'] > 1:
            show['state'] = PlayState.WATCHING
        del show['state_count']
        res.append(show)

    return res
示例#21
0
def shows_create_post():
    # called to create new shows in the db, upon submitting new show listing form
    # TODO: insert form data as a new Show record in the db, instead
    try:
        venue = request.form.get('venue_id', '')
        artist = request.form.get('artist_id', '')
        date = request.form.get('start_time', '')
        show = Show(venue_id=venue, artist_id=artist, start_time=date)
        db.session.add(show)
        db.session.commit()
        # on successful db insert, flash success
        flash('Show was successfully listed!')
        return render_template('pages/home.html')
    except IntegrityError as e:

        flash(str(e))
        return render_template('pages/home.html')
示例#22
0
文件: seed.py 项目: he1en/hb_project
def load_show(year, season, brand):
    """Load shows into database."""

    print "Show"

    brand_id = db.session.query(Brand).filter_by(
        brand_name=brand).one().brand_id

    year = 2017
    show = Show(season=season, year=year, brand_id=brand_id)

    # We need to add to the session or it won't ever be stored
    db.session.add(show)

    # Once we're done, we should commit our work
    db.session.commit()
    return show
示例#23
0
文件: app.py 项目: marlonxteban/fyyur
def create_show_submission():
    try:
        new_show = Show(
            artist_id=request.form.get('artist_id', ''),
            venue_id=request.form.get('venue_id', ''),
            start_time=request.form.get('start_time', datetime.now()),
        )
        db.session.add(new_show)
        db.session.commit()
        flash('Show was successfully listed!')
    except:
        flash('An error occurred. Show could not be listed')
        flash(sys.exc_info())
        db.session.rollback()
    finally:
        db.session.close()
        return render_template('pages/home.html')
示例#24
0
def add_or_update_show(title):

    # Обрабатываем отсутствие результатов поиска
    try:
        episodes, number_of_seasones, serial_title = parse_toramp(title)
    except ValueError as e:
        print '{} для {}'.format(e.message, title)
        return

    # Если сериал существует - работаем с ним
    try:
        show = Show.nodes.get(title_lower=serial_title.lower())
    except neomodel.DoesNotExist:
        show = Show(title=unicode(serial_title)).save()

    for i in xrange(number_of_seasones):

        # Если сезон уже существует - работаем с ним
        try:
            season = show.seasons.get(number=i+1)
        except neomodel.DoesNotExist:
            season = Season(show=show, number=i+1).save()
            show.seasons.connect(season)

        episodes_in_season = filter(lambda x: x['season'] == i + 1, episodes)

        for element in episodes_in_season:

            # Если эпизод уже есть - пропускаем
            try:
                episode = season.episodes.get(
                    number=element['number'],
                    title=element['title'],
                    release_date=element['release'],
                )

            except neomodel.DoesNotExist:
                episode = Episode(
                    season=season,
                    title=unicode(element['title']),
                    release_date=element['release'],
                    number=element['number'],
                    is_already_shown=element['release'] < datetime.datetime.now()
                ).save()
                season.episodes.connect(episode)
def create_show_submission():
    try:
        form = ShowForm(request.form)

        show = Show(artist_id=form.artist_id.data,
                    venue_id=form.venue_id.data,
                    start_time=form.start_time.data)
        db.session.add(show)
        db.session.commit()
        flash('Show: {0} created successfully'.format(show.id))
    except Exception as err:
        flash('An error occurred creating the Show: {0}. Error: {1}'.format(
            show.id, 'Invalid information'))
        db.session.rollback()
    finally:
        db.session.close()

    return render_template('pages/home.html'), 201
示例#26
0
    def test_availability(self):
        ''' Tests availabity properties of object. '''

        configure_for_unittest()
        from model import Show, Season, Episode

        show = Show(title='House of Cards').save()
        season1 = Season(show=show, number=1).save()
        season2 = Season(show=show, number=2).save()
        episode1 = Episode(season=season1,
                           number=1,
                           release_date=dt(2010, 1, 1)).save()
        episode2 = Episode(season=season1, number=2).save()

        show.seasons.connect(season1)
        show.seasons.connect(season2)
        season1.episodes.connect(episode1)
        season1.episodes.connect(episode2)

        self.assertEqual(season1.available_episodes[0], episode1)
        self.assertEqual(season1.unavailable_episodes[0], episode2)
示例#27
0
文件: app.py 项目: akinyeleolat/fyyur
def create_show_submission():
    try:
        venue_id = request.form.get('venue_id')
        artist_id = request.form.get('artist_id')
        start_time = request.form.get('start_time')

        # TODO: insert form data as a new Venue record in the db, instead
        data = Show(
            venue_id=venue_id,
            artist_id=artist_id,
            start_time=start_time
        )
        # TODO: modify data to be the data object returned from db insertion
        db.session.add(data)
        db.session.commit()
        # on successful db insert, flash success
        flash('Show was successfully listed!')
    except:
        db.session.rollback()
        # TODO: on unsuccessful db insert, flash an error instead.
        flash('An error occurred. Show could not be listed.')
    finally:
        db.session.close()
    return render_template('pages/home.html')
示例#28
0
    def test_default(self):
        ''' Tests responses on messages that are not commands. '''

        configure_for_unittest()
        from command import default, subscribe, unsubscribe, setlanguage, watch
        from model import Chat, Show, Season, Episode, Video

        chat = Chat(id=1).save()

        show = Show(title='House of Cards').save()
        season1 = Season(show=show, number=1).save()
        season2 = Season(show=show, number=2).save()
        episode1 = Episode(season=season1,
                           number=1,
                           release_date=dt(2010, 1, 1)).save()
        episode2 = Episode(season=season1, number=2).save()
        episode3 = Episode(season=season2, number=1).save()
        video1 = Video(link='link to video').save()
        video2 = Video(link='one more link').save()

        show.seasons.connect(season1)
        show.seasons.connect(season2)
        season1.episodes.connect(episode1)
        season1.episodes.connect(episode2)
        season2.episodes.connect(episode3)
        episode1.videos.connect(video1)
        episode1.videos.connect(video2)
        chat.rated_videos.connect(video1, {'value': 1})

        bot = FakeBot()
        upd = FakeUpdate(message=FakeMessage(chat=FakeChat(id=1)))

        # random input
        upd.message.text = 'random input'
        default(bot, upd)

        self.assertTrue('You can control' in bot.sended_message['text'])

        # subscribe in 2 steps
        upd.message.text = '/subscribe'
        subscribe(bot, upd)

        upd.message.text = 'house of cards'
        default(bot, upd)

        self.assertEqual(bot.sended_message['text'],
                         _('You have subscribed to the show.'))

        # unsubscribe in 2 steps
        upd.message.text = '/unsubscribe'
        unsubscribe(bot, upd)

        upd.message.text = 'house of cards'
        default(bot, upd)

        self.assertEqual(bot.sended_message['text'],
                         _('You have unsubscribed from the show.'))

        # setlanguage in 2 steps
        upd.message.text = '/setlanguage'
        setlanguage(bot, upd)

        upd.message.text = 'en'
        default(bot, upd)

        self.assertEqual(bot.sended_message['text'],
                         _('You are already using this language!'))

        # watch in 4 steps
        upd.message.text = '/watch'
        watch(bot, upd)

        self.assertEqual(bot.sended_message['text'],
                         _('Which TV show would you like to see?'))

        upd.message.text = 'house of cards'
        default(bot, upd)

        self.assertEqual(bot.sended_message['text'],
                         _('Which season would you like to see?'))

        upd.message.text = '1'
        default(bot, upd)

        self.assertEqual(bot.sended_message['text'],
                         _('Which episode would you like to see?'))

        upd.message.text = '1'
        default(bot, upd)

        self.assertEqual(bot.sended_message['text'], 'link to video')

        chat.referer = ''
        chat.save()

        # positive review - say 'thank you'
        upd.message.text = '/watch house of cards s1 e1'
        watch(bot, upd)

        upd.message.text = Emoji.THUMBS_UP_SIGN
        default(bot, upd)

        self.assertEqual(bot.sended_message['text'],
                         _('Thanks for the feedback!'))
示例#29
0
    def test_rate(self):
        ''' Tests rating of video. '''

        configure_for_unittest()
        from command import rate
        from model import Chat, Show, Season, Episode, Video

        chat = Chat(id=1).save()

        show = Show(title='House of Cards').save()
        season1 = Season(show=show, number=1).save()
        season2 = Season(show=show, number=2).save()
        episode1 = Episode(season=season1,
                           number=1,
                           release_date=dt(2010, 1, 1)).save()
        episode2 = Episode(season=season1, number=2).save()
        episode3 = Episode(season=season2, number=1).save()
        video1 = Video(link='link to video').save()
        video2 = Video(link='one more link').save()

        show.seasons.connect(season1)
        show.seasons.connect(season2)
        season1.episodes.connect(episode1)
        season1.episodes.connect(episode2)
        season2.episodes.connect(episode3)
        episode1.videos.connect(video1)
        episode1.videos.connect(video2)
        chat.rated_videos.connect(video1, {'value': 1})

        bot = FakeBot()
        upd = FakeUpdate(message=FakeMessage(chat=FakeChat(id=1)))

        # positive review
        upd.message.text = ' '.join(
            ['/rate link to video',
             unicode(Emoji.THUMBS_UP_SIGN, 'utf-8')])
        rate(bot, upd)

        self.assertEqual(bot.sended_message['text'],
                         _('Thanks for the feedback!'))
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardHide)

        # negative review
        upd.message.text = ' '.join(
            ['/rate link to video',
             unicode(Emoji.THUMBS_DOWN_SIGN, 'utf-8')])
        rate(bot, upd)

        self.assertEqual(bot.sended_message['text'], 'one more link')
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardMarkup)
        self.assertEqual(bot.sended_message['reply_markup'].keyboard,
                         [[Emoji.THUMBS_UP_SIGN, Emoji.THUMBS_DOWN_SIGN]])

        # unknown review
        upd.message.text = ' '.join(['/rate link to video', 'unknown'])
        rate(bot, upd)

        self.assertEqual(bot.sended_message['text'],
                         _('Please rate the video.'))
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardMarkup)
        self.assertEqual(bot.sended_message['reply_markup'].keyboard,
                         [[Emoji.THUMBS_UP_SIGN, Emoji.THUMBS_DOWN_SIGN]])

        chat.referer = ''
        chat.save()
示例#30
0
    def test_watch(self):
        ''' Tests responses on watch request. '''

        configure_for_unittest()
        from command import watch
        from model import Chat, Show, Season, Episode, Video

        chat = Chat(id=1).save()

        show = Show(title='House of Cards').save()
        season1 = Season(show=show, number=1).save()
        season2 = Season(show=show, number=2).save()
        episode1 = Episode(season=season1,
                           number=1,
                           release_date=dt(2010, 1, 1)).save()
        episode2 = Episode(season=season1, number=2).save()
        episode3 = Episode(season=season2, number=1).save()
        video1 = Video(link='link to video').save()
        video2 = Video(link='one more link').save()

        show.seasons.connect(season1)
        show.seasons.connect(season2)
        season1.episodes.connect(episode1)
        season1.episodes.connect(episode2)
        season2.episodes.connect(episode3)
        episode1.videos.connect(video1)
        episode1.videos.connect(video2)
        chat.rated_videos.connect(video1, {'value': 1})

        bot = FakeBot()
        upd = FakeUpdate(message=FakeMessage(chat=FakeChat(id=1)))

        # valid request
        upd.message.text = '/watch house of cards s1 e1'
        watch(bot, upd)

        self.assertEqual(bot.sended_message['text'], 'link to video')
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardMarkup)
        self.assertEqual(bot.sended_message['reply_markup'].keyboard,
                         [[Emoji.THUMBS_UP_SIGN, Emoji.THUMBS_DOWN_SIGN]])

        chat.referer = ''  # bot is waiting for feedback
        chat.save()

        # valid request - without arguments
        upd.message.text = '/watch'
        watch(bot, upd)

        chat.refresh()

        self.assertEqual('/watch', chat.referer)
        self.assertEqual(bot.sended_message['text'],
                         _('Which TV show would you like to see?'))
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardHide)

        # valid request - continue with show_title
        upd.message.text = ' '.join([chat.referer, 'house of cards'])
        watch(bot, upd)

        chat.refresh()

        self.assertEqual(chat.referer, '/watch house of cards')
        self.assertEqual(bot.sended_message['text'],
                         _('Which season would you like to see?'))
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardMarkup)
        self.assertEqual(bot.sended_message['reply_markup'].keyboard, [['1']])

        # valid request - continue with seasons number
        upd.message.text = ' '.join([chat.referer, 's1'])
        watch(bot, upd)

        chat.refresh()

        self.assertEqual(chat.referer, '/watch house of cards s1')
        self.assertEqual(bot.sended_message['text'],
                         _('Which episode would you like to see?'))
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardMarkup)
        self.assertEqual(bot.sended_message['reply_markup'].keyboard, [['1']])

        # valid request - continue with episode number
        upd.message.text = ' '.join([chat.referer, 'e1'])
        watch(bot, upd)

        chat.refresh()

        self.assertEqual(chat.referer, '/rate link to video')
        self.assertEqual(bot.sended_message['text'], 'link to video')
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardMarkup)
        self.assertEqual(bot.sended_message['reply_markup'].keyboard,
                         [[Emoji.THUMBS_UP_SIGN, Emoji.THUMBS_DOWN_SIGN]])

        chat.referer = ''
        chat.save()

        # trying to watch non-existent TV show
        upd.message.text = '/watch kitchen'
        watch(bot, upd)

        self.assertEqual(bot.sended_message['text'],
                         _('This TV show is not available.'))
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardHide)

        # trying to watch non-existent season
        upd.message.text = '/watch house of cards s5'
        watch(bot, upd)

        self.assertEqual(bot.sended_message['text'],
                         _('This season is not available.'))
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardHide)

        # trying to watch unavailable season
        upd.message.text = '/watch house of cards s2 e1'
        watch(bot, upd)

        self.assertEqual(bot.sended_message['text'],
                         _('This season is not available.'))
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardHide)

        # trying to watch non-existent episode
        upd.message.text = '/watch house of cards s1 e5'
        watch(bot, upd)

        self.assertEqual(bot.sended_message['text'],
                         _('This episode is not available.'))
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardHide)

        # trying to watch unavailable episode
        upd.message.text = '/watch house of cards s1 e2'
        watch(bot, upd)

        self.assertEqual(bot.sended_message['text'],
                         _('This episode is not available.'))
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardHide)
示例#31
0
 def clear_model():
     Episode.delete()
     Season.delete()
     Show.delete()
示例#32
0
def new_show_page_process():

    user_id = session.get("user_id")

    monday = request.json.get("monday")
    tuesday = request.json.get("tuesday")
    wednesday = request.json.get("wednesday")
    thursday = request.json.get("thursday")
    friday = request.json.get("friday")
    saturday = request.json.get("saturday")
    sunday = request.json.get("sunday")
    morning = request.json.get("morning")
    late_morning = request.json.get("late_morning")
    early_night = request.json.get("early_night")
    late_night = request.json.get("late_night")

    new_time = Time(monday=monday,
                    tuesday=tuesday,
                    wednesday=wednesday,
                    thursday=thursday,
                    friday=friday,
                    saturday=saturday,
                    sunday=sunday,
                    morning=morning,
                    late_morning=late_morning,
                    early_night=early_night,
                    late_night=late_night)

    db.session.add(new_time)
    db.session.commit()
    db.session.refresh(new_time)

    berkeley = request.json.get("berkeley")
    burlingame = request.json.get("burlingame")
    daly_city = request.json.get("daly_city")
    dublin = request.json.get("dublin")
    emeryville = request.json.get("emeryville")
    palo_alto = request.json.get("palo_alto")
    san_francisco = request.json.get("san_francisco")
    san_jose = request.json.get("san_jose")
    santa_clara = request.json.get("santa_clara")
    sunnyvale = request.json.get("sunnyvale")

    new_location = Location(berkeley=berkeley,
                            burlingame=burlingame,
                            daly_city=daly_city,
                            dublin=dublin,
                            emeryville=emeryville,
                            palo_alto=palo_alto,
                            san_francisco=san_francisco,
                            san_jose=san_jose,
                            santa_clara=santa_clara,
                            sunnyvale=sunnyvale)

    db.session.add(new_location)
    db.session.commit()
    db.session.refresh(new_location)

    show_name = request.json.get("show_name")
    show_type = request.json.get("show_type")
    show_url = request.json.get("show_url")
    show_amount_people = request.json.get("show_amount_people")
    show_dressing_room = request.json.get("show_dressing_room")
    show_length = request.json.get("show_length")
    show_location_preferred = request.json.get("show_location_preferred")
    show_ticket_price = request.json.get("show_ticket_price")
    show_rent = request.json.get("show_rent")

    new_show = Show(user_id=user_id,
                    show_name=show_name,
                    show_type=show_type,
                    show_url=show_url,
                    show_amount_people=show_amount_people,
                    show_dressing_room=show_dressing_room,
                    show_length=show_length,
                    location_id=new_location.location_id,
                    show_ticket_price=show_ticket_price,
                    time_id=new_time.time_id,
                    show_rent=show_rent)

    db.session.add(new_show)
    db.session.commit()
    db.session.refresh(new_show)

    show_rarking = adding_ranking("show", new_show.show_id)

    user = User.query.filter_by(user_id=user_id).first()

    return jsonify(user_fname=user.user_fname,
                   monday=monday,
                   tuesday=tuesday,
                   wednesday=wednesday,
                   thursday=thursday,
                   friday=friday,
                   saturday=saturday,
                   sunday=sunday,
                   morning=morning,
                   late_morning=late_morning,
                   early_night=early_night,
                   late_night=late_night,
                   show_name=show_name,
                   show_type=show_type,
                   show_url=show_url,
                   show_amount_people=show_amount_people,
                   show_dressing_room=show_dressing_room,
                   show_length=show_length,
                   show_ticket_price=show_ticket_price,
                   show_rent=show_rent,
                   show_id=new_show.show_id,
                   berkeley=berkeley,
                   burlingame=burlingame,
                   daly_city=daly_city,
                   dublin=dublin,
                   emeryville=emeryville,
                   palo_alto=palo_alto,
                   san_francisco=san_francisco,
                   san_jose=san_jose,
                   santa_clara=santa_clara,
                   sunnyvale=sunnyvale)