def fetch_bigger_poster(self):
	match = 0
	self.debug.show("fetching poster from amazon")
	movie = self.db.Movie.get_by(movie_id=self._movie_id)
	if movie is None:
		gutils.error(self,_("You have no movies in your database"), self.widgets['window'])
		return False
	current_poster = movie.image
	amazon.setLicense("04GDDMMXX8X9CJ1B22G2")

	locale = self.config.get('amazon_locale', 0, section='add')
	keyword = self.widgets['movie']['o_title'].get_text().decode('utf-8')
	if locale == '1':
		locale = 'uk'
	elif locale == '2':
		locale = 'de'
		keyword = self.widgets['movie']['title'].get_text().decode('utf-8')
	elif locale == '3':
		locale = 'ca'
	elif locale == '4':
		locale = 'fr'
	elif locale == '5':
		locale = 'jp'
	else:
		locale = None

	try:
		result = amazon.searchByKeyword(keyword, type="Large", product_line="DVD", locale=locale)
		self.debug.show("Posters found on amazon: %s posters" % result.TotalResults)
	except:
		gutils.warning(self, _("No posters found for this movie."))
		return

	from widgets import connect_poster_signals, reconnect_add_signals
	connect_poster_signals(self, get_poster_select_dc, result, current_poster)

	if not len(result.Item):
		gutils.warning(self, _("No posters found for this movie."))
		reconnect_add_signals(self)
		return

	for f in range(len(result.Item)):
		if self.widgets['movie']['o_title'].get_text().decode('utf-8') == result.Item[f].ItemAttributes.Title:
			get_poster(self, f, result, current_poster)
			return

	self.treemodel_results.clear()
	self.widgets['add']['b_get_from_web'].set_sensitive(False) # disable movie plugins (result window is shared)

	for f in range(len(result.Item)):
		if hasattr(result.Item[f], "LargeImage") and len(result.Item[f].LargeImage.URL):
			title = result.Item[f].ItemAttributes.Title
			myiter = self.treemodel_results.insert_before(None, None)
			self.treemodel_results.set_value(myiter, 0, str(f))
			self.treemodel_results.set_value(myiter, 1, title)

	self.widgets['results']['window'].show()
	self.widgets['results']['window'].set_keep_above(True)
def fetch_bigger_poster(self):
    match = 0
    self.debug.show("fetching poster from amazon")
    movie = self.db.Movie.get_by(movie_id=self._movie_id)
    if movie is None:
        gutils.error(self, _("You have no movies in your database"), self.widgets["window"])
        return False
    current_poster = movie.image
    amazon.setLicense("04GDDMMXX8X9CJ1B22G2")

    locale = self.config.get("amazon_locale", 0)
    if locale == 1:
        locale = "uk"
    elif locale == 2:
        locale = "de"
    elif locale == 3:
        locale = "uk"
    else:
        locale = None

    try:
        result = amazon.searchByKeyword(
            self.widgets["movie"]["o_title"].get_text(), type="lite", product_line="dvd", locale=locale
        )
        self.debug.show("Posters found on amazon: %s posters" % len(result))
    except:
        gutils.warning(self, _("No posters found for this movie."))
        return

    from widgets import connect_poster_signals, reconnect_add_signals

    connect_poster_signals(self, get_poster_select_dc, result, current_poster)

    if not len(result):
        gutils.warning(self, _("No posters found for this movie."))
        reconnect_add_signals(self)
        return

    for f in range(len(result)):
        if self.widgets["movie"]["o_title"].get_text() == result[f].ProductName:
            get_poster(self, f, result, current_poster)
            return

    self.treemodel_results.clear()
    self.widgets["add"]["b_get_from_web"].set_sensitive(False)  # disable movie plugins (result window is shared)

    for f in range(len(result)):

        if len(result[f].ImageUrlLarge):
            title = result[f].ProductName
            myiter = self.treemodel_results.insert_before(None, None)
            self.treemodel_results.set_value(myiter, 0, str(f))
            self.treemodel_results.set_value(myiter, 1, title)

    self.widgets["results"]["window"].show()
    self.widgets["results"]["window"].set_keep_above(True)
def get_poster(self, f, result, current_poster):
	from widgets import reconnect_add_signals
	if f is None:
		treeselection = self.widgets['results']['treeview'].get_selection()
		(tmp_model, tmp_iter) = treeselection.get_selected()
		if tmp_iter is None:
			return False
		f = int(tmp_model.get_value(tmp_iter, 0))
		self.widgets['results']['window'].hide()

	file_to_copy = tempfile.mktemp(suffix=self.widgets['movie']['number'].get_text(), \
		dir=self.locations['temp'])
	file_to_copy += ".jpg"
	if len(result[f].ImageUrlLarge):
		try:
			progress = movie.Progress(self.widgets['window'],_("Fetching poster"),_("Wait a moment"))
			retriever = movie.Retriever(result[f].ImageUrlLarge, self.widgets['window'], progress, file_to_copy)
			retriever.start()
			while retriever.isAlive():
				progress.pulse()
				if progress.status:
					retriever.suspend()
				while gtk.events_pending():
					gtk.main_iteration()
			progress.close()
			urlcleanup()
		except:
			gutils.warning(self, _("Sorry. A connection error has occurred."))

	if  os.path.isfile(file_to_copy):
		try:
			im = Image.open(file_to_copy)
		except IOError:
			self.debug.show("failed to identify %s"%file_to_copy)

		if im.size == (1,1):
			from urllib import FancyURLopener, urlretrieve
			url = FancyURLopener().open("http://www.amazon.com/gp/product/images/%s" % result[f].Asin).read()
			if url.find('no-img-sm._V47056216_.gif') > 0:
				self.debug.show('No image available')
				gutils.warning(self, _("Sorry. This movie is listed but has no poster available at Amazon.com."))
				return False
			url = gutils.after(url, 'id="imageViewerDiv"><img src="')
			url = gutils.before(url, '" id="prodImage"')
			urlretrieve(url, file_to_copy)
			try:
				im = Image.open(file_to_copy)
			except IOError:
				self.debug.show("failed to identify %s"%file_to_copy)

		if im.mode != 'RGB': # convert GIFs
			im = im.convert('RGB')
			im.save(file_to_copy, 'JPEG')
		
		handler = self.widgets['big_poster'].set_from_file(file_to_copy)

		self.widgets['poster_window'].show()
		self.widgets['poster_window'].move(0,0)
		response = gutils.question(self, \
				_("Do you want to use this poster instead?"), \
				1, self.widgets['window'])
		if response == -8:
			self.debug.show("Using fetched poster, updating and removing old one from disk.")
			update_image(self, self.widgets['movie']['number'].get_text(), file_to_copy)
		else:
			self.debug.show("Reverting to previous poster and deleting new one from disk.")
			try:
				os.remove(file_to_copy)
			except:
				self.debug.show("no permission for %s"%file_to_copy)

		self.widgets['poster_window'].hide()
	else:
		gutils.warning(self, _("Sorry. This movie is listed but has no poster available at Amazon.com."))
	reconnect_add_signals(self)
def get_poster(self, f, result):
    from widgets import reconnect_add_signals
    if f is None:
        treeselection = self.widgets['results']['treeview'].get_selection()
        (tmp_model, tmp_iter) = treeselection.get_selected()
        if tmp_iter is None:
            return False
        f = int(tmp_model.get_value(tmp_iter, 0))
        self.widgets['results']['window'].hide()

    file_to_copy = tempfile.mktemp(suffix=self.widgets['movie']['number'].get_text(), \
        dir=self.locations['temp'])
    file_to_copy += ".jpg"
    canceled = False
    if len(result.Item[f].LargeImage.URL):
        try:
            progress = movie.Progress(self.widgets['window'],_("Fetching poster"),_("Wait a moment"))
            retriever = movie.Retriever(result.Item[f].LargeImage.URL, self.widgets['window'], progress, file_to_copy)
            retriever.start()
            while retriever.isAlive():
                progress.pulse()
                if progress.status:
                    canceled = True
                while gtk.events_pending():
                    gtk.main_iteration()
            progress.close()
            urlcleanup()
        except:
            canceled = True
            gutils.warning(_("Sorry. A connection error has occurred."))
            try:
                os.remove(file_to_copy)
            except:
                log.error("no permission for %s"%file_to_copy)

    if not canceled:
        if os.path.isfile(file_to_copy):
            im = None
            try:
                im = Image.open(file_to_copy)
            except IOError:
                log.warn("failed to identify %s"%file_to_copy)

            if im and im.size == (1,1):
                url = FancyURLopener().open("http://www.amazon.com/gp/product/images/%s" % result.Item[f].ASIN).read()
                if url.find('no-img-sm._V47056216_.gif') > 0:
                    log.warn('No image available')
                    gutils.warning(_("Sorry. This movie is listed but has no poster available at Amazon.com."))
                    return False
                url = gutils.after(url, 'id="imageViewerDiv"><img src="')
                url = gutils.before(url, '" id="prodImage"')
                urlretrieve(url, file_to_copy)
                try:
                    im = Image.open(file_to_copy)
                except IOError:
                    log.warn("failed to identify %s"%file_to_copy)

            if not im:
                # something wrong with the image, give some feedback to the user
                log.warn('No image available')
                gutils.warning(_("Sorry. This movie is listed but has no poster available at Amazon.com."))
                return False

            if im.mode != 'RGB': # convert GIFs
                im = im.convert('RGB')
                im.save(file_to_copy, 'JPEG')
            # set to None because the file is locked otherwise (os.remove throws an exception)
            im = None

            handler = self.widgets['big_poster'].set_from_file(file_to_copy)

            self.widgets['poster_window'].show()
            self.widgets['poster_window'].move(0,0)
            response = gutils.question(_("Do you want to use this poster instead?"), True, self.widgets['window'])
            if response == -8:
                log.info("Using fetched poster, updating and removing old one from disk.")
                update_image(self, self.widgets['movie']['number'].get_text(), file_to_copy)
            else:
                log.info("Reverting to previous poster and deleting new one from disk.")
                try:
                    os.remove(file_to_copy)
                except:
                    log.error("no permission for %s"%file_to_copy)

            self.widgets['poster_window'].hide()
        else:
            gutils.warning(_("Sorry. This movie is listed but has no poster available at Amazon.com."))
    else:
        # cleanup temporary files after canceling the download
        if os.path.isfile(file_to_copy):
            try:
                os.remove(file_to_copy)
            except:
                log.error("no permission for %s"%file_to_copy)
    # reconnect the signals to the shared result list
    reconnect_add_signals(self)
def fetch_bigger_poster(self):
    match = 0
    log.info("fetching poster from amazon...")
    movie = self.db.session.query(db.Movie).filter_by(movie_id=self._movie_id).first()
    if movie is None:
        gutils.error(self,_("You have no movies in your database"), self.widgets['window'])
        return False
    current_poster_md5 = movie.poster_md5
    if current_poster_md5:
        current_poster = gutils.get_image_fname(current_poster_md5, self.db)
    else:
        current_poster = None
    amazon.setLicense("04GDDMMXX8X9CJ1B22G2")

    locale = self.config.get('amazon_locale', 0, section='add')
    keyword = self.widgets['movie']['o_title'].get_text()
    if locale == '1':
        locale = 'uk'
    elif locale == '2':
        locale = 'de'
        keyword = self.widgets['movie']['title'].get_text()
    elif locale == '3':
        locale = 'ca'
    elif locale == '4':
        locale = 'fr'
    elif locale == '5':
        locale = 'jp'
    else:
        locale = None

    try:
        result = amazon.searchByTitle(keyword, type="Large", product_line="DVD", locale=locale)
        if hasattr(result, 'TotalPages'):
            # get next result pages
            pages = int(result.TotalPages)
            page = 2
            while page <= pages and page < 11:
                tmp = amazon.searchByTitle(keyword, type='Large', product_line='DVD', locale=locale, page=page)
                result.Item.extend(tmp.Item)
                page = page + 1
        if not hasattr(result, 'Item') or not len(result.Item):
            # fallback if nothing is found by title
            result = amazon.searchByKeyword(keyword, type="Large", product_line="DVD", locale=locale)
            if hasattr(result, 'TotalPages'):
                # get next result pages
                pages = int(result.TotalPages)
                page = 2
                while page <= pages and page < 11:
                    tmp = amazon.searchByKeyword(keyword, type='Large', product_line='DVD', locale=locale, page=page)
                    result.Item.extend(tmp.Item)
                    page = page + 1
        log.info("... %s posters found" % result.TotalResults)
    except:
        gutils.warning(_("No posters found for this movie."))
        return

    from widgets import connect_poster_signals, reconnect_add_signals
    connect_poster_signals(self, get_poster_select_dc, result, current_poster)

    if not hasattr(result, 'Item') or not len(result.Item):
        gutils.warning(_("No posters found for this movie."))
        reconnect_add_signals(self)
        return

    if len(result.Item) == 1:
        o_title = self.widgets['movie']['o_title'].get_text().decode('utf-8')
        if o_title == result.Item[0].ItemAttributes.Title or keyword == result.Item[0].ItemAttributes.Title:
            get_poster(self, 0, result)
            return

    self.treemodel_results.clear()
    self.widgets['add']['b_get_from_web'].set_sensitive(False) # disable movie plugins (result window is shared)

    for f in range(len(result.Item)):
        if hasattr(result.Item[f], "LargeImage") and len(result.Item[f].LargeImage.URL):
            title = result.Item[f].ItemAttributes.Title
            if hasattr(result.Item[f].ItemAttributes, 'ProductGroup'):
                title = title + u' - ' + result.Item[f].ItemAttributes.ProductGroup
            elif hasattr(result.Item[f].ItemAttributes, 'Binding'):
                title = title + u' - ' + result.Item[f].ItemAttributes.Binding
            if hasattr(result.Item[f].ItemAttributes, 'ReleaseDate'):
                title = title + u' - ' + result.Item[f].ItemAttributes.ReleaseDate[:4]
            elif hasattr(result.Item[f].ItemAttributes, 'TheatricalReleaseDate'):
                result.Item[f].ItemAttributes.TheatricalReleaseDate[:4]
            if hasattr(result.Item[f].ItemAttributes, 'Studio'):
                title = title + u' - ' + result.Item[f].ItemAttributes.Studio
            myiter = self.treemodel_results.insert_before(None, None)
            self.treemodel_results.set_value(myiter, 0, str(f))
            self.treemodel_results.set_value(myiter, 1, title)

    self.widgets['results']['window'].show()
    self.widgets['results']['window'].set_keep_above(True)
def fetch_bigger_poster(self):
    match = 0
    log.info("fetching poster from amazon...")
    movie = self.db.session.query(db.Movie).filter_by(movie_id=self._movie_id).first()
    if movie is None:
        gutils.error(self, _("You have no movies in your database"), self.widgets["window"])
        return False
    current_poster_md5 = movie.poster_md5
    if current_poster_md5:
        current_poster = gutils.get_image_fname(current_poster_md5, self.db)
    else:
        current_poster = None
    amazon.setLicense("04GDDMMXX8X9CJ1B22G2")

    locale = self.config.get("amazon_locale", 0, section="add")
    keyword = self.widgets["movie"]["o_title"].get_text()
    if locale == "1":
        locale = "uk"
    elif locale == "2":
        locale = "de"
        keyword = self.widgets["movie"]["title"].get_text()
    elif locale == "3":
        locale = "ca"
    elif locale == "4":
        locale = "fr"
    elif locale == "5":
        locale = "jp"
    else:
        locale = None

    try:
        result = amazon.searchByTitle(keyword, type="Large", product_line="DVD", locale=locale)
        if hasattr(result, "TotalPages"):
            # get next result pages
            pages = int(result.TotalPages)
            page = 2
            while page <= pages and page < 11:
                tmp = amazon.searchByTitle(keyword, type="Large", product_line="DVD", locale=locale, page=page)
                result.Item.extend(tmp.Item)
                page = page + 1
        if not hasattr(result, "Item") or not len(result.Item):
            # fallback if nothing is found by title
            result = amazon.searchByKeyword(keyword, type="Large", product_line="DVD", locale=locale)
            if hasattr(result, "TotalPages"):
                # get next result pages
                pages = int(result.TotalPages)
                page = 2
                while page <= pages and page < 11:
                    tmp = amazon.searchByKeyword(keyword, type="Large", product_line="DVD", locale=locale, page=page)
                    result.Item.extend(tmp.Item)
                    page = page + 1
        log.info("... %s posters found" % result.TotalResults)
    except:
        gutils.warning(_("No posters found for this movie."))
        return

    from widgets import connect_poster_signals, reconnect_add_signals

    connect_poster_signals(self, get_poster_select_dc, result, current_poster)

    if not hasattr(result, "Item") or not len(result.Item):
        gutils.warning(_("No posters found for this movie."))
        reconnect_add_signals(self)
        return

    if len(result.Item) == 1:
        o_title = self.widgets["movie"]["o_title"].get_text().decode("utf-8")
        if o_title == result.Item[0].ItemAttributes.Title or keyword == result.Item[0].ItemAttributes.Title:
            get_poster(self, 0, result)
            return

    self.treemodel_results.clear()
    self.widgets["add"]["b_get_from_web"].set_sensitive(False)  # disable movie plugins (result window is shared)

    for f in range(len(result.Item)):
        if hasattr(result.Item[f], "LargeImage") and len(result.Item[f].LargeImage.URL):
            title = result.Item[f].ItemAttributes.Title
            if hasattr(result.Item[f].ItemAttributes, "ProductGroup"):
                title = title + u" - " + result.Item[f].ItemAttributes.ProductGroup
            elif hasattr(result.Item[f].ItemAttributes, "Binding"):
                title = title + u" - " + result.Item[f].ItemAttributes.Binding
            if hasattr(result.Item[f].ItemAttributes, "ReleaseDate"):
                title = title + u" - " + result.Item[f].ItemAttributes.ReleaseDate[:4]
            elif hasattr(result.Item[f].ItemAttributes, "TheatricalReleaseDate"):
                result.Item[f].ItemAttributes.TheatricalReleaseDate[:4]
            if hasattr(result.Item[f].ItemAttributes, "Studio"):
                title = title + u" - " + result.Item[f].ItemAttributes.Studio
            myiter = self.treemodel_results.insert_before(None, None)
            self.treemodel_results.set_value(myiter, 0, str(f))
            self.treemodel_results.set_value(myiter, 1, title)

    self.widgets["results"]["window"].show()
    self.widgets["results"]["window"].set_keep_above(True)
def get_poster(self, f, result, current_poster):
	from widgets import reconnect_add_signals
	if f is None:
		treeselection = self.widgets['results']['treeview'].get_selection()
		(tmp_model, tmp_iter) = treeselection.get_selected()
		if tmp_iter is None:
			return False
		f = int(tmp_model.get_value(tmp_iter, 0))
		self.widgets['results']['window'].hide()

	file_to_copy = tempfile.mktemp(suffix=self.widgets['movie']['number'].get_text(), \
		dir=self.locations['temp'])
	file_to_copy += ".jpg"
	try:
		progress = movie.Progress(self.widgets['window'],_("Fetching poster"),_("Wait a moment"))
		retriever = movie.Retriever(result[f].ImageUrlLarge, self.widgets['window'], progress, file_to_copy)
		retriever.start()
		while retriever.isAlive():
			progress.pulse()
			if progress.status:
				retriever.suspend()
			while gtk.events_pending():
				gtk.main_iteration()
		progress.close()
		urlcleanup()
	except:
		gutils.warning(self, _("Sorry. A connection error was occurred."))

	if  os.path.isfile(file_to_copy):
		handler = self.widgets['big_poster'].set_from_file(file_to_copy)
		gutils.garbage(handler)

		try:
			im = Image.open(file_to_copy)
		except IOError:
			self.debug.show("failed to identify %s"%file_to_copy)
		else:
			if im.format == "GIF":
				gutils.warning(self, _("Sorry. This poster image format is not supported."))
				os.remove(file_to_copy)
				reconnect_add_signals(self)
				return
		self.widgets['poster_window'].show()
		self.widgets['poster_window'].move(0,0)
		response = gutils.question(self, \
				_("Do you want to use this poster instead?"), \
				1, self.widgets['window'])
		if response == -8:
			self.debug.show("Using fetched poster, updating and removing old one from disk.")
			update_image(self, self.widgets['movie']['number'].get_text(), file_to_copy)
		else:
			self.debug.show("Reverting to previous poster and deleting new one from disk.")
			try:
                            os.remove(file_to_copy)
                        except:
                            self.debug.show("no permission for %s"%file_to_copy)

		self.widgets['poster_window'].hide()
	else:
		gutils.warning(self, _("Sorry. This movie is listed but have no poster available at Amazon.com."))
	reconnect_add_signals(self)