Beispiel #1
0
 def tearDown(self):
     """ Removes uninstall.exe created for tests and data path."""
     fix_winpaths.fix()
     if os.path.exists(paths.data_path("musicDL")):
         shutil.rmtree(paths.data_path("musicDL"))
     if os.path.exists(os.path.join(paths.app_path(), "uninstall.exe")):
         os.remove(os.path.join(paths.app_path(), "uninstall.exe"))
Beispiel #2
0
def setup():
    global data_directory, app_type
    if len(glob.glob("Uninstall.exe")) > 0:  # installed copy
        if os.path.exists(paths.data_path("musicDL")) == False:
            os.mkdir(paths.data_path("musicDL"))
        data_directory = paths.data_path("musicDL")
        app_type = "installed"
    else:
        app_type = "portable"
        data_directory = os.path.join(paths.app_path(), "data")
        if os.path.exists(data_directory) == False:
            os.mkdir(data_directory)
Beispiel #3
0
def setup():
 logging.debug("Initializing GUI subsystem.")
 #Create the wx app
 try:
  os.remove(paths.data_path('wx.log'))
 except:
  pass
 application.wx_app = wx.App(redirect=True, useBestVisual=True, filename=paths.data_path('wx.log'))
 #Create a default frame for the application
 application.main_frame = wx.Frame(None, wx.ID_ANY, application.name)
 application.main_frame.Center()
 #Capture system shutdown events and shutdown the application.
 application.wx_app.Bind(wx.EVT_END_SESSION, on_end_session)
Beispiel #4
0
def setup():
    logging.debug("Initializing GUI subsystem.")
    #Create the wx app
    try:
        os.remove(paths.data_path('wx.log'))
    except:
        pass
    application.wx_app = wx.App(redirect=True,
                                useBestVisual=True,
                                filename=paths.data_path('wx.log'))
    #Create a default frame for the application
    application.main_frame = wx.Frame(None, wx.ID_ANY, application.name)
    application.main_frame.Center()
    #Capture system shutdown events and shutdown the application.
    application.wx_app.Bind(wx.EVT_END_SESSION, on_end_session)
Beispiel #5
0
def setup ():
 global main
 try:
  main = Configuration(data_path(MAINFILE), app_path(MAINSPEC))
 except ConfigurationResetException:
  import output
  output.speak("Unable to load configuration file. Loading default configuration instead.", 0)
Beispiel #6
0
def setup():
    global main
    try:
        main = Configuration(data_path(MAINFILE), app_path(MAINSPEC))
    except ConfigurationResetException:
        import output
        output.speak(
            "Unable to load configuration file. Loading default configuration instead.",
            0)
Beispiel #7
0
    def ImportDatabase(self):
        """Import an old-style  .db qwitter database, or .session file into the current session's storage."""
        def import_buffer(tablename, buffername):
            table = new.load_table(tablename)
            newtable = new.convert_table(table)
            buf = self.session.get_buffer_by_name(buffername)
            buf.storage.extend(newtable)
            buf.storage.sort(key=lambda a: calendar.timegm(
                rfc822.parsedate(a['created_at'])))
            buf.storage = misc.RemoveDuplicates(buf.storage, lambda x: x['id'])

        f = wx.Frame(None, wx.ID_ANY, "FileDialog")
        dlg = wx.FileDialog(
            f,
            message="Select Database",
            defaultDir=paths.data_path(),
            wildcard=
            "Session files (*.session)|*.session|Qwitter Databases (*.DB)|*.db"
        )
        f.Raise()
        if dlg.ShowModal() == wx.ID_OK:
            filename = dlg.GetPath()
            dlg.Destroy()
            f.Destroy()
        else:
            output.speak(_("Canceled"), True)
            dlg.Destroy()
            f.Destroy()
            return
        if filename.lower().endswith('.db'):
            new = Importer(filename)
            home = new.load_table("tweets")
            directs = new.load_table("directs")
            mentions = new.load_table("replies")
            sent = new.load_table("sent")
            total = len(home) + len(directs) + len(mentions) + len(sent)
            yesno = wx.MessageBox(
                _("Are you sure you want to import %d items from old database?"
                  ) % total,
                _("Are you sure?"),
                style=wx.YES | wx.NO)
            if yesno == wx.YES:
                output.speak(_("Importing, please wait."), True)
            else:
                return output.speak(_("Canceled."), True)
            for i in [("tweets", "Home"), ("replies", "Mentions"),
                      ("directs", "Direct Messages"), ("sent", "Sent")]:
                import_buffer(*i)
        elif filename.lower().endswith('.session'):
            try:
                new = SessionImporter(filename)
            except TypeError:
                return output.speak(_("Session type mismatch."))
            new.do_import()
        wx.MessageBox(_("Import completed successfully."),
                      _("Import complete."))
Beispiel #8
0
 def test_installer_path(self):
     """ Testing if paths are generated appropiately. """
     # this is a temporary fix for winpaths.
     fake_installer_file = open(
         os.path.join(paths.app_path(), "Uninstall.exe"), "w")
     fake_installer_file.close()
     fix_winpaths.fix()
     storage.setup()
     self.assertEquals(storage.app_type, "installed")
     self.assertTrue(os.path.exists(storage.data_directory))
     self.assertEquals(storage.data_directory, paths.data_path("musicDL"))
Beispiel #9
0
def import_durus():
 old_stdout = sys.stdout
 old_stderr = sys.stderr
 sys.stdout = sys.__stdout__
 sys.stderr = sys.__stderr__
 from durus import logger
 logger.direct_output(open(paths.data_path('durus.log'), 'w'))
 sys.stdout = old_stdout
 sys.stderr = old_stderr
 from durus.file_storage import FileStorage
 from durus.connection import Connection
 return (FileStorage, Connection)
Beispiel #10
0
def import_durus():
    old_stdout = sys.stdout
    old_stderr = sys.stderr
    sys.stdout = sys.__stdout__
    sys.stderr = sys.__stderr__
    from durus import logger
    logger.direct_output(open(paths.data_path('durus.log'), 'w'))
    sys.stdout = old_stdout
    sys.stderr = old_stderr
    from durus.file_storage import FileStorage
    from durus.connection import Connection
    return (FileStorage, Connection)
Beispiel #11
0
def check_for_update():
 if not is_frozen():
  return
 url = updater.find_update_url(application.update_url, application.version)
 if url is None:
  return
 new_path = os.path.join(paths.data_path(application.name), 'updates', 'update.zip')
 app_updater = updater.AutoUpdater(url, new_path, 'bootstrap.exe', app_path=paths.app_path(), postexecute=paths.executable_path(), finish_callback=update_complete)
 d = question_dialog(parent=application.main_frame, caption=_("Update %s") % application.name, message=_("An update for %s is available, would you like to download and install it now?") % application.name, style=wx.YES|wx.NO|wx.ICON_WARNING)
 if d!= wx.ID_YES:
  return logging.warning("User denied the update request!")
 logging.debug("User requested %s update.  Initializing update process." % application.name)
 app_updater.start_update()
Beispiel #12
0
def check_for_update():
 if not is_frozen():
  return
 url = updater.find_update_url(application.update_url, application.version)
 if url is None:
  return
 new_path = os.path.join(paths.data_path(application.name), 'updates', 'update.zip')
 app_updater = updater.AutoUpdater(url, new_path, 'bootstrap.exe', app_path=paths.app_path(), postexecute=paths.executable_path(), finish_callback=update_complete)
 d = question_dialog(parent=application.main_frame, caption=_("Update %s") % application.name, message=_("An update for %s is available, would you like to download and install it now?") % application.name, style=wx.YES|wx.NO|wx.ICON_WARNING)
 if d!= wx.ID_YES:
  return logging.warning("User denied the update request!")
 logging.debug("User requested %s update.  Initializing update process." % application.name)
 app_updater.start_update()
Beispiel #13
0
 def ImportDatabase(self):
  """Import an old-style  .db qwitter database, or .session file into the current session's storage."""

  def import_buffer (tablename, buffername):
   table = new.load_table(tablename)
   newtable = new.convert_table(table)
   buf = self.session.get_buffer_by_name(buffername)
   buf.storage.extend(newtable)
   buf.storage.sort(key=lambda a: calendar.timegm(rfc822.parsedate(a['created_at'])))
   buf.storage = misc.RemoveDuplicates(buf.storage, lambda x: x['id'])
  f = wx.Frame(None, wx.ID_ANY, "FileDialog")
  dlg = wx.FileDialog(f, message="Select Database", defaultDir=paths.data_path(), wildcard="Session files (*.session)|*.session|Qwitter Databases (*.DB)|*.db")
  f.Raise()
  if dlg.ShowModal() == wx.ID_OK:
   filename = dlg.GetPath()
   dlg.Destroy()
   f.Destroy()
  else:
   output.speak(_("Canceled"), True)
   dlg.Destroy()
   f.Destroy()
   return
  if filename.lower().endswith('.db'):
   new = Importer(filename)
   home = new.load_table("tweets")
   directs = new.load_table("directs")
   mentions = new.load_table("replies")
   sent = new.load_table("sent")
   total = len(home) + len(directs) + len(mentions) + len(sent)
   yesno = wx.MessageBox(_("Are you sure you want to import %d items from old database?") % total, _("Are you sure?"), style=wx.YES|wx.NO)
   if yesno == wx.YES:
    output.speak(_("Importing, please wait."), True)
   else:
    return output.speak(_("Canceled."), True)
   for i in [("tweets", "Home"), ("replies", "Mentions"), ("directs", "Direct Messages"), ("sent", "Sent")]:
    import_buffer(*i)
  elif filename.lower().endswith('.session'):
   try:
    new = SessionImporter(filename)
   except TypeError:
    return output.speak(_("Session type mismatch."))
   new.do_import()
  wx.MessageBox(_("Import completed successfully."), _("Import complete."))
Beispiel #14
0
def NewConnection (file):
 global connection
 filename = paths.data_path(file)
 if not glob(filename):
  logging.debug("Database: Database file does not exist.")
  NewDatabase(filename)
 if type(threading.currentThread()) is threading._MainThread:
  global connection
  if not connection:
   connection = sqlite.connect(filename)
   return connection
 ThreadLocalData = threading.local()
 try:
  output = ThreadLocalData.connection
#  logging.info("Retrieving connection from local thread storage.")
 except:
#  logging.info("Establishing Thread Database connection to %s from thread %s" % (filename, threading.currentThread().name))
  con = sqlite.connect(filename)
  #con.row_factory = sqlite.dbapi2.Row
  ThreadLocalData.connection = con
  return ThreadLocalData.connection
Beispiel #15
0
def NewConnection(file):
    global connection
    filename = paths.data_path(file)
    if not glob(filename):
        logging.debug("Database: Database file does not exist.")
        NewDatabase(filename)
    if type(threading.currentThread()) is threading._MainThread:
        global connection
        if not connection:
            connection = sqlite.connect(filename)
            return connection
    ThreadLocalData = threading.local()
    try:
        output = ThreadLocalData.connection


#  logging.info("Retrieving connection from local thread storage.")
    except:
        #  logging.info("Establishing Thread Database connection to %s from thread %s" % (filename, threading.currentThread().name))
        con = sqlite.connect(filename)
        #con.row_factory = sqlite.dbapi2.Row
        ThreadLocalData.connection = con
        return ThreadLocalData.connection
Beispiel #16
0
from logging.handlers import RotatingFileHandler
import paths
import sys

APP_LOG_FILE = 'The Qube.log'
ERROR_LOG_FILE = "error.log"
MESSAGE_FORMAT = "%(asctime)s %(name)s %(levelname)s: %(message)s"
DATE_FORMAT = "%a %b %d, %Y %H:%M:%S"

formatter = logging.Formatter(MESSAGE_FORMAT, datefmt=DATE_FORMAT)

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

#handlers

app_handler = RotatingFileHandler(paths.data_path(APP_LOG_FILE), maxBytes=1000000)
app_handler.setFormatter(formatter)
app_handler.setLevel(logging.DEBUG)
logger.addHandler(app_handler)

error_handler = logging.FileHandler(paths.data_path(ERROR_LOG_FILE))
error_handler.setFormatter(formatter)
error_handler.setLevel(logging.ERROR)
logger.addHandler(error_handler)
if not hasattr(sys, 'frozen'):
 console_handler = logging.StreamHandler()
 console_handler.setLevel(logging.ERROR)
 console_handler.setFormatter(formatter)
 logger.addHandler(console_handler)
Beispiel #17
0
 def load_file(self, filename):
  output.speak(_("Loading file..."))
  FileStorage, Connection = misc.import_durus()
  self.file = FileStorage(paths.data_path(filename))
  self.connection = Connection(self.file)
  self.root = self.connection.root
Beispiel #18
0
APP_LOG_FILE = "{0}.log".format(application.name)
ERROR_LOG_FILE = "error.log"
MESSAGE_FORMAT = "%(levelname)s: %(message)s"
#MESSAGE_FORMAT = "%(asctime)s %(name)s %(levelname)s: %(message)s"

DATE_FORMAT = "%H:%M:%S"

formatter = logging.Formatter(MESSAGE_FORMAT, datefmt=DATE_FORMAT)

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

#handlers

app_handler = RotatingFileHandler(paths.data_path(APP_LOG_FILE),
                                  maxBytes=1000000)
app_handler.setFormatter(formatter)
app_handler.setLevel(logging.DEBUG)
logger.addHandler(app_handler)

error_handler = logging.FileHandler(paths.data_path(ERROR_LOG_FILE))
error_handler.setFormatter(formatter)
error_handler.setLevel(logging.ERROR)
logger.addHandler(error_handler)
if not hasattr(sys, 'frozen'):
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.ERROR)
    console_handler.setFormatter(formatter)
    logger.addHandler(console_handler)
Beispiel #19
0
 def rename_session(self, new_name):
     shutil.move(self.session_path, paths.data_path(new_name))
     super(FileSystem, self).rename_session(new_name)
Beispiel #20
0
 def session_path(self):
     """Returns the path where all of this session's data is stored."""
     return paths.data_path(self.name)
Beispiel #21
0
 def session_path(self):
  """Returns the path where all of this session's data is stored."""
  return paths.data_path(self.name)
Beispiel #22
0
 def rename_session(self, new_name):
  shutil.move(self.session_path, paths.data_path(new_name))
  super(FileSystem, self).rename_session(new_name)
Beispiel #23
0
MESSAGE_FORMAT = u"%(asctime)s %(name)s %(levelname)s: %(message)s"
DATE_FORMAT = u"%a %b %d, %Y %H:%M:%S"

formatter = logging.Formatter(MESSAGE_FORMAT, datefmt=DATE_FORMAT)
requests_log = logging.getLogger("requests")
requests_log.setLevel(logging.WARNING)
oauthlib_log = logging.getLogger("oauthlib")
oauthlib_log.setLevel(logging.WARNING)
server_log = logging.getLogger("BaseHTTPServer")
server_log.setLevel(logging.WARNING)

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

#handlers

app_handler = TheQubeFileHandler(paths.data_path(APP_LOG_FILE), "w", 102400)
app_handler.setFormatter(formatter)
app_handler.setLevel(logging.DEBUG)
logger.addHandler(app_handler)

error_handler = TheQubeFileHandler(paths.data_path(ERROR_LOG_FILE), "w", 102400)
error_handler.setFormatter(formatter)
error_handler.setLevel(logging.WARNING)
logger.addHandler(error_handler)
if not hasattr(sys, 'frozen'):
 console_handler = logging.StreamHandler()
 console_handler.setLevel(logging.ERROR)
 console_handler.setFormatter(formatter)
 logger.addHandler(console_handler)
Beispiel #24
0
from logHandler import logger
logging = logger.getChild('core.config')

import os
import confspecs
import paths
import application
from UserDict import UserDict
from configobj import ConfigObj, ParseError
from validate import Validator, VdtValueError

configFile = paths.data_path(application.name + ".ini")
confspec = ConfigObj(confspecs.defaults, list_values=False, encoding="UTF-8")
confspec.newlines = "\r\n"
conf = None


class ConfigurationResetException(Exception):
    pass


class Configuration(UserDict):
    def __init__(self, file=None, spec=None, *args, **kwargs):
        self.file = file
        self.spec = spec
        self.validator = Validator()
        self.setup_config(file=file, spec=spec)
        self.validated = self.config.validate(self.validator, copy=True)
        if self.validated:
            self.write()
        UserDict.__init__(self, self.config)