Пример #1
0
def delete_person(self):
    has_history = False
    has_history_msg = ''
    try:
        treeselection = self.widgets['people']['treeview'].get_selection()
        (tmp_model, tmp_iter) = treeselection.get_selected()
        person = tmp_model.get_value(tmp_iter,0).decode('utf-8')
    except:
        return
    person = self.db.session.query(db.Person).filter_by(name=person).first()
    if not person:
        return False
    if person.loaned_movies_count > 0:
        gutils.info(_("This person has loaned films from you. Return them first."), self.widgets['people']['window'])
        return False
    if person.returned_movies_count > 0:
        has_history = True
        has_history_msg = _("This person has data in the loan history. This data will be erased if you continue.")
    
    if gutils.question(_("%s\nAre you sure you want to delete this person?" % has_history_msg), self.widgets['people']['window']):
        treeselection = self.widgets['people']['treeview'].get_selection()
        (tmp_model, tmp_iter) = treeselection.get_selected()
        self.db.session.delete(person)
        try:
            self.db.session.commit()
        except Exception, e:
            log.info(str(e))
        else:
            self.p_treemodel.remove(tmp_iter)
            self.treeview_clicked()
Пример #2
0
def delete(gsql, widgets):
    """deletes the current selected filter"""

    #hier muss was anderes her! nicht den text prüfen, da bei manchem anwender ein leereintrag existiert
    name = widgets['cb_name'].get_active_text().decode('utf-8')
    if not name:
        log.debug("search rule name is empty")
        info(_("Name is empty"), widgets['window'])
        return False

    session = gsql.Session()
    filter = session.query(db.Filter).filter_by(name=name).first()
    if filter:
        session.delete(filter)
        try:
            session.commit()
        except:
            session.rollback()
            log.exception('')
            warning(_("Cannot delete search conditions"), widgets['window'])
            return False
        else:
            widgets['cb_name'].remove_text(widgets['cb_name'].get_active())
        info(_("Search conditions deleted"), widgets['window'])
    widgets['name'].set_text('')
 def export_csv(self):
     basedir = None
     if not self.persistent_config is None:
         basedir = self.persistent_config.get('export_dir', None, section='export-csv')
     if basedir is None:
         filename = gutils.file_chooser(_("Export a %s document")%"CSV", action=gtk.FILE_CHOOSER_ACTION_SAVE, \
             buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_SAVE,gtk.RESPONSE_OK),name='griffith_list.csv')
     else:
         filename = gutils.file_chooser(_("Export a %s document")%"CSV", action=gtk.FILE_CHOOSER_ACTION_SAVE, \
             buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_SAVE,gtk.RESPONSE_OK),name='griffith_list.csv',folder=basedir)
     if filename[0]:
         if not self.persistent_config is None and filename[1]:
             self.persistent_config.set('export_dir', filename[1], section='export-csv')
             self.persistent_config.save()
         overwrite = None
         if os.path.isfile(filename[0]):
             response = gutils.question(self, _("File exists. Do you want to overwrite it?"), 1, self.parent)
             if response==-8:
                 overwrite = True
             else:
                 overwrite = False
                 
         if overwrite == True or overwrite is None:
             writer = csv.writer(file(filename[0], 'w'), dialect=csv.excel)
             for movie in self.db.Movie.select():
                 t = []
                 for s in ('number', 'o_title', 'title', 'director', 'year', 'classification', 'country',
                         'genre', 'rating', 'runtime', 'studio', 'seen', 'loaned', 'o_site', 'site', 'trailer',
                         'plot', 'cast', 'notes','image'):
                     t.append(movie[s])
                 writer.writerow(t)
             gutils.info(self, _("%s file has been created.")%"CSV", self.parent)
Пример #4
0
def spellcheck(self):
    global spell_support
    spell_error = False
    if self.posix and spell_support:
        if self.config.get('gtkspell', False, section='spell') == True:
            if self.config.get('notes', True, section='spell') == True and self.config.get('lang', section='spell') != '':
                try:
                    self.notes_spell = gtkspell.Spell(self.widgets['add']['cast'], self.config.get('lang', section='spell'))
                except:
                    spell_error = True
            if self.config.get('plot', True, section='spell')==True and self.config.get('lang', section='spell') != '':
                try:
                    self.plot_spell = gtkspell.Spell(self.widgets['add']['plot'], self.config.get('lang', section='spell'))
                except:
                    spell_error = True
            if spell_error:
                log.info('Dictionary not available. Spellcheck will be disabled.')
                if not self.config.get('notified', False, section='spell'):
                    gutils.info(_("Dictionary not available. Spellcheck will be disabled. \n" + \
                        "Please install the aspell-%s package or adjust the spellchekcer preferences.")%self.config.get('lang', section='spell'), \
                        self.widgets['preferences']['window'])
                    self.config.set('notified', True, section='spell')
                    self.config.save()
    else:
        log.info('Spellchecker is not available')
Пример #5
0
def gtkspell(self):
	global spell_support
	spell_error = False
	if self.posix and spell_support:
		if self.config.get('use_gtkspell', False) == 'True':
			if self.config.get('spell_notes', True) == 'True' and \
				self.config.get('spell_lang')!='':
				try:
					self.notes_spell = gtkspell.Spell(self.widgets['add']['cast'], self.config.get('spell_lang'))
				except:
					spell_error = True
			if self.config.get('spell_plot', True)=='True' and \
				self.config.get('spell_lang')!='':
				try:
					self.plot_spell = gtkspell.Spell(self.widgets['add']['plot'], self.config.get('spell_lang'))
				except:
					spell_error = True
			if spell_error:
				self.debug.show('Dictionary not available. Spellcheck will be disabled.')
				if not self.config.get('spell_notify', False):
					gutils.info(self, _("Dictionary not available. Spellcheck will be disabled. \n" + \
						"Please install the aspell-%s package or adjust the spellchekcer preferences.")%self.config.get('spell_lang'), \
						self.widgets['preferences']['window'])
					self.config['spell_notify'] = True
					self.config.save()
	else:
		self.debug.show('Spellchecker is not available')
Пример #6
0
def on_import_button_clicked(button, self, *args):
	import plugins.imp, gutils
	plugin_name = self.widgets['import']['plugin'].get_active_text()
	filenames = self.widgets['import']['fcw'].get_filenames()
	
	fields = []
	w = self.widgets['import']['fields']
	for i in w:
		if w[i].get_active():
			fields.append(i)

	__import__("plugins.imp.%s" % plugin_name)
	ip = eval("plugins.imp.%s.ImportPlugin(self, fields)" % plugin_name)
	if ip.initialize():
		self.widgets['window'].set_sensitive(False)
		self.widgets['import']['window'].hide()
		self.widgets['import']['pabort'].connect('clicked', ip.abort, ip)
		for filename in filenames:
			self.widgets['import']['progressbar'].set_fraction(0)
			self.widgets['import']['progressbar'].set_text('')
			if ip.run(filename):
				gutils.info(self, _("%s file has been imported. %s movies added.") \
					% (plugin_name, ip.imported), self.widgets['window'])
				self.populate_treeview()
			ip.clear()
		ip.destroy()
		self.widgets['import']['pwindow'].hide()
		self.widgets['window'].set_sensitive(True)
Пример #7
0
def restore(self):
	"""restores a griffith compressed backup"""
	filename = gutils.file_chooser(_("Restore Griffith backup"), \
		action=gtk.FILE_CHOOSER_ACTION_OPEN, buttons= \
		(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, \
		gtk.STOCK_OPEN, gtk.RESPONSE_OK))
	if filename[0]:
		try:
			zip = zipfile.ZipFile(filename[0], 'r')
		except:
			gutils.error(self, _("Can't read backup file"), self.widgets['window'])
			return False
		mypath = os.path.join(self.locations['posters'])
		for each in zip.namelist():
			file_to_restore = os.path.split(each)
			if not os.path.isdir(file_to_restore[1]):
				if file_to_restore[1] == '':
					continue
				if file_to_restore[1].endswith('.jpg'):
					myfile = os.path.join(mypath,file_to_restore[1])
				else:
					myfile = os.path.join(self.locations['home'],file_to_restore[1])
				outfile = open(myfile, 'wb')
				outfile.write(zip.read(each))
				outfile.flush()
				outfile.close()
		zip.close()

		# restore config file
		self.config = config.Config(file=os.path.join(self.locations['home'],'griffith.conf'))
		filename = os.path.join(self.locations['home'], self.config["default_db"])

		self.db.metadata.engine.dispose() # close DB
		from sqlalchemy.orm import clear_mappers
		clear_mappers()

		# check if file needs conversion
		if self.config['default_db'].lower().endswith('.gri'):
			self.debug.show('Old database format detected. Converting...')
			from dbupgrade import convert_from_old_db
			from initialize	import location_posters
			if convert_from_old_db(self, filename, os.path.join(self.locations['home'], 'griffith.db')):
				self.config.save()
				location_posters(self.locations, self.config)
			else:
				print 'Cant convert old database, exiting.'
				import sys
				sys.exit(4)

		self.db = sql.GriffithSQL(self.config, self.debug, self.locations['home'])
		from initialize	import dictionaries, people_treeview
		dictionaries(self)
		people_treeview(self)
		# let's refresh the treeview
		self.clear_details()
		self.populate_treeview()
		self.go_last()
		self.treeview_clicked()
		self.count_statusbar()
		gutils.info(self, _("Backup restored"), self.widgets['window'])
Пример #8
0
def convert_from_old_db(config, source_file, destination_file, locations):  # {{{
    """
    convert .gri database into .bd one
    """

    log.info("Converting old database - it can take several minutes...")
    log.debug("Source file: %s", source_file)
    gutils.info(
        _(
            "Griffith will now convert your database to the new format. This can take several minutes if you have a large database."
        )
    )
    from sql import GriffithSQL
    from gutils import digits_only
    import os

    if not os.path.isfile(source_file):
        return False

    if "home" not in locations:
        log.error("locations doesn't contain home path, cannot convert old database")
        return False

    if open(source_file).readline()[:47] == "** This file contains an SQLite 2.1 database **":
        log.debug("SQLite 2.1 detected")
        try:
            import sqlite
        except ImportError:
            log.error("Old DB conversion: please install pysqlite legacy (v1.0)")
            gutils.warning(_("Old DB conversion: please install pysqlite legacy (v1.0)"))
            return False
    else:
        try:  # Python 2.5
            from sqlite3 import dbapi2 as sqlite
        except ImportError:  # Python < 2.5 - try to use pysqlite2
            from pysqlite2 import dbapi2 as sqlite

    if os.path.isfile(destination_file):
        # rename destination_file if it already exist
        i = 1
        while True:
            if os.path.isfile("%s_%s" % (destination_file, i)):
                i += 1
            else:
                break
        os.rename(destination_file, "%s_%s" % (destination_file, i))

    try:
        old_db = sqlite.connect(source_file)
    except sqlite.DatabaseError, e:
        if str(e) == "file is encrypted or is not a database":
            print "Your database is most probably in SQLite2 format, please convert it to SQLite3:"
            print "$ sqlite ~/.griffith/griffith.gri .dump | sqlite3 ~/.griffith/griffith.gri3"
            print "$ mv ~/.griffith/griffith.gri{,2}"
            print "$ mv ~/.griffith/griffith.gri{3,}"
            print "or install pysqlite in version 1.0"
            gutils.warning(_("Your database is most probably in SQLite2 format, please convert it to SQLite3"))
        else:
            raise
        return False
Пример #9
0
def on_import_button_clicked(button, self, *args):
    import plugins.imp
    import gutils
    plugin_name = self.widgets['import']['plugin'].get_active_text()
    filenames = self.widgets['import']['fcw'].get_filenames()

    fields = []
    w = self.widgets['import']['fields']
    for i in w:
        if w[i].get_active():
            fields.append(i)

    __import__("plugins.imp.%s" % plugin_name)
    if self.debug_mode:
        log.debug('reloading %s', plugin_name)
        import sys
        reload(sys.modules["plugins.imp.%s" % plugin_name])
    ip = eval("plugins.imp.%s.ImportPlugin(self, fields)" % plugin_name)
    if ip.initialize():
        self.widgets['window'].set_sensitive(False)
        try:
            self.widgets['import']['window'].hide()
            self.widgets['import']['pabort'].connect('clicked', ip.abort, ip)
            for filename in filenames:
                self.widgets['import']['progressbar'].set_fraction(0)
                self.widgets['import']['progressbar'].set_text('')
                if ip.run(filename):
                    gutils.info(_("%s file has been imported. %s movies added.") \
                        % (plugin_name, ip.imported), self.widgets['window'])
                    self.populate_treeview()
                ip.clear()
        except Exception, e:
            log.exception('')
            gutils.error(str(e), self.widgets['window'])
        finally:
Пример #10
0
def spellcheck(self):
    global spell_support
    spell_error = False
    if self.posix and spell_support:
        if self.config.get('gtkspell', False, section='spell') == True:
            if self.config.get('notes', True,
                               section='spell') is True and self.config.get(
                                   'lang', section='spell') != '':
                try:
                    self.notes_spell = gtkspell.Spell(
                        self.widgets['add']['notes'],
                        self.config.get('lang', section='spell'))
                except:
                    spell_error = True
            if self.config.get('plot', True,
                               section='spell') is True and self.config.get(
                                   'lang', section='spell') != '':
                try:
                    self.plot_spell = gtkspell.Spell(
                        self.widgets['add']['plot'],
                        self.config.get('lang', section='spell'))
                except:
                    spell_error = True
            if spell_error:
                log.info(
                    'Dictionary not available. Spell check will be disabled.')
                if not self.config.get('notified', False, section='spell'):
                    gutils.info(_("Dictionary not available. Spellcheck will be disabled. \n" + \
                        "Please install the aspell-%s package or adjust the spellchecker preferences.") % self.config.get('lang', section='spell'), \
                        self.widgets['preferences']['window'])
                    self.config.set('notified', True, section='spell')
                    self.config.save()
    else:
        log.info('Spellchecker is not available')
Пример #11
0
def delete_person(self):
    has_history = False
    has_history_msg = ""
    try:
        treeselection = self.widgets["people"]["treeview"].get_selection()
        (tmp_model, tmp_iter) = treeselection.get_selected()
        person = tmp_model.get_value(tmp_iter, 0).decode("utf-8")
    except:
        return
    person = self.db.session.query(db.Person).filter_by(name=person).first()
    if not person:
        return False
    if person.loaned_movies_count > 0:
        gutils.info(_("This person has loaned films from you. Return them first."), self.widgets["people"]["window"])
        return False
    if person.returned_movies_count > 0:
        has_history = True
        has_history_msg = _("This person has data in the loan history. This data will be erased if you continue.")

    if gutils.question(
        _("%s\nAre you sure you want to delete this person?" % has_history_msg), self.widgets["people"]["window"]
    ):
        treeselection = self.widgets["people"]["treeview"].get_selection()
        (tmp_model, tmp_iter) = treeselection.get_selected()
        self.db.session.delete(person)
        try:
            self.db.session.commit()
        except Exception, e:
            log.info(str(e))
        else:
            self.p_treemodel.remove(tmp_iter)
            self.treeview_clicked()
Пример #12
0
def delete_person(self):
    response = None
    has_history = False
    has_history_msg = ''
    try:
        treeselection = self.widgets['people']['treeview'].get_selection()
        (tmp_model, tmp_iter) = treeselection.get_selected()
        person = tmp_model.get_value(tmp_iter,0).decode('utf-8')
    except:
        return
    person = self.db.session.query(db.Person).filter_by(name=person).first()
    if not person:
        return False
    data = self.db.session.query(db.Loan).filter_by(person_id=person.person_id, return_date=None).all()
    if len(data)>0:
        gutils.info(_("This person has loaned films from you. Return them first."), self.widgets['people']['window'])
        return False
    data = self.db.session.query(db.Loan).filter_by(person_id=person.person_id).all()
    if len(data)>0:
        has_history = True
        has_history_msg = _("This person has data in the loan history. This data will be erased if you continue.")
    response = gutils.question(_("%s\nAre you sure you want to delete this person?" % has_history_msg), \
                               True, self.widgets['people']['window'])

    if response == -8:
        treeselection = self.widgets['people']['treeview'].get_selection()
        (tmp_model, tmp_iter) = treeselection.get_selected()
        self.db.session.delete(person)
        try:
            self.db.session.commit()
        except Exception, e:
            log.info(str(e))
        else:
            self.p_treemodel.remove(tmp_iter)
            self.treeview_clicked()
	def export_xml(self):
		filename = gutils.file_chooser(_("Export a %s document")%"XML", action=gtk.FILE_CHOOSER_ACTION_SAVE, \
			buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_SAVE,gtk.RESPONSE_OK),name='griffith_list.xml')
		if filename[0]:
			overwrite = None
			if os.path.isfile(filename[0]):
				response = gutils.question(self, _("File exists. Do you want to overwrite it?"), 1, self.parent)
				if response==-8:
					overwrite = True
				else:
					overwrite = False
					
			if overwrite == True or overwrite == None:
				# create document
				impl = xml.dom.minidom.getDOMImplementation()
				doc  = impl.createDocument(None, "root", None)
				root = doc.documentElement
				
				# create object
				data = self.db.get_all_data(order_by="number ASC")
				for row in data:
					e = doc.createElement('movie')
					root.appendChild(e)
					for key,value in row.items():
						e2 = doc.createElement(key)
						t = doc.createTextNode(str(value))
						e2.appendChild(t)
						e.appendChild(e2)
					
				# write XML to file
				fp = open(filename[0], "w")
				xml.dom.ext.PrettyPrint(doc, fp)
				fp.close()
				gutils.info(self, _("%s file has been created.")%"XML", self.parent)
Пример #14
0
def mailto(self, tls, port, server, auth, user, password, sender, to, subject, msg):
    """
    sends an email
    """
    try:
        session = smtplib.SMTP(server, port)
        session.set_debuglevel(1)
    except socket.timeout:
        gutils.error(_("Connection timed out"), \
            self.widgets['window'])
        return()
    if tls == True:
        session.ehlo()
        session.starttls()
        session.ehlo()
    if auth:
        try:
            session.login(user, password)
        except:
            gutils.error(_("Error sending e-mail: %s")%_("login failure"), \
                self.widgets['window'])
            return
    headers = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" \
        % (sender, to, subject)
    try:
        smtpresult = session.sendmail(sender, to, headers+msg)
        gutils.info(_("E-mail sent sucessfuly"), self.widgets['window'])
        return
    except:
        gutils.error(_("Error sending e-mail: %s")%"", self.widgets['window'])
        
    session.quit()
Пример #15
0
def on_import_button_clicked(button, self, *args):
    import plugins.imp
    import gutils
    plugin_name = self.widgets['import']['plugin'].get_active_text()
    filenames = self.widgets['import']['fcw'].get_filenames()

    fields = []
    w = self.widgets['import']['fields']
    for i in w:
        if w[i].get_active():
            fields.append(i)

    __import__("plugins.imp.%s" % plugin_name)
    if self.debug_mode:
        log.debug('reloading %s', plugin_name)
        import sys
        reload(sys.modules["plugins.imp.%s" % plugin_name])
    ip = eval("plugins.imp.%s.ImportPlugin(self, fields)" % plugin_name)
    if ip.initialize():
        self.widgets['window'].set_sensitive(False)
        try:
            self.widgets['import']['window'].hide()
            self.widgets['import']['pabort'].connect('clicked', ip.abort, ip)
            for filename in filenames:
                self.widgets['import']['progressbar'].set_fraction(0)
                self.widgets['import']['progressbar'].set_text('')
                if ip.run(filename):
                    gutils.info(_("%s file has been imported. %s movies added.") \
                        % (plugin_name, ip.imported), self.widgets['window'])
                    self.populate_treeview()
                ip.clear()
        except Exception, e:
            log.exception('')
            gutils.error(str(e), self.widgets['window'])
        finally:
Пример #16
0
def mailto(self, tls, port, server, auth, user, password, sender, to, subject,
           msg):
    """
    sends an email
    """
    try:
        session = smtplib.SMTP(server, port)
        session.set_debuglevel(1)
    except socket.timeout:
        gutils.error(_("Connection timed out"), \
            self.widgets['window'])
        return ()
    if tls == True:
        session.ehlo()
        session.starttls()
        session.ehlo()
    if auth:
        try:
            session.login(user, password)
        except:
            gutils.error(_("Error sending e-mail: %s")%_("login failure"), \
                self.widgets['window'])
            return
    headers = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" \
        % (sender, to, subject)
    try:
        smtpresult = session.sendmail(sender, to, headers + msg)
        gutils.info(_("E-mail sent successfully"), self.widgets['window'])
        return
    except:
        gutils.error(
            _("Error sending e-mail: %s") % "", self.widgets['window'])

    session.quit()
	def do_test_plugin(self, plugin_name, domsgbox=True):
		result = True
		
		plugin = __import__(plugin_name)
		try:
			pluginTestConfig = plugin.PluginTest()
		except:
			print "Warning: Plugin test could not be executed for %s because of missing configuration class PluginTest." % plugin_name
			pluginTestConfig = None
		
		if not pluginTestConfig == None:
			logFile = open(plugin_name + '-loadtest.txt', 'w+')
			try:
				for i in pluginTestConfig.test_configuration:
					moviePlugin = plugin.Plugin(i)
					if not self.test_one_movie(moviePlugin, logFile, pluginTestConfig.test_configuration[i]):
						result = False
					sleep(1) # needed for amazon
			finally:
				logFile.close()

		if domsgbox:
			if not result:
				gutils.error(self, 'PluginTest %s: Test NOT successful !' % plugin_name)
			else:
				gutils.info(self, 'PluginTest %s: Test successful !' % plugin_name)
		
		return result
Пример #18
0
def save(gsql, widgets):
    """saves search conditions from current filter window"""

    cond = get_conditions(widgets)
    name = widgets['cb_name'].get_active_text().decode('utf-8')
    if not name:
        log.debug("search rule name is empty")
        info(_("Name is empty"), widgets['window'])
        return False

    session = gsql.Session()
    filter_ = session.query(db.Filter).filter_by(name=name).first()
    if filter_:
        filter_.data = cond
        isnew = False
    else:
        filter_ = db.Filter(name=name, data=cond)
        isnew = True
    session.add(filter_)
    try:
        session.commit()
    except Exception, e:
        session.rollback()
        log.warn(e)
        warning(_("Cannot save search conditions"), widgets['window'])
        return False
Пример #19
0
def save(gsql, widgets):
    """saves search conditions from current filter window"""

    cond = get_conditions(widgets)
    name = widgets['cb_name'].get_active_text().decode('utf-8')
    if not name:
        log.debug("search rule name is empty")
        info(_("Name is empty"), widgets['window'])
        return False

    session = gsql.Session()
    filter_ = session.query(db.Filter).filter_by(name=name).first()
    if filter_:
        filter_.data = cond
        isnew = False
    else:
        filter_ = db.Filter(name=name, data=cond)
        isnew = True
    session.add(filter_)
    try:
        session.commit()
    except Exception, e:
        session.rollback()
        log.warn(e)
        warning(_("Cannot save search conditions"), widgets['window'])
        return False
Пример #20
0
def delete_person(self):
	response = None
	has_history = False
	has_history_msg = ''
	try:
		treeselection = self.widgets['people']['treeview'].get_selection()
		(tmp_model, tmp_iter) = treeselection.get_selected()
		person = tmp_model.get_value(tmp_iter,0)
	except:
		return
	person = self.db.Person.get_by(name=person)
	if not person:
		return False
	data = self.db.Loan.select_by(person_id=person.person_id, return_date=None)
	if len(data)>0:
		gutils.info(self, _("This person has loaned films from you. Return them first."), self.widgets['people']['window'])
		return False
	data = self.db.Loan.select_by(person_id=person.person_id)
	if len(data)>0:
		has_history = True
		has_history_msg = _("This person has data in the loan history. This data will be erased if you continue.")
	response = gutils.question(self,_("%s\nAre you sure you want to delete this person?" % has_history_msg), \
		1, self.widgets['people']['window'])

	if response == -8:
		treeselection = self.widgets['people']['treeview'].get_selection()
		(tmp_model, tmp_iter) = treeselection.get_selected()
		if person.remove_from_db():
			self.p_treemodel.remove(tmp_iter)
			self.treeview_clicked()
	self.widgets['people']['window'].present()
    def run(self):
        basedir = None
        if self.config is not None:
            basedir = self.config.get('export_dir', None, section='export-csv')
        if not basedir:
            filename = gutils.file_chooser(_("Export a %s document")%"CSV", action=gtk.FILE_CHOOSER_ACTION_SAVE, \
                buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK), name='griffith_list.csv')
        else:
            filename = gutils.file_chooser(_("Export a %s document")%"CSV", action=gtk.FILE_CHOOSER_ACTION_SAVE, \
                buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE,gtk.RESPONSE_OK), name='griffith_list.csv', folder=basedir)
        if filename and filename[0]:
            if self.config is not None and filename[1]:
                self.config.set('export_dir', filename[1], section='export-csv')
                self.config.save()
            overwrite = None
            if os.path.isfile(filename[0]):
                if gutils.question(_("File exists. Do you want to overwrite it?"), self.parent_window):
                    overwrite = True
                else:
                    overwrite = False
            
            if overwrite or overwrite is None:
                movies = self.get_query().execute()

                writer = csv.writer(file(filename[0], 'w'), dialect=csv.excel)
                # write column header row
                writer.writerow(self.fields_to_export)
                # write data rows
                for movie in movies:
                    t = []
                    for s in self.exported_columns:
                        t.append(movie[s])
                    writer.writerow(t)
                gutils.info(_("%s file has been created.") % "CSV", self.parent_window)
    def do_test_searchplugin(self, plugin_name, domsgbox=True):
        result = True

        plugin = __import__(plugin_name)
        try:
            pluginTestConfig = plugin.SearchPluginTest()
        except:
            print "Warning: SearchPlugin test could not be executed for %s because of missing configuration class SearchPluginTest." % plugin_name
            pluginTestConfig = None

        if not pluginTestConfig == None:
            logFile = open(plugin_name + "-searchtest.txt", "w+")
            try:
                for i in pluginTestConfig.test_configuration:
                    searchPlugin = plugin.SearchPlugin()
                    if not self.test_search(
                        searchPlugin,
                        logFile,
                        i,
                        pluginTestConfig.test_configuration[i][0],
                        pluginTestConfig.test_configuration[i][1],
                    ):
                        result = False
                    sleep(1)  # needed for amazon
            finally:
                logFile.close()

        if domsgbox:
            if not result:
                gutils.error(self, "SearchPluginTest %s: Test NOT successful !" % plugin_name)
            else:
                gutils.info("SearchPluginTest %s: Test successful !" % plugin_name)

        return result
Пример #23
0
 def do_test(self, domsgbox=True):
     global myconfig
     self._tmp_home = None
     home_dir, config_name = gconsole.check_args()
     if not (config_name.find('/') >= 0 or config_name.find('\\') >= 0):
         config_name = os.path.join(home_dir, config_name)
     log.debug("config file used: %s", config_name)
     myconfig = config.Config(file=config_name)
     initialize.locations(self, home_dir)
     gettext.install('griffith', self.locations['i18n'], unicode=1)
     search_successful = ''
     search_unsuccessful = ''
     get_successful = ''
     get_unsuccessful = ''
     # test all plugins ?
     test_all = True
     dialog = gtk.MessageDialog(
         None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
         gtk.MESSAGE_QUESTION, gtk.BUTTONS_NONE, 'Test all plugins ?')
     dialog.add_buttons(gtk.STOCK_YES, gtk.RESPONSE_YES, gtk.STOCK_NO,
                        gtk.RESPONSE_NO)
     dialog.set_default_response(gtk.RESPONSE_NO)
     dialog.set_skip_taskbar_hint(False)
     response = dialog.run()
     dialog.destroy()
     if not response == gtk.RESPONSE_YES:
         test_all = False
     # iterate through all testable plugins
     for i in self.test_plugins:
         if domsgbox and test_all == False:
             # ask for test of that specific plugin
             dialog = gtk.MessageDialog(
                 None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                 gtk.MESSAGE_QUESTION, gtk.BUTTONS_NONE,
                 'Test plugin %s ?' % i)
             dialog.add_buttons(gtk.STOCK_YES, gtk.RESPONSE_YES,
                                gtk.STOCK_NO, gtk.RESPONSE_NO)
             dialog.set_default_response(gtk.RESPONSE_NO)
             dialog.set_skip_taskbar_hint(False)
             response = dialog.run()
             dialog.destroy()
             if not response == gtk.RESPONSE_YES:
                 continue
         print "Starting test of plugin: %s" % i
         plugin = __import__(i)
         # search test
         if self.do_test_searchplugin(i, False):
             search_successful = search_successful + i + ', '
         else:
             search_unsuccessful = search_unsuccessful + i + ', '
         # movie test
         if self.do_test_plugin(i, False):
             get_successful = get_successful + i + ', '
         else:
             get_unsuccessful = get_unsuccessful + i + ', '
     if domsgbox:
         gutils.info(
             'SearchPluginTests\n  Success: %s\n  Failed: %s\n\nPluginTests\n  Success: %s\n  Failed: %s'
             % (search_successful, search_unsuccessful, get_successful,
                get_unsuccessful))
Пример #24
0
    def do_test_plugin(self, plugin_name, domsgbox=True):
        result = True

        plugin = __import__(plugin_name)
        try:
            pluginTestConfig = plugin.PluginTest()
        except:
            print "Warning: Plugin test could not be executed for %s because of missing configuration class PluginTest." % plugin_name
            pluginTestConfig = None

        if not pluginTestConfig == None:
            logFile = open(plugin_name + '-loadtest.txt', 'w+')
            try:
                for i in pluginTestConfig.test_configuration:
                    moviePlugin = plugin.Plugin(i)
                    if not self.test_one_movie(
                            moviePlugin, logFile,
                            pluginTestConfig.test_configuration[i]):
                        result = False
                    sleep(1)  # needed for amazon
            finally:
                logFile.close()

        if domsgbox:
            if not result:
                gutils.error('PluginTest %s: Test NOT successful !' %
                             plugin_name)
            else:
                gutils.info('PluginTest %s: Test successful !' % plugin_name)

        return result
    def export_simple_pdf(self):
        """exports a simple movie list to a pdf file"""
        
        myconfig = config.Config()
        if myconfig.get('font', '')!='':
        	self.fontName = "custom_font"
        	pdfmetrics.registerFont(TTFont(self.fontName, myconfig.get('font', '')))
        else:
        	self.fontName = "Helvetica"
        	
        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")
        if filename[0]:
            overwrite = None
            if os.path.isfile(filename[0]):
                response = gutils.question(self,_("File exists. Do you want to overwrite it?"),1,self.parent)
                if response==-8:
                    overwrite = True
                else:
                    overwrite = False
                    
            if overwrite == True or overwrite == None:        
                c = SimpleDocTemplate(filename[0])    
                style = self.styles["Normal"]        
                Story = [Spacer(1,2*inch)]
                # define some custom stylesheetfont
                total = self.db.count_records('movies')
                p = Paragraph("<font name='" + self.fontName +"' size=\"18\">" + saxutils.escape((_("List of films")).encode('utf-8')) + '</font>', self.styles["Heading1"] )
                Story.append(p)
                Story.append(Paragraph(" ",style))
                p = Paragraph("<font name='" + self.fontName +"' size=\"10\">" + saxutils.escape((_("Total Movies: %s") % str(total)).encode('utf-8'))  + '</font>', self.styles["Heading3"])
                Story.append(p)
                Story.append(Paragraph(" ",style))
                data = self.db.get_all_data(order_by="number ASC")
                for row in data:
                    number = str(row['number'])
		    number = number.encode('utf-8')
                    original_title = str(row['original_title'])
                    original_title = original_title.encode('utf-8')
                    title = str(row['title'])
                    title = title.encode('utf-8')
                    if row['year']:
                        year = ' - ' + str(row['year'])
                    else:
                        year = ""
		    year = year.encode('utf-8')
                    if row['director']:
                        director = ' - ' + str(row['director'])
                    else:
                        director = ""
                    director = director.encode('utf-8')
                    p = Paragraph("<font name=" + self.fontName + " size=\"7\">" + \
                        saxutils.escape(number + " | " + original_title) + \
                        "</font><font name=" + self.fontName + " size=\"7\">" + \
                        saxutils.escape(" (" + title + ")" + year + director) + \
                        "</font>", self.styles["Normal"])
                    Story.append(p)
                c.build(Story, onFirstPage=self.page_template, onLaterPages=self.page_template)
                gutils.info(self, _("PDF has been created."), self.parent)
Пример #26
0
 def run(self):
     if self.show_dialog() == True:
         # create xml document
         impl = xml.dom.minidom.getDOMImplementation()
         doc  = impl.createDocument(None, None, None)
         self.export_to_document(doc, doc.documentElement)
         # write xml document to file
         self.export_document_to_file(doc, self.filepath)
         gutils.info(_('%s file has been created.') % self.export_name, self.parent_window)
Пример #27
0
 def do_test(self, domsgbox=True):
     global myconfig
     self._tmp_home = None
     home_dir, config_name = gconsole.check_args()
     if not (config_name.find('/') >= 0 or config_name.find('\\') >= 0):
         config_name = os.path.join(home_dir, config_name)
     log.debug("config file used: %s", config_name)
     myconfig = config.Config(file=config_name)
     initialize.locations(self, home_dir)
     gettext.install('griffith', self.locations['i18n'], unicode=1)
     search_successful = ''
     search_unsuccessful = ''
     get_successful = ''
     get_unsuccessful = ''
     # test all plugins ?
     test_all = True
     dialog = gtk.MessageDialog(None,
         gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
         gtk.MESSAGE_QUESTION, gtk.BUTTONS_NONE, 'Test all plugins ?')
     dialog.add_buttons(gtk.STOCK_YES, gtk.RESPONSE_YES,
         gtk.STOCK_NO, gtk.RESPONSE_NO)
     dialog.set_default_response(gtk.RESPONSE_NO)
     dialog.set_skip_taskbar_hint(False)
     response = dialog.run()
     dialog.destroy()
     if not response == gtk.RESPONSE_YES:
         test_all = False
     # iterate through all testable plugins
     for i in self.test_plugins:
         if domsgbox and test_all == False:
             # ask for test of that specific plugin
             dialog = gtk.MessageDialog(None,
                 gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                 gtk.MESSAGE_QUESTION, gtk.BUTTONS_NONE, 'Test plugin %s ?' %i)
             dialog.add_buttons(gtk.STOCK_YES, gtk.RESPONSE_YES,
                 gtk.STOCK_NO, gtk.RESPONSE_NO)
             dialog.set_default_response(gtk.RESPONSE_NO)
             dialog.set_skip_taskbar_hint(False)
             response = dialog.run()
             dialog.destroy()
             if not response == gtk.RESPONSE_YES:
                 continue
         print "Starting test of plugin: %s" % i
         plugin = __import__(i)
         # search test
         if self.do_test_searchplugin(i, False):
             search_successful = search_successful + i + ', '
         else:
             search_unsuccessful = search_unsuccessful + i + ', '
         # movie test
         if self.do_test_plugin(i, False):
             get_successful = get_successful + i + ', '
         else:
             get_unsuccessful = get_unsuccessful + i + ', '
     if domsgbox:
         gutils.info('SearchPluginTests\n  Success: %s\n  Failed: %s\n\nPluginTests\n  Success: %s\n  Failed: %s' % (search_successful, search_unsuccessful, get_successful, get_unsuccessful))
	def do_test(self, domsgbox=True):
		global debug, myconfig
		debug = self.debug = gdebug.GriffithDebug()
		#self.debug.set_debug(True)
		self._tmp_home = None
		self._tmp_config = 'griffith.cfg'
		initialize.locations(self)
		gettext.install('griffith', self.locations['i18n'], unicode=1)
		configFileName = os.path.join(self.locations['home'], self._tmp_config)
		myconfig = self.config = config.Config(file=configFileName)
		search_successful = ''
		search_unsuccessful = ''
		get_successful = ''
		get_unsuccessful = ''
		# test all plugins ?
		test_all = True
		dialog = gtk.MessageDialog(None,
			gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
			gtk.MESSAGE_QUESTION, gtk.BUTTONS_NONE, 'Test all plugins ?')
		dialog.add_buttons(gtk.STOCK_YES, gtk.RESPONSE_YES,
			gtk.STOCK_NO, gtk.RESPONSE_NO)
		dialog.set_default_response(gtk.RESPONSE_NO)
		dialog.set_skip_taskbar_hint(False)
		response = dialog.run()
		dialog.destroy()
		if not response == gtk.RESPONSE_YES:
			test_all = False
		# iterate through all testable plugins
		for i in self.test_plugins:
			if domsgbox and test_all == False:
				# ask for test of that specific plugin
				dialog = gtk.MessageDialog(None,
					gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
					gtk.MESSAGE_QUESTION, gtk.BUTTONS_NONE, 'Test plugin %s ?' %i)
				dialog.add_buttons(gtk.STOCK_YES, gtk.RESPONSE_YES,
					gtk.STOCK_NO, gtk.RESPONSE_NO)
				dialog.set_default_response(gtk.RESPONSE_NO)
				dialog.set_skip_taskbar_hint(False)
				response = dialog.run()
				dialog.destroy()
				if not response == gtk.RESPONSE_YES:
					continue
			plugin = __import__(i)
			# search test
			if self.do_test_searchplugin(i, False):
				search_successful = search_successful + i + ', '
			else:
				search_unsuccessful = search_unsuccessful + i + ', '
			# movie test
			if self.do_test_plugin(i, False):
				get_successful = get_successful + i + ', '
			else:
				get_unsuccessful = get_unsuccessful + i + ', '
		if domsgbox:
			gutils.info(self, 'SearchPluginTests\n  Success: %s\n  Failed: %s\n\nPluginTests\n  Success: %s\n  Failed: %s' % (search_successful, search_unsuccessful, get_successful, get_unsuccessful))
Пример #29
0
    def open_source(self):
        import csv
        import codecs

        # get user values for converting/opening the csv-file
        self.start_row = int(digits_only(self.gtk.get_widget("e_startrow").get_text()))
        encoding = self.gtk.get_widget("e_encoding").get_active_text()
        encoding = encoding[: string.find(encoding, " ")]
        delimiter = self.gtk.get_widget("e_delimiter").get_text()
        if delimiter == "":
            delimiter = ","
        # quotechar
        quotechar = self.gtk.get_widget("e_quotechar").get_text()
        if quotechar == "":
            quotechar == '"'
        # lineterminator
        active = self.gtk.get_widget("e_lineterminator").get_active()
        # default for none selected and the same for linux and macintosh
        lineterminator = "\r"
        # windows lineterminator
        if active == 1:
            lineterminator = "\r\n"

        # open file
        try:
            self.data = csv.reader(
                codecs.open(self.__source_name, "r", encoding),
                dialect="excel",
                quotechar=quotechar,
                delimiter=delimiter,
                lineterminator=lineterminator,
            )

            # get the first line in csv file for the field names
            self.csv_header = self.data.next()

            # if the user wants to import line 0 then we have to open it again
            if self.start_row == 0:
                self.data = csv.reader(
                    codecs.open(self.__source_name, "r", encoding),
                    dialect="excel",
                    quotechar=quotechar,
                    delimiter=delimiter,
                    lineterminator=lineterminator,
                )

            # fill the found csv-headers in the simple string list
            self.ls_csv.clear()
            for name in self.csv_header:
                iterator = self.ls_csv.append()
                self.ls_csv.set_value(iterator, 0, name)
            return True
        except:
            gutils.info(_("Can't open the file %s") % self.__source_name, self.gtk.get_widget("d_import"))
            return False
Пример #30
0
    def open_source(self):
        import csv
        import codecs
        # get user values for converting/opening the csv-file
        self.start_row = int(
            digits_only(self.gtk.get_widget('e_startrow').get_text()))
        encoding = self.gtk.get_widget('e_encoding').get_active_text()
        encoding = encoding[:string.find(encoding, ' ')]
        delimiter = self.gtk.get_widget('e_delimiter').get_text()
        if delimiter == '':
            delimiter = ","
        # quotechar
        quotechar = self.gtk.get_widget('e_quotechar').get_text()
        if quotechar == '':
            quotechar == '"'
        # lineterminator
        active = self.gtk.get_widget('e_lineterminator').get_active()
        # default for none selected and the same for linux and macintosh
        lineterminator = '\r'
        # windows lineterminator
        if active == 1:
            lineterminator = '\r\n'

        # open file
        try:
            self.data = csv.reader(codecs.open(self.__source_name, 'r',
                                               encoding),
                                   dialect='excel',
                                   quotechar=quotechar,
                                   delimiter=delimiter,
                                   lineterminator=lineterminator)

            # get the first line in csv file for the field names
            self.csv_header = self.data.next()

            # if the user wants to import line 0 then we have to open it again
            if self.start_row == 0:
                self.data = csv.reader(codecs.open(self.__source_name, 'r',
                                                   encoding),
                                       dialect='excel',
                                       quotechar=quotechar,
                                       delimiter=delimiter,
                                       lineterminator=lineterminator)

            # fill the found csv-headers in the simple string list
            self.ls_csv.clear()
            for name in self.csv_header:
                iterator = self.ls_csv.append()
                self.ls_csv.set_value(iterator, 0, name)
            return True
        except:
            gutils.info(
                _("Can't open the file %s") % self.__source_name,
                self.gtk.get_widget('d_import'))
            return False
Пример #31
0
 def run(self):
     if self.show_dialog() == True:
         # create xml document
         impl = xml.dom.minidom.getDOMImplementation()
         doc = impl.createDocument(None, None, None)
         self.export_to_document(doc, doc.documentElement)
         # write xml document to file
         self.export_document_to_file(doc, self.filepath)
         gutils.info(
             _('%s file has been created.') % self.export_name,
             self.parent_window)
Пример #32
0
    def _clicked(self, widget, event=None, data=None):
        if widget == self.b_cancel:
            self.gtk.get_widget('d_import').hide()
            self.gtk.get_widget('d_import').response(gtk.RESPONSE_CANCEL)

        if widget == self.b_back:
            if self.nb_pages.get_current_page() == 1:
                self.nb_pages.prev_page()

        if widget == self.b_next:
            if self.nb_pages.get_current_page() == 0:
                self.nb_pages.get_nth_page(1).show()
                self.nb_pages.next_page()
            else:
                if self.nb_pages.get_current_page() == 1:
                    # test if at least one field is assigned
                    if self.ls_assigned.get_iter_first() is not None:
                        # prepare tabelle for import
                        self.create_import_table()
                        # hide everything
                        self.gtk.get_widget('d_import').hide()
                        self.gtk.get_widget('d_import').response(
                            gtk.RESPONSE_OK)
                    else:
                        gutils.info(
                            _("Please assign at least one field first!"),
                            self.gtk.get_widget('d_import'))

        if widget == self.b_add:
            iterator = self.ls_assigned.append()
            self.ls_assigned.set_value(
                iterator, 0, "%s > %s" %
                (self.selected_csv, self.fields[self.selected_griffith]))
            # add information for the import tabelle
            self.ls_assigned.set_value(iterator, 1, self.selected_griffith)
            self.ls_assigned.set_value(
                iterator, 2, str(self.csv_header.index(self.selected_csv)))
            self.ls_griffith.remove(self.iter_griffith)
            self.selected_griffith = None

            self.b_add.set_sensitive(False)

        if widget == self.b_del:
            # re-add field to griffith
            field_name = self.ls_assigned.get_value(self.iter_assigned, 1)

            iterator = self.ls_griffith.append()
            self.ls_griffith.set_value(iterator, 0, field_name)
            self.ls_griffith.set_value(iterator, 1, self.fields[field_name])

            # remove assigned row
            self.ls_assigned.remove(self.iter_assigned)

            self.b_del.set_sensitive(False)
 def run(self):
     basedir = None
     if self.config is not None:
         basedir = self.config.get('export_dir', None, section='export-xml')
     if basedir is None:
         filename = gutils.file_chooser(_("Export a %s document")%"XML", action=gtk.FILE_CHOOSER_ACTION_SAVE, \
             buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_SAVE,gtk.RESPONSE_OK),name='griffith_list.xml')
     else:
         filename = gutils.file_chooser(_("Export a %s document")%"XML", action=gtk.FILE_CHOOSER_ACTION_SAVE, \
             buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_SAVE,gtk.RESPONSE_OK),name='griffith_list.xml',folder=basedir)
     if filename and filename[0]:
         if self.config is not None and filename[1]:
             self.config.set('export_dir', filename[1], section='export-xml')
             self.config.save()
         overwrite = None
         if os.path.isfile(filename[0]):
             response = gutils.question(_("File exists. Do you want to overwrite it?"), True, self.parent_window)
             if response==-8:
                 overwrite = True
             else:
                 overwrite = False
                 
         if overwrite or overwrite is None:
             # create document
             impl = xml.dom.minidom.getDOMImplementation()
             doc  = impl.createDocument(None, "root", None)
             root = doc.documentElement
             
             movies = self.get_query().execute().fetchall()
             # create object
             for movie in movies:
                 e = doc.createElement('movie')
                 root.appendChild(e)
                 for key in self.exported_columns:
                     e2 = doc.createElement(str(key).replace('movies_', ''))
                     if movie[key] is None:
                         value = ''
                     elif movie[key] in (True, False):
                         value = str(int(movie[key]))
                     else:
                         if movie[key] is unicode:
                             value = movie[key].encode('utf-8')
                         else:
                             value = str(movie[key])
                     t = doc.createTextNode(value)
                     e2.appendChild(t)
                     e.appendChild(e2)
                 
             # write XML to file
             fp = open(filename[0], "w")
             xml.dom.ext.PrettyPrint(doc, fp)
             fp.close()
             gutils.info( _("%s file has been created.")%"XML", self.parent_window)
Пример #34
0
def loan_movie(self):
	data = self.db.get_all_data("people","name ASC")
	model = gtk.ListStore(str)
	if data:
		for row in data:
			model.append([row['name']])
		self.loan_to.set_model(model)
		self.loan_to.set_text_column(0)
		self.loan_to.set_active(0)
		self.w_loan_to.show()
	else:
		gutils.info(self, _("No person is defined yet."), self.main_window)
    def export_simple_pdf(self):
        """exports a simple movie list to a pdf file"""
        
        myconfig = config.Config(os.path.join(self.locations['home'], 'griffith.conf'))
        if myconfig.get('font', '')!='':
                self.fontName = "custom_font"
                pdfmetrics.registerFont(TTFont(self.fontName, myconfig.get('font', '')))
        else:
                self.fontName = "Helvetica"

        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")
        if filename[0]:
            overwrite = None
            if os.path.isfile(filename[0]):
                response = gutils.question(self,_("File exists. Do you want to overwrite it?"),1,self.parent)
                if response==-8:
                    overwrite = True
                else:
                    overwrite = False
                    
            if overwrite == True or overwrite is None:
                c = SimpleDocTemplate(filename[0])
                style = self.styles["Normal"]
                Story = [Spacer(1,2*inch)]
                # define some custom stylesheetfont
                total = self.db.Movie.count()
                p = Paragraph("<font name='" + self.fontName +"' size=\"18\">" + saxutils.escape((_("List of films")).encode('utf-8')) + '</font>', self.styles["Heading1"] )
                Story.append(p)
                Story.append(Paragraph(" ",style))
                p = Paragraph("<font name='" + self.fontName +"' size=\"10\">" + saxutils.escape((_("Total Movies: %s") % str(total)).encode('utf-8'))  + '</font>', self.styles["Heading3"])
                Story.append(p)
                Story.append(Paragraph(" ",style))
                movies = self.db.Movie.select()
		for movie in movies:
                    number = movie.number
                    original_title = str(movie.o_title)
                    title = str(movie.title)
                    if movie.year:
                        year = ' - ' + str(movie.year)
                    else:
                        year = ""
                    if movie.director:
                        director = ' - ' + str(movie.director)
                    else:
                        director = ""
                    p = Paragraph("<font name=" + self.fontName + " size=\"7\">" + \
                        saxutils.escape(str(number) + " | " + original_title) + \
                        "</font><font name=" + self.fontName + " size=\"7\">" + \
                        saxutils.escape(" (" + title + ")" + year + director) + \
                        "</font>", self.styles["Normal"])
                    Story.append(p)
                c.build(Story, onFirstPage=self.page_template, onLaterPages=self.page_template)
                gutils.info(self, _("PDF has been created."), self.parent)
Пример #36
0
def loan_movie(self):
	people = self.db.Person.select(order_by='name ASC')
	model = gtk.ListStore(str)
	if len(people)>0:
		for person in people:
			model.append([person.name])
		self.widgets['movie']['loan_to'].set_model(model)
		self.widgets['movie']['loan_to'].set_text_column(0)
		self.widgets['movie']['loan_to'].set_active(0)
		self.widgets['w_loan_to'].show()
	else:
		gutils.info(self, _("No person is defined yet."), self.widgets['window'])
Пример #37
0
def loan_movie(self):
    people = self.db.session.query(db.Person.name).order_by(db.Person.name.asc()).all()
    model = gtk.ListStore(str)
    if len(people)>0:
        for person in people:
            model.append([person.name])
        self.widgets['movie']['loan_to'].set_model(model)
        self.widgets['movie']['loan_to'].set_text_column(0)
        self.widgets['movie']['loan_to'].set_active(0)
        self.widgets['w_loan_to'].show()
    else:
        gutils.info(_("No person is defined yet."), self.widgets['window'])
Пример #38
0
def loan_movie(self):
    people = self.db.session.query(db.Person.name).order_by(
        db.Person.name.asc()).all()
    model = gtk.ListStore(str)
    if len(people) > 0:
        for person in people:
            model.append([person.name])
        self.widgets['movie']['loan_to'].set_model(model)
        self.widgets['movie']['loan_to'].set_text_column(0)
        self.widgets['movie']['loan_to'].set_active(0)
        self.widgets['w_loan_to'].show()
    else:
        gutils.info(_("No person is defined yet."), self.widgets['window'])
Пример #39
0
def save(gsql, widgets):
    """saves search conditions from current filter window"""

    cond = get_conditions(widgets)
    name = widgets['cb_name'].get_active_text().decode('utf-8')
    if not name:
        log.debug("search rule name is empty")
        info(_("Name is empty"), widgets['window'])
        return False

    if sql.save_conditions(gsql, name, cond):
        info(_("Search conditions saved"), widgets['window'])
    else:
        warning(_("Cannot save search conditions"), widgets['window'])
Пример #40
0
    def _clicked(self, widget, event=None, data=None):
        if widget == self.b_cancel:
            self.gtk.get_widget("d_import").hide()
            self.gtk.get_widget("d_import").response(gtk.RESPONSE_CANCEL)

        if widget == self.b_back:
            if self.nb_pages.get_current_page() == 1:
                self.nb_pages.prev_page()

        if widget == self.b_next:
            if self.nb_pages.get_current_page() == 0:
                self.nb_pages.get_nth_page(1).show()
                self.nb_pages.next_page()
            else:
                if self.nb_pages.get_current_page() == 1:
                    # test if at least one field is assigned
                    if self.ls_assigned.get_iter_first() is not None:
                        # prepare tabelle for import
                        self.create_import_table()
                        # hide everything
                        self.gtk.get_widget("d_import").hide()
                        self.gtk.get_widget("d_import").response(gtk.RESPONSE_OK)
                    else:
                        gutils.info(_("Please assign at least one field first!"), self.gtk.get_widget("d_import"))

        if widget == self.b_add:
            iterator = self.ls_assigned.append()
            self.ls_assigned.set_value(
                iterator, 0, "%s > %s" % (self.selected_csv, self.fields[self.selected_griffith])
            )
            # add information for the import tabelle
            self.ls_assigned.set_value(iterator, 1, self.selected_griffith)
            self.ls_assigned.set_value(iterator, 2, str(self.csv_header.index(self.selected_csv)))
            self.ls_griffith.remove(self.iter_griffith)
            self.selected_griffith = None

            self.b_add.set_sensitive(False)

        if widget == self.b_del:
            # re-add field to griffith
            field_name = self.ls_assigned.get_value(self.iter_assigned, 1)

            iterator = self.ls_griffith.append()
            self.ls_griffith.set_value(iterator, 0, field_name)
            self.ls_griffith.set_value(iterator, 1, self.fields[field_name])

            # remove assigned row
            self.ls_assigned.remove(self.iter_assigned)

            self.b_del.set_sensitive(False)
	def export_xml(self):
		basedir = None
		if not self.persistent_config is None:
			basedir = self.persistent_config.get('export_dir', None, section='export-xml')
		if basedir is None:
			filename = gutils.file_chooser(_("Export a %s document")%"XML", action=gtk.FILE_CHOOSER_ACTION_SAVE, \
				buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_SAVE,gtk.RESPONSE_OK),name='griffith_list.xml')
		else:
			filename = gutils.file_chooser(_("Export a %s document")%"XML", action=gtk.FILE_CHOOSER_ACTION_SAVE, \
				buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_SAVE,gtk.RESPONSE_OK),name='griffith_list.xml',folder=basedir)
		if filename[0]:
			if not self.persistent_config is None and filename[1]:
				self.persistent_config.set('export_dir', filename[1], section='export-xml')
				self.persistent_config.save()
			overwrite = None
			if os.path.isfile(filename[0]):
				response = gutils.question(self, _("File exists. Do you want to overwrite it?"), 1, self.parent)
				if response==-8:
					overwrite = True
				else:
					overwrite = False
					
			if overwrite == True or overwrite is None:
				# create document
				impl = xml.dom.minidom.getDOMImplementation()
				doc  = impl.createDocument(None, "root", None)
				root = doc.documentElement
				
				# create object
				for movie in self.db.Movie.select():
					e = doc.createElement('movie')
					root.appendChild(e)
					for key in movie.c.keys():
						e2 = doc.createElement(key)
						if movie[key] is None:
							value = ''
						elif movie[key] in (True, False):
							value = str(int(movie[key]))
						else:
							value = str(movie[key])
						t = doc.createTextNode(value)
						e2.appendChild(t)
						e.appendChild(e2)
					
				# write XML to file
				fp = open(filename[0], "w")
				xml.dom.ext.PrettyPrint(doc, fp)
				fp.close()
				gutils.info(self, _("%s file has been created.")%"XML", self.parent)
Пример #42
0
def convert_from_old_db(self, source_file, destination_file):	#{{{
	print 'Converting old database - it can take several minutes...'
	gutils.info(self,_("Griffith will now convert your database to the new format. This can take several minutes if you have a large database."))
	from sqlalchemy.orm import clear_mappers
	from sql import GriffithSQL
	from gutils import digits_only
	import os

	if not os.path.isfile(source_file):
		return False
	if open(source_file).readline()[:47] == '** This file contains an SQLite 2.1 database **':
		try:
			import sqlite
			from sqlite import DatabaseError
		except ImportError:
			print 'Old DB conversion: please install pysqlite legacy (v1.0)'
			gutils.warning(self,_("Old DB conversion: please install pysqlite legacy (v1.0)"))
			return False
	else:
		try:	# Python 2.5
			from sqlite3 import dbapi2 as sqlite
			from sqlite3.dbapi2 import DatabaseError
		except ImportError: # Python < 2.5 - try to use pysqlite2
			from pysqlite2 import dbapi2 as sqlite
			from pysqlite2.dbapi2 import DatabaseError

	if os.path.isfile(destination_file):
		# rename destination_file if it already exist
		i = 1
		while True:
			if os.path.isfile("%s_%s" % (destination_file, i)):
				i += 1
			else:
				break
		os.rename(destination_file, "%s_%s" % (destination_file, i))

	try:
		old_db = sqlite.connect(source_file)
	except DatabaseError, e:
		if str(e) == 'file is encrypted or is not a database':
			print 'Your database is most probably in wrong SQLite format, please convert it to SQLite3:'
			print '$ sqlite ~/.griffith/griffith.gri .dump | sqlite3 ~/.griffith/griffith.gri3'
			print '$ mv ~/.griffith/griffith.gri{,2}'
			print '$ mv ~/.griffith/griffith.gri{3,}'
			print 'or install pysqlite in version 1.0'
			gutils.warning(self,_("Your database is most probably in SQLite2 format, please convert it to SQLite3"))
		else:
			raise
		return False
Пример #43
0
    def run(self):
        basedir = None
        if self.config is not None:
            basedir = self.config.get('export_dir', None, section='export-csv')
        if not basedir:
            filename = gutils.file_chooser(_("Export a %s document")%"CSV", action=gtk.FILE_CHOOSER_ACTION_SAVE, \
                buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK), name='griffith_list.csv')
        else:
            filename = gutils.file_chooser(_("Export a %s document")%"CSV", action=gtk.FILE_CHOOSER_ACTION_SAVE, \
                buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE,gtk.RESPONSE_OK), name='griffith_list.csv', folder=basedir)
        if filename and filename[0]:
            if self.config is not None and filename[1]:
                self.config.set('export_dir',
                                filename[1],
                                section='export-csv')
                self.config.save()
            overwrite = None
            if os.path.isfile(filename[0]):
                if gutils.question(
                        _("File exists. Do you want to overwrite it?"),
                        self.parent_window):
                    overwrite = True
                else:
                    overwrite = False

            if overwrite or overwrite is None:
                movies = self.get_query().execute()

                writer = csv.writer(file(filename[0], 'w'), dialect=csv.excel)
                # write column header row
                writer.writerow(self.fields_to_export)
                # write data rows
                for movie in movies:
                    t = []
                    for s in self.exported_columns:
                        t.append(movie[s])
                    writer.writerow(t)
                gutils.info(
                    _("%s file has been created.") % "CSV", self.parent_window)
Пример #44
0
def send_email(self):
    if len(self.person_email):
        if self.config.get('use_auth', False, section='mail') == True:
            use_auth = 1
        else:
            use_auth = 0
        try:
            mailto(self, self.config.get('mail_use_tls', False, section='mail'), \
                self.config.get('mail_smtp_port', '25', section='mail'), \
                self.config.get('smtp_server', 'localhost', section='mail'), \
                use_auth, self.config.get('username', '', section='mail'), \
                self.config.get('password', '', section='mail'), \
                self.config.get('email', 'griffith', section='mail'), self.person_email, \
                _("Movie loan reminder"), _("Hi, %s!\n\nJust to remind you that I'm really needing the following movie I have loaned to you recently:\n\n%s (%s)\n\nLoaned on %s") \
                %(self.person_name, self.widgets['movie']['o_title'].get_text().decode('utf-8'), \
                self.widgets['movie']['title'].get_text().decode('utf-8'), self.loan_date[:10]))
        except:
            gutils.error(
                _("Mail could not be sent. Please check e-mail preferences."),
                self.widgets['window'])
    else:
        gutils.info(_("This person has no e-mail address defined."), \
            self.widgets['window'])
Пример #45
0
    def run(self):
        tmp_dir = mkdtemp()
        griffith_list = open(os.path.join(tmp_dir, "movies"), "w")
        t = []

        def checkForNoneAndEncode(val):
            if val is None:
                return ''
            return val.encode('utf-8')

        movies = self.get_query().execute().fetchall()
        for movie in movies:
            t.append("%s | %s | %s | %s" % (movie['number'], \
                checkForNoneAndEncode(movie['o_title']),
                checkForNoneAndEncode(movie['title']),
                checkForNoneAndEncode(movie['director'])))

        griffith_list.write("<title>%s</title><br><br>" % _("My Movies List"))

        for movie in t:
            griffith_list.write(movie)
            griffith_list.write("<br>")

        griffith_list.close()

        # this is a mac, lets export to iPod's notes folder
        # TODO: windows and linux iPod autodetection
        if platform.system() == 'Darwin':
            thisPod = Path2iPod()
            thisPath = thisPod.returnPath()

            if thisPath:
                commands.getoutput('mv ' + os.path.join(tmp_dir, "movies") +
                                   ' "' + thisPath + '/Notes/"')  # FIXME: WTF?
                gutils.info(_("List successfully exported to iPod."),
                            self.parent_window)
            else:
                gutils.info(_("iPod is not connected."), self.parent_window)
        # this is not a mac, lets save the file
        else:
            filename = gutils.file_chooser(_("Export a %s document")%"iPod", action=gtk.FILE_CHOOSER_ACTION_SAVE, \
                buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_SAVE,gtk.RESPONSE_OK),name='ipod_griffith_list')
            if filename and filename[0]:
                overwrite = None
                if os.path.isfile(filename[0]):
                    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:
                    shutil.copyfile(os.path.join(tmp_dir, "movies"),
                                    filename[0])
                    gutils.info(
                        _("The list was successfully exported. Now you should move it to the 'Notes' folder on your iPod."
                          ), self.parent_window)
Пример #46
0
    def toolbar_icon_clicked(self, widget, movie):
        #
        # remove unused posters
        #
        session = self.db.Session()
        delete_posters = delete(posters_table)
        delete_posters = delete_posters.where(not_(exists([movies_table.c.movie_id], and_(posters_table.c.md5sum==movies_table.c.poster_md5)).correlate(posters_table)))
        log.debug(delete_posters)
        session.execute(delete_posters)
        session.commit()
        #
        # compressing sqlite databases
        #
        if self.app.config.get('type', 'sqlite', section='database') == 'sqlite':
            databasefilename = "%s.db" % os.path.join(self.app.locations['home'], self.app.config.get('name', section='database'))
            pagesize = gutils.get_filesystem_pagesize(databasefilename)

            # works since sqlite 3.5.8
            # python 2.5 doesn't include 3.x but perhaps in future versions
            # another way is the installation of pysqlite2 with 2.5.6/2.6.0 or higher
            try:
                from pysqlite2 import dbapi2 as sqlite3

                con = sqlite3.connect(databasefilename)
                try:
                    con.isolation_level = None
                    cur = con.cursor()
                    cur.execute('PRAGMA page_size=' + str(pagesize))
                    cur.execute('VACUUM;')
                finally:
                    con.close()
            except:
                log.error('fallback to default driver')
                self.app.db.engine.execute('PRAGMA page_size=' + str(pagesize))
                self.app.db.engine.execute('VACUUM;')
        gutils.info(_("Finished"))
Пример #47
0
                exported_file.close()
                page = page + 1
                item = 1
                tmp2 = None
            else:
                item = item + 1
            i = i + 1
        #}}}
        if fields['movies_image']:
            # convert/copy the griffith picture for movies without a poster
            image_file_src = os.path.join(self.locations['images'],
                                          'griffith.png')
            image_file_dst = os.path.join(
                posters_dir, 'nopic.' + config['poster_format'].lower())
            try:
                if config['poster_convert']:
                    im = Image.open(image_file_src,
                                    'r').convert(config['poster_mode'])
                    im.thumbnail(
                        (config['poster_width'], config['poster_height']),
                        Image.ANTIALIAS)
                else:
                    im = Image.open(image_file_src, 'r')
                im.save(image_file_dst, config['poster_format'])
            except:
                log.info("Can't convert %s" % image_file_src)
        gutils.info(_("Document has been generated."), self.widgets['window'])
        self.on_quit()

    #}}}
Пример #48
0
        isnew = False
    else:
        filter_ = db.Filter(name=name, data=cond)
        isnew = True
    session.add(filter_)
    try:
        session.commit()
    except Exception, e:
        session.rollback()
        log.warn(e)
        warning(_("Cannot save search conditions"), widgets['window'])
        return False
    else:
        if isnew:
            widgets['cb_name'].append_text(name)
    info(_("Search conditions saved"), widgets['window'])


def load(gsql, widgets, field_names):
    name = widgets['cb_name'].get_active_text().decode('utf-8')
    if not name:
        log.debug("search rule name is empty")
        return False
    cond = gsql.session.query(db.Filter).filter_by(name=name).first().data
    if cond:
        return set_conditions(widgets, cond, field_names)
    else:
        return False


def delete(gsql, widgets):
Пример #49
0
    def run(self):
        basedir = None
        if self.config is not None:
            basedir = self.config.get('export_dir', None, section='export-xml')
        if basedir is None:
            filename = gutils.file_chooser(_("Export a %s document")%"XML", action=gtk.FILE_CHOOSER_ACTION_SAVE, \
                buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_SAVE,gtk.RESPONSE_OK),name='griffith_list.xml')
        else:
            filename = gutils.file_chooser(_("Export a %s document")%"XML", action=gtk.FILE_CHOOSER_ACTION_SAVE, \
                buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_SAVE,gtk.RESPONSE_OK),name='griffith_list.xml',folder=basedir)
        if filename and filename[0]:
            if self.config is not None and filename[1]:
                self.config.set('export_dir',
                                filename[1],
                                section='export-xml')
                self.config.save()
            overwrite = None
            if os.path.isfile(filename[0]):
                if gutils.question(
                        _("File exists. Do you want to overwrite it?"),
                        self.parent_window):
                    overwrite = True
                else:
                    overwrite = False

            posterdir = os.path.join(os.path.dirname(filename[0]), 'posters')
            if not os.path.exists(posterdir):
                os.mkdir(posterdir)

            if overwrite or overwrite is None:
                # create document
                impl = xml.dom.minidom.getDOMImplementation()
                doc = impl.createDocument(None, "root", None)
                root = doc.documentElement

                movies = self.get_query().execute().fetchall()
                # create object
                for movie in movies:
                    e = doc.createElement('movie')
                    root.appendChild(e)
                    for key in self.exported_columns:
                        e2 = doc.createElement(str(key).replace('movies_', ''))
                        if movie[key] is None:
                            value = ''
                        elif movie[key] in (True, False):
                            value = str(int(movie[key]))
                        else:
                            if movie[key] is unicode:
                                value = movie[key].encode('utf-8')
                            else:
                                value = str(movie[key])
                        t = doc.createTextNode(value)
                        e2.appendChild(t)
                        e.appendChild(e2)
                    # create image file in ./posters/...
                    md5sum = None
                    posterfilepath = ''
                    if 'poster_md5' in self.exported_columns and movie[
                            'poster_md5']:
                        md5sum = movie['poster_md5']
                    if 'movies_poster_md5' in self.exported_columns and movie[
                            'movies_poster_md5']:
                        md5sum = movie['movies_poster_md5']
                    if md5sum:
                        if gutils.create_imagefile(posterdir, md5sum, self.db):
                            posterfilepath = os.path.join(
                                '.', 'posters', md5sum + '.jpg')
                    e2 = doc.createElement('image')
                    # relative path to image related to xml file
                    t = doc.createTextNode(posterfilepath)
                    e2.appendChild(t)
                    e.appendChild(e2)

                # write XML to file
                xmldata = doc.toprettyxml(encoding='utf-8')
                fp = open(filename[0], "w")
                try:
                    fp.write(xmldata)
                finally:
                    fp.close()
                gutils.info(
                    _("%s file has been created.") % "XML", self.parent_window)
Пример #50
0
def restore(self, merge=False):
    """
    Merge database from:
    * compressed backup (*.zip)
    * SQLite2 *.gri file
    * SQLite3 *.db file
    """
    # let user select a backup file
    filename, path = gutils.file_chooser(_("Restore Griffith backup"), \
                action=gtk.FILE_CHOOSER_ACTION_OPEN, backup=True, \
                buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
    if not filename:
        log.debug('no file selected')
        return False

    try:
        tmp_db = None
        tmp_dir = mkdtemp()
        os.mkdir(os.path.join(tmp_dir, 'posters'))
        print filename
        if filename.lower().endswith('.zip'):
            try:
                zip_file = zipfile.ZipFile(filename, 'r')
            except:
                gutils.error(_("Can't read backup file"), self.widgets['window'])
                return False

            old_config_file = False
            # unpack files to temporary directory
            for file_path in zip_file.namelist():
                file_name = os.path.split(file_path)[-1]
                if not os.path.isdir(file_name):
                    if not file_name:
                        log.debug('skipping %s', file_path)
                        continue

                    if 'posters' in file_path:
                        new_file = os.path.join(tmp_dir, 'posters', file_name)
                    else:
                        new_file = os.path.join(tmp_dir, file_name)
                    if file_name.endswith('.conf'):
                        old_config_file = new_file
                    outfile = open(new_file, 'wb')
                    outfile.write(zip_file.read(file_path))
                    outfile.close()
            zip_file.close()

            # restore config file (new one will be created if old config format is detected)
            tmp_config = config.Config(file=os.path.join(tmp_dir, 'griffith.cfg'))
            if old_config_file:
                log.info('Old config file detected. Please note that it will not be used.')
                f = open(old_config_file, 'r')
                old_config_raw_data = f.read()
                f.close()
                if old_config_raw_data.find('griffith.gri') >= -1:
                    tmp_config.set('file', 'griffith.gri', section='database')

            # update filename var. to point to the unpacked database
            filename = os.path.join(tmp_dir, tmp_config.get('name', 'griffith', section='database') + '.db')
        else:  # not a zip file? prepare a fake config file then
            tmp_config = config.Config(file=os.path.join(tmp_dir, 'griffith.cfg'))
            tmp_config.set('type', 'sqlite', section='database')
            tmp_config.set('file', 'griffith.db', section='database')

        # prepare temporary GriffithSQL instance
        locations = {'home': tmp_dir}
        # check if file needs conversion
        if filename.lower().endswith('.gri'):
            from dbupgrade import convert_from_old_db
            tmp_db = convert_from_old_db(tmp_config, filename, os.path.join(tmp_dir, 'griffith.db'), locations)
            if not tmp_db:
                log.info("MERGE: Can't convert database, aborting.")
                return False
        else:
            tmp_db = sql.GriffithSQL(tmp_config, tmp_dir, fallback=False)

        if merge:
            merge_db(tmp_db, self.db)
        else:
            self.db.session.rollback()  # cancel all pending operations
            copy_db(tmp_db.session.bind, self.db.session.bind)
            # update old database section with current config values
            # (important while restoring to external databases)
            for key in ('name', 'passwd', 'host', 'user', 'file', 'type', 'port'):
                tmp_config.set(key, self.config.get(key, section='database'), section='database')
            tmp_config._file = self.config._file
            self.config = tmp_config
            self.config.save()
            dictionaries(self)
            people_treeview(self)
            # let's refresh the treeview
            self.clear_details()
            self.populate_treeview()
        #gutils.info(_("Databases merged!\n\nProcessed movies: %s\nMerged movies: %s"%(movies, merged)), self.widgets['window'])
        gutils.info(_("Backup restored"), self.widgets['window'])
    except:
        log.exception('')
        raise
    finally:
        # disposing the temporary db connection before rmtree and in finally block to avoid locked db file
        if tmp_db:
            tmp_db.dispose()
        log.debug('temporary directory no logger needed, removing %s', tmp_dir)
        rmtree(tmp_dir)
Пример #51
0
def create(self):
    """perform a compressed griffith database/posters/preferences backup"""
    #if self.db.session.bind.engine.name != 'sqlite':
    #    gutils.error(_("Backup function is available only for SQLite engine for now"), self.widgets['window'])
    #    return False
    
    default_name = "%s_backup_%s.zip" % (self.config.get('name', 'griffith', section='database'),\
                    datetime.date.isoformat(datetime.datetime.now()))
    filename = gutils.file_chooser(_("Save Griffith backup"), \
        action=gtk.FILE_CHOOSER_ACTION_SAVE, name=default_name, \
        buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK))

    if filename and filename[0]:
        proceed = True
        zipfilename = filename[0].decode('utf-8')
        log.debug('Backup filename: %s', zipfilename)
        if os.path.isfile(zipfilename):
            if not gutils.question(_("File exists. Do you want to overwrite it?"), window=self.widgets['window']):
                proceed = False

        if proceed:
            try:
                if zipfile.zlib is not None:
                    log.debug('Creating zip file with compression')
                    mzip = zipfile.ZipFile(zipfilename, 'w', zipfile.ZIP_DEFLATED)
                else:
                    log.debug('Creating zip file without compression')
                    mzip = zipfile.ZipFile(zipfilename, 'w')
            except:
                gutils.error(_("Error creating backup"), self.widgets['window'])
                return False
            log.debug('Preparing data and saving it to the zip archive')
            if self.db.session.bind.engine.name == 'sqlite':
                mzip.write(os.path.join(self.locations['home'], 'griffith.cfg').encode('utf-8'), arcname='griffith.cfg')
                db_file_name = "%s.db" % self.config.get('name', 'griffith', section='database')
                file_path = os.path.join(self.locations['home'], db_file_name).encode('utf-8')
                mzip.write(file_path, arcname=db_file_name)
            else:
                tmp_engine = None
                try:
                    tmp_dir = mkdtemp()
                    tmp_config_file = os.path.join(tmp_dir, 'griffith.cfg')
                    self.config.save(tmp_config_file)
                    tmp_config = config.Config(file=tmp_config_file)
                    tmp_config.set('type', 'sqlite', section='database')
                    tmp_config.set('file', 'griffith.db', section='database')
                    tmp_config.set('name', 'griffith', section='database')
                    tmp_config.save()
                    mzip.write(tmp_config._file, arcname='griffith.cfg')

                    tmp_file = os.path.join(tmp_dir, 'griffith.db')
                    tmp_engine = create_engine("sqlite:///%s" % tmp_file)
                    db.metadata.create_all(bind=tmp_engine)

                    # SQLite doesn't care about foreign keys much so we can just copy the data
                    for table in db.metadata.sorted_tables:
                        if table.name in ('posters', 'filters'):
                            continue  # see below
                        data = table.select(bind=self.db.session.bind).execute().fetchall()
                        if data:
                            table.insert(bind=tmp_engine).execute(data)

                    # posters
                    for poster in db.metadata.tables['posters'].select(bind=self.db.session.bind).execute():
                        db.metadata.tables['posters'].insert(bind=tmp_engine).execute(md5sum=poster.md5sum, data=StringIO(poster.data).read())

                    mzip.write(tmp_file, arcname='griffith.db')
                finally:
                    # disposing the temporary db connection before rmtree and in finally block to avoid locked db file
                    if tmp_engine:
                        tmp_engine.dispose()
                    rmtree(tmp_dir)
            gutils.info(_("Backup has been created"), self.widgets['window'])
Пример #52
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))
Пример #53
0
def convert_from_old_db(config, source_file, destination_file,
                        locations):  #{{{
    """
    convert .gri database into .bd one
    """

    log.info('Converting old database - it can take several minutes...')
    log.debug("Source file: %s", source_file)
    gutils.info(
        _("Griffith will now convert your database to the new format. This can take several minutes if you have a large database."
          ))
    from sql import GriffithSQL
    from gutils import digits_only
    import os

    if not os.path.isfile(source_file):
        return False

    if 'home' not in locations:
        log.error(
            "locations doesn't contain home path, cannot convert old database")
        return False

    if open(source_file).readline(
    )[:47] == '** This file contains an SQLite 2.1 database **':
        log.debug('SQLite 2.1 detected')
        try:
            import sqlite
        except ImportError:
            log.error(
                'Old DB conversion: please install pysqlite legacy (v1.0)')
            gutils.warning(
                _("Old DB conversion: please install pysqlite legacy (v1.0)"))
            return False
    else:
        try:  # Python 2.5
            from sqlite3 import dbapi2 as sqlite
        except ImportError:  # Python < 2.5 - try to use pysqlite2
            from pysqlite2 import dbapi2 as sqlite

    if os.path.isfile(destination_file):
        # rename destination_file if it already exist
        i = 1
        while True:
            if os.path.isfile("%s_%s" % (destination_file, i)):
                i += 1
            else:
                break
        os.rename(destination_file, "%s_%s" % (destination_file, i))

    try:
        old_db = sqlite.connect(source_file)
    except sqlite.DatabaseError, e:
        if str(e) == 'file is encrypted or is not a database':
            print 'Your database is most probably in SQLite2 format, please convert it to SQLite3:'
            print '$ sqlite ~/.griffith/griffith.gri .dump | sqlite3 ~/.griffith/griffith.gri3'
            print '$ mv ~/.griffith/griffith.gri{,2}'
            print '$ mv ~/.griffith/griffith.gri{3,}'
            print 'or install pysqlite in version 1.0'
            gutils.warning(
                _("Your database is most probably in SQLite2 format, please convert it to SQLite3"
                  ))
        else:
            raise
        return False