def treeview_clicked(self):
    if self.initialized is False:
        return False
    if self.total:
        treeselection = self.widgets['treeview'].get_selection()
        (tmp_model, tmp_iter) = treeselection.get_selected()
        if tmp_iter is None:
            log.info('Treeview: no selection')
            return False
        number = tmp_model.get_value(tmp_iter, 0)
        movie = self.db.session.query(db.Movie).filter_by(number=number).first()
        if movie is None:
            log.info("Treeview: movie doesn't exists (number=%s)", number)
        elif self.widgets['poster_window'].flags() & gtk.VISIBLE == gtk.VISIBLE:
            # poster window is visible
            filename = None
            if movie.poster_md5:
                filename = gutils.get_image_fname(movie.poster_md5, self.db)
            if not filename:
                filename = gutils.get_defaultimage_fname(self)
            self.widgets['big_poster'].set_from_file(filename)
        for ext in self.extensions:
            ext.maintree_clicked(treeselection, movie)
        set_details(self, movie)
    else:
        set_details(self, {})
def treeview_clicked(self):
    if self.initialized is False:
        return False
    if len(self.selected) == 1:
        movie = self.db.session.query(db.Movie).filter_by(number=int(self.selected[0])).first()
        if self.widgets['poster_window'].flags() & gtk.VISIBLE == gtk.VISIBLE:
            # poster window is visible
            filename = None
            if movie.poster_md5:
                filename = gutils.get_image_fname(movie.poster_md5, self.db)
            if not filename:
                filename = gutils.get_defaultimage_fname(self)
            self.widgets['big_poster'].set_from_file(filename)
        #for ext in self.extensions:
            #ext.maintree_clicked(treeselection, movie)
        set_details(self, movie)
    else:
        return False
Пример #3
0
def treeview_clicked(self):
    if self.initialized is False:
        return False
    if len(self.selected) == 1:
        movie = self.db.session.query(
            db.Movie).filter_by(number=int(self.selected[0])).first()
        if self.widgets['poster_window'].flags() & gtk.VISIBLE == gtk.VISIBLE:
            # poster window is visible
            filename = None
            if movie.poster_md5:
                filename = gutils.get_image_fname(movie.poster_md5, self.db)
            if not filename:
                filename = gutils.get_defaultimage_fname(self)
            self.widgets['big_poster'].set_from_file(filename)
        #for ext in self.extensions:
        #ext.maintree_clicked(treeselection, movie)
        set_details(self, movie)
    else:
        return False
Пример #4
0
def setmovie(self, movie, iter, treemodel=None):  # {{{
    if not treemodel:
        treemodel = self.treemodel

    treemodel.set_value(iter, 0, '%004d' % int(movie.number))

    if self.config.get('image', True, section='mainlist') == True:
        filename = None
        if movie.poster_md5:
            filename = gutils.get_image_fname(movie.poster_md5, self.db, "s")
        if not filename:
            filename = os.path.join(self.locations['images'],
                                    'default_thumbnail.png')

        self.Image.set_from_file(filename)
        try:
            pixbuf = self.Image.get_pixbuf()
            treemodel.set_value(iter, 1, pixbuf)
        except:
            log.exception("can't load the image %s" % filename)

    treemodel.set_value(iter, 2, movie.o_title)
    treemodel.set_value(iter, 3, movie.title)
    treemodel.set_value(iter, 4, movie.director)
    treemodel.set_value(iter, 5, movie.genre)
    treemodel.set_value(iter, 6, movie.seen)
    if movie.year is not None and (isinstance(movie.year, int)
                                   or isinstance(movie.year, long)):
        treemodel.set_value(iter, 7, str(movie.year))
    if movie.runtime is not None and (isinstance(movie.runtime, int)
                                      or isinstance(movie.runtime, long)):
        treemodel.set_value(iter, 8, '%003d' % movie.runtime + _(' min'))
    if movie.rating is not None and (isinstance(movie.rating, int)
                                     or isinstance(movie.rating, long)):
        treemodel.set_value(iter, 9, movie.rating)
    if movie.created:
        treemodel.set_value(iter, 10, movie.created.strftime('%Y-%m-%d %H:%M'))
    if movie.updated:
        treemodel.set_value(iter, 11, movie.updated.strftime('%Y-%m-%d %H:%M'))
    return iter
def setmovie(self, movie, iter, treemodel = None): #{{{
    if not treemodel:
        treemodel = self.treemodel

    treemodel.set_value(iter, 0, '%004d' % int(movie.number))

    if self.config.get('image', True, section='mainlist') == True:
        filename = None
        if movie.poster_md5:
            filename = gutils.get_image_fname(movie.poster_md5, self.db, "s")
        if not filename:
            filename = os.path.join(self.locations['images'], 'default_thumbnail.png')

        self.Image.set_from_file(filename)
        try:
            pixbuf = self.Image.get_pixbuf()
            treemodel.set_value(iter, 1, pixbuf)
        except:
            log.exception("can't load the image %s" % filename)

    treemodel.set_value(iter, 2, movie.o_title)
    treemodel.set_value(iter, 3, movie.title)
    treemodel.set_value(iter, 4, movie.director)
    treemodel.set_value(iter, 5, movie.genre)
    treemodel.set_value(iter, 6, movie.seen)
    if movie.year is not None and (isinstance(movie.year, int) or isinstance(movie.year, long)):
        treemodel.set_value(iter, 7, movie.year)
    if movie.runtime is not None and (isinstance(movie.runtime, int) or isinstance(movie.runtime, long)):
        treemodel.set_value(iter, 8, '%003d' % movie.runtime + _(' min'))
    if movie.rating is not None and (isinstance(movie.rating, int) or isinstance(movie.rating, long)):
        treemodel.set_value(iter, 9, movie.rating)
    if movie.created:
        treemodel.set_value(iter, 10, movie.created.strftime('%Y-%m-%d %H:%M'))
    if movie.updated:
        treemodel.set_value(iter, 11, movie.updated.strftime('%Y-%m-%d %H:%M'))
    return iter
Пример #6
0
def cover_simple(self, number):
    size = self.widgets['print_cover']['cs_size'].get_active()
    print_number = self.widgets['print_cover'][
        'cs_include_movie_number'].get_active()
    poster = self.widgets['print_cover']['cs_include_poster'].get_active()

    if self.config.get('font', '') != '':
        fontName = "custom_font"
        pdfmetrics.registerFont(TTFont(fontName, self.config.get('font', '')))
    else:
        fontName = "Helvetica"

    if size == 0:
        #standard
        cover_x = 774
        cover_y = 518
    elif size == 1:
        #slim
        cover_x = 757
        cover_y = 518
    else:
        #double slim
        cover_x = 757
        cover_y = 518

    # A4 landscape definition
    pageWidth = 842
    pageHeight = 595

    # hardcoded to A4
    pos_x = (pageWidth - cover_x) / 2
    pos_y = (pageHeight - cover_y) / 2
    # make a pdf
    c = canvas.Canvas(os.path.join(self.griffith_dir, "cover.pdf"),
                      (pageWidth, pageHeight))
    c.setFont(fontName, 8)

    # copyright line
    c.drawString(20,20,_("Cover generated by Griffith v").encode('utf-8') + \
        version.pversion+" (C) 2004-2009 Vasco Nunes/Piotr Ozarowski - "+ \
        _("Released Under the GNU/GPL License").encode('utf-8'))

    # draw cover area
    c.rect(pos_x, pos_y, cover_x, cover_y)

    # get movie information from db
    movie = self.db.session.query(db.Movie).filter_by(number=number).first()
    if movie is not None:
        if print_number:
            c.setFont(fontName, 10)
            c.drawCentredString(pageWidth / 2, 530, number)

        c.setFont(fontName, 16)
        c.rotate(90)
        c.drawString(60, (-pageWidth / 2) - 8, movie.title.encode('utf-8'))
        c.rotate(-90)
        if movie.poster_md5:
            filename = gutils.get_image_fname(movie.poster_md5, self.db)
            if filename:
                c.drawImage(filename,
                            x=(pageWidth - 30) / 2,
                            y=470,
                            width=30,
                            height=50)
        # print movie info
        c.setFont(fontName, 8)
        textObject = c.beginText()
        textObject.setTextOrigin(pageWidth - cover_x, 300)
        textObject.setFont(fontName, 8)
        textObject.textLine("%s: %s" % (_('Original Title'), movie.o_title))
        textObject.textLine("%s: %s" % (_('Title'), movie.title))
        textObject.textLine('')
        textObject.textLine("%s: %s" % (_('Director'), movie.director))
        textObject.textLine('')
        textObject.textLine("%s: %s %s" %
                            (_('Running Time'), movie.runtime, _(' min')))
        textObject.textLine("%s: %s" % (_('Country'), movie.country))
        textObject.textLine("%s: %s" % (_('Genre'), movie.genre))
        plotlines = textwrap.wrap(movie.plot, 80)
        plotlinenr = 0
        textObject.textLine("%s:" % (_('Plot')))
        for plotline in plotlines:
            textObject.textLine(plotline)
            plotlinenr = plotlinenr + 1
            if plotlinenr > 15:
                textObject.textLine('...')
                break
        textObject.textLine('')
        c.drawText(textObject)
        # draw bigger poster image
        if poster and movie.poster_md5 and filename:
            c.drawImage(filename,
                        x=(pageWidth - (pageWidth - cover_x) - 235),
                        y=(pageHeight / 2) - 125,
                        width=180,
                        height=250)
    c.showPage()
    c.save()
    self.widgets['print_cover']['window_simple'].hide()
    cover_file = os.path.join(self.griffith_dir, 'cover.pdf')
    if self.windows:
        os.popen3("\"" + cover_file + "\"")
    elif self.mac:
        os.popen3("open -a Preview" + " " + cover_file)
    else:
        os.popen3(self.pdf_reader + " " + cover_file)
def set_details(self, item=None):#{{{
    if item is None:
        item = {}
    if 'movie_id' in item and item['movie_id']:
        self._movie_id = item['movie_id']
    else:
        self._movie_id = None
    w = self.widgets['movie']

    if 'number' in item and item['number']:
        w['number'].set_text(str(int(item['number'])))
    else:
        w['number'].set_text('')
    if 'title' in item and item['title']:
        w['title'].set_markup("<b><span size='large'>%s</span></b>" % gutils.html_encode(item['title']))
    else:
        w['title'].set_text('')
    if 'o_title' in item and item['o_title']:
        w['o_title'].set_markup("<span size='medium'><i>%s</i></span>" % gutils.html_encode(item['o_title']))
    else:
        w['o_title'].set_text('')
    if 'director' in item and item['director']:
        w['director'].set_markup("<i>%s</i>" % gutils.html_encode(item['director']))
    else:
        w['director'].set_text('')
    if 'plot' in item and item['plot']:
        w['plot'].set_text(str(item['plot']))
    else:
        w['plot'].set_text('')
    if 'year' in item and item['year']:
        w['year'].set_text(str(item['year']))
    else:
        w['year'].set_text('')
    if 'resolution' in item and item['resolution']:
        if self.config.get('use_resolution_alias', True):
            w['resolution'].set_text(item['resolution'])
        elif 'height' in item and item['height'] and 'width' in item and item['width']:
            w['resolution'].set_text("%dx%d" % (item['width'], item['height']))
        else: # fallback to 'resolution'
            w['resolution'].set_text(item['resolution'])
    else:
        w['resolution'].set_text('')
        pass
    if 'runtime' in item and item['runtime']:
        w['runtime'].set_text(str(int(item['runtime'])))
    else:
        w['runtime'].set_text('x')
    if 'cameraman' in item and item['cameraman']:
        w['cameraman'].set_markup("<i>%s</i>" % gutils.html_encode(item['cameraman']))
    else:
        w['cameraman'].set_text('')
    if 'screenplay' in item and item['screenplay']:
        w['screenplay'].set_markup("<i>%s</i>" % gutils.html_encode(item['screenplay']))
    else:
        w['screenplay'].set_text('')
    if 'cast' in item and item['cast']:
        w['cast'].set_text(str(item['cast']))
    else:
        w['cast'].set_text('')
    if 'country' in item and item['country']:
        w['country'].set_markup("<i>%s</i>" % gutils.html_encode(item['country']))
    else:
        w['country'].set_text('')
    if 'genre' in item and item['genre']:
        w['genre'].set_markup("<i>%s</i>" % gutils.html_encode(item['genre']))
    else:
        w['genre'].set_text('')
    if 'cond' in item and item['cond']:
        if str(item['cond']) in [str(i) for i in range(len(self._conditions))]:
            w['condition'].set_markup("<i>%s</i>" % self._conditions[item['cond']])
        else:
            w['condition'].set_text('')
            log.info("Wrong value in 'condition' field (movie_id=%s, cond=%s)" % (item['movie_id'], item['cond']))
    else:
        w['condition'].set_text('')
    if 'region' in item and item['region']:
        if str(item['region']) in [str(i) for i in range(len(self._regions))]:
            w['region'].set_markup("<i>%s</i>" % gutils.html_encode(item['region']))
            if int(item['region']) < 9:
                self.widgets['tooltips'].set_tip(w['region'], self._regions[int(item['region'])])
        else:
            log.info("Wrong value in 'region' field (movie_id=%s, region=%s)" % (item['movie_id'], item['region']))
            w['region'].set_text('')
            self.widgets['tooltips'].set_tip(w['region'], self._regions[0]) # N/A
    else:
        w['region'].set_text('')
        self.widgets['tooltips'].set_tip(w['region'], self._regions[0]) # N/A
    if 'layers' in item and item['layers']:
        if str(item['layers']) in [str(i) for i in range(len(self._layers))]:
            w['layers'].set_markup("<i>%s</i>" % self._layers[item['layers']])
        else:
            log.info("Wrong value in 'layers' field (movie_id=%s, layers=%s)" % (item['movie_id'], item['layers']))
            w['layers'].set_text('')
    else:
        w['layers'].set_text('')
    if 'color' in item and item['color']:
        if str(item['color']) in [str(i) for i in range(len(self._colors))]:
            w['color'].set_markup("<i>%s</i>" % self._colors[item['color']])
        else:
            log.info("Wrong value in 'color' field (movie_id=%s, color=%s)" % (item['movie_id'], item['color']))
            w['color'].set_markup('')
    else:
        w['color'].set_markup('')
    if 'classification' in item and item['classification']:
        w['classification'].set_markup("<i>%s</i>" % gutils.html_encode(item['classification']))
    else:
        w['classification'].set_text('')
    if 'studio' in item and item['studio']:
        w['studio'].set_markup("<i>%s</i>" % gutils.html_encode(item['studio']))
    else:
        w['studio'].set_text('')
    if 'o_site' in item and item['o_site']:
        self._o_site_url = str(item['o_site'])
        w['go_o_site_button'].set_sensitive(True)
    else:
        self._o_site_url = None
        w['go_o_site_button'].set_sensitive(False)
    if 'site' in item and item['site']:
        self._site_url = str(item['site'])
        w['go_site_button'].set_sensitive(True)
    else:
        self._site_url = None
        w['go_site_button'].set_sensitive(False)
    if 'trailer' in item and item['trailer']:
        self._trailer_url = str(item.trailer)
        w['go_trailer_button'].set_sensitive(True)
    else:
        self._trailer_url = None
        w['go_trailer_button'].set_sensitive(False)
    if 'seen' in item and item['seen'] == True:
        w['seen_icon'].set_from_file(os.path.join(self.locations['images'], 'seen.png'))
    else:
        w['seen_icon'].set_from_file(os.path.join(self.locations['images'], 'unseen.png'))
    if 'notes' in item and item['notes']:
        w['notes'].set_text(str(item.notes))
    else:
        w['notes'].set_text('')
    tmp = ''
    if 'media_num' in item and item['media_num']:
        tmp = str(item.media_num)
    else:
        tmp = '0'
    if 'medium_id' in item and item['medium_id']:
        if item.medium is not None:
            tmp += ' x ' + item.medium.name
        else:
            pass
    w['medium'].set_markup("<i>%s</i>" % gutils.html_encode(tmp))
    if 'vcodec_id' in item:
        if item.vcodec is not None:
            w['vcodec'].set_markup("<i>%s</i>" % gutils.html_encode(item.vcodec.name))
        else:
            w['vcodec'].set_text('')
    else:
        w['vcodec'].set_text('')
    # TODO: add widgets in main and edit windows
    #if 'ratio_id' in item:
    #    if item.ratio is not None:
    #        w['ratio'].set_markup("<i>%s</i>" % gutils.html_encode(item.ratio.name))
    #    else:
    #        w['ratio'].set_text('')
    #else:
    #    w['ratio'].set_text('')

    # poster
    if 'poster_md5' in item and item['poster_md5']:
        filename = gutils.get_image_fname(item['poster_md5'], self.db, 'm')
        if filename and os.path.isfile(filename):
            image_path = filename
            self.widgets['add']['delete_poster'].set_sensitive(True)
            w['picture_button'].set_sensitive(True)
        else:
            image_path = gutils.get_defaultimage_fname(self)
            self.widgets['add']['delete_poster'].set_sensitive(False)
            w['picture_button'].set_sensitive(False)
    else:
        image_path = gutils.get_defaultimage_fname(self)
        w['picture_button'].set_sensitive(False)
    w['picture'].set_from_file(image_path)
    # ratig
    rimage = int(self.config.get('rating_image', 0))
    if rimage:
        prefix = ''
    else:
        prefix = 'meter'
    if 'rating' in item and item['rating']:
        rating_file = "%s/%s0%d.png" % (self.locations['images'], prefix, item['rating'])
    else:
        rating_file = "%s/%s0%d.png" % (self.locations['images'], prefix, 0)
    handler = w['image_rating'].set_from_pixbuf(gtk.gdk.pixbuf_new_from_file(rating_file))
    gutils.garbage(handler)

    # check loan status and adjust buttons and history box
    if 'loaned' in item and item['loaned'] is True:
        self.widgets['popups']['loan'].set_sensitive(False)
        self.widgets['popups']['email'].set_sensitive(True)
        self.widgets['popups']['return'].set_sensitive(True)
        self.widgets['menu']['loan'].set_sensitive(False)
        self.widgets['menu']['email'].set_sensitive(True)
        self.widgets['menu']['return'].set_sensitive(True)
        w['loan_button'].set_sensitive(False)
        w['email_reminder_button'].set_sensitive(True)
        w['return_button'].set_sensitive(True)

        if getattr(item, 'loan_details', None) is None:
            log.warning("movie has no loan data, changing 'loaned' flag to False (movie_id: %s)", item['movie_id'])
            item.loaned = False
        else:
            self.person_name = item.loan_details.person.name
            self.person_email = item.loan_details.person.email
            self.loan_date = str(item.loan_details.date)
            w['loan_info'].set_use_markup(False)
            w['loan_info'].set_label(_("This movie has been loaned to %s on %s") % (self.person_name, self.loan_date[:10]))
    if 'loaned' in item and not item['loaned']: # "loaned" status can be changed above, so don't use "else:" in this line
        self.widgets['popups']['loan'].set_sensitive(True)
        self.widgets['popups']['email'].set_sensitive(False)
        self.widgets['popups']['return'].set_sensitive(False)
        self.widgets['menu']['loan'].set_sensitive(True)
        self.widgets['menu']['email'].set_sensitive(False)
        self.widgets['menu']['return'].set_sensitive(False)
        w['return_button'].set_sensitive(False)
        w['email_reminder_button'].set_sensitive(False)
        w['loan_button'].set_sensitive(True)
        w['loan_info'].set_markup("<b>%s</b>" % _("Movie not loaned"))

    # loan history
    self.loans_treemodel.clear()
    if getattr(item, 'loan_history', None) is not None:
        for loan in item.loan_history:
            myiter = self.loans_treemodel.append(None)
            self.loans_treemodel.set_value(myiter, 0, '%s' % str(loan.date)[:10])
            if loan.return_date and  loan.return_date != '':
                self.loans_treemodel.set_value(myiter, 1, str(loan.return_date)[:10])
            else:
                self.loans_treemodel.set_value(myiter, 1, "---")
            person = self.db.session.query(db.Person.name).filter_by(person_id=loan.person.person_id).first()
            self.loans_treemodel.set_value(myiter, 2, person.name)

    # volumes/collections
    if 'volume_id' in item and item['volume_id'] > 0:
        if 'volume' in item and item['volume']:
            w['volume'].set_markup("<b>%s</b>" % gutils.html_encode(item['volume'].name))
            w['show_volume_button'].set_sensitive(True)
        else:
            w['volume'].set_text('')
            w['show_volume_button'].set_sensitive(False)
    else:
            w['volume'].set_text('')
            w['show_volume_button'].set_sensitive(False)
    if 'collection_id' in item and item['collection_id'] > 0:
        if 'collection' in item and item['collection']:
            w['collection'].set_markup("<b>%s</b>" % gutils.html_encode(item['collection'].name))
            w['show_collection_button'].set_sensitive(True)
        else:
            w['collection'].set_text('')
            w['show_collection_button'].set_sensitive(False)
    else:
        w['collection'].set_text('')
        w['show_collection_button'].set_sensitive(False)

    # languages
    for i in w['audio_vbox'].get_children():
        i.destroy()
    for i in w['subtitle_vbox'].get_children():
        i.destroy()
    if 'languages' in item and len(item['languages']) > 0:
        for i in item['languages']:
            if i.type == 3: # subtitles
                if i.subformat:
                    tmp = "%s - %s" % (i.language.name, i.subformat.name)
                else:
                    tmp = "%s" % i.language.name
                w['subtitle_vbox'].pack_start(gtk.Label(tmp))
            else:
                language = i.language.name
                if i.type is not None and len(self._lang_types[i.type]) > 0:
                    language += " <i>%s</i>" % self._lang_types[i.type]
                tmp = ''
                if i.achannel:
                    tmp = i.achannel.name
                if i.acodec:
                    if len(tmp) > 0:
                        tmp += ", %s" % i.acodec.name
                    else:
                        tmp = i.acodec.name
                if len(tmp) > 0:
                    tmp = "%s (%s)" % (language, tmp)
                else:
                    tmp = language
                widget = gtk.Label(tmp)
                widget.set_use_markup(True)
                w['audio_vbox'].pack_start(widget)
    w['audio_vbox'].show_all()
    w['subtitle_vbox'].show_all()
    #tags
    if 'tags' in item:
        tmp = ''
        for tag in item['tags']:
            tmp += "%s, " % tag.name
        tmp = tmp[:-2] # cut last comma
        w['tags'].set_text(tmp)
Пример #8
0
class ExportPlugin(Base):
    name = 'HTML'
    description = _('Plugin exports data using templates')
    author = 'Piotr Ożarowski'
    email = '*****@*****.**'
    version = '4.0'

    #==[ configuration - default values ]==========={{{
    settings = {
        'sorting': 'movies_title',
        'sorting2': 'ASC',
        'export_dir': '',
        'template': 2,
        'title': _("Griffith's movies list"),
        'style': 0,
        'custom_style': False,
        'custom_style_file': None,
        'split_num': 50,  # split into x files/pages
        'split_by': 1,  # 0==files, 1==movies
        'poster_convert': False,  # dont convert
        'poster_height': 200,
        'poster_width': 150,
        'poster_mode': 'RGB',  # RGB == color, L == black and white
        'poster_format': 'jpeg'
    }
    fields = {
        'movies_cast': False,
        'movies_classification': False,
        'movies_country': True,
        'movies_genre': True,
        'movies_director': True,
        'movies_image': True,
        'movies_o_site': True,
        'movies_site': True,
        'movies_trailer': True,
        'movies_loaned': False,
        'movies_media_num': True,
        'movies_number': True,
        'movies_o_title': True,
        'movies_plot': False,
        'movies_rating': True,
        'movies_runtime': True,
        'movies_studio': False,
        'movies_seen': True,
        'movies_title': True,
        'movies_year': True,
        'movies_notes': False,
        'movies_screenplay': False,
        'movies_cameraman': False,
        'movies_width': False,
        'movies_height': False,
        'movies_barcode': False,
        #        'movies_region'         : False,
        #        'movies_layers'         : False,
        #        'movies_condition'      : False,
        #        'movies_color'          : False,
        #        'movies_volume_id'      : False,
        #        'movies_collection_id'  : False,
        'media_name': True,
        'collections_name': True,
        'volumes_name': True,
        #        'acodecs_name'          : True,
        'vcodecs_name': True,
    }

    fields_as_columns = {
        'movies_cast': 'cast',
        'movies_classification': 'classification',
        'movies_country': 'country',
        'movies_genre': 'genre',
        'movies_director': 'director',
        'movies_image': 'poster_md5',
        'movies_o_site': 'o_site',
        'movies_site': 'site',
        'movies_trailer': 'trailer',
        'movies_loaned': 'loaned',
        'movies_media_num': 'media_num',
        'movies_number': 'number',
        'movies_o_title': 'o_title',
        'movies_plot': 'plot',
        'movies_rating': 'rating',
        'movies_runtime': 'runtime',
        'movies_studio': 'studio',
        'movies_seen': 'seen',
        'movies_title': 'title',
        'movies_year': 'year',
        'movies_notes': 'notes',
        'movies_screenplay': 'screenplay',
        'movies_cameraman': 'cameraman',
        'movies_width': 'width',
        'movies_height': 'height',
        'movies_barcode': 'barcode',
        #        'movies_region'         : 'region',
        #        'movies_layers'         : 'layers',
        #        'movies_condition'      : 'condition',
        #        'movies_color'          : 'color',
        #        'movies_volume_id'      : 'volume_id',
        #        'movies_collection_id'  : 'collection_id',
        'media_name': 'name',
        'collections_name': 'name',
        'volumes_name': 'name',
        #        'acodecs_name'          : 'name',
        'vcodecs_name': 'name',
    }

    names = {
        _('Cast'):
        'movies_cast',
        _('Classification'):
        'movies_classification',
        _('Country'):
        'movies_country',
        _('Director'):
        'movies_director',
        _('Genre'):
        'movies_genre',
        _('Image'):
        'movies_image',
        _('Official site'):
        'movies_o_site',
        _('Site'):
        'movies_site',
        _('Trailer'):
        'movies_trailer',
        _('Loaned'):
        'movies_loaned',
        _('Discs'):
        'movies_media_num',
        _('Number'):
        'movies_number',
        _('Original Title'):
        'movies_o_title',
        _('Plot'):
        'movies_plot',
        _('Rating'):
        'movies_rating',
        _('Runtime'):
        'movies_runtime',
        _('Studio'):
        'movies_studio',
        _('Seen it'):
        'movies_seen',
        _('Title'):
        'movies_title',
        _('Year'):
        'movies_year',
        _('Notes'):
        'movies_notes',
        _('Screenplay'):
        'movies_screenplay',
        _('Cameraman'):
        'movies_cameraman',
        _('Width'):
        'movies_width',
        _('Height'):
        'movies_height',
        _('Barcode'):
        'movies_barcode',
        #        _('Region')         : 'movies_region',
        #        _('Layers')         : 'movies_layers',
        #        _('Condition')      : 'movies_condition',
        #        _('Color')          : 'movies_color',
        #        _('Volume')         : 'movies_volume_id',
        #        _('Collection')     : 'movies_collection_id',
        _('Media'):
        'media_name',
        _('Collection'):
        'collections_name',
        _('Volume'):
        'volumes_name',
        #        _('Audio codecs')   : 'acodecs_name',
        _('Video codec'):
        'vcodecs_name',
    }

    #}}}

    def initialize(self):  #{{{
        self.fields_to_export = []
        for field in ExportPlugin.fields:
            if field == 'movies_image':
                self.fields_to_export.append('movies.poster_md5')
            else:
                pos = field.find('_')
                self.fields_to_export.append("%s.%s" %
                                             (field[:pos], field[pos + 1:]))

        self.widgets = {}
        self.style_list = {}
        self.templates = self.make_template_list()
        # glade
        gf = os.path.join(self.locations['glade'], 'exporthtml.glade')
        self.load_configuration()
        self.define_widgets(gtk.glade.XML(gf))
        self.fill_widgets()
        return True

    #}}}

    def load_configuration(self):  #{{{
        # persist config
        if self.config is not None:
            config = self.settings
            for name, value in config.items():
                try:
                    tmp = self.config.get(name, value, section='export-html')
                    if isinstance(value, bool):
                        config[name] = bool(int(tmp))
                    elif isinstance(value, int):
                        config[name] = int(tmp)
                    else:
                        config[name] = tmp
                except:
                    pass
            selected_fields = self.config.get('selected_fields',
                                              '',
                                              section='export-html')
            if selected_fields:
                for name in self.fields:
                    self.fields[name] = False
                selected_fields = selected_fields.split(',')
                for selected_field in selected_fields:
                    if selected_field in self.fields:
                        self.fields[selected_field] = True

    #}}}

    def run(self):
        pass

    def get_node_value_by_language(self, parent, name, language='en'):  #{{{
        nodes = parent.getElementsByTagName(name)
        for node in nodes:
            if node.parentNode != parent:
                continue
            elif node.attributes.get('xml:lang') is not None:
                if node.attributes.get('xml:lang').value == language:
                    return node.firstChild.nodeValue
            else:  # set default value in case node has no xml:lang attribute
                value = node.firstChild.nodeValue
        return value

    #}}}

    def make_template_list(self):  #{{{
        language = 'en'
        if os.environ.has_key('LANG'):
            language = os.environ['LANG'][:2]
        templates = {}
        j = 0  # number of templates
        dirName = os.path.join(self.locations['share'], 'export_templates')
        items = os.listdir(dirName)
        items.sort()
        for i in items:
            fileName = os.path.join(dirName, i)
            if not os.path.islink(fileName) and os.path.isdir(fileName):
                # clear previous data
                doc = None
                styles = {}
                tpl_name = None
                tpl_author = None
                tpl_email = None
                tpl_version = None
                tpl_ext = None
                tpl_desc = None
                try:
                    doc = minidom.parse(os.path.join(fileName, 'config.xml'))
                except:
                    log.info(
                        "Can't parse configuration file for template: %s" %
                        fileName)
                    continue
                for template in doc.getElementsByTagName('template'):
                    tpl_name = self.get_node_value_by_language(
                        template, 'name', language)
                    tpl_author = template.getElementsByTagName(
                        'author')[0].firstChild.nodeValue
                    tpl_email = template.getElementsByTagName(
                        'email')[0].firstChild.nodeValue
                    tpl_version = template.getElementsByTagName(
                        'version')[0].firstChild.nodeValue
                    tpl_ext = template.getElementsByTagName(
                        'extension')[0].firstChild.nodeValue
                    tpl_desc = self.get_node_value_by_language(
                        template, 'description', language)
                    k = 0  # number of styles
                    try:
                        styles_list = template.getElementsByTagName(
                            'styles')[0].getElementsByTagName('style')
                        for style in styles_list:
                            tpl_style_name = self.get_node_value_by_language(
                                style, 'name', language)
                            tpl_style_file = style.getElementsByTagName(
                                'file')[0].firstChild.nodeValue
                            # get preview if available
                            try:
                                tpl_style_preview = style.getElementsByTagName(
                                    'preview')[0].firstChild.nodeValue
                            except:
                                tpl_style_preview = None
                            styles[k] = {
                                'name': tpl_style_name,
                                'file': tpl_style_file,
                                'preview': tpl_style_preview
                            }
                            k = k + 1
                    except:
                        styles = None
                if tpl_name == '':
                    continue
                templates[j] = {
                    'dir': i,
                    'name': tpl_name,
                    'author': tpl_author,
                    'email': tpl_email,
                    'version': tpl_version,
                    'ext': tpl_ext,
                    'desc': tpl_desc,
                    'styles': styles
                }
                j = j + 1
        return templates

    #}}}

    #==[ widgets ]=================================={{{
    def define_widgets(self, glade_file):
        get = lambda x: glade_file.get_widget(x)
        self.widgets = {
            'window': get('w_eh'),
            'fcw': get('fcw'),
            'box_include_1': get('box_include_1'),
            'box_include_2': get('box_include_2'),
            'box_include_3': get('box_include_3'),
            'sb_split_num': get('sb_split_num'),
            'rb_split_files': get('rb_split_files'),
            'rb_split_movies': get('rb_split_movies'),
            'entry_header': get('entry_header'),
            'cb_custom_style': get('cb_custom_style'),
            'cb_reverse': get('cb_reverse'),
            'combo_style': get('combo_style'),
            'combo_sortby': get('combo_sortby'),
            'combo_theme': get('combo_theme'),
            'fcb_custom_style_file': get('fcb_custom_style_file'),
            'l_tpl_author': get('l_tpl_author'),
            'l_tpl_email': get('l_tpl_email'),
            'l_tpl_version': get('l_tpl_version'),
            'l_tpl_desc': get('l_tpl_desc'),
            'image_preview': get('image_preview'),
            'vb_posters': get('vb_posters'),
            'sb_height': get('sb_height'),
            'sb_width': get('sb_width'),
            'cb_black': get('cb_black'),
            'combo_format': get('combo_format'),
            'cb_convert': get('cb_convert'),
        }

        # define handlers for general events
        glade_file.signal_autoconnect({
            'on_export_button_clicked':
            self.export_data,
            'on_rb_split_files_toggled':
            self.on_rb_split_files_toggled,
            'on_rb_split_movies_toggled':
            self.on_rb_split_movies_toggled,
            'on_cancel_button_clicked':
            self.on_quit,
            'on_cb_data_toggled':
            self.on_cb_data_toggled,
            'on_cb_custom_style_toggled':
            self.on_cb_custom_style_toggled,
            'on_fcb_custom_style_file_activated':
            self.on_fcb_custom_style_file_activated,
            'on_combo_style_changed':
            self.on_combo_style_changed,
            'on_combo_theme_changed':
            self.on_combo_theme_changed,
            'on_cb_convert_toggled':
            self.on_cb_convert_toggled,
        })

    def fill_widgets(self):
        # themes
        for i in self.templates:
            self.widgets['combo_theme'].insert_text(i,
                                                    self.templates[i]['name'])

        # sortby combo
        keys = self.names.keys()
        keys.sort()
        j = 0
        pos_o_title = 0
        for i in keys:
            self.widgets['combo_sortby'].append_text(i)
            if self.names[i] == self.settings['sorting']:
                pos_o_title = j
            j = j + 1
        self.widgets['combo_sortby'].set_wrap_width(3)

        # include data
        j = 0
        k = math.ceil(len(self.names) / float(3))
        for i in keys:
            j = j + 1
            field = self.names[i]
            self.widgets['cb_' + field] = gtk.CheckButton(i)
            self.widgets['cb_' + field].set_name("cb_%s" % field)
            self.widgets['cb_' + field].connect('toggled',
                                                self.on_cb_data_toggled)
            self.widgets['cb_' + field].set_active(self.fields[field])
            if j <= k:
                self.widgets['box_include_1'].add(self.widgets["cb_%s" %
                                                               field])
            elif j <= 2 * k:
                self.widgets['box_include_2'].add(self.widgets["cb_%s" %
                                                               field])
            else:
                self.widgets['box_include_3'].add(self.widgets["cb_%s" %
                                                               field])
        self.widgets['box_include_1'].show_all()
        self.widgets['box_include_2'].show_all()
        self.widgets['box_include_3'].show_all()

        # set defaults --------------------------------
        self.widgets['entry_header'].set_text(self.settings['title'])
        self.widgets['combo_sortby'].set_active(pos_o_title)
        if self.settings['sorting2'] == 'DESC':
            self.widgets['cb_reverse'].set_active(True)
        else:
            self.widgets['cb_reverse'].set_active(False)
        # template and theme
        style = self.settings[
            'style']  # save it temporary because change of the template set it 0
        self.widgets['combo_theme'].set_active(self.settings['template'])
        self.widgets['combo_style'].set_active(style)
        self.widgets['cb_custom_style'].set_active(
            self.settings['custom_style'])
        if self.settings['custom_style_file']:
            self.widgets['fcb_custom_style_file'].set_filename(
                self.settings['custom_style_file'])
        # spliting
        self.widgets['sb_split_num'].set_value(self.settings['split_num'])
        if self.settings['split_by'] == 0:
            self.widgets['rb_split_files'].set_active(True)
        else:
            self.widgets['rb_split_movies'].set_active(True)
        # posters
        self.widgets['combo_format'].set_active(0)
        if self.settings['poster_format'] == 'PNG':
            self.widgets['combo_format'].set_active(1)
        elif self.settings['poster_format'] == 'GIF':
            self.widgets['combo_format'].set_active(2)
        if self.settings['poster_convert'] and self.settings[
                'poster_convert'] == True:
            self.widgets['cb_convert'].set_active(True)
            self.widgets['vb_posters'].set_sensitive(True)
        else:
            self.widgets['cb_convert'].set_active(False)
            self.widgets['vb_posters'].set_sensitive(False)
        self.widgets['sb_height'].set_value(self.settings['poster_height'])
        self.widgets['sb_width'].set_value(self.settings['poster_width'])
        if self.settings['poster_mode'] == 'L':
            self.widgets['cb_black'].set_active(True)
        # destination dir
        if self.settings['export_dir']:
            self.widgets['fcw'].set_current_folder(self.settings['export_dir'])

    #}}}

    #==[ callbacks ]================================{{{
    # buttons:
    def on_quit(self, widget=None):
        self.widgets['window'].destroy()

    # data tab -------------------------------------#{{{
    def on_rb_split_files_toggled(self, widget):
        self.settings['split_by'] = 0  # files

    def on_rb_split_movies_toggled(self, widget):
        self.settings['split_by'] = 1  # movies

    # export frame
    def on_cb_data_toggled(self, widget):
        self.fields[gutils.after(widget.get_name(),
                                 'cb_')] = widget.get_active()

    # posters frame
    def on_cb_convert_toggled(self, widget):
        active = widget.get_active()
        self.settings['poster_convert'] = active
        if not active:
            self.widgets['vb_posters'].set_sensitive(False)
        else:
            self.widgets['vb_posters'].set_sensitive(True)

    #}}}

    # template tab ---------------------------------#{{{
    def on_combo_theme_changed(self, widget):
        old_id = self.settings['template']
        tpl_id = widget.get_active()
        self.settings['template'] = tpl_id
        # fill authors data
        self.widgets['l_tpl_author'].set_markup(
            "<i>%s</i>" % self.templates[tpl_id]['author'])
        self.widgets['l_tpl_email'].set_markup("<i>%s</i>" %
                                               self.templates[tpl_id]['email'])
        self.widgets['l_tpl_email'].set_selectable(True)
        self.widgets['l_tpl_version'].set_markup(
            "<i>%s</i>" % self.templates[tpl_id]['version'])
        self.widgets['l_tpl_desc'].set_markup("<i>%s</i>" %
                                              self.templates[tpl_id]['desc'])
        # remove old style list
        self.widgets['combo_style'].get_model().clear()
        # ... and add new
        if self.templates[tpl_id]['styles'] is not None:
            for i in self.templates[tpl_id]['styles']:
                self.widgets['combo_style'].insert_text(
                    i, self.templates[tpl_id]['styles'][i]
                    ['name'])  # template name
            self.widgets['combo_style'].set_active(0)
        else:
            self.settings['style'] = None
            self.widgets['image_preview'].set_from_stock(
                gtk.STOCK_MISSING_IMAGE, gtk.ICON_SIZE_LARGE_TOOLBAR)

    def on_combo_style_changed(self, widget):
        self.settings['style'] = widget.get_active()
        self.widgets['cb_custom_style'].set_active(False)
        preview_file = None

        tpl_id = self.settings['template']
        template_dir = os.path.join(self.locations['share'],
                                    'export_templates',
                                    self.templates[tpl_id]['dir'])
        if self.settings['style'] > -1:
            preview_file = self.templates[self.settings['template']]['styles'][
                self.settings['style']]['preview']
        if preview_file is not None:
            preview_file = os.path.join(template_dir, preview_file)
        if preview_file is not None and not os.path.isfile(preview_file):
            preview_file = os.path.join(
                template_dir, 'preview.jpg')  # try default preview image
            if not os.path.isfile(preview_file):
                preview_file = None
        if preview_file is not None:
            self.widgets['image_preview'].set_from_file(preview_file)
        else:
            self.widgets['image_preview'].set_from_stock(
                gtk.STOCK_MISSING_IMAGE, gtk.ICON_SIZE_LARGE_TOOLBAR)
        self.widgets['image_preview'].show()

    def on_cb_custom_style_toggled(self, widget):
        if widget.get_active():
            self.settings['custom_style'] = True
            self.widgets['image_preview'].hide()
        else:
            self.settings['custom_style'] = False
            self.widgets['image_preview'].show()

    def on_fcb_custom_style_file_activated(self, widget):
        self.settings['custom_style_file'] = widget.get_filename()
        self.widgets['cb_custom_style'].set_active(True)

    #}}} }}}

    def make_navigation(self, pages, current):  #{{{
        if pages > 1:  # navigation needed
            tpl_id = self.settings['template']
            t = '<div class="navi">\n\t<p id="prev">'
            if current > 1:
                t += '<a href="./page_%s.%s">%s</a>' % \
                    (str(current-1), self.templates[tpl_id]['ext'], _('previous'))
            else:  # first page
                t += _('previous')
            t += "</p>\n"
            for i in range(1, pages + 1):
                if i == current:
                    t += '\t<p id="current">%s</p>\n' % str(i)
                else:
                    t +='\t<p><a href="./page_%s.%s">%s</a></p>\n' % \
                        (str(i), self.templates[tpl_id]['ext'], str(i))
            t += '\t<p id="next">'
            if pages > current:
                t +='<a href="./page_%s.%s">%s</a>' % \
                        (str(current+1), self.templates[tpl_id]['ext'], _('next'))
            else:  # last page
                t += _('next')
            t += "</p>\n</div>"
            return t
        else:
            return ''

    #}}}

    def fill_template(self,
                      template,
                      field,
                      data='',
                      title='',
                      remove=False):  #{{{
        start = template.find('<@' + field + '>')
        end = template.find('</@' + field + '>', start + 1)
        if start > -1 and end > -1:
            if remove == True:
                return template[:start] + template[end + 4 + len(field):]
            else:
                tmp = gutils.trim(template, '<@' + field + '>',
                                  '</@' + field + '>')
                tmp = tmp.replace("@DATA@", data)
                tmp = tmp.replace("@TITLE@", title)
                tmp = template[:start] + tmp + template[end + 4 + len(field):]
                if tmp.find('<@' + field + '>') != -1:
                    tmp = self.fill_template(tmp, field, data, title, remove)
                return tmp
        else:
            return template

    #}}}

    def select(self):  #{{{
        config = self.settings
        # sort order TODO: update self.search_conditions["sort_by"]
        tmp = config['sorting'].split('_')
        sort_column = "%s.%s" % (tmp[0], '_'.join(tmp[1:]))

        if config['sorting2'] == 'ASC':
            sort_column += ' ASC'
        else:
            sort_column += ' DESC'

        self.search_conditions["sort_by"] = (sort_column, )
        query = self.get_query()

        return query.execute()

    #}}}

    #==[ main function ]============================{{{
    def export_data(self, widget):
        """Main exporting function"""

        config = self.settings
        fields = self.fields
        tid = config['template']

        # get data from widgets
        self.settings['export_dir'] = self.widgets['fcw'].get_filename()
        self.settings['title'] = self.widgets['entry_header'].get_text(
        ).decode('utf-8')
        self.settings['sorting'] = self.names[
            self.widgets['combo_sortby'].get_active_text().decode('utf-8')]
        if self.widgets['cb_reverse'].get_active():
            self.settings['sorting2'] = 'DESC'
        else:
            self.settings['sorting2'] = 'ASC'
        self.settings['split_num'] = self.widgets[
            'sb_split_num'].get_value_as_int()
        self.settings['poster_height'] = self.widgets[
            'sb_height'].get_value_as_int()
        self.settings['poster_width'] = self.widgets[
            'sb_width'].get_value_as_int()
        if self.widgets['cb_black'].get_active():
            self.settings['poster_mode'] = 'L'
        else:
            self.settings['poster_mode'] = 'RGB'
        self.settings['poster_format'] = self.widgets[
            'combo_format'].get_active_text()

        # persist config
        if self.config is not None:
            for name, value in config.items():
                self.config.set(name, value, section='export-html')
            selected_fields = ''
            for name, value in self.fields.items():
                if value:
                    selected_fields = selected_fields + name + ','
            self.config.set('selected_fields',
                            selected_fields,
                            section='export-html')
            self.config.save()

        # create directories
        if not config['export_dir']:
            log.info("Error: Folder name not set!")
            return 1

        if not os.path.isdir(config['export_dir']):
            try:
                os.mkdir(config['export_dir'])
            except:
                gutils.error(_("Can't create %s!") % config['export_dir'])
                return 2

        data_path = os.path.join(self.locations['share'], 'export_templates',
                                 self.templates[tid]['dir'], 'data')
        if os.path.isdir(data_path):
            try:
                gutils.copytree(data_path, config['export_dir'])
            except Exception, err:
                gutils.warning(str(err))

        if fields['movies_image']:
            # import modules needed later
            # modules are needed at least to convert griffith.png to nopic.(gif|jpeg|png)
            from PIL import Image
            # py2exe problem workaround:
            if os.name == 'nt' or os.name.startswith('win'):  # win32, win64
                from PIL import PngImagePlugin
                from PIL import GifImagePlugin
                from PIL import JpegImagePlugin
                Image._initialized = 2
            if not config['poster_convert']:
                config['poster_format'] = 'jpeg'  # replace 'jpeg'

            posters_dir = os.path.join(config['export_dir'], 'posters')
            if os.path.isdir(posters_dir):
                if gutils.question(
                        _("Directory %s already exists.\nDo you want to overwrite it?"
                          ) % posters_dir, self.widgets['window']):
                    try:
                        shutil.rmtree(posters_dir)
                    except:
                        gutils.error(
                            _("Can't remove %s!") % config['export_dir'])
                        return 3
                else:
                    return 4
            try:
                os.mkdir(posters_dir)
            except:
                gutils.error(_("Can't create %s!") % posters_dir)
                return 5

        if config['custom_style']:
            if config['custom_style_file'] is not None and os.path.isfile(
                    config['custom_style_file']):
                try:
                    shutil.copy(config['custom_style_file'],
                                config['export_dir'])
                except:
                    gutils.warning(_("Can't copy %s!") % style_file)
                    config['custom_style'] = False
                style = os.path.split(self.settings['custom_style_file'])[1]
            else:
                config['custom_style'] = False

        if config['style'] is not None and config['custom_style'] == False:
            style = self.templates[tid]['styles'][config['style']]['file']
            style_path = os.path.join(self.locations['share'],
                                      'export_templates',
                                      self.templates[tid]['dir'], style)
            try:
                shutil.copy(style_path, config['export_dir'])
            except:
                gutils.warning(_("Can't copy %s!") % style_path)

        # select exported movies
        exported_movies = self.select().fetchall()
        if self.settings['sorting'] in ('movies_title', 'movies_o_title'):
            # re-sorting movies case-insensitive and respect the current locale setting
            # if sorting by title or original title is selected
            import locale
            locale.setlocale(locale.LC_ALL, "")
            exported_movies.sort(cmp = locale.strcoll, \
                key = lambda k: k[self.settings['sorting']] and k[self.settings['sorting']].lower() or '', \
                reverse = self.settings['sorting2']=='DESC')
        number_of_exported_movies = len(exported_movies)

        if config['split_by'] == 1:  # split by number of movies per page
            self.entries_per_page = config['split_num']
        else:  # split by number of pagess
            if number_of_exported_movies < config['split_num']:
                self.entries_per_page = 1
            else:
                self.entries_per_page = int(number_of_exported_movies /
                                            config['split_num'])

        # calculate number of files to be created (pages)
        self.pages = int(
            math.ceil(
                float(number_of_exported_movies) / self.entries_per_page))

        template_dir = os.path.join(self.locations['share'],
                                    'export_templates',
                                    self.templates[tid]['dir'])
        try:
            filename = 'page.tpl'
            tpl_header = file(os.path.join(template_dir, filename), "r").read()
        except:
            gutils.error(_("Can't open %s!") % filename)
            return False

        tpl_header = self.fill_template(tpl_header, 'header', config['title'])
        try:
            tpl_header = self.fill_template(tpl_header, 'style', style)
        except:
            pass
        tmp = _('Document generated by Griffith v') + version.pversion + \
                ' - Copyright (C) ' + version.pyear + ' ' + version.pauthor + ' - ' + \
                _('Released Under the GNU/GPL License')
        tmp = gutils.html_encode(tmp)
        tmp = tmp.replace('@', ' at ')  # prevent spam
        tpl_header = self.fill_template(tpl_header, 'copyright', tmp)
        tmp = None

        tpl_header = self.fill_template(tpl_header, 'pages', self.pages)

        # count exported fields
        rowspan = 0
        for i in fields:
            if fields[i] == True:
                rowspan = rowspan + 1
        rowspan = str(rowspan)
        tpl_header = self.fill_template(tpl_header, 'rowspan', rowspan)

        # split template
        tpl_tail = gutils.after(tpl_header, '<!-- /ITEMS -->')
        tpl_item = gutils.trim(tpl_header, '<!-- ITEMS -->', '<!-- /ITEMS -->')
        tpl_header = gutils.before(tpl_header, '<!-- ITEMS -->')

        # fill header
        for j in self.names:
            if self.fields[self.names[j]] == True:
                tpl_header = self.fill_template(tpl_header, self.names[j], '',
                                                j)
            else:
                tpl_header = self.fill_template(tpl_header,
                                                self.names[j],
                                                remove=True)

        # check if line break needs conversion
        if tpl_header.upper().find('XHTML 1.0') > -1:
            linebreak_replacement = '<br />'
        else:
            linebreak_replacement = None

        item = 1  # item's position on page (1 - first, ...)
        i = 1
        page = 1  # page number
        for row in exported_movies:  # fill items {{{
            # check if new file has to be created
            if item == 1:
                filename = os.path.join(
                    config['export_dir'],
                    'page_%s.' % page + self.templates[tid]['ext'])
                try:
                    exported_file = file(filename, 'w')
                except:
                    gutils.error(_("Can't create %s!") % filename)
                    return False
                tmp2 = tpl_header + ''
                exported_file.write(self.fill_template(tmp2, 'page',
                                                       str(page)))
                tmp2 = None

            # ---------------------------------------------
            tmp = tpl_item + ''  # a copy (not a reference!)
            tmp = self.fill_template(tmp, 'id', str(item))
            tmp = self.fill_template(tmp, 'item', str(i))
            for j in self.names:
                if self.fields[self.names[j]] == True:
                    if self.names[j] == 'movies_image':
                        if row['movies_poster_md5']:
                            #image = row['movies_poster_md5'] + '.' + config['poster_format'].lower()
                            image = "%d.%s" % (row['movies_number'],
                                               config['poster_format'].lower())
                            tmp = self.fill_template(tmp, self.names[j], image,
                                                     j)
                        else:
                            tmp = self.fill_template(
                                tmp, self.names[j],
                                'nopic.' + config['poster_format'].lower(), j)
                    elif row[self.names[j]] is None:
                        tmp = self.fill_template(tmp, self.names[j], '', j)
                    elif row[self.names[j]] is True:
                        tmp = self.fill_template(tmp, self.names[j], _('Yes'),
                                                 j)
                    elif row[self.names[j]] is False:
                        tmp = self.fill_template(tmp, self.names[j], _('No'),
                                                 j)
                    else:
                        try:
                            data = str(row[self.names[j]]).encode('utf-8')
                            if linebreak_replacement is not None:
                                data = data.replace('\r\n',
                                                    linebreak_replacement)
                                data = data.replace('\n',
                                                    linebreak_replacement)
                            tmp = self.fill_template(tmp, self.names[j], data,
                                                     j)
                        except UnicodeDecodeError:
                            log.info(
                                "Unicode Decode Error occurred while decoding %s (movie number: %s)"
                                % (self.names[j], row['movies_number']))
                            data = str(row[self.names[j]])
                            if linebreak_replacement is not None:
                                data = data.replace('\r\n',
                                                    linebreak_replacement)
                                data = data.replace('\n',
                                                    linebreak_replacement)
                            tmp = self.fill_template(tmp, self.names[j], data,
                                                     j)
                        except Exception, ex:
                            log.info(
                                "Error occurred while decoding %s (movie number: %s)"
                                % (self.names[j], row['movies_number']))
                else:
                    tmp = self.fill_template(tmp, self.names[j], remove=True)
                tmp = gutils.convert_entities(tmp)
            exported_file.write(tmp)
            tmp = None
            # ---------------------------------------------

            # copy poster
            if fields['movies_image']:

                if row['movies_poster_md5']:
                    image_file_src = gutils.get_image_fname(
                        row['movies_poster_md5'], self.db)
                    image_file_dst = os.path.join(
                        posters_dir,
                        "%d.%s" % (row['movies_number'],
                                   config['poster_format'].lower()))
                    if not config['poster_convert']:  # copy file
                        try:
                            shutil.copy(image_file_src, image_file_dst)
                        except:
                            log.info("Can't copy %s", image_file_src)
                    else:  # convert posters
                        try:
                            im = Image.open(image_file_src,
                                            'r').convert(config['poster_mode'])
                            im.thumbnail((config['poster_width'],
                                          config['poster_height']),
                                         Image.ANTIALIAS)
                            im.save(image_file_dst, config['poster_format'])
                        except:
                            log.info("Can't convert %s", image_file_src)

            # close file if last item
            if ((page - 1) *
                    self.entries_per_page) + item == number_of_exported_movies:
                tmp2 = tpl_tail + ''
                exported_file.write(
                    self.fill_template(tmp2, 'navigation',
                                       self.make_navigation(self.pages, page)))
                exported_file.close()
                tmp2 = None

            # close file if last item in page
            elif item == self.entries_per_page:
                tmp2 = tpl_tail + ''
                exported_file.write(
                    self.fill_template(tmp2, 'navigation',
                                       self.make_navigation(self.pages, page)))
                exported_file.close()
                page = page + 1
                item = 1
                tmp2 = None
            else:
                item = item + 1
            i = i + 1
Пример #9
0
def cover_simple(self, number):
    size = self.widgets['print_cover']['cs_size'].get_active()
    print_number = self.widgets['print_cover']['cs_include_movie_number'].get_active()
    poster = self.widgets['print_cover']['cs_include_poster'].get_active()

    if self.config.get('font', '')!='':
        fontName = "custom_font"
        pdfmetrics.registerFont(TTFont(fontName,self.config.get('font', '')))
    else:
        fontName = "Helvetica"

    if size == 0:
        #standard
        cover_x=774
        cover_y=518
    elif size == 1:
        #slim
        cover_x=757;
        cover_y=518
    else:
        #double slim
        cover_x=757
        cover_y=518

    # A4 landscape definition
    pageWidth = 842
    pageHeight = 595

    # hardcoded to A4
    pos_x=(pageWidth-cover_x)/2;
    pos_y=(pageHeight-cover_y)/2;
    # make a pdf
    c = canvas.Canvas(os.path.join(self.griffith_dir, "cover.pdf"), (pageWidth, pageHeight))
    c.setFont(fontName,8)

    # copyright line
    c.drawString(20,20,_("Cover generated by Griffith v").encode('utf-8') + \
        version.pversion+" (C) 2004-2009 Vasco Nunes/Piotr Ozarowski - "+ \
        _("Released Under the GNU/GPL License").encode('utf-8'))

    # draw cover area
    c.rect(pos_x, pos_y, cover_x, cover_y)

    # get movie information from db
    movie = self.db.session.query(db.Movie).filter_by(number=number).first()
    if movie is not None:
        if print_number:
            c.setFont(fontName, 10)
            c.drawCentredString(pageWidth/2, 530, number)

        c.setFont(fontName, 16)
        c.rotate(90)
        c.drawString(60, (-pageWidth/2)-8, movie.o_title.encode('utf-8'))
        c.rotate(-90)
        if movie.poster_md5:
            filename = gutils.get_image_fname(movie.poster_md5, self.db)
            if filename:
                c.drawImage(filename, x=(pageWidth-30)/2, y=470, width=30, height=50)
        # print movie info
        c.setFont(fontName, 8)
        textObject = c.beginText()
        textObject.setTextOrigin(pageWidth-cover_x, 300)
        textObject.setFont(fontName, 8)
        textObject.textLine("%s: %s" % (_('Original Title'), movie.o_title))
        textObject.textLine("%s: %s" % (_('Title'), movie.title))
        textObject.textLine('')
        textObject.textLine("%s: %s" % (_('Director'), movie.director))
        textObject.textLine('')
        textObject.textLine("%s: %s %s" % (_('Running Time'), movie.runtime, _(' min')))
        textObject.textLine("%s: %s" % (_('Country'), movie.country))
        textObject.textLine("%s: %s" % (_('Genre'), movie.genre))
        textObject.textLine('')
        c.drawText(textObject)
        # draw bigger poster image
        if poster and movie.poster_md5 and filename:
            c.drawImage(filename, x=(pageWidth-(pageWidth-cover_x)-235), y=(pageHeight/2)-125, width=180, height=250)
    c.showPage()
    c.save()
    self.widgets['print_cover']['window_simple'].hide()
    cover_file = os.path.join(self.griffith_dir, 'cover.pdf')
    if self.windows:
        os.popen3("\"" + cover_file + "\"")
    elif self.mac:
        os.popen3("open -a Preview" + " " + cover_file)
    else:
        os.popen3(self.pdf_reader + " " + cover_file)
Пример #10
0
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)
Пример #11
0
def clone_movie(self):
    treeselection = self.widgets['treeview'].get_selection()
    (tmp_model, tmp_iter) = treeselection.get_selected()
    if tmp_iter is None:
        log.warn("cannot clone movie: no item selected")
        return False
    number = tmp_model.get_value(tmp_iter, 0)
    movie = self.db.session.query(db.Movie).filter_by(number=number).first()

    if movie is None:
        log.warn("cannot clone movie: Movie(%s) not found", number)
        return False

    next_number = gutils.find_next_available(self.db)
    
    # integer problem workaround
    if int(movie.seen)==1:
        seen = True
    else:
        seen = False
    new_movie = db.Movie()
    
    # TODO: WARNING: loan problems (don't copy volume/collection data until resolved)
    new_movie.cast           = movie.cast
    new_movie.classification = movie.classification
    new_movie.vcodec_id      = movie.vcodec_id
    new_movie.cameraman      = movie.cameraman
    new_movie.collection_id  = movie.collection_id
    new_movie.volume_id      = movie.volume_id
    new_movie.color          = movie.color
    new_movie.cond           = movie.cond
    new_movie.country        = movie.country
    new_movie.director       = movie.director
    new_movie.genre          = movie.genre
    new_movie.site           = movie.site
    new_movie.loaned         = movie.loaned
    new_movie.layers         = movie.layers
    new_movie.medium_id      = movie.medium_id
    new_movie.number         = next_number
    new_movie.media_num      = movie.media_num
    new_movie.notes          = movie.notes
    new_movie.o_title        = movie.o_title
    new_movie.plot           = movie.plot
    new_movie.poster_md5     = movie.poster_md5
    new_movie.ratio_id       = movie.ratio_id
    new_movie.rating         = movie.rating
    new_movie.region         = movie.region
    new_movie.runtime        = movie.runtime
    new_movie.screenplay     = movie.screenplay
    new_movie.seen           = seen
    new_movie.o_site         = movie.o_site
    new_movie.studio         = movie.studio
    new_movie.title          = movie.title
    new_movie.trailer        = movie.trailer
    new_movie.year           = movie.year
    
    new_movie.tags           = movie.tags
    new_movie.languages      = movie.languages
    new_movie.loans          = movie.loans
    
    # save
    self.db.session.add(new_movie)
    if not commit(self, self.db.session):
        return False

    image_path = gutils.get_image_fname(movie.poster_md5, self.db)
    if not image_path or not os.path.isfile(image_path):
        image_path = os.path.join(self.locations['images'], 'default.png')
    handler = self.Image.set_from_file(image_path)

    # change_filter calls populate_treeview which updates the status bar
    quick_filter.change_filter(self)
Пример #12
0
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)
Пример #13
0
    def run(self):
        """exports a simple movie list to a pdf file"""

        basedir = None
        if not self.config is None:
            basedir = self.config.get('export_dir', None, section='export-pdf')
        if basedir is None:
            filename = gutils.file_chooser(
                _("Export a PDF"),
                action=gtk.FILE_CHOOSER_ACTION_SAVE,
                buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE,
                         gtk.RESPONSE_OK),
                name="griffith_simple_list.pdf")
        else:
            filename = gutils.file_chooser(
                _("Export a PDF"),
                action=gtk.FILE_CHOOSER_ACTION_SAVE,
                buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE,
                         gtk.RESPONSE_OK),
                name="griffith_simple_list.pdf",
                folder=basedir)
        if filename is not False and filename[0]:
            if not self.config is None and filename[1]:
                self.config.set('export_dir',
                                filename[1],
                                section='export-pdf')
                self.config.save()
            overwrite = None
            pdffilename = filename[0].decode('utf-8')
            if os.path.isfile(pdffilename):
                if gutils.question(
                        _("File exists. Do you want to overwrite it?"),
                        self.parent_window):
                    overwrite = True
                else:
                    overwrite = False

            if overwrite == True or overwrite is None:
                try:
                    # filename encoding
                    defaultLang, defaultEnc = getdefaultlocale()
                    if defaultEnc is None:
                        defaultEnc = 'UTF-8'
                    c = SimpleDocTemplate(pdffilename.encode(defaultEnc), \
                        author = 'Griffith', \
                        title = _('List of films').encode('utf-8'), \
                        subject = _('List of films').encode('utf-8'), \
                        allowSplitting = False)
                    # data encoding
                    #if defaultEncoding == 'WinAnsiEncoding':
                    #    defaultEnc = 'cp1252'
                    #else:
                    defaultEnc = 'utf-8'

                    pdf_elements = self.config.get(
                        'pdf_elements', 'image,director,genre,cast').split(',')

                    self.create_styles()
                    style = self.styles["Normal"]
                    Story = [Spacer(1, 2 * inch)]

                    # select sort column - FIXME
                    sort_column_name = self.config.get('sortby',
                                                       'number',
                                                       section='mainlist')
                    sort_reverse = self.config.get('sortby_reverse',
                                                   False,
                                                   section='mainlist')
                    do_grouping = True
                    for i in sort_column_name.split(','):
                        if i != 'title' and i != 'o_title':
                            do_grouping = False

                    # build the query
                    query = self.get_query()
                    movies = query.execute().fetchall()

                    # define some custom stylesheetfont
                    total = len(movies)
                    p = Paragraph(
                        saxutils.escape((_("List of films")).encode('utf-8')),
                        self.styles["Heading1"])
                    Story.append(p)
                    Story.append(Paragraph(" ", style))
                    p = Paragraph(
                        saxutils.escape((_("Total Movies: %s") %
                                         str(total)).encode('utf-8')),
                        self.styles["Heading3"])
                    Story.append(p)
                    Story.append(Paragraph(" ", style))
                    # output movies
                    first_letter = ''
                    for movie in movies:
                        number = movie.movies_number
                        if movie.movies_o_title:
                            original_title = movie.movies_o_title.encode(
                                defaultEnc)
                        else:
                            original_title = ''
                        if movie.movies_title:
                            title = movie.movies_title.encode(defaultEnc)
                        else:
                            title = ''
                        grouping_title = movie.movies_title
                        if grouping_title is None:
                            grouping_title = u'None'
                        if movie.movies_director:
                            director = ' - ' + movie.movies_director.encode(
                                defaultEnc)
                        else:
                            director = ""
                        # group by first letter
                        # use movie.title/grouping_title for grouping because of encoding problems !!!
                        if do_grouping and grouping_title[0] != first_letter:
                            if grouping_title[0] in '0123456789':
                                # Group Numbers
                                if first_letter != '0-9':
                                    first_letter = '0-9'
                                    paragraph_text = saxutils.escape(
                                        first_letter)
                                    p = Paragraph(
                                        paragraph_text.decode(defaultEnc),
                                        self.styles['Heading2'])
                                    Story.append(p)
                            else:
                                first_letter = grouping_title[0]
                                paragraph_text = saxutils.escape(first_letter)
                                p = Paragraph(
                                    paragraph_text.decode(defaultEnc),
                                    self.styles['Heading2'])
                                Story.append(p)
                        # add movie title
                        paragraph_text = '<b>'+ saxutils.escape(title) + '</b>' + \
                            saxutils.escape(' (' + original_title + ') | ' + str(number))
                        p = Paragraph(paragraph_text.decode(defaultEnc),
                                      self.styles['Heading3'])
                        if 'image' in pdf_elements:
                            image_filename = None
                            if movie.movies_poster_md5:
                                image_filename = gutils.get_image_fname(
                                    movie.movies_poster_md5, self.db, 'm')
                            if image_filename:
                                p = ParagraphAndImage(p,
                                                      Image(image_filename,
                                                            width=30,
                                                            height=40),
                                                      side='left')
                                # wrap call needed because of a bug in reportlab flowables.py - ParagraphAndImage::split(self,availWidth, availHeight)
                                # AttributeError: ParagraphAndImage instance has no attribute 'wI'
                                p.wrap(30, 40)
                        Story.append(p)
                        if 'year' in pdf_elements and movie.movies_year:
                            paragraph_text = '<b>' + _(
                                'Year') + ': </b>' + saxutils.escape(
                                    str(movie.movies_year))
                            p = Paragraph(paragraph_text.decode(defaultEnc),
                                          self.styles['Normal'])
                            Story.append(p)
                        if 'runtime' in pdf_elements and movie.movies_runtime:
                            paragraph_text = '<b>' + _(
                                'Runtime') + ': </b>' + saxutils.escape(
                                    str(movie.movies_runtime))
                            p = Paragraph(paragraph_text.decode(defaultEnc),
                                          self.styles['Normal'])
                            Story.append(p)
                        if 'genre' in pdf_elements and movie.movies_genre:
                            paragraph_text = '<b>' + _(
                                'Genre') + ': </b>' + saxutils.escape(
                                    movie.movies_genre.encode(defaultEnc))
                            p = Paragraph(paragraph_text.decode(defaultEnc),
                                          self.styles['Normal'])
                            Story.append(p)
                        if 'director' in pdf_elements and movie.movies_director:
                            paragraph_text = '<i><b>' + _(
                                'Director') + ': </b>' + saxutils.escape(
                                    movie.movies_director.encode(
                                        defaultEnc)) + '</i>'
                            p = Paragraph(paragraph_text.decode(defaultEnc),
                                          self.styles['Normal'])
                            Story.append(p)
                        if 'cast' in pdf_elements and movie.movies_cast:
                            paragraph_text = '<i><b>' + _(
                                'Cast') + ': </b>' + saxutils.escape('; '.join(
                                    movie.movies_cast.encode(defaultEnc).split(
                                        "\n")[0:2])) + '</i>'
                            p = Paragraph(paragraph_text.decode(defaultEnc),
                                          self.styles['Normal'])
                            Story.append(p)
                        if 'plot' in pdf_elements and movie.movies_plot:
                            paragraph_text = '<i><b>' + _(
                                'Plot') + ': </b>' + saxutils.escape(
                                    movie.movies_plot.encode(
                                        defaultEnc)) + '</i>'
                            p = Paragraph(paragraph_text.decode(defaultEnc),
                                          self.styles['Normal'])
                            Story.append(p)
                        if 'notes' in pdf_elements and movie.movies_notes:
                            paragraph_text = '<i><b>' + _(
                                'Notes') + ': </b>' + saxutils.escape(
                                    movie.movies_notes.encode(
                                        defaultEnc)) + '</i>'
                            p = Paragraph(paragraph_text.decode(defaultEnc),
                                          self.styles['Normal'])
                            Story.append(p)
                        resolution = self._get_resolution(movie)
                        if resolution:
                            paragraph_text = '<i><b>' + _(
                                'Resolution') + ': </b>' + saxutils.escape(
                                    resolution.encode(defaultEnc)) + '</i>'
                            p = Paragraph(paragraph_text.decode(defaultEnc),
                                          self.styles['Normal'])
                            Story.append(p)
                        if movie.volumes_name:
                            paragraph_text = '<i><b>' + _(
                                'Volume') + ': </b>' + saxutils.escape(
                                    movie.volumes_name.encode(
                                        defaultEnc)) + '</i>'
                            p = Paragraph(paragraph_text.decode(defaultEnc),
                                          self.styles['Normal'])
                            Story.append(p)
                        if movie.collections_name:
                            paragraph_text = '<i><b>' + _(
                                'Collection') + ': </b>' + saxutils.escape(
                                    movie.collections_name.encode(
                                        defaultEnc)) + '</i>'
                            p = Paragraph(paragraph_text.decode(defaultEnc),
                                          self.styles['Normal'])
                            Story.append(p)
                    c.build(Story,
                            onFirstPage=self.page_template,
                            onLaterPages=self.page_template)
                    gutils.info(_('PDF has been created.'), self.parent_window)
                except Exception, e:
                    log.exception('')
                    gutils.error(str(e))
    def run(self):
        """exports a simple movie list to a pdf file"""

        basedir = None
        if not self.config is None:
            basedir = self.config.get("export_dir", None, section="export-pdf")
        if basedir is None:
            filename = gutils.file_chooser(
                _("Export a PDF"),
                action=gtk.FILE_CHOOSER_ACTION_SAVE,
                buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK),
                name="griffith_simple_list.pdf",
            )
        else:
            filename = gutils.file_chooser(
                _("Export a PDF"),
                action=gtk.FILE_CHOOSER_ACTION_SAVE,
                buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK),
                name="griffith_simple_list.pdf",
                folder=basedir,
            )
        if filename is not False and filename[0]:
            if not self.config is None and filename[1]:
                self.config.set("export_dir", filename[1], section="export-pdf")
                self.config.save()
            overwrite = None
            pdffilename = filename[0].decode("utf-8")
            if os.path.isfile(pdffilename):
                if gutils.question(_("File exists. Do you want to overwrite it?"), self.parent_window):
                    overwrite = True
                else:
                    overwrite = False

            if overwrite == True or overwrite is None:
                try:
                    # filename encoding
                    defaultLang, defaultEnc = getdefaultlocale()
                    if defaultEnc is None:
                        defaultEnc = "UTF-8"
                    c = SimpleDocTemplate(
                        pdffilename.encode(defaultEnc),
                        author="Griffith",
                        title=_("List of films").encode("utf-8"),
                        subject=_("List of films").encode("utf-8"),
                        allowSplitting=False,
                    )
                    # data encoding
                    # if defaultEncoding == 'WinAnsiEncoding':
                    #    defaultEnc = 'cp1252'
                    # else:
                    defaultEnc = "utf-8"

                    pdf_elements = self.config.get("pdf_elements", "image,director,genre,cast").split(",")

                    self.create_styles()
                    style = self.styles["Normal"]
                    Story = [Spacer(1, 2 * inch)]

                    # select sort column - FIXME
                    sort_column_name = self.config.get("sortby", "number", section="mainlist")
                    sort_reverse = self.config.get("sortby_reverse", False, section="mainlist")
                    do_grouping = True
                    for i in sort_column_name.split(","):
                        if i != "title" and i != "o_title":
                            do_grouping = False

                    # build the query
                    query = self.get_query()
                    movies = query.execute().fetchall()

                    # define some custom stylesheetfont
                    total = len(movies)
                    p = Paragraph(saxutils.escape((_("List of films")).encode("utf-8")), self.styles["Heading1"])
                    Story.append(p)
                    Story.append(Paragraph(" ", style))
                    p = Paragraph(
                        saxutils.escape((_("Total Movies: %s") % str(total)).encode("utf-8")), self.styles["Heading3"]
                    )
                    Story.append(p)
                    Story.append(Paragraph(" ", style))
                    # output movies
                    first_letter = ""
                    for movie in movies:
                        number = movie.movies_number
                        if movie.movies_o_title:
                            original_title = movie.movies_o_title.encode(defaultEnc)
                        else:
                            original_title = ""
                        if movie.movies_title:
                            title = movie.movies_title.encode(defaultEnc)
                        else:
                            title = ""
                        grouping_title = movie.movies_title
                        if grouping_title is None:
                            grouping_title = u"None"
                        if movie.movies_director:
                            director = " - " + movie.movies_director.encode(defaultEnc)
                        else:
                            director = ""
                        # group by first letter
                        # use movie.title/grouping_title for grouping because of encoding problems !!!
                        if do_grouping and grouping_title[0] != first_letter:
                            if grouping_title[0] in "0123456789":
                                # Group Numbers
                                if first_letter != "0-9":
                                    first_letter = "0-9"
                                    paragraph_text = saxutils.escape(first_letter)
                                    p = Paragraph(paragraph_text.decode(defaultEnc), self.styles["Heading2"])
                                    Story.append(p)
                            else:
                                first_letter = grouping_title[0]
                                paragraph_text = saxutils.escape(first_letter)
                                p = Paragraph(paragraph_text.decode(defaultEnc), self.styles["Heading2"])
                                Story.append(p)
                        # add movie title
                        paragraph_text = (
                            "<b>"
                            + saxutils.escape(title)
                            + "</b>"
                            + saxutils.escape(" (" + original_title + ") | " + str(number))
                        )
                        p = Paragraph(paragraph_text.decode(defaultEnc), self.styles["Heading3"])
                        if "image" in pdf_elements:
                            image_filename = None
                            if movie.movies_poster_md5:
                                image_filename = gutils.get_image_fname(movie.movies_poster_md5, self.db, "m")
                            if image_filename:
                                p = ParagraphAndImage(p, Image(image_filename, width=30, height=40), side="left")
                                # wrap call needed because of a bug in reportlab flowables.py - ParagraphAndImage::split(self,availWidth, availHeight)
                                # AttributeError: ParagraphAndImage instance has no attribute 'wI'
                                p.wrap(30, 40)
                        Story.append(p)
                        if "year" in pdf_elements and movie.movies_year:
                            paragraph_text = "<b>" + _("Year") + ": </b>" + saxutils.escape(str(movie.movies_year))
                            p = Paragraph(paragraph_text.decode(defaultEnc), self.styles["Normal"])
                            Story.append(p)
                        if "runtime" in pdf_elements and movie.movies_runtime:
                            paragraph_text = (
                                "<b>" + _("Runtime") + ": </b>" + saxutils.escape(str(movie.movies_runtime))
                            )
                            p = Paragraph(paragraph_text.decode(defaultEnc), self.styles["Normal"])
                            Story.append(p)
                        if "genre" in pdf_elements and movie.movies_genre:
                            paragraph_text = (
                                "<b>" + _("Genre") + ": </b>" + saxutils.escape(movie.movies_genre.encode(defaultEnc))
                            )
                            p = Paragraph(paragraph_text.decode(defaultEnc), self.styles["Normal"])
                            Story.append(p)
                        if "director" in pdf_elements and movie.movies_director:
                            paragraph_text = (
                                "<i><b>"
                                + _("Director")
                                + ": </b>"
                                + saxutils.escape(movie.movies_director.encode(defaultEnc))
                                + "</i>"
                            )
                            p = Paragraph(paragraph_text.decode(defaultEnc), self.styles["Normal"])
                            Story.append(p)
                        if "cast" in pdf_elements and movie.movies_cast:
                            paragraph_text = (
                                "<i><b>"
                                + _("Cast")
                                + ": </b>"
                                + saxutils.escape("; ".join(movie.movies_cast.encode(defaultEnc).split("\n")[0:2]))
                                + "</i>"
                            )
                            p = Paragraph(paragraph_text.decode(defaultEnc), self.styles["Normal"])
                            Story.append(p)
                        if "plot" in pdf_elements and movie.movies_plot:
                            paragraph_text = (
                                "<i><b>"
                                + _("Plot")
                                + ": </b>"
                                + saxutils.escape(movie.movies_plot.encode(defaultEnc))
                                + "</i>"
                            )
                            p = Paragraph(paragraph_text.decode(defaultEnc), self.styles["Normal"])
                            Story.append(p)
                        if "notes" in pdf_elements and movie.movies_notes:
                            paragraph_text = (
                                "<i><b>"
                                + _("Notes")
                                + ": </b>"
                                + saxutils.escape(movie.movies_notes.encode(defaultEnc))
                                + "</i>"
                            )
                            p = Paragraph(paragraph_text.decode(defaultEnc), self.styles["Normal"])
                            Story.append(p)
                        resolution = self._get_resolution(movie)
                        if resolution:
                            paragraph_text = (
                                "<i><b>"
                                + _("Resolution")
                                + ": </b>"
                                + saxutils.escape(resolution.encode(defaultEnc))
                                + "</i>"
                            )
                            p = Paragraph(paragraph_text.decode(defaultEnc), self.styles["Normal"])
                            Story.append(p)
                        if movie.volumes_name:
                            paragraph_text = (
                                "<i><b>"
                                + _("Volume")
                                + ": </b>"
                                + saxutils.escape(movie.volumes_name.encode(defaultEnc))
                                + "</i>"
                            )
                            p = Paragraph(paragraph_text.decode(defaultEnc), self.styles["Normal"])
                            Story.append(p)
                        if movie.collections_name:
                            paragraph_text = (
                                "<i><b>"
                                + _("Collection")
                                + ": </b>"
                                + saxutils.escape(movie.collections_name.encode(defaultEnc))
                                + "</i>"
                            )
                            p = Paragraph(paragraph_text.decode(defaultEnc), self.styles["Normal"])
                            Story.append(p)
                    c.build(Story, onFirstPage=self.page_template, onLaterPages=self.page_template)
                    gutils.info(_("PDF has been created."), self.parent_window)
                except Exception, e:
                    log.exception("")
                    gutils.error(str(e))
Пример #15
0
def clone_movie(self):
    session = self.db.Session()

    if self.selected_iter[0] is None:
        log.warn("cannot clone movie: no item selected")
        return False
    movie = session.query(db.Movie).filter_by(number=self.selected[0]).first()

    if movie is None:
        log.warn("cannot clone movie: Movie(%s) not found", number)
        return False

    next_number = gutils.find_next_available(self.db)

    # integer problem workaround
    if int(movie.seen) == 1:
        seen = True
    else:
        seen = False
    new_movie = db.Movie()

    # TODO: WARNING: loan problems (don't copy volume/collection data until resolved)
    new_movie.cast = movie.cast
    new_movie.classification = movie.classification
    new_movie.vcodec_id = movie.vcodec_id
    new_movie.barcode = movie.barcode
    new_movie.cameraman = movie.cameraman
    new_movie.collection_id = movie.collection_id
    new_movie.volume_id = movie.volume_id
    new_movie.color = movie.color
    new_movie.cond = movie.cond
    new_movie.country = movie.country
    new_movie.director = movie.director
    new_movie.genre = movie.genre
    new_movie.site = movie.site
    new_movie.loaned = movie.loaned
    new_movie.layers = movie.layers
    new_movie.medium_id = movie.medium_id
    new_movie.number = next_number
    new_movie.media_num = movie.media_num
    new_movie.notes = movie.notes
    new_movie.o_title = movie.o_title
    new_movie.plot = movie.plot
    new_movie.poster_md5 = movie.poster_md5
    new_movie.ratio_id = movie.ratio_id
    new_movie.rating = movie.rating
    new_movie.region = movie.region
    new_movie.runtime = movie.runtime
    new_movie.resolution = movie.resolution
    new_movie.screenplay = movie.screenplay
    new_movie.seen = seen
    new_movie.o_site = movie.o_site
    new_movie.studio = movie.studio
    new_movie.title = movie.title
    new_movie.trailer = movie.trailer
    new_movie.year = movie.year

    new_movie.tags = movie.tags
    new_movie.languages = movie.languages
    new_movie.loans = movie.loans

    # save
    session.add(new_movie)
    if not commit(session):
        return False

    if movie.poster_md5:
        image_path = gutils.get_image_fname(movie.poster_md5, self.db)
        if not image_path or not os.path.isfile(image_path):
            image_path = gutils.get_defaultimage_fname(self)
        handler = self.Image.set_from_file(image_path)

    # change_filter calls populate_treeview which updates the status bar
    quick_filter.change_filter(self)
Пример #16
0
def set_details(self, item=None):  #{{{
    if item is None:
        item = {}
    if 'movie_id' in item and item['movie_id']:
        self._am_movie_id = item['movie_id']
    else:
        self._am_movie_id = None
    w = self.widgets['add']

    cast_buffer = w['cast'].get_buffer()
    notes_buffer = w['notes'].get_buffer()
    plot_buffer = w['plot'].get_buffer()

    if 'o_title' in item and item['o_title']:
        w['o_title'].set_text(item['o_title'])
    else:
        w['o_title'].set_text('')
    if 'title' in item and item['title']:
        w['title'].set_text(item['title'])
    else:
        w['title'].set_text('')
    if 'number' in item and item['number']:
        w['number'].set_value(int(item['number']))
    else:
        w['number'].set_value(int(gutils.find_next_available(self.db)))
    if 'title' in item and item['title']:
        w['title'].set_text(item['title'])
    if 'year' in item and item['year']:
        w['year'].set_value(gutils.digits_only(item['year'], 2100))
    else:
        w['year'].set_value(0)
    if 'resolution' in item and item['resolution']:
        if self.config.get('use_resolution_alias', True):
            w['resolution'].get_child().set_text(item['resolution'])
        elif 'height' in item and item['height'] and 'width' in item and item[
                'width']:
            w['resolution'].get_child().set_text(
                "%dx%d" % (item['width'], item['height']))
        else:  # failback to 'resolution'
            w['resolution'].get_child().set_text(item['resolution'])
    else:
        w['resolution'].get_child().set_text('')
    if 'runtime' in item and item['runtime']:
        w['runtime'].set_value(gutils.digits_only(item['runtime']))
    else:
        w['runtime'].set_value(0)
    if 'barcode' in item and item['barcode']:
        w['barcode'].set_text(item['barcode'])
    else:
        w['barcode'].set_text('')
    if 'cameraman' in item and item['cameraman']:
        w['cameraman'].set_text(item['cameraman'])
    else:
        w['cameraman'].set_text('')
    if 'screenplay' in item and item['screenplay']:
        w['screenplay'].set_text(item['screenplay'])
    else:
        w['screenplay'].set_text('')
    if 'country' in item and item['country']:
        w['country'].set_text(item['country'])
    else:
        w['country'].set_text('')
    if 'classification' in item and item['classification']:
        w['classification'].set_text(item['classification'])
    else:
        w['classification'].set_text('')
    if 'studio' in item and item['studio']:
        w['studio'].set_text(item['studio'])
    else:
        w['studio'].set_text('')
    if 'o_site' in item and item['o_site']:
        w['o_site'].set_text(item['o_site'])
    else:
        w['o_site'].set_text('')
    if 'director' in item and item['director']:
        w['director'].set_text(item['director'])
    else:
        w['director'].set_text('')
    if 'site' in item and item['site']:
        w['site'].set_text(item['site'])
    else:
        w['site'].set_text('')
    if 'trailer' in item and item['trailer']:
        w['trailer'].set_text(item['trailer'])
    else:
        w['trailer'].set_text('')
    if 'genre' in item and item['genre']:
        w['genre'].set_text(item['genre'])
    else:
        w['genre'].set_text('')
    if 'color' in item and item['color']:
        w['color'].set_active(gutils.digits_only(item['color'], 3))
    else:
        w['color'].set_active(
            gutils.digits_only(self.config.get('color', 0, section='defaults'),
                               3))
    if 'layers' in item and item['layers']:
        w['layers'].set_active(gutils.digits_only(item['layers'], 4))
    else:
        w['layers'].set_active(
            gutils.digits_only(
                self.config.get('layers', 0, section='defaults'), 4))
    if 'region' in item and item['region'] >= 0:
        w['region'].set_active(gutils.digits_only(item['region'], 11))
    else:
        w['region'].set_active(
            gutils.digits_only(
                self.config.get('region', 0, section='defaults'), 11))
    if 'cond' in item and item['cond'] >= 0:
        w['condition'].set_active(gutils.digits_only(item['cond'], 5))
    else:
        w['condition'].set_active(
            gutils.digits_only(
                self.config.get('condition', 0, section='defaults'), 5))
    if 'media_num' in item and item['media_num']:
        w['discs'].set_value(gutils.digits_only(item['media_num']))
    else:
        w['discs'].set_value(1)
    if 'rating' in item and item['rating']:
        w['rating_slider'].set_value(gutils.digits_only(item['rating'], 10))
    else:
        w['rating_slider'].set_value(0)
    if 'seen' in item:
        if item['seen'] is True:
            w['seen'].set_active(True)
        else:
            w['seen'].set_active(False)
    else:
        w['seen'].set_active(
            bool(self.config.get('seen', True, section='defaults')))
    if 'cast' in item and item['cast']:
        cast_buffer.set_text(item['cast'])
    else:
        cast_buffer.set_text('')
    if 'notes' in item and item['notes']:
        notes_buffer.set_text(item['notes'])
    else:
        notes_buffer.set_text('')
    if 'plot' in item and item['plot']:
        plot_buffer.set_text(item['plot'])
    else:
        plot_buffer.set_text('')
    pos = 0
    if 'medium_id' in item and item['medium_id']:
        pos = gutils.findKey(item['medium_id'], self.media_ids)
    else:
        pos = gutils.findKey(
            int(self.config.get('media', 0, section='defaults')),
            self.media_ids)
    if pos is not None:
        w['media'].set_active(int(pos))
    else:
        w['media'].set_active(0)
    pos = 0
    if 'vcodec_id' in item and item['vcodec_id']:
        pos = gutils.findKey(item['vcodec_id'], self.vcodecs_ids)
    else:
        pos = gutils.findKey(
            int(self.config.get('vcodec', 0, section='defaults')),
            self.vcodecs_ids)
    if pos is not None:
        w['vcodec'].set_active(int(pos))
    else:
        w['vcodec'].set_active(0)
    pos = 0
    if 'volume_id' in item and item['volume_id']:
        pos = gutils.findKey(item['volume_id'], self.volume_combo_ids)
    if pos is not None:
        w['volume'].set_active(int(pos))
    else:
        w['volume'].set_active(0)
    pos = 0
    if 'collection_id' in item and item['collection_id']:
        pos = gutils.findKey(item['collection_id'], self.collection_combo_ids)
    if pos is not None:
        w['collection'].set_active(int(pos))
    else:
        w['collection'].set_active(0)
    # tags
    for tag in self.am_tags:
        self.am_tags[tag].set_active(False)
    if 'tags' in item:
        for tag in item['tags']:
            i = gutils.findKey(tag.tag_id, self.tags_ids)
            self.am_tags[i].set_active(True)
    # languages
    w['lang_treeview'].get_model().clear()
    if 'languages' in item and len(item['languages']) > 0:
        for i in item['languages']:
            self.create_language_row(i)
    # poster
    w['aremove_poster'].set_sensitive(True)
    if 'poster_md5' in item and item['poster_md5']:
        image_path = gutils.get_image_fname(item["poster_md5"], self.db, 'm')
        if not image_path:
            image_path = ''  # isfile doesn't like bool
            w['aremove_poster'].set_sensitive(False)
        w['image'].set_text(item['poster_md5'])
    elif 'image' in item and item['image']:
        if len(item['image']) == 32:  # md5
            image_path = gutils.get_image_fname(item["image"], self.db, 'm')
            if not image_path:
                image_path = ''  # isfile doesn't like bool
                w['aremove_poster'].set_sensitive(False)
            else:
                w['image'].set_text(item['image'])
        else:
            image_path = os.path.join(self.locations['posters'],
                                      "m_%s.jpg" % item['image'])
            log.warn("TODO: image=%s", item['image'])
    else:
        w['image'].set_text('')
        image_path = gutils.get_defaultimage_fname(self)
        w['aremove_poster'].set_sensitive(False)
    if not os.path.isfile(image_path):
        image_path = gutils.get_defaultimage_fname(self)
        w['aremove_poster'].set_sensitive(False)
    w['picture'].set_from_file(image_path)

    w['notebook'].set_current_page(0)
    w['o_title'].grab_focus()
    def run(self):
        """exports a simple movie list to a pdf file"""

        basedir = None
        if not self.config is None:
            basedir = self.config.get('export_dir', None, section='export-pdf')
        if basedir is None:
            filename = gutils.file_chooser(_("Export a PDF"), action=gtk.FILE_CHOOSER_ACTION_SAVE, buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_SAVE,gtk.RESPONSE_OK),name="griffith_simple_list.pdf")
        else:
            filename = gutils.file_chooser(_("Export a PDF"), action=gtk.FILE_CHOOSER_ACTION_SAVE, buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_SAVE,gtk.RESPONSE_OK),name="griffith_simple_list.pdf",folder=basedir)
        if filename is not False and filename[0]:
            if not self.config is None and filename[1]:
                self.config.set('export_dir', filename[1], section='export-pdf')
                self.config.save()
            overwrite = None
            pdffilename = filename[0].decode('utf-8')
            if os.path.isfile(pdffilename):
                if gutils.question(_("File exists. Do you want to overwrite it?"), self.parent_window):
                    overwrite = True
                else:
                    overwrite = False

            if overwrite == True or overwrite is None:
                # filename encoding
                defaultLang, defaultEnc = getdefaultlocale()
                if defaultEnc is None:
                    defaultEnc = 'UTF-8'
                c = SimpleDocTemplate(pdffilename.encode(defaultEnc), \
                    author = 'Griffith', \
                    title = _('List of films').encode('utf-8'), \
                    subject = _('List of films').encode('utf-8'))
                # data encoding
                #if defaultEncoding == 'WinAnsiEncoding':
                #    defaultEnc = 'cp1252'
                #else:
                defaultEnc = 'utf-8'

                pdf_elements = self.config.get('pdf_elements', 'image,director,genre,cast').split(',')

                self.create_styles()
                style = self.styles["Normal"]
                Story = [Spacer(1,2*inch)]

                # select sort column - FIXME
                sort_column_name = self.config.get('sortby', 'number', section='mainlist')
                sort_reverse = self.config.get('sortby_reverse', False, section='mainlist')
                do_grouping = True
                for i in sort_column_name.split(','):
                    if i != 'title' and i != 'o_title':
                        do_grouping = False

                # build the query
                query = self.get_query()
                movies = query.execute().fetchall()

                # define some custom stylesheetfont
                total = len(movies)
                p = Paragraph(saxutils.escape((_("List of films")).encode('utf-8')), self.styles["Heading1"] )
                Story.append(p)
                Story.append(Paragraph(" ",style))
                p = Paragraph(saxutils.escape((_("Total Movies: %s") % str(total)).encode('utf-8')), self.styles["Heading3"])
                Story.append(p)
                Story.append(Paragraph(" ",style))
                # output movies
                first_letter = ''
                for movie in movies:
                    number = movie.number
                    if movie.o_title:
                        original_title = movie.o_title.encode(defaultEnc)
                    else:
                        original_title = ''
                    if movie.title:
                        title = movie.title.encode(defaultEnc)
                    else:
                        title = ''
                    grouping_title = movie.title
                    if grouping_title is None:
                        grouping_title = u'None'
                    if movie.director:
                        director = ' - ' + movie.director.encode(defaultEnc)
                    else:
                        director = ""
                    # group by first letter
                    # use movie.title/grouping_title for grouping because of encoding problems !!!
                    if do_grouping and grouping_title[0] != first_letter:
                        if grouping_title[0] in '0123456789':
                            # Group Numbers
                            if first_letter != '0-9':
                                first_letter = '0-9'
                                paragraph_text = saxutils.escape(first_letter)
                                p = Paragraph(paragraph_text.decode(defaultEnc), self.styles['Heading2'])
                                Story.append(p)
                        else:
                            first_letter = grouping_title[0]
                            paragraph_text = saxutils.escape(first_letter)
                            p = Paragraph(paragraph_text.decode(defaultEnc), self.styles['Heading2'])
                            Story.append(p)
                    # add movie title
                    paragraph_text = '<b>'+ saxutils.escape(title) + '</b>' + \
                        saxutils.escape(' (' + original_title + ') | ' + str(number))
                    p = Paragraph(paragraph_text.decode(defaultEnc), self.styles['Heading3'])
                    if 'image' in pdf_elements:
                        image_filename = None
                        if movie.poster_md5:
                            image_filename = gutils.get_image_fname(movie.poster_md5, self.db, 'm')
                        if image_filename:
                            p = ParagraphAndImage(p, Image(image_filename, width = 30, height = 40), side = 'left')
                            # wrap call needed because of a bug in reportlab flowables.py - ParagraphAndImage::split(self,availWidth, availHeight)
                            # AttributeError: ParagraphAndImage instance has no attribute 'wI'
                            p.wrap(30, 40)
                    Story.append(p)
                    if 'year' in pdf_elements and movie.year:
                        paragraph_text = '<b>' + _('Year') + ': </b>' + saxutils.escape(str(movie.year))
                        p = Paragraph(paragraph_text.decode(defaultEnc), self.styles['Normal'])
                        Story.append(p)
                    if 'runtime' in pdf_elements and movie.runtime:
                        paragraph_text = '<b>' + _('Runtime') + ': </b>' + saxutils.escape(str(movie.runtime))
                        p = Paragraph(paragraph_text.decode(defaultEnc), self.styles['Normal'])
                        Story.append(p)
                    if 'genre' in pdf_elements and movie.genre:
                        paragraph_text = '<b>' + _('Genre') + ': </b>' + saxutils.escape(movie.genre.encode(defaultEnc))
                        p = Paragraph(paragraph_text.decode(defaultEnc), self.styles['Normal'])
                        Story.append(p)
                    if 'director' in pdf_elements and movie.director:
                        paragraph_text = '<i><b>' + _('Director') + ': </b>' + saxutils.escape(movie.director.encode(defaultEnc)) + '</i>'
                        p = Paragraph(paragraph_text.decode(defaultEnc), self.styles['Normal'])
                        Story.append(p)
                    if 'cast' in pdf_elements and movie.cast:
                        paragraph_text = '<i><b>' + _('Cast') + ': </b>' + saxutils.escape('; '.join(movie.cast.encode(defaultEnc).split("\n")[0:2])) + '</i>'
                        p = Paragraph(paragraph_text.decode(defaultEnc), self.styles['Normal'])
                        Story.append(p)
                    if 'plot' in pdf_elements and movie.plot:
                        paragraph_text = '<i><b>' + _('Plot') + ': </b>' + saxutils.escape(movie.plot.encode(defaultEnc)) + '</i>'
                        p = Paragraph(paragraph_text.decode(defaultEnc), self.styles['Normal'])
                        Story.append(p)
                    if 'notes' in pdf_elements and movie.notes:
                        paragraph_text = '<i><b>' + _('Notes') + ': </b>' + saxutils.escape(movie.notes.encode(defaultEnc)) + '</i>'
                        p = Paragraph(paragraph_text.decode(defaultEnc), self.styles['Normal'])
                        Story.append(p)
                c.build(Story, onFirstPage=self.page_template, onLaterPages=self.page_template)
                gutils.info(_('PDF has been created.'), self.parent_window)
Пример #18
0
                    import delete
                    old_poster = self.db.session.query(db.Poster).filter_by(md5sum=old_poster_md5).first()
                    if old_poster and len(old_poster.movies) == 1: # other movies are not using the same poster
                        self.db.session.delete(old_poster)
                        delete.delete_poster_from_cache(self, old_poster_md5)

    update_movie_instance(movie, details, self.db.session)
    
    self.db.session.add(movie)
    if commit(self, self.db.session):
        treeselection = self.widgets['treeview'].get_selection()
        (tmp_model, tmp_iter) = treeselection.get_selected()
        
        if new_poster_md5 and new_poster_md5 != old_poster_md5:
            # update thumbnail in main list
            new_image_path = gutils.get_image_fname(new_poster_md5, self.db)
            handler = self.Image.set_from_file(new_image_path)
            pixbuf = self.Image.get_pixbuf()
            tmp_model.set_value(tmp_iter,1, pixbuf.scale_simple(30,40,3))
        # update main treelist
        tmp_model.set_value(tmp_iter,0,'%004d' % int(movie.number))
        tmp_model.set_value(tmp_iter,2, movie.o_title)
        tmp_model.set_value(tmp_iter,3, movie.title)
        tmp_model.set_value(tmp_iter,4, movie.director)
        tmp_model.set_value(tmp_iter,5, movie.genre)
        tmp_model.set_value(tmp_iter,6, movie.seen)
        if movie.year is None:
            tmp_model.set_value(tmp_iter,7, '')
        else:
            tmp_model.set_value(tmp_iter,7, movie.year)
        if movie.runtime is None:
Пример #19
0
def set_details(self, item=None):  # {{{
    if item is None:
        item = {}
    if 'movie_id' in item and item['movie_id']:
        self._movie_id = item['movie_id']
    else:
        self._movie_id = None
    w = self.widgets['movie']

    if 'number' in item and item['number']:
        w['number'].set_text(str(int(item['number'])))
    else:
        w['number'].set_text('')
    if 'title' in item and item['title']:
        w['title'].set_markup("<b><span size='large'>%s</span></b>" %
                              gutils.html_encode(item['title']))
    else:
        w['title'].set_text('')
    if 'o_title' in item and item['o_title']:
        w['o_title'].set_markup("<span size='medium'><i>%s</i></span>" %
                                gutils.html_encode(item['o_title']))
    else:
        w['o_title'].set_text('')
    if 'director' in item and item['director']:
        w['director'].set_markup("<i>%s</i>" %
                                 gutils.html_encode(item['director']))
    else:
        w['director'].set_text('')
    if 'plot' in item and item['plot']:
        w['plot'].set_text(str(item['plot']))
    else:
        w['plot'].set_text('')
    if 'year' in item and item['year']:
        w['year'].set_text(str(item['year']))
    else:
        w['year'].set_text('')
    if 'resolution' in item and item['resolution']:
        if self.config.get('use_resolution_alias', True):
            w['resolution'].set_text(item['resolution'])
        elif 'height' in item and item['height'] and 'width' in item and item[
                'width']:
            w['resolution'].set_text("%dx%d" % (item['width'], item['height']))
        else:  # fallback to 'resolution'
            w['resolution'].set_text(item['resolution'])
    else:
        w['resolution'].set_text('')
        pass
    if 'runtime' in item and item['runtime']:
        w['runtime'].set_text(str(int(item['runtime'])))
    else:
        w['runtime'].set_text('x')
    if 'cameraman' in item and item['cameraman']:
        w['cameraman'].set_markup("<i>%s</i>" %
                                  gutils.html_encode(item['cameraman']))
    else:
        w['cameraman'].set_text('')
    if 'screenplay' in item and item['screenplay']:
        w['screenplay'].set_markup("<i>%s</i>" %
                                   gutils.html_encode(item['screenplay']))
    else:
        w['screenplay'].set_text('')
    if 'cast' in item and item['cast']:
        w['cast'].set_text(str(item['cast']))
    else:
        w['cast'].set_text('')
    if 'country' in item and item['country']:
        w['country'].set_markup("<i>%s</i>" %
                                gutils.html_encode(item['country']))
    else:
        w['country'].set_text('')
    if 'genre' in item and item['genre']:
        w['genre'].set_markup("<i>%s</i>" % gutils.html_encode(item['genre']))
    else:
        w['genre'].set_text('')
    if 'cond' in item and item['cond']:
        if str(item['cond']) in [str(i) for i in range(len(self._conditions))]:
            w['condition'].set_markup("<i>%s</i>" %
                                      self._conditions[item['cond']])
        else:
            w['condition'].set_text('')
            log.info(
                "Wrong value in 'condition' field (movie_id=%s, cond=%s)" %
                (item['movie_id'], item['cond']))
    else:
        w['condition'].set_text('')
    if 'region' in item and item['region']:
        if item['region'] < len(self._regions):
            w['region'].set_markup(
                "<i>%s</i>" %
                gutils.html_encode(self._regions[item['region']]))
            if int(item['region']) < 12:
                self.widgets['tooltips'].set_tip(
                    w['region'], self._regions[int(item['region'])])
        else:
            log.info("Wrong value in 'region' field (movie_id=%s, region=%s)" %
                     (item['movie_id'], item['region']))
            w['region'].set_text('')
            self.widgets['tooltips'].set_tip(w['region'],
                                             self._regions[0])  # N/A
    else:
        w['region'].set_text('')
        self.widgets['tooltips'].set_tip(w['region'], self._regions[0])  # N/A
    if 'layers' in item and item['layers']:
        if str(item['layers']) in [str(i) for i in range(len(self._layers))]:
            w['layers'].set_markup("<i>%s</i>" % self._layers[item['layers']])
        else:
            log.info("Wrong value in 'layers' field (movie_id=%s, layers=%s)" %
                     (item['movie_id'], item['layers']))
            w['layers'].set_text('')
    else:
        w['layers'].set_text('')
    if 'color' in item and item['color']:
        if str(item['color']) in [str(i) for i in range(len(self._colors))]:
            w['color'].set_markup("<i>%s</i>" % self._colors[item['color']])
        else:
            log.info("Wrong value in 'color' field (movie_id=%s, color=%s)" %
                     (item['movie_id'], item['color']))
            w['color'].set_markup('')
    else:
        w['color'].set_markup('')
    if 'classification' in item and item['classification']:
        w['classification'].set_markup(
            "<i>%s</i>" % gutils.html_encode(item['classification']))
    else:
        w['classification'].set_text('')
    if 'studio' in item and item['studio']:
        w['studio'].set_markup("<i>%s</i>" %
                               gutils.html_encode(item['studio']))
    else:
        w['studio'].set_text('')
    if 'o_site' in item and item['o_site']:
        self._o_site_url = str(item['o_site'])
        w['go_o_site_button'].set_sensitive(True)
    else:
        self._o_site_url = None
        w['go_o_site_button'].set_sensitive(False)
    if 'site' in item and item['site']:
        self._site_url = str(item['site'])
        w['go_site_button'].set_sensitive(True)
    else:
        self._site_url = None
        w['go_site_button'].set_sensitive(False)
    if 'trailer' in item and item['trailer']:
        self._trailer_url = str(item.trailer)
        w['go_trailer_button'].set_sensitive(True)
    else:
        self._trailer_url = None
        w['go_trailer_button'].set_sensitive(False)
    if 'seen' in item and item['seen'] == True:
        w['seen_icon'].set_from_file(
            os.path.join(self.locations['images'], 'seen.png'))
    else:
        w['seen_icon'].set_from_file(
            os.path.join(self.locations['images'], 'unseen.png'))
    if 'notes' in item and item['notes']:
        w['notes'].set_text(str(item.notes))
    else:
        w['notes'].set_text('')
    tmp = ''
    if 'media_num' in item and item['media_num']:
        tmp = str(item.media_num)
    else:
        tmp = '0'
    if 'medium_id' in item and item['medium_id']:
        if item.medium is not None:
            tmp += ' x ' + item.medium.name
        else:
            pass
    w['medium'].set_markup("<i>%s</i>" % gutils.html_encode(tmp))
    if 'vcodec_id' in item:
        if item.vcodec is not None:
            w['vcodec'].set_markup("<i>%s</i>" %
                                   gutils.html_encode(item.vcodec.name))
        else:
            w['vcodec'].set_text('')
    else:
        w['vcodec'].set_text('')
    # TODO: add widgets in main and edit windows
    #if 'ratio_id' in item:
    #    if item.ratio is not None:
    #        w['ratio'].set_markup("<i>%s</i>" % gutils.html_encode(item.ratio.name))
    #    else:
    #        w['ratio'].set_text('')
    #else:
    #    w['ratio'].set_text('')

    # poster
    if 'poster_md5' in item and item['poster_md5']:
        filename = gutils.get_image_fname(item['poster_md5'], self.db, 'm')
        if filename and os.path.isfile(filename):
            image_path = filename
            self.widgets['add']['delete_poster'].set_sensitive(True)
            w['picture_button'].set_sensitive(True)
        else:
            image_path = gutils.get_defaultimage_fname(self)
            self.widgets['add']['delete_poster'].set_sensitive(False)
            w['picture_button'].set_sensitive(False)
    else:
        image_path = gutils.get_defaultimage_fname(self)
        self.widgets['add']['delete_poster'].set_sensitive(False)
        w['picture_button'].set_sensitive(False)
    w['picture'].set_from_file(image_path)
    # ratig
    rimage = int(self.config.get('rating_image', 0))
    if rimage:
        prefix = ''
    else:
        prefix = 'meter'
    if 'rating' in item and item['rating']:
        rating_file = "%s/%s0%d.png" % (self.locations['images'], prefix,
                                        item['rating'])
    else:
        rating_file = "%s/%s0%d.png" % (self.locations['images'], prefix, 0)
    handler = w['image_rating'].set_from_pixbuf(
        gtk.gdk.pixbuf_new_from_file(rating_file))
    gutils.garbage(handler)

    # check loan status and adjust buttons and history box
    if 'loaned' in item and item['loaned'] is True:
        self.widgets['popups']['loan'].set_sensitive(False)
        self.widgets['popups']['email'].set_sensitive(True)
        self.widgets['popups']['return'].set_sensitive(True)
        self.widgets['menu']['loan'].set_sensitive(False)
        self.widgets['menu']['email'].set_sensitive(True)
        self.widgets['menu']['return'].set_sensitive(True)
        w['loan_button'].set_sensitive(False)
        w['email_reminder_button'].set_sensitive(True)
        w['return_button'].set_sensitive(True)

        if getattr(item, 'loan_details', None) is None:
            log.warning(
                "movie has no loan data, changing 'loaned' flag to False (movie_id: %s)",
                item['movie_id'])
            item.loaned = False
        else:
            self.person_name = item.loan_details.person.name
            self.person_email = item.loan_details.person.email
            self.loan_date = str(item.loan_details.date)
            w['loan_info'].set_use_markup(False)
            w['loan_info'].set_label(
                _("This movie has been loaned to %s on %s") %
                (self.person_name, self.loan_date[:10]))
    if 'loaned' in item and not item[
            'loaned']:  # "loaned" status can be changed above, so don't use "else:" in this line
        self.widgets['popups']['loan'].set_sensitive(True)
        self.widgets['popups']['email'].set_sensitive(False)
        self.widgets['popups']['return'].set_sensitive(False)
        self.widgets['menu']['loan'].set_sensitive(True)
        self.widgets['menu']['email'].set_sensitive(False)
        self.widgets['menu']['return'].set_sensitive(False)
        w['return_button'].set_sensitive(False)
        w['email_reminder_button'].set_sensitive(False)
        w['loan_button'].set_sensitive(True)
        w['loan_info'].set_markup("<b>%s</b>" % _("Movie not loaned"))

    # loan history
    self.loans_treemodel.clear()
    if getattr(item, 'loan_history', None) is not None:
        for loan in item.loan_history:
            myiter = self.loans_treemodel.append(None)
            self.loans_treemodel.set_value(myiter, 0,
                                           '%s' % str(loan.date)[:10])
            if loan.return_date and loan.return_date != '':
                self.loans_treemodel.set_value(myiter, 1,
                                               str(loan.return_date)[:10])
            else:
                self.loans_treemodel.set_value(myiter, 1, "---")
            if loan.person:
                person = self.db.session.query(db.Person.name).filter_by(
                    person_id=loan.person.person_id).first()
                self.loans_treemodel.set_value(myiter, 2, person.name)

    # volumes/collections
    if 'volume_id' in item and item['volume_id'] > 0:
        if 'volume' in item and item['volume']:
            w['volume'].set_markup("<b>%s</b>" %
                                   gutils.html_encode(item['volume'].name))
            w['show_volume_button'].set_sensitive(True)
        else:
            w['volume'].set_text('')
            w['show_volume_button'].set_sensitive(False)
    else:
        w['volume'].set_text('')
        w['show_volume_button'].set_sensitive(False)
    if 'collection_id' in item and item['collection_id'] > 0:
        if 'collection' in item and item['collection']:
            w['collection'].set_markup(
                "<b>%s</b>" % gutils.html_encode(item['collection'].name))
            w['show_collection_button'].set_sensitive(True)
        else:
            w['collection'].set_text('')
            w['show_collection_button'].set_sensitive(False)
    else:
        w['collection'].set_text('')
        w['show_collection_button'].set_sensitive(False)

    # languages
    for i in w['audio_vbox'].get_children():
        i.destroy()
    for i in w['subtitle_vbox'].get_children():
        i.destroy()
    if 'languages' in item and len(item['languages']) > 0:
        for i in item['languages']:
            if i.type == 3:  # subtitles
                if i.subformat:
                    tmp = "%s - %s" % (i.language.name, i.subformat.name)
                else:
                    tmp = "%s" % i.language.name
                w['subtitle_vbox'].pack_start(gtk.Label(tmp))
            else:
                language = i.language.name
                if i.type is not None and len(self._lang_types[i.type]) > 0:
                    language += " <i>%s</i>" % self._lang_types[i.type]
                tmp = ''
                if i.achannel:
                    tmp = i.achannel.name
                if i.acodec:
                    if len(tmp) > 0:
                        tmp += ", %s" % i.acodec.name
                    else:
                        tmp = i.acodec.name
                if len(tmp) > 0:
                    tmp = "%s (%s)" % (language, tmp)
                else:
                    tmp = language
                widget = gtk.Label(tmp)
                widget.set_use_markup(True)
                w['audio_vbox'].pack_start(widget)
    w['audio_vbox'].show_all()
    w['subtitle_vbox'].show_all()
    #tags
    if 'tags' in item:
        tmp = ''
        for tag in item['tags']:
            tmp += "%s, " % tag.name
        tmp = tmp[:-2]  # cut last comma
        w['tags'].set_text(tmp)
Пример #20
0
def set_details(self, item=None):#{{{
    if item is None:
        item = {}
    if 'movie_id' in item and item['movie_id']:
        self._am_movie_id = item['movie_id']
    else:
        self._am_movie_id = None
    w = self.widgets['add']

    cast_buffer  = w['cast'].get_buffer()
    notes_buffer = w['notes'].get_buffer()
    plot_buffer  = w['plot'].get_buffer()

    if 'o_title' in item and item['o_title']:
        w['o_title'].set_text(item['o_title'])
    else:
        w['o_title'].set_text('')
    if 'title' in item and item['title']:
        w['title'].set_text(item['title'])
    else:
        w['title'].set_text('')
    if 'number' in item and item['number']:
        w['number'].set_value(int(item['number']))
    else:
        w['number'].set_value(int(gutils.find_next_available(self.db)))
    if 'title' in item and item['title']:
        w['title'].set_text(item['title'])
    if 'year' in item and item['year']:
        w['year'].set_value( gutils.digits_only(item['year'], 2100))
    else:
        w['year'].set_value(0)
    if 'runtime' in item and item['runtime']:
        w['runtime'].set_value( gutils.digits_only(item['runtime']))
    else:
        w['runtime'].set_value(0)
    if 'cameraman' in item and item['cameraman']:
        w['cameraman'].set_text(item['cameraman'])
    else:
        w['cameraman'].set_text('')
    if 'screenplay' in item and item['screenplay']:
        w['screenplay'].set_text(item['screenplay'])
    else:
        w['screenplay'].set_text('')
    if 'country' in item and item['country']:
        w['country'].set_text(item['country'])
    else:
        w['country'].set_text('')
    if 'classification' in item and item['classification']:
        w['classification'].set_text(item['classification'])
    else:
        w['classification'].set_text('')
    if 'studio' in item and item['studio']:
        w['studio'].set_text(item['studio'])
    else:
        w['studio'].set_text('')
    if 'o_site' in item and item['o_site']:
        w['o_site'].set_text(item['o_site'])
    else:
        w['o_site'].set_text('')
    if 'director' in item and item['director']:
        w['director'].set_text(item['director'])
    else:
        w['director'].set_text('')
    if 'site' in item and item['site']:
        w['site'].set_text(item['site'])
    else:
        w['site'].set_text('')
    if 'trailer' in item and item['trailer']:
        w['trailer'].set_text(item['trailer'])
    else:
        w['trailer'].set_text('')
    if 'genre' in item and item['genre']:
        w['genre'].set_text(item['genre'])
    else:
        w['genre'].set_text('')
    if 'color' in item and item['color']:
        w['color'].set_active( gutils.digits_only(item['color'], 3))
    else:
        w['color'].set_active( gutils.digits_only(self.config.get('color', 0, section='defaults'), 3))
    if 'layers' in item and item['layers']:
        w['layers'].set_active( gutils.digits_only(item['layers'], 4))
    else:
        w['layers'].set_active( gutils.digits_only(self.config.get('layers', 0, section='defaults'), 4))
    if 'region' in item and item['region']>=0:
            w['region'].set_active( gutils.digits_only(item['region'], 8))
    else:
        w['region'].set_active( gutils.digits_only(self.config.get('region', 0, section='defaults'), 8))
    if 'cond' in item and item['cond']>=0:
        w['condition'].set_active( gutils.digits_only( item['cond'], 5) )
    else:
        w['condition'].set_active( gutils.digits_only( self.config.get('condition', 0, section='defaults'), 5))
    if 'media_num' in item and item['media_num']:
        w['discs'].set_value( gutils.digits_only(item['media_num']))
    else:
        w['discs'].set_value(1)
    if 'rating' in item and item['rating']:
        w['rating_slider'].set_value( gutils.digits_only(item['rating'], 10) )
    else:
        w['rating_slider'].set_value(0)
    if 'seen' in item and item['seen'] is True:
        w['seen'].set_active(True)
    else:
        w['seen'].set_active(False)
    if 'cast' in item and item['cast']:
        cast_buffer.set_text(item['cast'])
    else:
        cast_buffer.set_text('')
    if 'notes' in item and item['notes']:
        notes_buffer.set_text(item['notes'])
    else:
        notes_buffer.set_text('')
    if 'plot' in item and item['plot']:
        plot_buffer.set_text(item['plot'])
    else:
        plot_buffer.set_text('')
    pos = 0
    if 'medium_id' in item and item['medium_id']:
        pos = gutils.findKey(item['medium_id'], self.media_ids)
    else:
        pos = gutils.findKey(int(self.config.get('media', 0, section='defaults')), self.media_ids)
    if pos is not None:
        w['media'].set_active(int(pos))
    else:
        w['media'].set_active(0)
    pos = 0
    if 'vcodec_id' in item and item['vcodec_id']:
        pos = gutils.findKey(item['vcodec_id'], self.vcodecs_ids)
    else:
        pos = gutils.findKey(int(self.config.get('vcodec', 0, section='defaults')), self.vcodecs_ids)
    if pos is not None:
        w['vcodec'].set_active(int(pos))
    else:
        w['vcodec'].set_active(0)
    pos = 0
    if 'volume_id' in item and item['volume_id']:
        pos = gutils.findKey(item['volume_id'], self.volume_combo_ids)
    if pos is not None:
        w['volume'].set_active(int(pos))
    else:
        w['volume'].set_active(0)
    pos = 0
    if 'collection_id' in item and item['collection_id']:
        pos = gutils.findKey(item['collection_id'], self.collection_combo_ids)
    if pos is not None:
        w['collection'].set_active(int(pos))
    else:
        w['volume'].set_active(0)
    # tags
    for tag in self.am_tags:
        self.am_tags[tag].set_active(False)
    if 'tags' in item:
        for tag in item['tags']:
            i = gutils.findKey(tag.tag_id, self.tags_ids)
            self.am_tags[i].set_active(True)
    # languages
    w['lang_treeview'].get_model().clear()
    if 'languages' in item and len(item['languages'])>0:
        for i in item['languages']:
            self.create_language_row(i)
    # poster
    if 'poster_md5' in item and item['poster_md5']:
        image_path = gutils.get_image_fname(item["poster_md5"], self.db, 'm')
        if not image_path: image_path = '' # isfile doesn't like bool
        w['image'].set_text(item['poster_md5'])
    elif 'image' in item and item['image']:
        if len(item["image"])==32: # md5
            image_path = gutils.get_image_fname(item["image"], self.db, 'm')
            if not image_path: image_path = '' # isfile doesn't like bool
            else: w['image'].set_text(item['image'])
        else:
            image_path = os.path.join(self.locations['posters'], "m_%s.jpg" % item['image'])
            log.warn("TODO: image=%s", item['image'])
    else:
        w['image'].set_text('')
        image_path = os.path.join(self.locations['images'], 'default.png')
    if not os.path.isfile(image_path):
        image_path = os.path.join(self.locations['images'], 'default.png')
    w['picture'].set_from_file(image_path)
    
    w['notebook'].set_current_page(0)
    w['source'].set_active(self.d_plugin)
    w['o_title'].grab_focus()
Пример #21
0
def populate(self, movies=None, where=None, qf=True):#{{{
    if self.initialized is False: # dont try to fill movie list if Griffith is not initialized yet
        return False

    if qf and not movies or isinstance(movies, Select): # if ".execute().fetchall()" not invoked on movies yet
        if not where: # due to possible 'seen', 'loaned', 'collection_id' in where
            import advfilter

            # saved in advfilter
            name = self.widgets['filter']['advfilter'].get_active_text()[:-3].decode('utf-8') # :-3 due to additional '   ' in the name
            if name:
                cond = self.db.session.query(db.Filter).filter_by(name=name).first()
                if not cond:
                    cond = advfilter.get_def_conditions()
                else:
                    cond = cond.data
            else:
                cond = advfilter.get_def_conditions()
            # add sorting from config
            sort_column_name = self.config.get('sortby', 'number', section='mainlist')
            sort_reverse = self.config.get('sortby_reverse', False, section='mainlist')
            if sort_reverse:
                cond['sort_by'] = set((sort_column_name + ' DESC', ))
            else:
                cond['sort_by'] = set((sort_column_name, ))

            # seen / loaned
            if self.widgets['menu']['loaned_movies'].get_active():
                cond['loaned'] = True
            if self.widgets['menu']['not_seen_movies'].get_active():
                cond["seen"] = False
            # collection
            pos = self.widgets['filter']['collection'].get_active()
            if pos >= 0:
                col_id = self.collection_combo_ids[pos]
                if col_id > 0:
                    cond["collections"].add(col_id)

            movies = advfilter.create_select_query(self, None, cond, movies)
        else:
            # select sort column
            sort_column_name = self.config.get('sortby', 'number', section='mainlist')
            sort_reverse = self.config.get('sortby_reverse', False, section='mainlist')
            # explicit conditions, only empty dictionary needed to add the order by values
            cond = {}
            if sort_reverse:
                cond['sort_by'] = set((sort_column_name + ' DESC', ))
            else:
                cond['sort_by'] = set((sort_column_name, ))
            movies = sql.update_whereclause(movies, cond)

        # additional whereclause (volume_id, collection_id, ...)
        if where:
            for i in where:
                if i in db.Movie:
                    movies.append_whereclause(db.Movie[i] == where[i])
        movies = movies.execute().fetchall()

    self.total = len(movies)
    # disable refreshing while inserting
    self.widgets['treeview'].freeze_child_notify()
    self.widgets['treeview'].set_model(None)

    # save user sort column
    sort_column_id, order = self.treemodel.get_sort_column_id()

    # new treemodel (faster and prevents some problems)
    self.treemodel = gtk.TreeStore(str, gtk.gdk.Pixbuf, str, str, str, str, bool, str, str, int)

    # check preferences to hide or show columns
    if self.config.get('number', True, 'mainlist') == True:
        self.number_column.set_visible(True)
    else:
        self.number_column.set_visible(False)
    if self.config.get('otitle', True, 'mainlist') == True:
        self.otitle_column.set_visible(True)
    else:
        self.otitle_column.set_visible(False)
    if self.config.get('title', True, 'mainlist') == True:
        self.title_column.set_visible(True)
    else:
        self.title_column.set_visible(False)
    if self.config.get('director', True, 'mainlist') == True:
        self.director_column.set_visible(True)
    else:
        self.director_column.set_visible(False)
    if self.config.get('image', True, 'mainlist') == True:
        self.image_column.set_visible(True)
    else:
        self.image_column.set_visible(False)
    if self.config.get('genre', True, 'mainlist') == True:
        self.genre_column.set_visible(True)
    else:
        self.genre_column.set_visible(False)
    if self.config.get('seen', True, 'mainlist') == True:
        self.seen_column.set_visible(True)
    else:
        self.seen_column.set_visible(False)
    if self.config.get('year', True, 'mainlist') == True:
        self.year_column.set_visible(True)
    else:
        self.year_column.set_visible(False)
    if self.config.get('runtime', True, 'mainlist') == True:
        self.runtime_column.set_visible(True)
    else:
        self.runtime_column.set_visible(False)
    if self.config.get('rating', True, 'mainlist') == True:
        self.rating_column.set_visible(True)
    else:
        self.rating_column.set_visible(False)

    for movie in movies:
        myiter = self.treemodel.append(None)

        self.treemodel.set_value(myiter, 0, '%004d' % int(movie.number))

        if self.config.get('image', True, section='mainlist') == True:
            filename = None
            if movie.poster_md5:
                filename = gutils.get_image_fname(movie.poster_md5, self.db, "s")
            if not filename:
                filename = os.path.join(self.locations['images'], 'default_thumbnail.png')

            self.Image.set_from_file(filename)
            pixbuf = self.Image.get_pixbuf()
            self.treemodel.set_value(myiter, 1, pixbuf)
        self.treemodel.set_value(myiter, 2, movie.o_title)
        self.treemodel.set_value(myiter, 3, movie.title)
        self.treemodel.set_value(myiter, 4, movie.director)
        self.treemodel.set_value(myiter, 5, movie.genre)
        self.treemodel.set_value(myiter, 6, movie.seen)
        if movie.year is not None and (isinstance(movie.year, int) or isinstance(movie.year, long)):
            self.treemodel.set_value(myiter, 7, movie.year)
        if movie.runtime is not None and (isinstance(movie.runtime, int) or isinstance(movie.runtime, long)):
            self.treemodel.set_value(myiter, 8, '%003d' % movie.runtime + _(' min'))
        if movie.rating is not None and (isinstance(movie.rating, int) or isinstance(movie.rating, long)):
            self.treemodel.set_value(myiter, 9, movie.rating)

    # restore user sort column
    if sort_column_id is not None:
        self.treemodel.set_sort_column_id(sort_column_id, order)

    # add new treemodel and allow refreshs again
    self.widgets['treeview'].set_model(self.treemodel)
    self.widgets['treeview'].thaw_child_notify()
    if self.total:
        self.widgets['treeview'].set_cursor_on_cell(0)
    self.count_statusbar()
Пример #22
0
    # update the md5 *after* all other queries (so that UPDATE will not be invoked)
    movie.poster_md5 = poster_md5

    session.add(movie)
    try:
        session.commit()
    except Exception, e:
        session.rollback()
        log.error("cannot add poster to database: %s" % e)
        return False

    if old_poster_md5:
        delete.delete_poster(self, old_poster_md5)

    filename = gutils.get_image_fname(poster_md5, self.db, "s")
    if filename:
        update_tree_thumbnail(self, filename)

    self.widgets["movie"]["picture_button"].set_sensitive(True)
    self.widgets["add"]["delete_poster"].set_sensitive(True)

    self.update_statusbar(_("Image has been updated"))
    return True


def delete_poster(self, movie_id=None):
    if movie_id is None:
        movie_id = self._movie_id
    session = self.db.Session()
    movie = session.query(db.Movie).filter_by(movie_id=movie_id).first()
Пример #23
0
    # update the md5 *after* all other queries (so that UPDATE will not be invoked)
    movie.poster_md5 = poster_md5

    session.add(movie)
    try:
        session.commit()
    except Exception, e:
        session.rollback()
        log.error("cannot add poster to database: %s" % e)
        return False

    if old_poster_md5:
        delete.delete_poster(self, old_poster_md5)

    filename = gutils.get_image_fname(poster_md5, self.db, 's')
    if filename:
        update_tree_thumbnail(self, filename)

    self.widgets['movie']['picture_button'].set_sensitive(True)
    self.widgets['add']['delete_poster'].set_sensitive(True)

    self.update_statusbar(_("Image has been updated"))
    return True


def delete_poster(self, movie_id=None):
    if movie_id is None:
        movie_id = self._movie_id
    session = self.db.Session()
    movie = session.query(db.Movie).filter_by(movie_id=movie_id).first()