Exemple #1
0
    def __init__(self, access_token, database_url):
        self.api = pytvmaze.TVMaze()
        self.db = DB(database_url)
        self.access_token = access_token

        self.updater = Updater(token=self.access_token, use_context=True)
        dispatcher = self.updater.dispatcher

        start_handler = CommandHandler("start", self.start)
        search_handler = CommandHandler("search", self.search)
        list_handler = CommandHandler("list", self.list_favorites)
        show_picked_handler = CallbackQueryHandler(
                self.show_picked,
                pattern="show_picked_*"
                )
        add_show_handler = CallbackQueryHandler(
                self.add_show,
                pattern="add_show_*"
                )
        remove_show_handler = CallbackQueryHandler(
                self.remove_show,
                pattern="remove_show_*"
                )
        unknown_handler = MessageHandler(Filters.command, self.unknown)

        dispatcher.add_handler(start_handler)
        dispatcher.add_handler(search_handler)
        dispatcher.add_handler(add_show_handler)
        dispatcher.add_handler(remove_show_handler)
        dispatcher.add_handler(show_picked_handler)
        dispatcher.add_handler(list_handler)
        dispatcher.add_handler(unknown_handler)
Exemple #2
0
def prev(text, reply, message):
    tvm = pytvmaze.TVMaze()
    try:
        show = tvm.get_show(show_name=text)
        if show.previous_episode is not None:
            message(
                colors.parse(
                    '$(red)Previous Episode:$(clear) {} (S{}E{}) $(red)// Airing on:$(clear) {} $(red)//$(clear) {}'
                ).format(show.previous_episode.title,
                         show.previous_episode.season_number,
                         show.previous_episode.episode_number,
                         show.previous_episode.airdate,
                         show.previous_episode.summary))
            message(
                colors.parse('$(red)More at:$(clear) {}').format(
                    show.previous_episode.url))
        else:
            message(
                colors.parse(
                    '$(white, red){} does not have a previous episode$(clear)'
                ).format(show))
        pass
    except Exception as e:
        message(colors.parse('$(white, red)Show Not Found$(clear)'))
        pass
Exemple #3
0
def _when(request, bot, update_message, params, **kwargs):
    if len(params) == 0:
        message = "Please type a Show TV name!"
        return bot.sendMessage(update_message['chat']['id'], message)
    query = ' '.join(params)
    tvm = pytvmaze.TVMaze()
    try:
        show = tvm.get_show(show_name=query)
        context = {
            'show_name': show.name,
            'show_status': show.status,
            'show_summary': show.summary,
            'has_next_episode': show.next_episode is not None,
        }

        if show.next_episode is not None:
            context['next_episode_name'] = show.next_episode.title
            context['next_episode_runtime'] = show.next_episode.runtime
            context['next_episode_season'] = show.next_episode.season_number
            context['next_episode_number'] = show.next_episode.episode_number
            context['next_episode_airdatetime'] = datetime.strptime(show.next_episode.airdate+" "+show.next_episode.airtime, "%Y-%m-%d %H:%M")
        keyboard = InlineKeyboardMarkup(inline_keyboard=[[InlineKeyboardButton(text='More info', url=show.url)]])
        message = render(request, 'api/when.html', context).getvalue()
        return bot.sendMessage(update_message['chat']['id'], message, parse_mode="HTML", reply_markup=keyboard)
    except ShowNotFound:
        message = "{} not found.".format(query)
        return bot.sendMessage(update_message['chat']['id'], message)
Exemple #4
0
 def __init__(self, name):
     self.tvshowtable = ""  # used to display list of shows
     self.tvshow2table = ""  # used to display show info
     self.name = name
     self.tvn = pytvmaze.TVMaze()
     # define instance of the SQl class for favourate view
     self.myTvSql = mySql.TvSqLight("mysqlobject1")
Exemple #5
0
def test(request):
    tvm = pytvmaze.TVMaze()
    try:
        show = tvm.get_show(show_name='fsdfjdk')
    except ShowNotFound:
        return JsonResponse({'show': "NOT FOUND"}, safe=False)
    
    next_episode = show.next_episode
    return JsonResponse({'show': next_episode.title}, safe=False)
Exemple #6
0
def tomorrow(reply, message):
    tvm = pytvmaze.TVMaze()
    schedule = pytvmaze.get_schedule(
        date=str((datetime.now(timezone('US/Eastern')) +
                  timedelta(days=1)).strftime('%Y-%m-%d')))
    networks = [
        "NBC", "ABC", "CBS", "FOX", "Discovery Channel", "Food Network", "TNT",
        "Comedy Central", "HBO", "USA Network", "The CW", "tbs", "Bravo",
        "History", "FX", "Showtime", "Science", "AMC", "CBS All Access"
    ]
    lines = []
    times = []
    for episode in schedule:
        time = episode.airtime
        if time != '':
            if time > '19:30' or time < '03:15':
                if episode.show.network is not None:
                    if episode.show.network.name in networks:
                        if time not in times:
                            lines.append([])
                            times.append(time)
                        index = times.index(time)
                        lines[index].append(
                            '$(bold){}$(clear): $(orange){} (S{}E{})$(clear)'.
                            format(episode.show.network.name,
                                   episode.show.name, episode.season_number,
                                   episode.episode_number))
                elif episode.show.web_channel is not None:
                    if episode.show.web_channel.name in networks:
                        if time not in times:
                            lines.append([])
                            times.append(time)
                        index = times.index(time)
                        lines[index].append(
                            '$(bold){}$(clear): $(orange){} (S{}E{})$(clear)'.
                            format(episode.show.web_channel.name,
                                   episode.show.name, episode.season_number,
                                   episode.episode_number))
                else:
                    if time not in times:
                        lines.append([])
                        times.append(time)
                    index = times.index(time)
                    lines[index].append(
                        '$(bold){}$(clear): $(orange){} (S{}E{})$(clear)'.
                        format("Unknown", episode.show.name,
                               episode.season_number, episode.episode_number))

    for time in times:
        index = times.index(time)
        line = ' && '.join([str(i) for i in lines[index]])
        message(
            colors.parse('$(bold)$(red, white)[{}]$(clear) - {}'.format(
                time, line)))
Exemple #7
0
def upcoming(message, bot, conn):
    high_time = (datetime.now(timezone('US/Eastern')) +
                 timedelta(minutes=10)).strftime('%H:%M')
    current_hour = int(datetime.now(timezone('US/Eastern')).strftime('%H'))
    conn = bot.connections['P2PNET']
    if current_hour >= 18 or current_hour <= 3:
        tvm = pytvmaze.TVMaze()
        schedule = pytvmaze.get_schedule(primetime='yes')
        networks = [
            "NBC", "ABC", "CBS", "FOX", "Discovery Channel", "Food Network",
            "TNT", "Comedy Central", "HBO", "USA Network", "The CW", "tbs",
            "Bravo", "History", "FX", "Showtime", "Science", "AMC",
            "CBS All Access"
        ]
        lines = []
        for episode in schedule:
            time = episode.airtime
            if time != '':
                if time == high_time:
                    if episode.show.network is not None:
                        if episode.show.network.name in networks:
                            lines.append(
                                '$(bold){}$(clear): $(orange){} (S{}E{})$(clear)'
                                .format(episode.show.network.name,
                                        episode.show.name,
                                        episode.season_number,
                                        episode.episode_number))
                    elif episode.show.web_channel is not None:
                        if episode.show.web_channel.name in networks:
                            lines.append(
                                '$(bold){}$(clear): $(orange){} (S{}E{})$(clear)'
                                .format(episode.show.web_channel.name,
                                        episode.show.name,
                                        episode.season_number,
                                        episode.episode_number))
                    else:
                        lines.append(
                            '$(bold){}$(clear): $(orange){} (S{}E{})$(clear)'.
                            format("Unknown", episode.show.name,
                                   episode.season_number,
                                   episode.episode_number))
        if len(lines) > 0:
            line = ' && '.join([str(i) for i in lines])
            conn.message(
                '#phoenix-torrents',
                colors.parse('Airing in 10 minutes - {}'.format(line)))
        pass
Exemple #8
0
def search(data):
    """
    Search TVMaze for Show Info.

    :param data: show data
    :return: show details
    """
    year = data.get('year')
    country = data.get('country')
    clean_name = pynab.ids.clean_name(data.get('name'))

    log.debug('tvmaze: attempting to find "{}" online'.format(clean_name))

    # code contributed by srob650 (https://github.com/srob650)
    showname = ''

    if year:
        showname = clean_name[:-5]

    if country:
        showname = clean_name.split(country)[0].strip()

    if not year or country:
        showname = clean_name

    maze_show = None

    tvm = pytvmaze.TVMaze()

    try:
        maze_show = tvm.get_show(show_name=showname,
                                 show_year=year,
                                 show_country=country)
    except Exception as e:
        log.debug('tvmaze: exception: {}'.format(e))

    if maze_show:
        log.debug('tvmaze: returning show - {} with id - {}'.format(
            maze_show.name, maze_show.id))
        return maze_show.id
    else:
        log.debug('tvmaze: No show found')
        return None
Exemple #9
0
def ptfiles_pilot(match, bot, conn, chan):
    if chan == '#ptf-announce':
        name = match.group(1).replace(".", " ")
        url = match.group(2)
        tvm = pytvmaze.TVMaze()

        headers = {'User-Agent': bot.user_agent}
        strip = name.strip()
        params = {'t': strip, 'apikey': 'a7d6f6c'}

        try:
            request = requests.get("http://www.omdbapi.com/",
                                   params=params,
                                   headers=headers,
                                   timeout=5)
            if request.status_code == requests.codes.ok:
                content = request.json()
                if content['Response'] == 'True':
                    imdb = '$(red)https://www.imdb.com/title/{}$(clear)'.format(
                        content['imdbID'])
                else:
                    imdb = '$(white, red)IMDB not found!$(clear)'
            else:
                imdb = '$(white, red)IMDB not found!$(clear)'
        except Exception:
            imdb = '$(white, red)IMDB not found!$(clear)'
            pass

        try:
            show = tvm.get_show(show_name=name)
            tvmaze = '$(red){}$(clear)'.format(show.url)
            pass
        except Exception as e:
            tvmaze = '$(white, red)TVMaze Not Found$(clear)'
            pass
        conn.message(
            '#phoenix/staff',
            colors.parse('{} // {} // {} // {}'.format(name, url, tvmaze,
                                                       imdb)))
Exemple #10
0
def command_maze(bot, user, channel, args):
    tvm = pytvmaze.TVMaze("pyfibot")

    try:
        show = tvm.get_show(show_name=args, embed="episodes")
    except pytvmaze.exceptions.ShowNotFound:
        bot.say(channel, "Show '%s' not found" % args)
        return

    next_episode = None
    next_delta = None

    now = datetime.now(pytz.timezone("Europe/Helsinki"))

    # go through the episodes in reverse order
    for episode in reversed(show.episodes):
        # episode has id and name, but no airstamp yet (not announced)
        if not episode.airstamp:
            continue

        delta = relativedelta(parse(episode.airstamp), now)

        # episode is in the past, stop searching
        if delta.months <= 0 and delta.days <= 0 and delta.minutes <= 0:
            break
        else:
            # episode is (still) in the future
            next_episode = episode
            next_delta = delta

    # No new episodes found
    if not next_episode:
        # ended show, find latest episode
        if show.status == "Ended":
            next_episode = show.episodes.pop()
            latest_delta = relativedelta(now, parse(next_episode.airstamp))
        else:
            # Still running, ep airdate not yet known
            bot.say(channel, "No new episodes found for %s" % show.name)
            return

    show_id = "%s %s '%s'" % (
        show.name,
        "%dx%02d" % (next_episode.season_number, next_episode.episode_number),
        next_episode.title,
    )

    if show.status == "Ended":
        msg = "Latest episode of %s aired on %s (%s ago) on %s [Ended]" % (
            show_id,
            next_episode.airdate,
            _ago(latest_delta),
            show.network.name,
        )
    else:
        msg = "Next episode of {0} airs {1} ({2})".format(
            show_id, next_episode.airdate, _ago(next_delta))
        # Not all shows have network info for some reason
        if show.network:
            msg = "{0} on {1}".format(msg, show.network.name)
        elif show.web_channel:
            msg = "{0} on {1}".format(msg, show.web_channel.name)

    bot.say(channel, msg.encode("UTF-8"))
Exemple #11
0
from .models import UserList
from .forms import UserForm
from .forms import RegisterForm, LogInForm
from django.contrib.auth import authenticate, login as auth_login
from django.contrib.auth.models import User
from django.http import HttpResponse, HttpResponseRedirect
from sklearn.metrics.pairwise import linear_kernel
from sklearn.feature_extraction.text import TfidfVectorizer
# from django.shortcuts import HttpResponse
import pandas as pd
from matplotlib import pyplot as plt
from Collab_Filter import data2, indices, cosine_sim, movies_list
import pytvmaze
import numpy as np

tvm = pytvmaze.TVMaze()
from tvmaze.api import Api

api = Api()


def mainpage(response):
    return render(response, "main/login_init.html", {})


# Authenticate here
def login(request):
    if request.method == 'POST':
        form = LogInForm(request.POST or None)
        if form.is_valid():
            username = User.objects.get(email=form.cleaned_data['username'])
Exemple #12
0
from django.shortcuts import render, HttpResponseRedirect, redirect
from django.urls import reverse
from django.contrib import messages
from django.db.models import Count, Avg
from .models import Show, Episode, Review, EpisodeComment, EpisodeRating, ShowRating, RecentlyViewedShow
import datetime
import pytvmaze
import threading
import random

from ..login_registration.models import User
tvm = pytvmaze.TVMaze('mtjhartley')
# Create your views here.

# def is_user_logged_in(request):
#     if not 'id' in request.session:
#         return redirect(reverse('auth:index'))


def generate_rating_options():
    ratings = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    ratings_strings = [
        "(1) Appalling", "(2) Atrocious", "(3) Very Bad", "(4) No Good",
        "(5) Alright", "(6) Good", "(7) Enjoyable", "(8) Great", "(9) Amazing",
        "(10) Swag Me Out!"
    ]
    rating_options = zip(ratings, ratings_strings)
    return rating_options


def get_users_recently_viewed_shows(user):
Exemple #13
0
    def update(self, metadata, media, lang, force):
        Log.Debug('Update() called...')

        # Get main show info
        tvm = pytvmaze.TVMaze()
        show = tvm.get_show(maze_id=int(metadata.id), embed='cast')
        if not show:
            return

        # Title
        metadata.title = show.name

        # Summary
        try:
            metadata.summary = show.summary
        except:
            metadata.summary = None

        # Year
        try:
            metadata.originally_available_at = datetime.datetime.strptime(
                show.premiered, '%Y-%m-%d')
        except:
            metadata.originally_available_at = None

        # Duration
        try:
            metadata.duration = show.runtime
        except:
            metadata.duration = None

        # Rating
        try:
            metadata.rating = show.rating.get('average')
        except:
            metadata.rating = None

        # Content Rating - TVmaze doesn't provide content rating, so let's use the show's status (Running, Ended, Cancelled, etc)
        try:
            metadata.content_rating = show.status
        except:
            metadata.content_rating = None

        # Genres
        try:
            metadata.genres = show.genres
        except:
            metadata.genres = None

        # Studio - Add country code?
        if show.network:
            try:
                metadata.studio = show.network.name
            except:
                metadata.studio = None
        elif show.web_channel:
            try:
                metadata.studio = show.web_channel.name
            except:
                metadata.studio = None
        else:
            metadata.studio = None

        # Cast
        try:
            cast_data = zip(show.cast.people, show.cast.characters)
            _ = (e for e in cast_data
                 )  # test if cast data is iterable ie not null

            metadata.roles.clear()
            for person, character in cast_data:
                try:
                    role = metadata.roles.new()
                    role.role = character.name
                    role.name = person.name
                    # Prefer character over actor photo.
                    if character.image:
                        role.photo = character.image.get('original')
                    elif person.image:
                        role.photo = person.image.get('original')
                    else:
                        role.photo = None
                except:
                    pass
        except AttributeError:
            pass

        # Get poster if it exists
        if show.image:
            if show.image.get('original'):
                orig_url = show.image.get('original')
                if not orig_url in metadata.posters.keys():
                    metadata.posters[orig_url] = Proxy.Media(
                        HTTP.Request(orig_url).content)

        # Get season posters they exist
        seasons = pytvmaze.show_seasons(int(metadata.id))
        for s in seasons:
            # Get the season object from the model
            season = metadata.seasons[seasons[s].season_number]
            if seasons[int(s)].image:
                if seasons[int(s)].image.get('original'):
                    orig_url = seasons[int(s)].image.get('original')
                    if not orig_url in season.posters.keys():
                        season.posters[orig_url] = Proxy.Media(
                            HTTP.Request(orig_url).content)
            elif show.image:
                if show.image.get('original'):
                    orig_url = show.image.get('original')
                    season.posters[orig_url] = Proxy.Media(
                        HTTP.Request(orig_url).content)

        # Get episode info
        episodes = pytvmaze.episode_list(metadata.id)
        for ep in episodes:
            # Get the episode object from the model
            episode = metadata.seasons[ep.season_number].episodes[
                ep.episode_number]

            # Populate metadata attributes
            episode.show = show.name

            # Title
            try:
                episode.title = ep.title
            except:
                episode.title = None

            # Summary
            try:
                episode.summary = ep.summary
            except:
                episode.summary = None

            # Season
            try:
                episode.season = ep.season_number
            except:
                episode.season = None

            # Episode
            try:
                episode.index = ep.season_number
            except:
                episode.index = None

            # Air date
            try:
                airdate = datetime.datetime.strptime(ep.airdate, '%Y-%m-%d')
            except:
                airdate = ep.airdate
            try:
                episode.originally_available_at = airdate
            except:
                episode.originally_available_at = None

            # Duration
            episode.duration = ep.runtime

            # Download the episode thumbnail
            valid_names = list()

            # Get episode poster if it exists
            if ep.image:
                if ep.image.get('original'):
                    thumb_url = ep.image.get('original')
                    if thumb_url is not None and len(thumb_url) > 0:
                        # Check that the thumb doesn't already exist before downloading it
                        valid_names.append(thumb_url)
                        if thumb_url not in episode.thumbs:
                            try:
                                episode.thumbs[thumb_url] = Proxy.Media(
                                    HTTP.Request(thumb_url).content)
                            except:
                                # tvmaze doesn't have a thumb for this show
                                pass
    def update(self, metadata, media, lang, force):
        Log.Debug('Update() called...')

        # Get main show info
        tvm = pytvmaze.TVMaze()
        show = tvm.get_show(maze_id=int(metadata.id))
        if not show:
            return

        metadata.title = show.name
        metadata.summary = show.summary

        # Get poster if it exists
        if show.image:
            if show.image.get('medium'):
                med_url = show.image.get('medium')
                if not med_url in metadata.posters.keys():
                    metadata.posters[med_url] = Proxy.Preview(
                        HTTP.Request(med_url).content)
            if show.image.get('original'):
                orig_url = show.image.get('original')
                if not orig_url in metadata.posters.keys():
                    metadata.posters[orig_url] = Proxy.Media(
                        HTTP.Request(orig_url).content)

        # Get season posters they exist
        seasons = pytvmaze.show_seasons(int(metadata.id))
        for s in seasons:
            # Get the season object from the model
            season = metadata.seasons[seasons[s].season_number]
            if seasons[int(s)].image:
                if seasons[int(s)].image.get('medium'):
                    med_url = seasons[int(s)].image.get('medium')
                    if not med_url in season.posters.keys():
                        season.posters[med_url] = Proxy.Preview(
                            HTTP.Request(med_url).content)
                if seasons[int(s)].image.get('original'):
                    orig_url = seasons[int(s)].image.get('original')
                    if not orig_url in season.posters.keys():
                        season.posters[orig_url] = Proxy.Media(
                            HTTP.Request(orig_url).content)
            elif show.image:
                if show.image.get('medium'):
                    med_url = show.image.get('medium')
                    season.posters[med_url] = Proxy.Preview(
                        HTTP.Request(med_url).content)
                if show.image.get('original'):
                    orig_url = show.image.get('original')
                    season.posters[orig_url] = Proxy.Media(
                        HTTP.Request(orig_url).content)

        # Get episode info
        episodes = pytvmaze.episode_list(metadata.id)
        for ep in episodes:
            # Get the episode object from the model
            episode = metadata.seasons[ep.season_number].episodes[
                ep.episode_number]

            # Populate metadata attributes
            episode.show = show.name
            episode.title = ep.title
            episode.summary = ep.summary
            episode.index = ep.episode_number
            episode.season = ep.season_number
            try:
                airdate = datetime.datetime.strptime(ep.airdate, '%Y-%m-%d')
            except TypeError as e:
                airdate = ep.airdate
            episode.originally_available_at = airdate
            episode.duration = ep.runtime
Exemple #15
0
def show(text, reply, message):
    tvm = pytvmaze.TVMaze()
    try:
        show = tvm.get_show(show_name=text)
        message(colors.parse('$(bold)$(orange, white){}$(clear)').format(show))
        lines = []
        if show.type is not None:
            lines.append('$(red)Type:$(clear) {}'.format(show.type))
            pass
        if len(show.genres) > 0:
            lines.append('$(red)Genres:$(clear) {}'.format(', '.join(
                [str(i) for i in show.genres])))
            pass
        if show.status is not None:
            lines.append('$(red)Status:$(clear) {}'.format(show.status))
            pass
        if show.runtime is not None:
            lines.append('$(red)Runtime:$(clear) {}'.format(show.runtime))
            pass
        if len(show.schedule['days']) > 0 and len(show.schedule['time']) > 0:
            if show.network is not None:
                lines.append(
                    '$(red)Airing:$(clear) {} @ {} on $(bold){}$(clear)'.
                    format(show.schedule['days'][0], show.schedule['time'],
                           show.network.name))
            elif show.web_channel is not None:
                lines.append(
                    '$(red)Airing:$(clear) {} @ {} on $(bold){}$(clear)'.
                    format(show.schedule['days'][0], show.schedule['time'],
                           show.web_channel.name))
            else:
                lines.append(
                    '$(red)Airing:$(clear) {} @ {} on $(bold){}$(clear)'.
                    format(show.schedule['days'][0], show.schedule['time'],
                           "Unknown"))
            pass
        message(
            colors.parse('$(red) // $(clear)'.join([str(i) for i in lines])))
        if len(show.summary) > 400:
            output = []
            count = 0
            words = show.summary.split()
            for index in range(len(words)):
                if index == 0:
                    output.insert(count, words[index])
                elif len(output[count]) < 390:
                    output[count] = output[count] + " " + words[index]
                else:
                    count = count + 1
                    output.insert(count, words[index])
            for index in range(len(output)):
                if index == 0:
                    message(
                        colors.parse('$(red)Summary:$(clear) {}').format(
                            output[index]))
                else:
                    message(
                        colors.parse('$(red)Summary cont.:$(clear) {}').format(
                            output[index]))
        else:
            message(
                colors.parse('$(red)Summary:$(clear) {}').format(show.summary))
        message(colors.parse('$(red)More at:$(clear) {}').format(show.url))
        if show.next_episode is not None:
            message(
                colors.parse(
                    '$(red)Next Episode:$(clear) {} (S{}E{}) $(red)// Airing on:$(clear) {} $(red)//$(clear) {}'
                ).format(show.next_episode.title,
                         show.next_episode.season_number,
                         show.next_episode.episode_number,
                         show.next_episode.airdate, show.next_episode.summary))
        pass
    except Exception as e:
        message(colors.parse('$(white, red)Show Not Found$(clear)'))
        pass