Beispiel #1
0
def getDataFromTMDb(opts, movieName, movieYear):
    """docstring for getDataFromTMDb"""
    if opts.verbose == 2:
        print "!!Looking up data for: %s - %s" % (movieName, movieYear)
    #end if debug
    movieResults = tmdb.search(movieName.decode("utf-8"))
    movies = []

    if opts.verbose == 2:
        print "!!Search returned %s hits" % len(movieResults)
    #end if debug

    #we got zero hits, try replacing some commonly used replacement-characters due to filename illegality
    if len(movieResults) < 1:
        if movieName.count(';'):
            tempMovieName = movieName.replace(';', ':')
            return getDataFromTMDb(opts, tempMovieName, movieYear)
        elif movieName.count('_'):
            tempMovieName = movieName.replace('_', ' ')
            return getDataFromTMDb(opts, tempMovieName, movieYear)
        else:
            #last ditch attempt, search for movies by longest word in movie name as long as more then one word
            if len(movieName.split()) < 2:
                return movies
            #end if len
            movieNameLongestWord = max(movieName.split(), key=len)
            longestWordMovies = getDataFromTMDb(opts, movieNameLongestWord,
                                                movieYear)
            if opts.interactive or len(longestWordMovies) == 1:
                if opts.verbose == 2:
                    print "!!Using search result(s) based upon longest word search"
                #end if debug
                return longestWordMovies
            #end if interactive
            return movies
        #end if count
    #end if len

    if movieYear != "":
        for movieResult in movieResults:
            #check that the year tag in the file name matches with the release date, otherwise not the movie we are looking for
            if opts.verbose == 2:
                print "!!Potential hit: %s" % movieResult['name']
            if movieResult['released']:
                if movieResult['released'].startswith(
                        movieYear) or movieResult['released'].startswith(
                            str(int(movieYear) + 1)):
                    movie = tmdb.getMovieInfo(movieResult['id'])
                    movies.append(movie)
        #end for movie
    else:
        for movieResult in movieResults:
            #check that the year tag in the file name matches with the release date, otherwise not the movie we are looking for
            if opts.verbose == 2:
                print "!!Potential hit: %s" % movieResult['name']
            if movieResult['released']:
                movie = tmdb.getMovieInfo(movieResult['id'])
                movies.append(movie)
        #end for movie
    return movies
def getDataFromTMDb(opts, movieName, movieYear):
    """docstring for getDataFromTMDb"""
    if opts.verbose == 2:
        print "!!Looking up data for: %s - %s" % (movieName, movieYear)
    #end if debug
    movieResults = tmdb.search(movieName.decode("utf-8"))
    movies = []
    
    if opts.verbose == 2:
        print "!!Search returned %s hits" % len(movieResults)
    #end if debug
    
    #we got zero hits, try replacing some commonly used replacement-characters due to filename illegality
    if len(movieResults) < 1:
        if movieName.count(';'):
            tempMovieName = movieName.replace(';', ':')
            return getDataFromTMDb(opts, tempMovieName, movieYear)
        elif movieName.count('_'):
            tempMovieName = movieName.replace('_', ' ')
            return getDataFromTMDb(opts, tempMovieName, movieYear)
        else:
            #last ditch attempt, search for movies by longest word in movie name as long as more then one word
            if len(movieName.split()) < 2:
                return movies
            #end if len
            movieNameLongestWord = max(movieName.split(), key=len)
            longestWordMovies = getDataFromTMDb(opts, movieNameLongestWord, movieYear)
            if opts.interactive or len(longestWordMovies) == 1:
                if opts.verbose == 2:
                    print "!!Using search result(s) based upon longest word search"
                #end if debug
                return longestWordMovies
            #end if interactive
            return movies
        #end if count
    #end if len
    
    if movieYear != "":
        for movieResult in movieResults:
            #check that the year tag in the file name matches with the release date, otherwise not the movie we are looking for
            if opts.verbose == 2:
                print "!!Potential hit: %s" % movieResult['name']
            if movieResult['released']:
                if movieResult['released'].startswith(movieYear) or movieResult['released'].startswith(str(int(movieYear)+1)):
                    movie = tmdb.getMovieInfo(movieResult['id'])
                    movies.append(movie)
        #end for movie
    else:
        for movieResult in movieResults:
            #check that the year tag in the file name matches with the release date, otherwise not the movie we are looking for
            if opts.verbose == 2:
                print "!!Potential hit: %s" % movieResult['name']
            if movieResult['released']:
                movie = tmdb.getMovieInfo(movieResult['id'])
                movies.append(movie)
        #end for movie
    return movies
Beispiel #3
0
async def movieBegin(ctx, *, args):
    try:
        print("beginning movie")
        guild = ctx.guild
        memberList = guild.members
        for i in memberList:
            if (i.bot):
                pass
            else:
                print(i)
                await mute(ctx, i)
        movie = ''.join(args)
        movie = movie[1:-1]
        dump = tmdb.getMovieInfo(movie)
        movieInfo = discord.Embed(title=movie, color=discord.Color.blue())
        tagline = dump['tagline']
        popularity = dump['popularity']
        ratings = dump['ratings']
        movieInfo.add_field(name='Tagline', value=tagline, inline=False)
        for i in dump['genres']:
            genre = i['name']
            movieInfo.add_field(name='Genre', value=genre)
        movieInfo.add_field(name='Popularity:', value=popularity)
        movieInfo.add_field(name='Ratings', value=ratings)
        await ctx.send(embed=movieInfo)
    except Exception as e:
        await ctx.send(
            "Looks like something went wrong check back after a few mins :(")
        print('Exception:' + e)
        pass
Beispiel #4
0
def movie_detail(request, title):
    class MovieCommentsForm(forms.ModelForm):
        class Meta:
            model = Movie
            fields = ("comments",)

    movie = get_object_or_404(Movie.objects.select_related("director"), title=title)
    comments_form = MovieCommentsForm()
    if request.method == "POST":
        if not request.user.is_authenticated():
            return HttpResponse("You must be authenticated to do this.")
        if "save-comments" in request.POST:
            comments_form = MovieCommentsForm(data=request.POST, instance=movie)
            if comments_form.is_valid():
                comments_form.save()
    else:
        comments_form = MovieCommentsForm(instance=movie)
    viewings = movie.viewing_set.order_by("-date")
    if movie.tmdb_id:
        image_url = get_movie_thumbnail(tmdb.getMovieInfo(movie.tmdb_id))
        imdb_id = get_movie_imdb_id(movie.tmdb_id)
    return {
        "movie": movie,
        "viewings": viewings,
        "comments_form": comments_form,
        "image_url": image_url,
        "imdb_id": imdb_id,
    }
Beispiel #5
0
 def movie_from_tmdb_id(cls, tmdb_id, recommended_by=None):
     """Return a Movie object with the specified tmdb_id. As a side effect, create the Movie in
     the database and fill in its info from themoviedb if it doesn't already exist in the database."""
     movie, created = cls.objects.get_or_create(tmdb_id=tmdb_id)
     # if the Movie is already in the db, we won't change it at all, the assumption
     # being that all Movies will be added with this method so info will correct.
     if created:
         result = tmdb.getMovieInfo(tmdb_id)
         movie.title = result['name']
         # date_string is of the format "YYYY-MM-DD"
         date_string = result['released']
         year = int(date_string[0:4])
         month = int(date_string[5:7])
         day = int(date_string[8:10])
         movie.release_date = datetime.date(year, month, day)
         movie.runtime = int(result['runtime'])
         try:
             director_id = int(result['cast']['director'][0]['id'])
             director = Person.person_from_tmdb_id(director_id)
             movie.director = director
         except KeyError:
             pass
         if recommended_by:
             movie.recommended_by = recommended_by
         movie.save()
     return movie
    def refreshMovieTitle(self, title):
        global movie_title
        movie_title = title
        self["title"].setText(_("Searchtitle: %s") % movie_title)
        self["info"].setText(_("Filename: %s") % os.path.basename(self.service.getPath()))
        self.setTitle(_("Search result(s) for %s") % (movie_title))
        try:
            results = tmdb.search(movie_title)
        except:
            results = []
        if len(results) == 0:
            self.setTitle(_("Nothing found for: %s") % (movie_title))
            self["key_green"].setText(_("OK"))
            print "No info found for: " + movie_title
            return False

        self.l = []
        for searchResult in results:
            try:
                self["key_green"].setText(_("Save infos/cover"))
                movie = tmdb.getMovieInfo(searchResult['id'])
                released = movie['released'][:4]
                if released:
                    self.l.append((movie['name'].encode("utf-8") + " - " + released, movie))
                else:
                    self.l.append((movie['name'].encode("utf-8"), movie))
            except:
                pass

        self["list"].setList(self.l)
Beispiel #7
0
def test_get_movie_from_imdb():
    """Checks that a movie can be retrieved via its IMDb ID
    """
    movie = tmdb.getMovieInfo('tt0079023')

    assert len(movie['cast']['director']) == 2
    assert movie['cast']['director'][0]['name'] == "Jean-Marie Straub"
    assert movie['cast']['director'][1]['name'] == u"Dani\xe8lle Huillet"
def test_get_director():
    """Checks you can get the director of a film
    """
    mid = tmdb.search("Inglourious Basterds")[0]['id']
    movie = tmdb.getMovieInfo(mid)

    assert len(movie['cast']['director']) == 1
    assert movie['cast']['director'][0]['name'] == "Quentin Tarantino"
Beispiel #9
0
 def downloadMovieInfo(self, name, filename=None):
     import tmdb
     from EventInformationTable import createEIT
     results = tmdb.search(name)
     if results and len(results) > 0:
         searchResult = results[0]
         movie = tmdb.getMovieInfo(searchResult['id'])
         createEIT(filename, name, config.AdvancedMovieSelection.coversize.value, movie)
Beispiel #10
0
 def test_getmovieinfo_wrapper(self):
     """Tests tmdb.getMovieInfo() wrapper works correctly
     """
     r = tmdb.getMovieInfo(550)
     self.assertEquals(
         type(r),
         tmdb.Movie
     )
Beispiel #11
0
def test_get_director():
    """Checks you can get the director of a film
    """
    mid = tmdb.search("Inglourious Basterds")[0]['id']
    movie = tmdb.getMovieInfo(mid)

    assert len(movie['cast']['director']) == 1
    assert movie['cast']['director'][0]['name'] == "Quentin Tarantino"
    def downloadMovieInfo(self, name, filename=None):
        import tmdb
        from EventInformationTable import createEIT

        results = tmdb.search(name)
        if results and len(results) > 0:
            searchResult = results[0]
            movie = tmdb.getMovieInfo(searchResult["id"])
            createEIT(filename, name, config.AdvancedMovieSelection.coversize.value, movie)
Beispiel #13
0
def test_get_movie_from_imdb():
    """Checks that a movie can be retrieved via its IMDb ID
    """
    movie = tmdb.getMovieInfo('tt0079023')

    assert len(movie['cast']['director']) == 2
    assert movie['cast']['director'][0]['name'] == "Jean-Marie Straub"
    print(repr(movie['cast']['director'][1]['name']))
    assert movie['cast']['director'][1]['name'] == u"Dani\xe8le Huillet"
Beispiel #14
0
    def test_get_director(self):
        """Checks you can get the director of a film
        """
        mid = tmdb.search("Inglourious Basterds")[0]['id']
        movie = tmdb.getMovieInfo(mid)

        self.assertTrue(len(movie['cast']['director']) == 1)
        self.assertEquals(movie['cast']['director'][0]['name'],
                          "Quentin Tarantino")
Beispiel #15
0
 def test_search_to_info(self):
     """Gets a movie ID via search, then calls getMovieInfo using this
     """
     sr = tmdb.search("fight club")[0]
     movie = tmdb.getMovieInfo(sr['id'])
     self.assertEquals(
         sr['name'],
         movie['name']
     )
Beispiel #16
0
    def test_get_director(self):
        """Checks you can get the director of a film
        """
        mid = tmdb.search("Inglourious Basterds")[0]['id']
        movie = tmdb.getMovieInfo(mid)

        self.assertTrue(len(movie['cast']['director']) == 1)
        self.assertEquals(
            movie['cast']['director'][0]['name'],
            "Quentin Tarantino"
        )
    def __init__(self, filename, options):
        moviename = get_moviename(filename)
        if options.tmdbid:
            dbid = options.tmdbid
        else:
            results = tmdb.search(get_moviename(filename))
            if len(results) == 0:
                print "Movie not found in TMDB:", moviename
                dbid = prompt_mm("tmdb", "")
            else:
                search = results[0]
                dbid = search["id"]
                if mismatch(moviename, search["name"]):
                    print "Possible mismatch for: %s\n" % moviename
                    print "Search Result"
                    print "============="
                    print "Title: %s (%s)" % (search["name"], search["released"])
                    print search["url"]
                    dbid = prompt_mm("tmdb", search["id"])
        if dbid == "-1":
            print "Skipping art fetch"
        else:
            self.rawmovie = tmdb.getMovieInfo(dbid)
            print "Retrieving art:", self.rawmovie["name"]

            posterurl = self.get_url(self.rawmovie, "poster", options.interactive)
            if posterurl:
                posterpath = self.get_artpath(filename, posterurl, "poster")
                if not options.rescrape and os.path.exists(posterpath):
                    print "Art already exists:", posterpath
                else:
                    self.save_art(posterurl, posterpath)
            else:
                print "No posters found"

            backdropurl = self.get_url(self.rawmovie, "backdrop", options.interactive)
            if backdropurl:
                backdroppath = self.get_artpath(filename, backdropurl, "backdrop")
                if not options.rescrape and os.path.exists(backdroppath):
                    print "Art already exists:", backdroppath
                else:
                    self.save_art(backdropurl, backdroppath)
            else:
                print "No backdrops found"

            if options.allart:
                self.save_all_fanart(filename, self.rawmovie["images"].backdrops)
Beispiel #18
0
async def choosePoll(ctx, *, args):
    try:
        print('Choosing')
        movies = ''.join(args)[1:-1].split(',')
        chooseEmbed = discord.Embed(
            title='Choose Movie',
            color=discord.Color.purple(),
            description="Let's choose between the two movies")
        for movie in movies:
            chooseEmbed.add_field(name=movie,
                                  value=getMovieSummary(movie),
                                  inline=True)
        msg = await ctx.send(embed=chooseEmbed)
        reaction1 = "1️⃣"
        reaction2 = "2️⃣"
        reaction3 = "3️⃣"
        await msg.add_reaction(reaction1)
        await msg.add_reaction(reaction2)
        await msg.add_reaction(reaction3)
        print('Sleeping')
        await sleep(10)
        newMsg = await fetchMessage(ctx, msg.id)
        react = newMsg.reactions
        reactCount = [[movies[0], react[0].count], [movies[1], react[1].count],
                      [movies[2], react[2].count]]
        reactCount.sort(key=lambda x: x[1])
        await ctx.send('Looks like the public vote is to watch {}'.format(
            reactCount[2][0]))
        print(reactCount)
        dump = tmdb.getMovieInfo(reactCount[2][0])
        movieInfo = discord.Embed(title=reactCount[2][0],
                                  color=discord.Color.blue())
        tagline = dump['tagline']
        popularity = dump['popularity']
        ratings = dump['ratings']
        movieInfo.add_field(name='Tagline', value=tagline, inline=False)
        for i in dump['genres']:
            genre = i['name']
            movieInfo.add_field(name='Genre', value=genre)
        movieInfo.add_field(name='Popularity:', value=popularity)
        movieInfo.add_field(name='Ratings', value=ratings)
        await ctx.send(embed=movieInfo)
    except Exception as e:
        print('Exception')
        print(e)
    def loadMovie(self, metadata):
        details = tmdb.getMovieInfo(metadata.getId())
        metadata.plot(details['overview']).plotoutline(details['overview'])
        if details.has_key('runtime'):
            metadata.duration("%s minutes" % details['runtime'])
        if details.has_key('studios'):
            metadata.studio(", ".join([studio for studio in details['studios'].keys()]))
        if details.has_key('categories') and details['categories'].has_key('genre'):
            metadata.genre(", ".join([cat for cat in details['categories']['genre'].keys()]))
        if details.has_key('cast'):
            cast = details['cast']
            if cast.has_key('director'):
                metadata.director(", ".join([director['name'] for director in cast['director']]))
            if cast.has_key('screenplay'):
                metadata.writer(", ".join([writer['name'] for writer in cast['screenplay']]))
            if cast.has_key('actor'):
                metadata.cast([actor['name'] for actor in cast['actor']])
        if details .has_key('rating'):
            try:
                metadata.rating(float(details['rating']))
            except:
                log.warning("Could not parse rating from '%s'" % str(details['rating']))
        if details.has_key('released'):
            metadata.premiered(details['released'])
            try:
                import time
                metadata.year(time.strptime(details['released'], "%Y-%m-%d")[0])
            except:
                log.exception("Could not parse year")
        if details.has_key('images'):
            posters = details['images'].posters
            backdrops = details['images'].backdrops
            if len(posters) > 0:
                metadata.cover(posters[0]['cover'])
            if len(backdrops) > 0:
                metadata.fanart(backdrops[0]['poster'])

        log.debug("Found movie metadata from TMDB: %s" % str(metadata))
Beispiel #20
0
    def gen_movie_db(self):
        regex = re.compile(self.movie_regex)
        for root, dirs, files in os.walk(self.movie_directory, topdown=True):
            try:
                dirs.remove('.AppleDouble')
            except:
                pass

            for name in files:
                info = None
                comp = regex.match(name)
                if comp is not None:
                    info = comp.groupdict()
                    title = re.sub('\.',' ',info['title']).strip()
                    print 'Checking %s' % title
                    try:
                        movie = self.db['movies'][title]
                    except:
                        movie_list = tmdb.search(title)
                        if self.interactive:
                            idx = get_choice(movie_list)
                        else:
                            idx = 0
                        print 'got %s results' % movie_list
                        # for item in movie_list:
                        # # print item
                        try:
                            movie = Movie.select(Movie.q.name==movie_list[idx]['name']).getOne()
                            print 'found %s' % movie
                            movie.file_path = os.path.join(root,name)
                        except Exception as e:
                            item = tmdb.getMovieInfo(movie_list[idx]['id'])
                            movie = Movie()
                            movie.load(item)
                            movie.file_path = os.path.join(root,name)
                else:
                    print u'%s does not match' % name
Beispiel #21
0
def test_getmovieinfo_wrapper():
    """Tests tmdb.getMovieInfo() wrapper works correctly
    """
    r = tmdb.getMovieInfo(550)
    assert isinstance(r, tmdb.Movie)
Beispiel #22
0
 def test_getmovieinfo_wrapper(self):
     """Tests tmdb.getMovieInfo() wrapper works correctly
     """
     r = tmdb.getMovieInfo(550)
     self.assertEquals(type(r), tmdb.Movie)
Beispiel #23
0
def test_search_to_info():
    """Gets a movie ID via search helper, then calls getMovieInfo using this
    """
    sr = tmdb.search("fight club")[0]
    movie = tmdb.getMovieInfo(sr['id'])
    assert sr['name'] == movie['name']
Beispiel #24
0
        movies[genre][year] = []
        a = tmdb.browse(year=year, genres=genre_code, order_by="rating", order="desc", min_votes=5)
        movies_added = 0
        while movies_added < 2:
            i=0
            while i < len(a) and a[i]['name'] in movies_already:
                i += 1
            if i != len(a):
                movie = {}
                
                # grab the cover
                movie['cover'] = ""
                if len(a[i]['images']) > 0:
                    movie['cover'] = a[i]['images'][0]['cover']

                movieinfo = tmdb.getMovieInfo(a[i]['id'])

                movie['name'] =  a[i]['name']
                # movies[genre][year]['overview'] =  a[i]['overview']
                movie['rating'] =  a[i]['rating']
                movie['votes'] =  a[i]['votes']
                
                movie['actors'] = []
                for actor in movieinfo['cast']['actor']:
                    movie['actors'].append(actor['name'])
                    
                movie['directors'] = []
                for director in movieinfo['cast']['director']:
                    movie['directors'].append(director['name'])
                    
                # movies[genre][year]['year'] =  a[i]['released'].split("-")[0]
def insertMovie():
    try:
        html = ['''
                <html>
                <body>
                <form>
                Insert a movie into the Movie Database. <br />
                Note: TMDb's API will handle populating the movie's fields. <br /><br />
                Movie Title: <input type = "text" name = "movie" id="movietitle"/> 
                <input id="searchmovieTitle" type = "button" value = "Submit" onclick="loadXMLDoc(this)" />
                </form>
                ''']
        http_headers()
        print "\n".join(html)           
        
        form = cgi.FieldStorage()
        
        if form.has_key("movieID"):
            movieAPI = tmdb.getMovieInfo(form["movieID"].value)
            movie = movieObject.Movie(movieAPI['name'])
            
            try:
                year_released = movieAPI['released']
                year_released2 = year_released.split('-', 1 ) #show only the year, not whole date
                year_released = year_released2[0]
                movie.setYear(year_released)
            except:
                movie.setYear("Unavailable")
                
            try:
                photo_url = movieAPI['images'].posters[0]['cover']
                movie.setPhoto(photo_url)
            except:
                #Image Unavailable" picture is copyright of Town Of Warner(tm)
                movie.setPhoto("http://www.townofwarner.com/images/businesses/notavailable.gif")
            
            if form.has_key("trailerURL"):
                movie.setTrailer(form["trailerURL"].value)
            else:
                movie.setTrailer("Unavailable")
            
            try:
                genres = movieAPI['categories']['genre']
                movie.setGenre(genres.keys()[0])
            except:
                movie.setGenre("Unavailable")
        
            try:
                directors = movieAPI['cast']['director']
                
                directors_first = []
                directors_last = []
                
                for director in directors:
                    directors_name = director['name'].partition(' ')
                    directors_first.append(directors_name[0])
                    directors_last.append(directors_name[2])
                    
                movie.setDirectorsFirst(directors_first)
                movie.setDirectorsLast(directors_last)
                
            except:
                movie.setDirectorsFirst([])
                movie.setDirectorsLast([])

            try:
                actors = movieAPI['cast']['actor']
                
                actors_first = []
                actors_last = []
                
                for actor in actors:
                    actor_name = actor['name'].partition(' ')
                    actors_first.append(actor_name[0])
                    actors_last.append(actor_name[2])
                    
                movie.setCastFirst(actors_first)
                movie.setCastLast(actors_last)
                
            except:
                movie.setCastFirst([])
                movie.setCastLast([])
                
            try:
                summary = movieAPI['overview']
                movie.setSummary(summary)
            except:
                movie.setSummary("Unavailable")
                
            displayMovieInfo(movie)
            
            
        elif form.has_key("movie"):
            results = tmdb.search(form["movie"].value)
            
            try:
                results[0] #this checks if the movie list isn't empty
                
                html = ['''
                <br \><p><strong>Based on the list provided below, submit the
                    proper ID number in order to insert the movie.</strong></p>
                <p><i>Unfortunately, TMDb API does not supply trailer links. <strong>If applicable</strong>,
                    please also supply a URL for the movie's trailer.</i></p> 
                <form name = "movie_input">
                Movie ID: <input type = "text" name = "movieID"  id="mid"/> <br />
                Trailer URL: <input type = "text" name = "trailerURL" id="turl" /> <br />
                <input type = "button" value = "Submit" onclick="loadXMLDoc(this)" id="fulldetail" /><br \> <br \>
                <strong>LIST OF MOVIES</strong> <br />
                     ''']
                print "\n".join(html)
                
                #This prints out all of the possible movies based on the movie title the employee writes.
                #It prints the movie's ID, title, and year released (if provided in API).
                for searchResult in results:
                    print tmdb.getMovieInfo(searchResult['id'])['id'] + ": "
                    print tmdb.getMovieInfo(searchResult['id'])['name']
                    
                    year_released = tmdb.getMovieInfo(searchResult['id'])['released']
                    if year_released != None:
                            year_released = year_released.split('-', 1 ) #show only the year, not whole date
                            print "(%s)" %year_released[0]
                    html = ["<br />"]
                    print "\n".join(html)
            except:
                print "The movie could not be found in the API."  
                
                #Sometimes this will show at the end of the list even though
                #movies have been found. Try typing Transformers; the last
                #item in the list will show this. I think it's an ascii error.
    
        html = ['''
                </body>
                </html>
                ''']
        print "\n".join(html)
    
    except:
        http_headers()
        print "<!-- --> <hr><h1>Oops... an error occurred.</h1>"
        cgi.print_exception()
Beispiel #26
0
def test_getmovieinfo_wrapper():
    """Tests tmdb.getMovieInfo() wrapper works correctly
    """
    r = tmdb.getMovieInfo(550)
    assert isinstance(r, tmdb.Movie)
Beispiel #27
0
def test_search_to_info():
    """Gets a movie ID via search helper, then calls getMovieInfo using this
    """
    sr = tmdb.search("fight club")[0]
    movie = tmdb.getMovieInfo(sr['id'])
    assert sr['name'] == movie['name']
def insertMovie():
    try:
        html = [
            """
                <html>
                <body>
                <form name = "input" action = "insertMovie.py" method = "post">
                Insert a movie into the Movie Database. <br />
                Note: TMDb's API will handle populating the movie's fields. <br /><br />
                Movie Title: <input type = "text" name = "movie"/> 
                <input type = "submit" value = "Submit" />
                </input>
                </form>
                """
        ]

        http_headers()
        print "\n".join(html)

        form = cgi.FieldStorage()

        if form.has_key("movieID"):
            movie_ID = form["movieID"].value
            movie = tmdb.getMovieInfo(movie_ID)

            print "The movie '%s' has been successfully inserted" % movie["name"]
            # This is in a try block because the API doesn't always have all the fields filled in.
            # There are some nested try blocks--this is because certain fields (like the poster image or
            # summary) are more unlikely to be unavailable.
            try:
                try:
                    url = movie["images"].posters[0]["cover"]
                    html = ['<br /><br /><center><img src="']
                    print "\n".join(html)
                    print url
                    html = ["""" alt="poster" align = "top"/></center><br />"""]
                    print "".join(html)
                # image copyright of Town Of Warner(tm)
                except:
                    html = [
                        """
                            <br /><br /><center><img src="http://www.townofwarner.com/images/businesses
                            /notavailable.gif" alt="poster" align = "top"/></center><br />
                            """
                    ]
                    print "".join(html)

                print "<strong>Movie Name:</strong> %s <br /><br />" % movie["name"]
                print "<strong>Date Released:</strong> %s <br /><br />" % movie["released"]

                # Sometimes the API won't successfully show the overview (usually due to
                # an ascii codec error).
                try:
                    print "<strong>Movie Summary:</strong> %s <br /><br />" % movie["overview"]
                except:
                    print ""

                print "<strong>Movie Director(s):</strong>"
                directors = movie["cast"]["director"]
                for director in directors:
                    print " %s, " % director["name"]

                print "<br /> <br /><strong>Movie Cast:</strong>"
                cast = movie["cast"]["actor"]
                for member in cast:
                    print " %s, " % member["name"]

                print "<br /> <br /><strong>Movie Genre(s):</strong>"
                genres = movie["categories"]["genre"]
                for genre in genres:
                    print " %s, " % genre
            except:
                print ""

        elif form.has_key("movie"):
            results = tmdb.search(form["movie"].value)

            try:
                results[0]  # this checks if the list isn't empty

                html = [
                    """
                <br \><p>Based on the list provided below, submit the proper ID number in order to insert the movie.</p>       
                <form name = "movie_input" action = "insertMovie.py" method = "post">
                Movie ID: <input type = "text" name = "movieID" /> 
                <input type = "submit" value = "Submit" /><br \> <br \>
                     """
                ]
                print "\n".join(html)

                # This prints out all of the possible movies based on the movie title the employee writes.
                # It prints the movie's ID, title, and year released (if provided in API).
                for searchResult in results:
                    print tmdb.getMovieInfo(searchResult["id"])["id"] + ": "
                    print tmdb.getMovieInfo(searchResult["id"])["name"]

                    year_released = tmdb.getMovieInfo(searchResult["id"])["released"]
                    if year_released != None:
                        year_released = year_released.split("-", 1)  # show only the year, not whole date
                        print "(%s)" % year_released[0]

                    html = ["<br />"]
                    print "\n".join(html)
            except:
                print "The movie could not be found in the API."

                # If not found in API, maybe employee can manually insert the movie?

                # Sometimes this will show at the end of the list even though
                # movies have been found. Try typing Transformers; the last
                # item in the list will show this.

    except:
        http_headers()
        print "<!-- --> <hr><h1>Oops... an error occurred.</h1>"
        cgi.print_exception()
Beispiel #29
0
def get_movie_imdb_id(tmdb_id):
    return tmdb.getMovieInfo(tmdb_id)["imdb_id"]
Beispiel #30
0
 def test_search_to_info(self):
     """Gets a movie ID via search, then calls getMovieInfo using this
     """
     sr = tmdb.search("fight club")[0]
     movie = tmdb.getMovieInfo(sr['id'])
     self.assertEquals(sr['name'], movie['name'])