Exemple #1
0
	def testMovieWeekend(self):
		m = Movie(121, "Saturday", True, True)

		m.addTicket(20,False)
		price = m.finishPurchase()

		self.assertEquals(price, 17.0)
Exemple #2
0
        def loadActresses(self, count=100):	
                """function to read actresses data and create a relationship between actress and movie,"""

                # read actresses from file
                actresses = self.readArtists("actress", count)
                self.filePointerActresses = self.fileHandleActresses.tell()
                objActress = Actress("", 0)
                objMovie = Movie("", "", 0)

                for actress in actresses:
                        name, title, year = actress
                        actress = objActress.getArtistByName(name, self.actressesList)

                        # check if actress already not exist then add it
                        if actress == None:
                                self.artistCounter += 1
                                actressId = self.artistCounter
                                newActress = Actress(actressId, name)
                                self.actressesList.append(newActress)
                        else:
                                actressId = actress.getArtistId()

                        # check if movie already exists. only if the movie doesn't exist, it will create an ID and 
                        if not objMovie.doesMovieExist(title, self.moviesList) and \
                           objMovie.getMovieByName(title, self.moviesList) == None:
                                self.movieCounter += 1
                                movieId = self.movieCounter
                                movie = Movie(movieId, title, year)
                                self.moviesList.append(movie)

                                # create relation between actor and  movie
                                relation = ArtistMovieRelation(actressId, movieId)

                                self.relationsList.append(relation)
Exemple #3
0
        def loadActors(self, count=100):
                """function to read actors data and create a relationship between actors and movie."""

                actors = self.readArtists("actor", count)
                self.filePointerActors = self.fileHandleActors.tell()

                objActor = Actor("", 0)
                objMovie = Movie("", "", 0)

                for actor in actors:
                        name, title, year = actor
                        
                        # check if actor does not exist else create ID
                        if objActor.getArtistByName(name, self.actorsList) == None:
                                self.artistCounter += 1
                                actorId = self.artistCounter
                                newActor = Actor(actorId, name)
                                self.actorsList.append(newActor)
                                
                                # searches the movie list to check if movies have not been already visualized
                                if not objMovie.doesMovieExist(title, self.moviesList) and \
                                   objMovie.getMovieByName(title, self.moviesList) == None:
                                        self.movieCounter += 1
                                        movieId = self.movieCounter
                                        movie = Movie(movieId, title, year)
                                        self.moviesList.append(movie)

                                        # create relation between actor and  movie
                                        relation = ArtistMovieRelation(actorId, movieId)
                                        self.relationsList.append(relation)
class MovieTest(unittest.TestCase):
    def setUp(self):
        self.movie = Movie("Test Movie", 5)

    def test_create_movie_get_name_and_rating(self):
        self.assertEqual("Test Movie", self.movie.get_name())
        self.assertEqual(5, self.movie.get_rating())
Exemple #5
0
        def onObjectClick(self, event): 
                """function to get movie details on the movie when clicked."""
                

                tempMovie = Movie(2, 4, "132")
                tempMovie = tempMovie.getMovieByOvalId(event.widget.find_closest(event.x, event.y)[0], self.moviesList)

                # get id's of the artists starring in this movie
                artistmovierelation = ArtistMovieRelation(0,0)
                artistStarring = artistmovierelation.getArtistsByMovieId(tempMovie.getMovieId(), self.relationsList)

                tempActor = Actor("","")
                tempActress = Actress("","")

                # fetches the name of the actor or actress. finds out whether it originated from tbe actor or actress class.

                artistsStartingNames = []
                for artistId in artistStarring:
                        actor = tempActor.getArtistByid(artistId, self.actorsList)
                        if actor != None:
                                artistsStartingNames.append(actor.getArtistName())
                        else:
                                actress = tempActress.getArtistByid(artistId, self.actressesList)
                                if actress != None:
                                        artistsStartingNames.append(actress.getArtistName())

                #  labels to show the film details
                self.movieDetailsVar.set('Title of the Film   : ' + tempMovie.getMovieTitle() + "\n" + "\n" 
                                         "Year Film Released : " + tempMovie.getMovieYear() + "\n"+ "\n" 
                                         "Actor/Actress Name  : " + ", ".join(artistsStartingNames))
Exemple #6
0
	def testGoingWithLotsOfPeopleOnThursday(self):
		m = Movie(110, "Thursday", True, True)
		
		for i in range(30):
			m.addTicket(20+i,True)
		
		price = m.finishPurchase()
		self.assertEquals(price,30 * 9)
class TestMovieClass(unittest.TestCase):
    def setUp(self):
        self.m = Movie("Best.Movie.Ever.", 2014, 10)

    def test_get_movie_title(self):
        self.assertEqual("Best.Movie.Ever.", self.m.get_title())

    def test_get_movie_year(self):
        self.assertEqual(2014, self.m.get_year())

    def test_get_movie_rating(self):
        self.assertEqual(10, self.m.get_rating())

    @unittest.skip("This works but no point in generating extra movies.")
    def test_save_movie(self):
        self.assertTrue(self.m.save())
Exemple #8
0
    def _loadFactory(self):
        if len(self._plugins) <= 0:
            return

        self._factory = fact.Factory(Movie.getTypeName())
        for plug in self._plugins:
            self._factory.addModule(plug)
Exemple #9
0
    def get_top_movies(self, top_x, min_ratings):
        movie_rows_list = Movie.read_movie_file()

        movie_list_with_min_ratings = []
        for movie in movie_rows_list:
            movie_id = movie[0]
            movie_name = movie[1]

            ratings_list = self.get_movie_rating_list(movie_id)
            # print("movie_id", movie_id)
            # print("ratings", ratings_list)

            if len(ratings_list) >= min_ratings:
                movie_avg_tup = (movie_id, movie_name, self.get_avg_rating(movie_id))
                movie_list_with_min_ratings.append(movie_avg_tup)

        sorted_list = sorted(movie_list_with_min_ratings, key = lambda x: x[2])
        reversed_list = list(reversed(sorted_list))
        # print(sorted_list)
        # print(reversed_list)

        top_x_list = reversed_list[:top_x]
        #print(top_x_list)

        return top_x_list
Exemple #10
0
 def getMovieInfoByTMDB_ID(self, tmdb_id=''):
     self.domain = 'movie'
     self.action = 'getInfo'
     if tmdb_id:
         self.tmdb_id = tmdb_id
     
     try:    
         movie_list = Movie.select(Movie.q.tmdb_id==self.tmdb_id)
         if movie_list.count() == 1:
             oMovie = movie_list[0]
         elif movie_list.count() == 0:
             raise SQLObjectNotFound
         else:
             raise AttributeError
     except SQLObjectNotFound:
     
         self.url = "%s%s" % (self.urls.generateURL(self.domain, self.action), self.tmdb_id)        
         self.movie_info = self._getResponse(self.url)
                 
         oMovie = Movie(tmdb_id = self._getKey('id', 0),
                        imdb_id = self._getKey('imdb_id', ''),
                        title = self._getKey('name', ''),
                        year = int(self._getYearFromDate(self._getKey('released', ''))),
                        genre = self._getPrimaryGenre(self._getKey('genres', [])),
                        mpaa = Movie.ratings.index(self._getKey('certification', 'NR')),
                        director = self._getDirector(self._getKey('cast', [])),
                        actors = self._getPrimaryActors(self._getKey('cast', [])),
                        description = self._getKey('overview', ''),
                        length = int(self._getKey('runtime', 0)),
                        poster_URL = self._getPosterURL(self._getKey('posters', '')),
                        )
     
     return oMovie
class TestMovie(unittest.TestCase):
    """Tests for movie objects"""
    def setUp(self):
        self.movie = Movie('../test.mkv')

    def test_get_extension(self):
        self.assertEqual('.mkv', self.movie.get_extension())

    def test_get_filename(self):
        self.assertEqual('test', self.movie.get_filename())

    def test_get_title(self):
        self.assertEqual(None, self.movie.get_title())

    def test_get_duration(self):
        self.assertEqual('0:21:37', self.movie.get_duration())
Exemple #12
0
 def load_movies(self):
     self.cursor.execute("SELECT * FROM movies")
     unparsed_movies = self.cursor.fetchall()
     movies = {}
     if unparsed_movies:
         for unparsed_movie in unparsed_movies:
             #get info from database
             movie_id = unparsed_movie[0]
             title = unparsed_movie[1]
             year = unparsed_movie[2]
             rating = unparsed_movie[3]
             #create a new Movie object and add it to {movie_id: Movie}
             movie = Movie(title, year, rating)
             movie.cast = self.get_actors_in_movie(int(movie_id))
             movies[movie_id] = movie
     return movies
	def find_movie(self,user_action):
		self.header_output("Finding....")
		print "\n Example: find iron or find Iron Man 3 \n"
		movies = Movie.read_movies_from_file()
		if user_action != []:
			arg    = user_action.pop(0)
			found  = [x for x in movies if self.search(x,arg)]
			self.movie_table_output(found)
 def __init__(self, movie_name):
     super(Controller, self).__init__()
     self.session = login()
     self.movie_name = movie_name
     self.movie = Movie(self.movie_name, self.session)
     #self.url = 'http://s.weibo.com/weibo/'
     self.url = 'http://s.weibo.com/wb/'
     self.page_count = 0
class Controller(object):
    """docstring for Controller"""
    def __init__(self, movie_name):
        super(Controller, self).__init__()
        self.session = login()
        self.movie_name = movie_name
        self.movie = Movie(self.movie_name, self.session)

    def start(self):
        start_time = datetime.datetime.strptime(START_TIME, '%Y-%m-%d-%H')
        end_time = datetime.datetime.strptime(END_TIME, '%Y-%m-%d-%H')
        if start_time < end_time:
            while True:
                time.sleep(3)
                cursor_time = start_time + datetime.timedelta(hours=1)
                timescope = datetime.datetime.strftime(start_time, '%Y-%m-%d-%H') +':' + datetime.datetime.strftime(cursor_time, '%Y-%m-%d-%H')
                url = 'http://s.weibo.com/weibo/'+ quote(self.movie_name) +'&timescope=custom:'+ quote(timescope)
                response = self.session.get(url)
                count = self.get_page_count(response.content)
                self.handle_one_page(url, count, self.movie.id)
                start_time = cursor_time
                if start_time > end_time:
                    break
        else:
            print 'ERROR:Start time must early than end time!'

    def get_page_count(self, content):
        max_count = 0
        result = re.findall(r'&page=\d+', content)
        for index in result:
            info = index.split('=')
            if int(info[1]) > max_count:
                max_count = int(info[1])
        print 'max_page:', max_count
        return max_count

    def handle_one_page(self, url_head, page_count, movie_id):
        for i in xrange(1, page_count + 1):
            page = str(i)
            url = url_head +"&page=" + page
            response = self.session.get(url)
            self.movie.decode_content(response.content, movie_id)
            print "现在是第%s页" % page
            time.sleep(3)
	def add(self):
		args = []
		self.header_output("Adding....")
		args.append(raw_input("Enter Movie Name: ").strip())
		args.append(raw_input("Enter Release year: ").strip())
		args.append(raw_input("Enter Movie Rating: ").strip())
		if Movie.add_movie_into_file(args):
			print("\nNew movie has been added to your movie list")
		else:
			print("\nSorry File Error!")
Exemple #17
0
    def __init__(self):

        super(RenameMovie, self).__init__()

        rename_group = DadVision.cmdoptions.parser.add_argument_group(
            "Rename Options", description=None)
        rename_group.add_argument(
            "--force-rename",
            dest="force_rename",
            action="store_true",
            default=False,
            help="Force Renames for Files That Already Exist")
        rename_group.add_argument(
            "--force-delete",
            "--fd",
            dest="force_delete",
            action="store_true",
            default=False,
            help="Force Deletes for Files That Already Exist")
        rename_group.add_argument(
            "--ignore_excludes",
            dest="ignore_excludes",
            action="store_true",
            default=False,
            help="Process all Files Regardless of Excludes")
        rename_group.add_argument("--no-check_video",
                                  dest="check_video",
                                  action="store_false",
                                  default=True,
                                  help="Bypass Video Checks")
        rename_group.add_argument(
            "--no-move",
            "--nm",
            dest="move",
            action="store_false",
            default=True,
            help="Do not change directories, rename in place")
        rename_group.add_argument("--dir",
                                  type=str,
                                  dest='dir',
                                  nargs='?',
                                  default=None,
                                  help="Rename and place in this directory")

        self.movieopts = CmdOptions()
        self.movie = Movie()

        self.regex_repack = re.compile('^.*(repack|proper).*$', re.IGNORECASE)
        self.regex_NewMoviesDir = re.compile('^{}.*$'.format(
            DadVision.settings.NewMoviesDir, re.IGNORECASE))

        return
Exemple #18
0
def Create_new_movie(check):
    title = input("Tytul: ")
    genre = input("Gatunek: ")
    year = input("Rok: ")
    x = Movie(None, title, genre, year)  #tworzenie obiektu klasy movie
    c.execute("INSERT INTO movie VALUES(:movie_id,:title,:genre,:year)", {
        'movie_id': x.movie_id,
        'title': x.title,
        'genre': x.genre,
        'year': x.year
    })
    conn.commit()
    menu(check)
Exemple #19
0
def movie_edit_page(movie_key):
    db = current_app.config["db"]
    movie = db.get_movie(movie_key)
    form = MovieEditForm()
    if form.validate_on_submit():
        title = form.data["title"]
        year = form.data["year"]
        movie = Movie(title, year=year)
        db.update_movie(movie_key, movie)
        return redirect(url_for("movie_page", movie_key=movie_key))
    form.title.data = movie.title
    form.year.data = movie.year if movie.year else ""
    return render_template("movie_edit.html", form=form)
Exemple #20
0
 def load_from_file(cls, filename):  #cls stands for the User class.
     with open(filename, 'r') as f:
         content = f.readlines()
         username = content[0].rstrip()
         movies = []
         for line in content[1:]:
             movie_data = line.rstrip('\n').split(',')
             movies.append(
                 Movie(movie_data[0], movie_data[1],
                       movie_data[2] == 'True'))
     user = cls(username)  #cls stands for the User class.
     user.movies = movies
     return user
Exemple #21
0
 def get_movies(id):
     r = requests.get(
         f'https://api.themoviedb.org/3/movie/{id}?api_key={TMDB_API_KEY}&language=fr_FR'
     ).json()
     return Movie(title=r['title'],
                  duration=r['runtime'],
                  imdb_id=r['imdb_id'],
                  original_title=r['original_title'],
                  production_budget=r['budget'],
                  synopsis=r['overview'],
                  release_date=datetime.datetime.strptime(
                      r['release_date'], "%Y-%m-%d").strftime("%Y-%m-%d"),
                  productors=Tmdb.get_productors(r))
Exemple #22
0
def findAll(table):
    cnx = connectToDatabase()
    cursor = createCursor(cnx)
    cursor.execute(findAllQuery(table))
    results = cursor.fetchall()  # liste de dictionnaires contenant des valeurs scalaires
    closeCursor(cursor)
    disconnectDatabase(cnx)
    if (table == "movies"):
        movies = []
        for result in results: # result: dictionnaire avec id, title, ...
            movie = Movie(
                title=result['title'],
                original_title=result['original_title'],
                duration=result['duration'],
                release_date=result['release_date'],
                rating=result['rating']
            )
            movie.id = result['id']
            movies.append(movie)
        return movies

    if (table == "people"):
        people = []
        for result in results: # result: dictionnaire avec id, title, ...
            person = Person(
                imdb_id=result['imdb_id'],
                name=result['name'],
            )
            person.id = result['id']
            people.append(person)
        return people

    if (table == "genres"):
        genres = []
        for result in results: # result: dictionnaire avec id, title, ...
            genre = Genre(name=result['name'])
            genre.id = result['id']
            genres[genre.name] = genre
        return genres
Exemple #23
0
def download(request, id):
    try:
        card = Query(Card).get(id)
        tid = card.get('template')
        type = card.get('type')
        msstream = BytesIO()
        data = {
            'copyright': '天天码图',
            'author': card.get('author'),
            'id': card.id,
            'url': card.get('img_url'),
            'title': card.get('name'),
            'content': card.get('content')
        }
        if type == 'movie':
            Movie.movie(data, msstream)
        elif type == 'music':
            Music.music(data, msstream)
        elif type == 'book':
            Book.book(data, msstream)
        else:
            if tid == 1:
                template(card, msstream)
            elif tid == 2:
                template2(card, msstream)
            elif tid == 3:
                template3(card, msstream)
            elif tid == 4:
                template4(card, msstream)
            else:
                template(card, msstream)
        return HttpResponse(msstream.getvalue(), content_type="image/png")
    except LeanCloudError as e:
        if e.code == 101:  # 服务端对应的 Class 还没创建
            card = ''
            return HttpResponse(e, content_type="text/plain")
        else:
            raise e
            return HttpResponse(e, content_type="text/plain")
Exemple #24
0
 def load_from_file(cls, filename):
     with open(filename, 'r') as f:
         content = f.readlines()
         username = content[0]
         movie_name = []
         for line in content[1:]:
             movie_data = line.split(",")
             movie_name.append(
                 Movie(movie_data[0], movie_data[1],
                       movie_data[2] == "True"))
     user = cls(username)
     user.movies = movie_name
     return user
Exemple #25
0
def movie_add_page():
    if not current_user.is_admin:
        abort(401)
    form = MovieEditForm()
    if form.validate_on_submit():
        title = form.data["title"]
        year = form.data["year"]
        movie = Movie(title, year=year)
        db = current_app.config["db"]
        movie_key = db.add_movie(movie)
        flash("Exam added.")
        return redirect(url_for("movie_page", movie_key=movie_key))
    return render_template("movie_edit.html", form=form)
Exemple #26
0
def find(table, id):
    cnx = connectToDatabase()
    cursor = createCursor(cnx)
    query = findQuery(table, id)
    cursor.execute(query)
    results = cursor.fetchall()

    entity = None
    if (cursor.rowcount == 1):
        row = results[0]
        if (table == "movies"):
            entity = Movie(row['title'], row['original_title'],
                           row['release_date'], row['duration'], row['rating'])
            entity.id = row['id']
        if table == "people":
            entity = Person(row['firstname'], row['lastname'])
            entity.id = row['id']

    closeCursor(cursor)
    disconnectDatabase(cnx)

    return entity
    def addMovie(self, title, description, genre):
        '''
        :param title: string
        :param description: string
        :param genre: string
        :return: None
        '''

        movie = Movie(len(self.movies) + 1, title, description, genre)

        self.movies[self.movies.get_index()] = movie

        self.undoList.append(['addMovie', title, description, genre])
Exemple #28
0
def topmovies():
    '''
        A web scraper to extract top movies information out of imdb website
        and create movie objects and return a list of movies
    '''

    imdburl = 'https://www.imdb.com'
    url = 'https://www.imdb.com/list/ls068082370/'
    page = requests.get(url)

    soup = BeautifulSoup(page.content, 'html.parser')
    results = soup.find(id='main')
    movies_content = results.find_all('div', class_='lister-item-content')

    movies = []

    for movie_elem in movies_content:
        header = movie_elem.find('h3', class_='lister-item-header')

        index = header.find('span', class_='lister-item-index unbold text-primary')

        title = header.find('a')
        yearobject = header.find('span', class_='lister-item-year')
        yearpattern = re.compile(r'(\d{4})')
        yearsearch = yearpattern.search(yearobject.text)
        yearnum = None
        if yearsearch:
            yearnum = int(yearsearch.group(0))

        link = title['href']

        description = movie_elem.find('p', class_='')

        moreinfo = movie_elem.find_all('p', class_='text-muted text-small')
        genre = moreinfo[0].find('span', class_='genre')
        duration = moreinfo[0].find('span', class_='runtime')
        director = moreinfo[1].find('a')
        stars = moreinfo[1].find_all('a')[1:-1]
        starlist = []
        for star_elem in stars:
            starlist.append(star_elem.text.strip())

        rate = movie_elem.find('div', class_='ipl-rating-widget').find('span', class_='ipl-rating-star__rating')
        
        movie = Movie(title=title.text.strip(),
                year=yearnum,
                director=director.text.strip(),
                stars = starlist,
                genre=genre.text.strip().split(', '),
                duration=int(duration.text.strip()[0:-4]),
                rate=float(rate.text.strip()), 
                description=description.text.strip())

        movie.setindex(index.text)
        movie.setlink(imdburl+link)
        movies.append(movie)


    return movies
Exemple #29
0
def main():
    """
    Contains a menu with four capabilities; displaying a movie list, adding to the movie list,
    watching a movie from the list and quitting the program.
    """
    MENU = "Menu:\nL - List movies\nA - Add new movie\nW - Watch a movie\nQ - Quit"

    movie_collection = MovieCollection()
    movie_collection.load_movies("movies.csv")

    print("Movies To Watch 2.0 - by Jonache Hilton\n{} movies loaded\n\n{}".format(len(movie_collection.movies), MENU))
    menu_choice = input(">>>").upper()
    while menu_choice != "Q":
        if menu_choice == "L":
            display_list(movie_collection.movies, calculate_dynamic_width(movie_collection.movies), movie_collection)

        elif menu_choice == "A":
            movie_name = ""
            is_valid_input = False
            while not is_valid_input:
                print("Title:")
                movie_name = input(">>>")
                is_valid_input = check_string_error(movie_name)

            print("Year:")
            movie_year = check_integer_error()

            print("Category:")
            movie_category = ""
            is_valid_input = False
            while not is_valid_input:
                movie_category = input(">>>")
                is_valid_input = check_string_error(movie_category)

            movie_to_add = Movie(movie_name, movie_year, movie_category, False)
            movie_collection.add_movie(movie_to_add)
            print("{} ({} from {}) added to movie list".format(movie_name, movie_category, movie_year))

        elif menu_choice == "W":
            if movie_collection.get_number_of_watched_movies() == len(movie_collection.movies):
                print("No more movies to watch!")
            else:
                print("Enter the number of a movie to mark as watched")
                watch_movie(movie_collection.movies)
        else:
            print("Invalid menu choice")

        print(MENU)
        menu_choice = input(">>>").upper()

    movie_collection.save_movies("movies.csv")
Exemple #30
0
def movie_from_div(div):
    """
    从一个 div 里面获取到一个电影信息
    """
    e = pq(div)

    # 小作用域变量用单字符
    m = Movie()
    m.name = e('.title').text()
    m.other = e('.other').text()
    m.score = e('.rating_num').text()
    m.quote = e('.inq').text()
    m.cover_url = e('img').attr('src')
    m.ranking = e('.pic').find('em').text()
    return m
Exemple #31
0
def insert_if_ok(movies, name, imdb_id, year):
    imdb_url = "https://www.imdb.com/title/" + imdb_id

    response = requests.get(imdb_url)
    if response.status_code != 200:
        print(
            "\n\nError: movie with id {} failed to load from imdb\n\n".format(
                imdb_id))
        return False

    html = BeautifulSoup(response.content, 'html.parser')

    # get genres
    genres = []
    for line in html.find("div", class_="subtext").find_all("a")[:-1]:
        genres.append(str(line.contents[0]).strip())
    if "Animation" in set(genres):
        return False

    # get language
    languages = []
    for line in list(html.find("div",
                               id="titleDetails").children)[9].find_all('a'):
        languages.append(str(line.contents[0]))
    if "English" not in languages:
        return False

    # get number of votes
    count = int(html.find("div", class_="imdbRating").find('a').find("span")\
      .contents[0].replace(',', ''))
    if count < 250000:
        return False

    if imdb_id not in movies:
        movies[imdb_id] = Movie(name, imdb_id, year)
        movies[imdb_id].imdb_features['genre'] = genres

    return True
Exemple #32
0
    def __init__(self, parent, preferences_dialog):
        QDialog.__init__(self, parent)

        self.ui = loadUi("renaming_rule_dialog.ui", self)

        self.ui.preferences_dialog = preferences_dialog

        # creates an example movie, used to test the renaming rule
        self.example_movie = Movie()

        # TODO
        # self.populate_list_visual_rule()
        # self.update_representations()
        # TODO
        # renaming_rule = utils.preferences.value("renaming_rule").toString()
        # self.update_example_movie(renaming_rule)

        ## slots connection
        self.ui.list_visual_rule.model().rowsInserted.connect(self.rule_changed)
        self.ui.list_visual_rule.model().rowsRemoved.connect(self.rule_changed)

        self.ui.button_remove_rule.clicked.connect(self.remove_rule)
        self.ui.button_clean_rule.clicked.connect(self.clean_rule)

        self.ui.button_add_title.clicked.connect(self.add_title)
        self.ui.button_add_original_title.clicked.connect(self.add_original_title)
        self.ui.button_add_year.clicked.connect(self.add_year)
        self.ui.button_add_director.clicked.connect(self.add_director)
        self.ui.button_add_duration.clicked.connect(self.add_duration)
        self.ui.button_add_language.clicked.connect(self.add_language)

        self.ui.button_add_round_brackets.clicked.connect(self.add_round_brackets)
        self.ui.button_add_square_brackets.clicked.connect(self.add_square_brackets)
        self.ui.button_add_curly_brackets.clicked.connect(self.add_curly_brackets)

        self.ui.button_show_preferences.clicked.connect(self.show_preferences)

        self.ui.button_close.clicked.connect(self.close)
def find_all(table):
    global db
    cursor = db.get_cursor()
    cursor.execute(find_all_query(table))
    results = cursor.fetchall(
    )  # liste de dictionnaires contenant des valeurs scalaires
    if (table == "movies"):
        movies = []
        for result in results:  # dico avec Id, title...
            movie = Movie(imdb_id=result['imdb_id'],
                          title=result['title'],
                          original_title=result['original_title'],
                          genre=result['genre'],
                          synopsis=result['synopsis'],
                          tagline=result['tagline'],
                          duration=result['duration'],
                          production_budget=result['production_budget'],
                          marketing_budget=result['marketing_budget'],
                          release_date=result['release_date'],
                          rating=result['rating'],
                          imdb_score=result['imdb_score'],
                          box_office=result['box_office'],
                          popularity=result['popularity'],
                          awards=result['awards'],
                          is_3D=result['is_3D'])
            movie.id = result['id']
            movies.append(movie)
        return movies
    if (table == "people"):
        people = []
        for result in results:  # dico avec Id, firstname...
            person = Person(
                firstname=result['firstname'],
                lastname=result['lastname'],
            )
            person.id = result['id']
            people.append(person)
        return people
 def find_all(self):
     cnx = self.connect_to_database()
     cursor = self.create_cursor()
     stmt = ("SELECT * FROM movies")
     cursor.execute(stmt)
     results = cursor.fetchall()  # liste de données scalaires
     movies = []
     for result in results:  #result: dictionnaire
         movie = Movie(title=result['title'],
                       original_title=result['original_title'],
                       synopsis=result['synopsis'],
                       duration=result['duration'],
                       rating=result['rating'],
                       release_date=result['release_date'],
                       budget=result['budget'],
                       revenue=result['revenue'],
                       imdb_id=result['imdb_id'],
                       score=result['score'])
         movie.id = result['id']
         movies.append(movie)
     self.close_cursor()
     self.disconnect_database()
     return movies
Exemple #35
0
def rename(filename):
	filename_without_extension = filename
	extension = ""
	
	if os.path.isdir(filename) == False: 
		filename_without_extension, extension = os.path.splitext(filename)
	    
	query = ImdbQuery.create_query_from_filename(filename_without_extension)
	movie = Movie.create_movie_from_imdb_query(query)
	if movie.title == "None":
#		sys.stdout.write("Query Was: " + query + "\n")
		return "None"
		
	return unicode(movie).encode("utf-8") + extension
def fetch_movies():
    """ fetches data from data.txt file and
        returns a list of  Movie objects
    """
    movies = []
    # Read data from data.txt
    with open("data.txt") as f:
        content = f.readlines()

    # Create movie objects from the data collected
    for c in content:
        m = c.split(";")
        movies.append(Movie(m[0], m[1], m[2], m[3], m[4]))
    return movies
Exemple #37
0
def check_synopsis():
    """Check the database to make sure synopsis have been collected for every movie."""

    movies_df = database_helper.select_query("movies", {"enabled": '1'})
    movies = []
    with tqdm(total=len(movies_df)) as pbar:
        for index, row in movies_df.iterrows():
            movie = Movie(row)
            movies.append(movie)

            #if there is no synopsis print movie to command line
            if (movie.synopsis == ''):
                print(movie.title + " (" + movie.imdbId + ") no synopsis")
            pbar.update(1)
Exemple #38
0
 def load_movies(self, FILE_NAME):
     """ Method to load movies from csv file """
     if not os.path.isfile(FILE_NAME):
         return
     movie_output_file = open(FILE_NAME, "r")
     for line in movie_output_file.readlines():
         movie_string = line.strip("\n").split(",")
         if movie_string[3] == "w":
             is_watched = True
         else:
             is_watched = False
         movie = Movie(movie_string[0], int(movie_string[1]), movie_string[2], is_watched)
         self.movies.append(movie)
     movie_output_file.close()
 def find_one_by_id(self, id):
     cnx = self.connect_to_database()
     cursor = self.create_cursor()
     stmt = ("SELECT * FROM movies WHERE id = {} LIMIT 1".format(id))
     cursor.execute(stmt)
     results = cursor.fetchall()
     movie = None
     if cursor.rowcount == 1:
         row = results[0]
         movie = Movie(title=row['title'],
                       original_title=row['original_title'],
                       synopsis=row['synopsis'],
                       duration=row['duration'],
                       rating=row['rating'],
                       release_date=row['release_date'],
                       budget=row['budget'],
                       revenue=row['revenue'],
                       imdb_id=row['imdb_id'],
                       score=row['vote_average'])
         movie.id = row['id']
     self.close_cursor()
     self.disconnect_database()
     return movie
Exemple #40
0
def deploy():
    print("resetting database....")
    db.drop_all()
    db.create_all()

    gosling = Actor(name="Ryan Gosling", age="37")
    evans = Actor(name="Chris Evans", age="36")
    lawrence = Actor(name="Jennifer Lawrence", age="27")

    notebook = Movie(
        title="The Notebook",
        year="2004",
        description=
        "This movie is incredibly romantic. I would reccomend seeing this with a loved one, or if its a girls night and you want to cry. This is such a beautiful movie!",
        actor=gosling)
    avengers = Movie(
        title="The Avengers",
        year="2012",
        description=
        "The Avengers is the best superhero movie ever made so far. Different superheros come together to fight in an awesome squad to beat aliens and villians.",
        actor=evans)
    sparrow = Movie(
        title="Red Sparrow",
        year="2018",
        description=
        "The Red Sparrow is definitely not your average movie, it is action packed, bloody and sexual all at the same time.",
        actor=lawrence)

    db.session.add(gosling)
    db.session.add(evans)
    db.session.add(lawrence)

    db.session.add(notebook)
    db.session.add(avengers)
    db.session.add(sparrow)

    db.session.commit()
    def tmdb_get_by_id(self, id):
        r = requests.get(
            f'https://api.themoviedb.org/3/movie/{id}?api_key={self.api_key}')
        r = r.json()
        if 'status_code' not in r:
            title = r['title']
            original_title = r['original_title']
            release_date = r['release_date']
            if r['adult'] == 'False':
                rating = 'TP'
            else:
                rating = '-18'
            duration = r['runtime']
            box_office = r['revenue']
            imdb_id = r['imdb_id']
            imdb_score = r['vote_average']
            synopsis = r['overview']
            production_budget = r['budget']
            popularity = r['popularity']
            awards = None
            marketing_budget = None
            tagline = r['tagline']
            if r['genres']:
                if r['genres'][0]:
                    genre_split0 = r['genres'][0]
                    genre0 = genre_split0['name']
                    if r['genres'][1]:
                        genre_split1 = r['genres'][1]
                        genre1 = genre_split1['name']
                        if r['genres'][2]:
                            genre_split2 = r['genres'][2]
                            genre2 = genre_split2['name']
                            genre = f"{genre0}, {genre1}, {genre2}"
                        else:
                            genre = f"{genre0}, {genre1}"
                    else:
                        genre = f"{genre0}"
            else:
                genre = None
            is_3D = None

            movie = Movie(imdb_id, title, original_title, genre, synopsis,
                          tagline, duration, production_budget,
                          marketing_budget, release_date, rating, imdb_score,
                          box_office, popularity, awards, is_3D)
            return movie
        if r['status_code'] == 34:
            movie = f"Aucun film avec l'id {id} n'existe dans TMDBapi"
            return movie
Exemple #42
0
    def create_movie(self, json_data):
        '''Creates Movie() object.

        :type json_data: dict
        :param json_data: movie data in json format

        :rtype Movie: Movie object
        :returns: created movie object
        '''
        movie_data = {}
        movie_data['imdb_id'] = json_data.get('imdb_id', None)
        movie_data['title'] = json_data.get('title', None)
        movie_data['year'] = json_data.get('year', None)
        movie_data['description'] = json_data.get('description', None)
        return Movie(**movie_data)
Exemple #43
0
    def load_from_file(self, filename):
        with open(filename, 'r') as f:
            csv_reader = csv.reader(f, delimiter=',', quotechar='"')
            username = next(csv_reader)

            movies = []
            for row in csv_reader:
                movie_data = row
                movies.append(
                    Movie(movie_data[0], movie_data[1],
                          movie_data[2] == "True"))

            user = User(username)
            user.movies = movies
            return user
Exemple #44
0
    def tmdb_get_by_id(self, id, api_key):
        r = requests.get(
            f'https://api.themoviedb.org/3/movie/{id}?api_key={api_key}')
        r = r.json()
        if 'status_code' not in r:
            title = r['title']
            original_title = r['original_title']
            release_date = r['release_date']
            if r['adult'] == 'False':
                rating = 'TP'
            else:
                rating = '-18'
            duration = r['runtime']
            box_office = r['revenue']
            imdb_id = r['imdb_id']
            imdb_id = imdb_id.replace("tt", "")
            imdb_score = r['vote_average']
            synopsis = r['overview']
            production_budget = r['budget']
            movie = Movie(title, original_title, release_date, duration,
                          rating)
            movie.imdb_id = imdb_id
            movie.imdb_score = imdb_score
            movie.box_office = box_office

            actors = r['Actors']
            for actor in actors:
                firstname = actor[0]
                lastname = actor[1]

                app.insert_people(firstname, lastname)

            return movie
        if r['status_code'] == 34:
            movie = f"Aucun film avec l'id {id} n'existe dans la base"
            return movie
Exemple #45
0
def main():
    view = View()
    view.show_all()
    movie_to_add = Movie(title="The Imitation Game",
                         date_released=2014,
                         actors=[
                             Actor(name="Benedict",
                                   last_name="Cumberbatch",
                                   role="Alan Turing"),
                             Actor(name="Kira",
                                   last_name="Knightley",
                                   role="Joan Clarke")
                         ])
    view.add_movie(movie_obj=movie_to_add)
    view.show_all()
Exemple #46
0
 def load_movies_run(self, filepaths):
     renaming_rule = utils.preferences.value("renaming_rule").toString()
     # loop on file paths
     for filepath in filepaths:
         # set loading label text, show current file name
         self.ui.label_loading.setText(QApplication.translate('GUI', "Getting information from ")\
                                        + os.path.split(filepath)[1])
         # create a new movie object
         movie = Movie(filepath)
         # generate new movie name based on renaming rule
         movie.generate_new_name(renaming_rule)
         # add movie to list
         self.movies.append(movie)
         # insert a new row in movie table
         self.ui.table_movies.insertRow(self.ui.table_movies.rowCount())
         # create a table item with original movie file name
         item_original_name = QTableWidgetItem(movie.original_file_name())
         item_original_name.setForeground(QBrush(Qt.black))
         self.ui.table_movies.setItem(self.ui.table_movies.rowCount() - 1, 0, item_original_name)
         # create a table item with new movie file name
         item_new_name = QTableWidgetItem(movie.new_file_name())
         item_new_name.setForeground(QBrush(Qt.black))
         self.ui.table_movies.setItem(self.ui.table_movies.rowCount() - 1, 1, item_new_name)
     self.load_movies_finished.emit()
Exemple #47
0
def movie_content_analyse(item, star):
    '''
    Analyse the web data of one star
    :param item: web content of one block
    :param star: javbus code of one star
    :return: return a Movie element or nothing
    '''

    tmp_content = item.find_all("date")
    item_name = item.img.get('title')
    item_img = item.img.get('src')
    item_url = item.a.get('href')
    item_code = tmp_content[0].string
    item_date = tmp_content[1].string
    return Movie(item_name, item_img, item_url, item_code, item_date, star)
Exemple #48
0
 def make_gif(self):
     print('make gif from list')
     self.statusvalor.set('make gif instruction')
     # if os.path.exists(self.file_select.get()):
     #     movie = Movie(self.file_select.get(), bool(self.chimgvar.get()))
     #     print(movie)
     #     movie.run()
     # else:
     #     return
     if not os.path.isdir(self.dirpathmovies.get()):
         return
     else:
         # limpiamos box_list
         self.box_list.delete(0, tk.END)
         # make directorio put thumbais
         working_file = os.path.join(self.dirpathmovies.get(), 'Thumbails')
         if not os.path.exists(working_file):
             os.mkdir(working_file)
         # make list objects
         self.crear_listas(self.dirpathmovies.get())
         # vamos a hacer el primero de la lista.
         if len(self.list_files_not_makegif) > 0:
             # cogemos el 1 elemento que lo eliminamos de la lista.
             item = self.list_files_not_makegif.pop(0)
             self.file_select.set(os.path.join(self.dirpathmovies.get(), item))
             self.statusvalor.set('>> next_movie: ' + item + ' | len: '+ str(len(self.list_files_not_makegif)))
             # print(self.file_select.get())
             try:
                 self.movie = Movie(self.file_select.get(), bool(self.chimgvar.get()))
                 self.movie.setwidget(self)
                 print(self.movie)
                 self.movie.run()
             except Exception as ex:
                 print(ex)
         else:
             self.statusvalor.set('>> anything to make: ' )
Exemple #49
0
def save_to_ndb(movie_dic):
    save_num = 0

    for m in movie_dic:
        if Movie.query(Movie.name_md5 == m['name_md5']).count() == 0:
            Movie(
                    name_md5=m['name_md5'],
                    name=m['name'],
                    content=m['content'],
                    info=m['info'],
                    href=m['href'],
                    is_email='no'
                ).put()
            save_num += 1
            
    return save_num
Exemple #50
0
 def handle_starttag(self, tag, attrs):
     if tag == 'div':
         for attr in attrs:
             if attr[0] == 'class' and attr[1] == 'info':
                 # <div class="info"> starts a new movie entry.
                 self._output_entry = True
                 self._movie = Movie()
                 self._output_entry_finish_tag = tag
     elif self._output_entry:
         if tag == 'li':
             for attr in attrs:
                 if attr[0] == 'class' and attr[1] == 'title':
                     # <li class="title"> includes movie name
                     self._start_movie_name = True
                 elif attr[0] == 'class' and attr[1] == 'intro':
                     # <li class="intro"> includes movie intro
                     self._output_finish_tag = tag
                     self._grab_data = True
                     self._start_intro = True
         elif tag == 'span':
             for attr in attrs:
                 if attr[0] == 'class' and attr[1] == 'date':
                     # <span class="date"> includes movie view date.
                     self._output_finish_tag = tag
                     self._grab_data = True
                     self._start_date = True
                     #TODO
                     # watched list has
                     #     <dev class="info">
                     #       everything
                     #     </dev>
                     # but wish list has
                     #     <dev class="info">
                     #        movie info
                     #     </dev>
                     #     <li>
                     #        entry creation day
                     #     </li>
                 if attr[0] == 'class' and attr[1].find('rating') >= 0:
                     # <span class="ratingX-t"> has rating information.
                     def GetRating(s):
                         return ((s.split('rating'))[1].split('-'))[0]
                     self._movie.set_rating(int(GetRating(attr[1])))
         elif self._start_movie_name and tag == MOVIE_NAME_START_TAG:
             # movie name tag is encountered. Store next data.
             self._output_finish_tag = tag
             self._grab_data = True
	def list_movie(self,kwargs):
		print "\n Example: list name, list rating, list date or list by name etc. \n"
		sort_order = 'name'
		if kwargs != []:
			if kwargs[0] == 'by':
				sort_order = kwargs.pop(1)
			else: 
				sort_order = kwargs.pop(0)
		
		movies = Movie.read_movies_from_file()
		if sort_order == 'date':
			movies.sort(cmp = lambda x, y: cmp(x.date, y.date))
		elif sort_order == 'rating':
			movies.sort(cmp = lambda x, y: cmp(x.rating, y.rating))			
		else:
			movies.sort(cmp = lambda x, y: cmp(x.movie, y.movie))
		self.movie_table_output(movies)
Exemple #52
0
    def getMovieIDByName(self, name):
        self.domain = 'movie'
        self.action = 'search'
        self.searchTerm = quote_plus(name)
        
        try:
            movie_list = Movie.select("""movie.title LIKE '%s'""" % name)
            if movie_list.count() == 1:
                self.tmdb_id = movie_list[0].tmdb_id
            else:
                raise SQLObjectNotFound
        except SQLObjectNotFound:
            self.url = "%s%s" % (self.urls.generateURL(self.domain, self.action), self.searchTerm)

            movie_info = self._getResponse(self.url)
            self.tmdb_id = movie_info['id']
        
        return self.tmdb_id
Exemple #53
0
def load(fn=None):
  if fn == None:
    print "filename required."
    return
  else:
    with open(fn, "r") as f:
      try:
        movies = json.load(f)['movies']
      except KeyError:
        print "json file must have a top level key 'movies'"
        return

  accessor = {}
  ms = []
  for m in movies:
     ms.append(Movie.load(m))
     accessor[m['title']] = ms[-1]

  calculate(ms)
  return ms, accessor
Exemple #54
0
 def _processListRequest(self):
     """ Process a list Request. """
     log.level = -1
     listItems = []
     for dirName in sorted(os.listdir(self.baseDir)):
         if (os.path.isdir(dirName)):
             dirPath = "%s/%s" % (self.baseDir, dirName)
             movie = Movie(dirPath)
             if   (self.list == 'novideo'): listItems += movie.getNoVideoList()
             elif (self.list == 'badnfo'):  listItems += movie.getBadNfoList()
             elif (self.list == 'nonfo'):   listItems += movie.getMissingNfoList()
             elif (self.list == 'hassub'):  listItems += movie.getHasSubtitleList()
             elif (self.list == 'nosub'):   listItems += movie.getNoSubtitleList()
             elif (self.list == 'suberr'):  listItems += movie.getSubtitleErrorList()
     # Print the Result
     if (listItems) and (self.print0):
         sys.stdout.write("\0".join(listItems))
     elif (listItems):
         print "\n".join(listItems)
 def add_movie(self):
     self.movie_title = input('title >')
     self.movie_year = input('year >')
     while True:
         self.movie_rating = int(input('rating >'))
         if self.movie_rating <= 10 and self.movie_rating > 0:
             break
         else:
             print("Rating can only be a number between 1 and 10.")
     self.m = Movie(self.movie_title,
                    self.movie_year,
                    self.movie_rating)
     if(self.m.get_title() not in self.movies.keys()
        and self.m.get_year() not in self.movies.values()):
         self.movies[self.movie_title] = self.movie_year
         self.m.save()
         print('{} ({}) {}'.format(self.movie_title,
                                   self.movie_year,
                                   'was added to your catalog!'))
     else:
         print('Movie already exists!')
Exemple #56
0
    def __init__(self, parent, preferences_dialog):
        QDialog.__init__(self, parent)

        self.ui = loadUi("renaming_rule_dialog.ui", self)

        self.ui.preferences_dialog = preferences_dialog

        # creates an example movie, used to test the renaming rule
        self.example_movie = Movie()

        self.populate_list_visual_rule()
        self.update_representations()
        renaming_rule = utils.preferences.value("renaming_rule").toString()
        self.update_example_movie(renaming_rule)

        ## slots connection
        self.ui.list_visual_rule.model().rowsInserted.connect(self.rule_changed)
        self.ui.list_visual_rule.model().rowsRemoved.connect(self.rule_changed)

        self.ui.button_remove_rule.clicked.connect(self.remove_rule)
        self.ui.button_clean_rule.clicked.connect(self.clean_rule)

        self.ui.button_add_title.clicked.connect(self.add_title)
        self.ui.button_add_original_title.clicked.connect(self.add_original_title)
        self.ui.button_add_year.clicked.connect(self.add_year)
        self.ui.button_add_director.clicked.connect(self.add_director)
        self.ui.button_add_duration.clicked.connect(self.add_duration)
        self.ui.button_add_language.clicked.connect(self.add_language)

        self.ui.button_add_round_brackets.clicked.connect(self.add_round_brackets)
        self.ui.button_add_square_brackets.clicked.connect(self.add_square_brackets)
        self.ui.button_add_curly_brackets.clicked.connect(self.add_curly_brackets)

        self.ui.button_show_preferences.clicked.connect(self.show_preferences)

        self.ui.button_close.clicked.connect(self.close)
Exemple #57
0
        def loadMoreMovies(self):
                """function to load more movies"""
                
                self.loadActors(self.moviesToLoadEachTime)

                self.loadActresses(self.moviesToLoadEachTime)
                

                if self.moviesDrawnCount < len(self.moviesList):
                        
                        for i in range(self.moviesDrawnCount, len(self.moviesList)):
                                
                                titleOfMovie=((Movie.getMovieTitle(self.moviesList[i])))
                                #adds the title of the movie to the movieNames array.
                                self.movieNames.append(titleOfMovie)
                                
                                
                                # generate random x-axis and y-axis for the ellipses
                                
                                x = random.randint(10, 800)

                                y = random.randint(10, 420)

                                # draw ellipses on the circle
                                oval = self.canvas.create_oval(x, y, x + 20, y + 20, outline="gold", fill="black", width=1)
                                
                                # keep a reference of the oval 


                                self.moviesList[i].setOvalId(oval)
                                self.canvas.tag_bind(oval, '<Button-1>', self.onObjectClick)
                        self.cls()
                        
                        self.Sort(self.movieNames)  
        
                        self.moviesDrawnCount += len(self.moviesList) - self.moviesDrawnCount
        frame = frame[npx/2:npx/2+cutoff,:]
        sz,sx = frame.shape
        if iframe==0:
            stack = np.zeros((N_frames,sz,sx),dtype=np.complex64)
        stack[iframe,:,:] = frame


    astack = np.abs(stack)
    smax = np.max(stack)
    smin = np.min(stack)

    avifn = os.path.join(frame_dir,'frames.avi')
    make_movie = not os.path.exists(avifn)

    if make_movie:
        mov = Movie(avifn)
        fig = plt.figure()

        for k in range(N_frames):
            plt.cla()
            plt.imshow(astack[k,:,:],interpolation='none',aspect='auto')
            plt.clim((smin,smax))
            if k==0:
                plt.colorbar()
            mov.add(fig)
            plt.pause(.1)

        mov.make()


    sz,sy,sx = stack.shape
import csv
from movie import Movie
from user import User

movies = Movie.read_movies('u.item')

users = User.read_users('u.user')

class Rating:
    def __init__(self, user_id, movie_id, score):
        self.user_id = user_id
        self.movie_id = movie_id
        self.score = score

def add_rating(rating):
    movie = movies[movie_id]
    movie.add_rating(rating)

    user = users[user_id]
    user.add_rating(rating)

with open('u.data', 'r') as movies_file:
    reader = csv.DictReader(movies_file, fieldnames=['user_id', 'movie_id', 'score'], delimiter='\t')
    for row in reader:
        user_id = row['user_id']
        movie_id = row['movie_id']
        score = row['score']

        rating = Rating(user_id, movie_id, score)

        add_rating(rating)
Exemple #60
0
class RenamingRuleDialog(QDialog):

    TITLE = QApplication.translate('RenamingRuleDialog', "Title")
    ORIGINAL_TITLE = QApplication.translate('RenamingRuleDialog', "Original title")
    YEAR = QApplication.translate('RenamingRuleDialog', "Year")
    DIRECTOR = QApplication.translate('RenamingRuleDialog', "Director")
    DURATION = QApplication.translate('RenamingRuleDialog', "Duration")
    LANGUAGE = QApplication.translate('RenamingRuleDialog', "Language")
    OPENED_ROUND_BRACKET = "("
    CLOSED_ROUND_BRACKET = ")"
    OPENED_SQUARE_BRACKET = "["
    CLOSED_SQUARE_BRACKET = "]"
    OPENED_CURLY_BRACKET = "{"
    CLOSED_CURLY_BRACKET = "}"

    RENAMING_TO_VISUAL_RULE = {
        Movie.TITLE:TITLE,
        Movie.ORIGINAL_TITLE:ORIGINAL_TITLE,
        Movie.YEAR:YEAR,
        Movie.DIRECTOR:DIRECTOR,
        Movie.DURATION:DURATION,
        Movie.LANGUAGE:LANGUAGE,
        OPENED_ROUND_BRACKET:OPENED_ROUND_BRACKET,
        CLOSED_ROUND_BRACKET:CLOSED_ROUND_BRACKET,
        OPENED_SQUARE_BRACKET:OPENED_SQUARE_BRACKET,
        CLOSED_SQUARE_BRACKET:CLOSED_SQUARE_BRACKET,
        OPENED_CURLY_BRACKET:OPENED_CURLY_BRACKET,
        CLOSED_CURLY_BRACKET:CLOSED_CURLY_BRACKET
    }

    VISUAL_TO_RENAMING_RULE = {
       TITLE:Movie.TITLE,
       ORIGINAL_TITLE:Movie.ORIGINAL_TITLE,
       YEAR:Movie.YEAR,
       DIRECTOR:Movie.DIRECTOR,
       DURATION:Movie.DURATION,
       LANGUAGE:Movie.LANGUAGE,
       OPENED_ROUND_BRACKET:OPENED_ROUND_BRACKET,
       CLOSED_ROUND_BRACKET:CLOSED_ROUND_BRACKET,
       OPENED_SQUARE_BRACKET:OPENED_SQUARE_BRACKET,
       CLOSED_SQUARE_BRACKET:CLOSED_SQUARE_BRACKET,
       OPENED_CURLY_BRACKET:OPENED_CURLY_BRACKET,
       CLOSED_CURLY_BRACKET:CLOSED_CURLY_BRACKET
   }

    def __init__(self, parent, preferences_dialog):
        QDialog.__init__(self, parent)

        self.ui = loadUi("renaming_rule_dialog.ui", self)

        self.ui.preferences_dialog = preferences_dialog

        # creates an example movie, used to test the renaming rule
        self.example_movie = Movie()

        self.populate_list_visual_rule()
        self.update_representations()
        renaming_rule = utils.preferences.value("renaming_rule").toString()
        self.update_example_movie(renaming_rule)

        ## slots connection
        self.ui.list_visual_rule.model().rowsInserted.connect(self.rule_changed)
        self.ui.list_visual_rule.model().rowsRemoved.connect(self.rule_changed)

        self.ui.button_remove_rule.clicked.connect(self.remove_rule)
        self.ui.button_clean_rule.clicked.connect(self.clean_rule)

        self.ui.button_add_title.clicked.connect(self.add_title)
        self.ui.button_add_original_title.clicked.connect(self.add_original_title)
        self.ui.button_add_year.clicked.connect(self.add_year)
        self.ui.button_add_director.clicked.connect(self.add_director)
        self.ui.button_add_duration.clicked.connect(self.add_duration)
        self.ui.button_add_language.clicked.connect(self.add_language)

        self.ui.button_add_round_brackets.clicked.connect(self.add_round_brackets)
        self.ui.button_add_square_brackets.clicked.connect(self.add_square_brackets)
        self.ui.button_add_curly_brackets.clicked.connect(self.add_curly_brackets)

        self.ui.button_show_preferences.clicked.connect(self.show_preferences)

        self.ui.button_close.clicked.connect(self.close)

    def populate_list_visual_rule(self):
        """
        populate renaming rule by rule read from settings
        """

        renaming_rule = utils.preferences.value("renaming_rule").toString()
        # split rule
        rules = renaming_rule.split('.')
        # if rule is empty, reset it to 'title'
        if rules[0] == '':
            rules[0] = Movie.TITLE
            renaming_rule = Movie.TITLE
            utils.preferences.setValue("renaming_rule", renaming_rule)
        visual_rule = []
        # loop on rules
        for rule in rules:
            visual_rule.append(self.RENAMING_TO_VISUAL_RULE[rule])
        self.ui.list_visual_rule.addItems(visual_rule)

    def update_representations(self):
        duration_index = utils.preferences.value("duration_representation").toInt()[0]
        duration_representation = PreferencesDialog.DURATION_REPRESENTATIONS[duration_index]
        self.ui.label_duration_representation.setText(duration_representation)

        language_index = utils.preferences.value("language_representation").toInt()[0]
        language_representation = PreferencesDialog.LANGUAGE_REPRESENTATIONS[language_index]
        self.ui.label_language_representation.setText(language_representation)

        separator_index = utils.preferences.value("words_separator").toInt()[0]
        separator_representation = PreferencesDialog.WORDS_SEPARATORS_REPRESENTATIONS[separator_index]
        self.ui.label_separator_representation.setText(separator_representation)

    def update_example_movie(self, renaming_rule):
        # generate new name for example movie
        example_movie_new_name = self.example_movie.generate_new_name(renaming_rule)
        # show it on label
        self.ui.label_example_movie_name.setText(example_movie_new_name)

    def rule_changed(self, parent = None, start = None, end = None):
        """
        called when renaming rule changes
        
        creates and saves new renaming rule, and generate the movie example's new name
        """

        rule = []
        for index in range(self.ui.list_visual_rule.count()):
            text = self.ui.list_visual_rule.item(index).text()
            # when an item is moved inside the list_visual_rule, firstly 
            # a new empty item is inserted into the destination location, then 
            # the item from source location is deleted. that function is called 
            # for both events (insertion and deletion), and when is called for
            # the insertion event after a list items move, the list contains an empty item,
            # which is a kind of error. 
            if text != '':
                rule.append(self.VISUAL_TO_RENAMING_RULE[text])
        # creates renaming rule
        renaming_rule = '.'.join(rule)
        #save renaming rule on settings
        utils.preferences.setValue("renaming_rule", renaming_rule)
        #update example movie
        self.update_example_movie(renaming_rule)

    def remove_rule(self):
        """
        removes selected rule
        """

        # get selected items in rule
        selected_items = self.ui.list_visual_rule.selectedItems()
        # remove its from list
        for item in reversed(selected_items):
            row = self.ui.list_visual_rule.row(item)
            self.ui.list_visual_rule.takeItem(row)

    def clean_rule(self):
        """
        cleans rule (remove all renaming rules)
        """

        self.ui.list_visual_rule.clear()
        # needs to call rule_changed because clear() doesn't 
        # throw any signal
        self.rule_changed()

    def add_title(self):
        """
        add title to rule
        """

        self.ui.list_visual_rule.addItem(self.TITLE)

    def add_original_title(self):
        """
        add aka to rule
        """

        self.ui.list_visual_rule.addItem(self.ORIGINAL_TITLE)

    def add_year(self):
        """
        add year to rule
        """

        self.ui.list_visual_rule.addItem(self.YEAR)

    def add_director(self):
        """
        add director to rule
        """

        self.ui.list_visual_rule.addItem(self.DIRECTOR)

    def add_duration(self):
        """
        add runtime to rule
        """

        self.ui.list_visual_rule.addItem(self.DURATION)

    def add_language(self):
        """
        add language to rule
        """

        self.ui.list_visual_rule.addItem(self.LANGUAGE)

    def add_round_brackets(self):
        """
        add opened and closed round brackets to rule
        """

        self.ui.list_visual_rule.addItem(self.OPENED_ROUND_BRACKET)
        self.ui.list_visual_rule.addItem(self.CLOSED_ROUND_BRACKET)

    def add_square_brackets(self):
        """
        add opened and closed square brackets to rule
        """

        self.ui.list_visual_rule.addItem(self.OPENED_SQUARE_BRACKET)
        self.ui.list_visual_rule.addItem(self.CLOSED_SQUARE_BRACKET)

    def add_curly_brackets(self):
        """
        add opened and closed curly brackets to rule
        """

        self.ui.list_visual_rule.addItem(self.OPENED_CURLY_BRACKET)
        self.ui.list_visual_rule.addItem(self.CLOSED_CURLY_BRACKET)

    def show_preferences(self):
        self.ui.preferences_dialog.exec_()
        renaming_rule = utils.preferences.value("renaming_rule").toString()
        self.update_representations()
        # update example movie
        self.update_example_movie(renaming_rule)

    def close(self):
        send_usage_statistics()
        self.accept()