def __init__(self, filename=None, data_path=None): #Version constants self.version = "1.9.2-dev" #Process command line options self.startup_options = self.get_options() #Setup logging self.environment = Environment(platform.get_platform(), self.startup_options.conf_dir) self.environment.create_directories() self.set_logging(self.startup_options.log_level, self.startup_options.log_type) logging.debug('>>') logging.debug("PyTrainer version %s" % (self.version)) self.data_path = data_path self.date = Date() self.ddbb = None # Checking profile logging.debug('Checking configuration and profile...') self.profile = Profile(self.environment, self.data_path, self) self.uc = UC() self.windowmain = None self.ddbb = DDBB(self.profile, self) logging.debug('connecting to DDBB') self.ddbb.connect() initialize_data(self.ddbb, self.environment.conf_dir) self._sport_service = SportService(self.ddbb) self.record = Record(self._sport_service, data_path, self) self.athlete = Athlete(data_path, self) self.stats = Stats(self._sport_service, self) pool_size = self.profile.getIntValue("pytraining", "activitypool_size", default=1) self.activitypool = ActivityPool(self, size=pool_size) #preparamos la ventana principal self.windowmain = Main(self._sport_service, data_path, self, self.version, gpxDir=self.profile.gpxdir) self.date = Date(self.windowmain.calendar) self.waypoint = Waypoint(data_path, self) self.extension = Extension(data_path, self) self.plugins = Plugins(data_path, self) self.importdata = Importdata(self._sport_service, data_path, self, self.profile) self.loadPlugins() self.loadExtensions() self.windowmain.setup() self.windowmain.on_calendar_selected(None) self.refreshMainSportList() self.windowmain.run() logging.debug('<<')
def __init__(self,filename = None, data_path = None): #Version constants self.version ="1.9.2-dev" #Process command line options self.startup_options = self.get_options() #Setup logging self.environment = Environment(platform.get_platform(), self.startup_options.conf_dir) self.environment.create_directories() self.set_logging(self.startup_options.log_level, self.startup_options.log_type) logging.debug('>>') logging.debug("PyTrainer version %s" % (self.version)) self.data_path = data_path self.date = Date() self.ddbb = None # Checking profile logging.debug('Checking configuration and profile...') self.profile = Profile(self.environment, self.data_path,self) self.uc = UC() self.windowmain = None self.ddbb = DDBB(self.profile, self) logging.debug('connecting to DDBB') self.ddbb.connect() initialize_data(self.ddbb, self.environment.conf_dir) self._sport_service = SportService(self.ddbb) self.record = Record(self._sport_service, data_path, self) self.athlete = Athlete(data_path,self) self.stats = Stats(self._sport_service, self) pool_size = self.profile.getIntValue("pytraining","activitypool_size", default=1) self.activitypool = ActivityPool(self, size=pool_size) #preparamos la ventana principal self.windowmain = Main(self._sport_service, data_path,self,self.version, gpxDir=self.profile.gpxdir) self.date = Date(self.windowmain.calendar) self.waypoint = Waypoint(data_path,self) self.extension = Extension(data_path, self) self.plugins = Plugins(data_path, self) self.importdata = Importdata(self._sport_service, data_path, self, self.profile) self.loadPlugins() self.loadExtensions() self.windowmain.setup() self.windowmain.on_calendar_selected(None) self.refreshMainSportList() self.windowmain.run() logging.debug('<<')
def setUp(self): self.mock_ddbb = mock.Mock(spec=Sql) self.sport_service = SportService(self.mock_ddbb)
class SportServiceTest(unittest.TestCase): def setUp(self): self.mock_ddbb = mock.Mock(spec=Sql) self.sport_service = SportService(self.mock_ddbb) def test_store_sport_should_insert_row_when_sport_has_no_id(self): def mock_select(table, columns, where): call_count = self.mock_ddbb.select.call_count if call_count == 2: return [[1]] return [] self.mock_ddbb.select = mock.Mock(wraps=mock_select) sport = Sport() sport.name = u"Test name" self.sport_service.store_sport(sport) self.mock_ddbb.insert.assert_called_with("sports", "name,weight,met,max_pace,color", [u"Test name", 0.0, None, None, "0000ff"]) def test_store_sport_should_update_row_when_sport_has_id(self): def mock_select(table, columns, where): if columns == "id_sports": return [[1]] else: return [(1, u"", 0, 0, 0, "0")] self.mock_ddbb.select = mock.Mock(wraps=mock_select) sport = Sport() sport.id = 1 sport.name = u"New name" self.sport_service.store_sport(sport) self.mock_ddbb.update.assert_called_with("sports", "name,weight,met,max_pace,color", [u"New name", 0.0, None, None, "0000ff"], "id_sports=1") def test_store_sport_should_return_stored_sport(self): sport_ids = [] def update_sport_ids(*args): sport_ids.append([1]) self.mock_ddbb.insert.side_effect = update_sport_ids def mock_select(table, columns, where): if columns == "id_sports": return sport_ids else: return [(2, u"", 0, 0, 0, "0")] self.mock_ddbb.select = mock.Mock(wraps=mock_select) sport = Sport() stored_sport = self.sport_service.store_sport(sport) self.assertEquals(2, stored_sport.id) def test_store_sport_should_error_when_sport_has_unknown_id(self): self.mock_ddbb.select.return_value = [] sport = Sport() sport.id = 100 try: self.sport_service.store_sport(sport) except(SportServiceException): pass else: self.fail() def test_store_sport_should_error_when_new_sport_has_duplicate_name(self): self.mock_ddbb.select.return_value = [(1, u"Test name", 150, 12.5, 200, "0")] sport = Sport() sport.name = u"Test name" try: self.sport_service.store_sport(sport) except(SportServiceException): pass else: self.fail() def test_store_sport_should_error_when_existing_sport_has_duplicate_name(self): def mock_select(table, columns, where): if columns == pytrainer.sport._ID_COLUMN: return [[2]] else: return [(1, u"Test name", 0, 0.0, "0"), (2, u"New name", 0, 0.0, "0")] self.mock_ddbb.select = mock.Mock(wraps=mock_select) sport = Sport() sport.id = 1 sport.name = u"New name" try: self.sport_service.store_sport(sport) except(SportServiceException): pass else: self.fail() def test_get_sport_returns_none_for_nonexistant_sport(self): self.mock_ddbb.select.return_value = [] sport = self.sport_service.get_sport(1) self.assertEquals(None, sport) def test_get_sport_returns_sport_with_id(self): self.mock_ddbb.select.return_value = [(1, u"", 0, 0, 0, "0")] sport = self.sport_service.get_sport(1) self.assertEquals(1, sport.id) def test_get_sport_raises_error_for_id_none(self): try: self.sport_service.get_sport(None) except(ValueError): pass else: self.fail() def test_get_sport_by_name_returns_none_for_nonexistant_sport(self): self.mock_ddbb.select.return_value = [] sport = self.sport_service.get_sport("no such sport") self.assertEquals(None, sport) def test_get_sport_by_name_returns_sport_with_name(self): def mock_select(table, columns, where): if columns == "id_sport": return [(1)] else: return [(1, u"rugby", 0, 0, 0, "0")] self.mock_ddbb.select = mock.Mock(wraps=mock_select) sport = self.sport_service.get_sport("rugby") self.assertEquals(u"rugby", sport.name) def test_get_sport_by_name_raises_error_for_none_sport_name(self): try: self.sport_service.get_sport_by_name(None) except(ValueError): pass else: self.fail() def test_get_all_sports_should_return_all_sports_in_query_result(self): self.mock_ddbb.select.return_value = [(1, u"Test name", 0, 0, 0, "0"), (2, u"Test name 2", 0, 0, 0, "0")] sports = self.sport_service.get_all_sports() self.assertEquals(2, len(sports)) sport1 = sports[0] self.assertEquals(1, sport1.id) sport2 = sports[1] self.assertEquals(2, sport2.id) def test_get_all_sports_should_return_no_sports_when_query_result_empty(self): self.mock_ddbb.select.return_value = [] sports = self.sport_service.get_all_sports() self.assertEquals(0, len(sports)) def test_remove_sport_should_error_when_sport_has_no_id(self): self.mock_ddbb.select.return_value = [(1, u"Test name", 150, 12.5, 200, "0")] sport = Sport() try: self.sport_service.remove_sport(sport) except(SportServiceException): pass else: self.fail() def test_remove_sport_should_error_when_sport_has_unknown_id(self): self.mock_ddbb.select.return_value = [] sport = Sport() sport.id = 100 try: self.sport_service.remove_sport(sport) except(SportServiceException): pass else: self.fail() def test_remove_sport_should_delete_sport_with_specified_id(self): self.mock_ddbb.select.return_value = [[1]] sport = Sport() sport.id = 1 self.sport_service.remove_sport(sport) self.mock_ddbb.delete.assert_called_with("sports", "id_sports=1") def test_remove_sport_should_remove_associated_entries(self): self.mock_ddbb.select.return_value = [[1]] sport = Sport() sport.id = 1 delete_arguments = [] def mock_delete(*args): delete_arguments.append(args) self.mock_ddbb.delete = mock.Mock(wraps=mock_delete) self.sport_service.remove_sport(sport) self.assertEquals(("records", "sport=1"), delete_arguments[0])
class SportServiceTest(unittest.TestCase): def setUp(self): self.mock_ddbb = mock.Mock(spec=Sql) self.sport_service = SportService(self.mock_ddbb) def test_store_sport_should_insert_row_when_sport_has_no_id(self): def mock_select(table, columns, where): call_count = self.mock_ddbb.select.call_count if call_count == 2: return [[1]] return [] self.mock_ddbb.select = mock.Mock(wraps=mock_select) sport = Sport() sport.name = u"Test name" self.sport_service.store_sport(sport) self.mock_ddbb.insert.assert_called_with( "sports", "name,weight,met,max_pace,color", [u"Test name", 0.0, None, None, "0000ff"]) def test_store_sport_should_update_row_when_sport_has_id(self): def mock_select(table, columns, where): if columns == "id_sports": return [[1]] else: return [(1, u"", 0, 0, 0, "0")] self.mock_ddbb.select = mock.Mock(wraps=mock_select) sport = Sport() sport.id = 1 sport.name = u"New name" self.sport_service.store_sport(sport) self.mock_ddbb.update.assert_called_with( "sports", "name,weight,met,max_pace,color", [u"New name", 0.0, None, None, "0000ff"], "id_sports=1") def test_store_sport_should_return_stored_sport(self): sport_ids = [] def update_sport_ids(*args): sport_ids.append([1]) self.mock_ddbb.insert.side_effect = update_sport_ids def mock_select(table, columns, where): if columns == "id_sports": return sport_ids else: return [(2, u"", 0, 0, 0, "0")] self.mock_ddbb.select = mock.Mock(wraps=mock_select) sport = Sport() stored_sport = self.sport_service.store_sport(sport) self.assertEquals(2, stored_sport.id) def test_store_sport_should_error_when_sport_has_unknown_id(self): self.mock_ddbb.select.return_value = [] sport = Sport() sport.id = 100 try: self.sport_service.store_sport(sport) except (SportServiceException): pass else: self.fail() def test_store_sport_should_error_when_new_sport_has_duplicate_name(self): self.mock_ddbb.select.return_value = [(1, u"Test name", 150, 12.5, 200, "0")] sport = Sport() sport.name = u"Test name" try: self.sport_service.store_sport(sport) except (SportServiceException): pass else: self.fail() def test_store_sport_should_error_when_existing_sport_has_duplicate_name( self): def mock_select(table, columns, where): if columns == pytrainer.sport._ID_COLUMN: return [[2]] else: return [(1, u"Test name", 0, 0.0, "0"), (2, u"New name", 0, 0.0, "0")] self.mock_ddbb.select = mock.Mock(wraps=mock_select) sport = Sport() sport.id = 1 sport.name = u"New name" try: self.sport_service.store_sport(sport) except (SportServiceException): pass else: self.fail() def test_get_sport_returns_none_for_nonexistant_sport(self): self.mock_ddbb.select.return_value = [] sport = self.sport_service.get_sport(1) self.assertEquals(None, sport) def test_get_sport_returns_sport_with_id(self): self.mock_ddbb.select.return_value = [(1, u"", 0, 0, 0, "0")] sport = self.sport_service.get_sport(1) self.assertEquals(1, sport.id) def test_get_sport_raises_error_for_id_none(self): try: self.sport_service.get_sport(None) except (ValueError): pass else: self.fail() def test_get_sport_by_name_returns_none_for_nonexistant_sport(self): self.mock_ddbb.select.return_value = [] sport = self.sport_service.get_sport("no such sport") self.assertEquals(None, sport) def test_get_sport_by_name_returns_sport_with_name(self): def mock_select(table, columns, where): if columns == "id_sport": return [(1)] else: return [(1, u"rugby", 0, 0, 0, "0")] self.mock_ddbb.select = mock.Mock(wraps=mock_select) sport = self.sport_service.get_sport("rugby") self.assertEquals(u"rugby", sport.name) def test_get_sport_by_name_raises_error_for_none_sport_name(self): try: self.sport_service.get_sport_by_name(None) except (ValueError): pass else: self.fail() def test_get_all_sports_should_return_all_sports_in_query_result(self): self.mock_ddbb.select.return_value = [(1, u"Test name", 0, 0, 0, "0"), (2, u"Test name 2", 0, 0, 0, "0") ] sports = self.sport_service.get_all_sports() self.assertEquals(2, len(sports)) sport1 = sports[0] self.assertEquals(1, sport1.id) sport2 = sports[1] self.assertEquals(2, sport2.id) def test_get_all_sports_should_return_no_sports_when_query_result_empty( self): self.mock_ddbb.select.return_value = [] sports = self.sport_service.get_all_sports() self.assertEquals(0, len(sports)) def test_remove_sport_should_error_when_sport_has_no_id(self): self.mock_ddbb.select.return_value = [(1, u"Test name", 150, 12.5, 200, "0")] sport = Sport() try: self.sport_service.remove_sport(sport) except (SportServiceException): pass else: self.fail() def test_remove_sport_should_error_when_sport_has_unknown_id(self): self.mock_ddbb.select.return_value = [] sport = Sport() sport.id = 100 try: self.sport_service.remove_sport(sport) except (SportServiceException): pass else: self.fail() def test_remove_sport_should_delete_sport_with_specified_id(self): self.mock_ddbb.select.return_value = [[1]] sport = Sport() sport.id = 1 self.sport_service.remove_sport(sport) self.mock_ddbb.delete.assert_called_with("sports", "id_sports=1") def test_remove_sport_should_remove_associated_entries(self): self.mock_ddbb.select.return_value = [[1]] sport = Sport() sport.id = 1 delete_arguments = [] def mock_delete(*args): delete_arguments.append(args) self.mock_ddbb.delete = mock.Mock(wraps=mock_delete) self.sport_service.remove_sport(sport) self.assertEquals(("records", "sport=1"), delete_arguments[0])
class pyTrainer: def __init__(self,filename = None, data_path = None): #Version constants self.version ="1.9.2-dev" #Process command line options self.startup_options = self.get_options() #Setup logging self.environment = Environment(platform.get_platform(), self.startup_options.conf_dir) self.environment.create_directories() self.set_logging(self.startup_options.log_level, self.startup_options.log_type) logging.debug('>>') logging.debug("PyTrainer version %s" % (self.version)) self.data_path = data_path self.date = Date() self.ddbb = None # Checking profile logging.debug('Checking configuration and profile...') self.profile = Profile(self.environment, self.data_path,self) self.uc = UC() self.windowmain = None self.ddbb = DDBB(self.profile, self) logging.debug('connecting to DDBB') self.ddbb.connect() initialize_data(self.ddbb, self.environment.conf_dir) self._sport_service = SportService(self.ddbb) self.record = Record(self._sport_service, data_path, self) self.athlete = Athlete(data_path,self) self.stats = Stats(self._sport_service, self) pool_size = self.profile.getIntValue("pytraining","activitypool_size", default=1) self.activitypool = ActivityPool(self, size=pool_size) #preparamos la ventana principal self.windowmain = Main(self._sport_service, data_path,self,self.version, gpxDir=self.profile.gpxdir) self.date = Date(self.windowmain.calendar) self.waypoint = Waypoint(data_path,self) self.extension = Extension(data_path, self) self.plugins = Plugins(data_path, self) self.importdata = Importdata(self._sport_service, data_path, self, self.profile) self.loadPlugins() self.loadExtensions() self.windowmain.setup() self.windowmain.on_calendar_selected(None) self.refreshMainSportList() self.windowmain.run() logging.debug('<<') def get_options(self): ''' Define usage and accepted options for command line startup returns: options - dict with option: value pairs ''' usage = '''usage: %prog [options] For more help on valid options try: %prog -h ''' parser = OptionParser(usage=usage) parser.set_defaults(log_level=logging.ERROR, validate=False, equip=False, newgraph=True, conf_dir=None, log_type="file") parser.add_option("-d", "--debug", action="store_const", const=logging.DEBUG, dest="log_level", help="enable logging at debug level") parser.add_option("-i", "--info", action="store_const", const=logging.INFO, dest="log_level", help="enable logging at info level") parser.add_option("-w", "--warn", action="store_const", const=logging.WARNING, dest="log_level", help="enable logging at warning level") parser.add_option("--valid", action="store_true", dest="validate", help="enable validation of files imported by plugins (details at info or debug logging level) - note plugin must support validation") parser.add_option("--oldgraph", action="store_false", dest="newgraph", help="Turn off new graphing approach") parser.add_option("--newgraph", action="store_true", dest="newgraph", help="Deprecated Option: Turn on new graphing approach") parser.add_option("--confdir", dest="conf_dir", help="Specify the directory where application configuration will be stored.") parser.add_option("--logtype", dest="log_type", metavar="TYPE", type="choice" , choices=["file", "console"], help="Specify where logging should be output to. TYPE is one of 'file' (default), or 'console'.") (options, args) = parser.parse_args() return options def set_logging(self, level, log_type): '''Setup rotating log file with customized format''' if("console" == log_type): handler = logging.StreamHandler(sys.stdout) else: handler = logging.handlers.RotatingFileHandler(self.environment.log_file, maxBytes=100000, backupCount=5) formatter = logging.Formatter('%(asctime)s|%(levelname)s|%(module)s|%(funcName)s|%(message)s') handler.setFormatter(formatter) logging.getLogger('').addHandler(handler) self.set_logging_level(self.startup_options.log_level) def set_logging_level(self, level): '''Set level of information written to log''' logging.debug("Setting logger to level: "+ str(level)) logging.getLogger('').setLevel(level) def quit(self): logging.debug('--') logging.info("Exit!") #self.webservice.stop() self.windowmain.gtk_main_quit() logging.shutdown() sys.exit() # Any nonzero value is considered "abnormal termination" by shells and the like def loadPlugins(self): logging.debug('>>') activeplugins = self.plugins.getActivePlugins() if (len(activeplugins)<1): logging.info("No active plugins") else: for plugin in activeplugins: txtbutton = self.plugins.loadPlugin(plugin) self.windowmain.addImportPlugin(txtbutton) logging.debug('<<') def loadExtensions(self): logging.debug('>>') activeextensions = self.extension.getActiveExtensions() if (len(activeextensions)<1): logging.info("No active extensions") else: for extension in activeextensions: txtbutton = self.extension.loadExtension(extension) self.windowmain.addExtension(txtbutton) logging.debug('<<') def runPlugin(self,widget,pathPlugin): logging.debug('>>') self.pluginClass = self.plugins.importClass(pathPlugin) pluginFiles = self.pluginClass.run() if pluginFiles is not None: logging.debug("Plugin returned %d files" % (len(pluginFiles)) ) #process returned GPX files for (pluginFile, sport) in pluginFiles: if os.path.isfile(pluginFile): logging.info('File exists. Size: %d. Sport: %s' % (os.path.getsize(pluginFile), sport)) if self.record.importFromGPX(pluginFile, sport) is None: logging.error("Error importing file "+pluginFile) else: logging.error('File '+pluginFile+' not valid') else: logging.debug("No files returned from Plugin") self.refreshListRecords() self.refreshGraphView("day") logging.debug('<<') def runExtension(self,extension,id): logging.debug('>>') #print("Extension id: %s" % str(id)) activity = self.activitypool.get_activity(id) txtbutton,pathExtension,type = extension self.extensionClass = self.extension.importClass(pathExtension) self.extensionClass.run(id, activity) #if type == "record": # #Si es record le tenemos que crear el googlemaps, el gpx y darle el id de la bbdd # alert = self.extension.runExtension(pathExtension,id) logging.debug('<<') def refreshMainSportList(self): logging.debug('>>') sports = self._sport_service.get_all_sports() self.windowmain.updateSportList(sports) logging.debug('<<') def refreshGraphView(self, view, sport=None): logging.debug('>>') if self.windowmain is None: logging.debug("First call to refreshGraphView") logging.debug('<<') return date_selected = self.date.getDate() if view=="record": logging.debug('record view') if self.windowmain.recordview.get_current_page()==0: self.refreshRecordGraphView("info") elif self.windowmain.recordview.get_current_page()==1: self.refreshRecordGraphView("graphs") elif self.windowmain.recordview.get_current_page()==2: self.refreshRecordGraphView("map") elif self.windowmain.recordview.get_current_page()==3: self.refreshRecordGraphView("heartrate") elif self.windowmain.recordview.get_current_page()==4: self.refreshRecordGraphView("analytics") elif view=="day": logging.debug('day view') sport = self.windowmain.activeSport sport_id = self.record.getSportId(sport) record_list = self.record.getrecordList(date_selected, sport_id) self.windowmain.actualize_dayview(record_list=record_list) #selected,iter = self.windowmain.recordTreeView.get_selection().get_selected() elif view=="week": logging.debug('week view') date_ini, date_end = self.date.getWeekInterval(date_selected, self.profile.prf_us_system) sport = self.windowmain.activeSport sport_id = self.record.getSportId(sport) record_list = self.record.getrecordPeriod(date_ini, date_end, sport_id) self.windowmain.actualize_weekview(record_list, date_ini, date_end) elif view=="month": logging.debug('month view') date_ini, date_end = self.date.getMonthInterval(date_selected) sport = self.windowmain.activeSport sport_id = self.record.getSportId(sport) # record_list = self.record.getrecordPeriodSport(date_ini, date_end,sport_id) record_list = self.record.getrecordPeriod(date_ini, date_end, sport_id) nameMonth, daysInMonth = self.date.getNameMonth(date_selected) self.windowmain.actualize_monthview(record_list, nameMonth) self.windowmain.actualize_monthgraph(record_list, daysInMonth) elif view=="year": logging.debug('year view') date_ini, date_end = self.date.getYearInterval(date_selected) sport = self.windowmain.activeSport sport_id = self.record.getSportId(sport) year = self.date.getYear(date_selected) # record_list = self.record.getrecordPeriodSport(date_ini, date_end,sport_id) record_list = self.record.getrecordPeriod(date_ini, date_end, sport_id) self.windowmain.actualize_yearview(record_list, year) self.windowmain.actualize_yeargraph(record_list) elif view=="listview": logging.debug('list view') self.refreshListView() elif view=="athlete": logging.debug('athlete view') self.windowmain.on_athleteview_activate() elif view=="stats": logging.debug('stats view') self.windowmain.on_statsview_activate() else: print "Unknown view %s" % view logging.debug('<<') def refreshRecordGraphView(self, view, id_record=None): logging.debug('>>') logging.info('Working on '+view+' graph') if id_record is not None: #Refresh called for a specific record #Select correct record in treeview model = self.windowmain.recordTreeView.get_model() #Loop through all records in treeview looking for the correct one to highlight for i,row in enumerate(model): if row[0] == id_record: self.windowmain.recordTreeView.set_cursor(i) else: selected,iter = self.windowmain.recordTreeView.get_selection().get_selected() if iter: id_record = selected.get_value(iter,0) else: id_record = None view="info" activity = self.activitypool.get_activity(id_record) if view=="info": self.windowmain.actualize_recordview(activity) if view=="graphs": self.windowmain.actualize_recordgraph(activity) if view=="map": self.refreshMapView() if view=="heartrate": self.windowmain.actualize_heartrategraph(activity) self.windowmain.actualize_hrview(activity) if view=="analytics": self.windowmain.actualize_analytics(activity) logging.debug('<<') def refreshMapView(self, full_screen=False): logging.debug('>>') if self.windowmain is None: logging.debug('Called before windowmain initialisation') logging.debug('<<') return selected,iter = self.windowmain.recordTreeView.get_selection().get_selected() id_record = selected.get_value(iter,0) activity = self.activitypool.get_activity(id_record) logging.debug('Trying to show map for record '+str(id_record)) self.windowmain.actualize_map(activity, full_screen) logging.debug('<<') def refreshListRecords(self): logging.debug('>>') #Refresh list view #self.refreshListView() # old variant self.refreshListView(self.windowmain.listsearch.condition) #Refresh list records date = self.date.getDate() sport = self.windowmain.activeSport id_sport = self.record.getSportId(sport) record_ids = self.record.getrecordList(date, id_sport) self.windowmain.actualize_recordTreeView(record_ids) #Mark the monthly calendar to show which days have activity? record_list = self.record.getRecordDayList(date, id_sport) self.windowmain.actualize_calendar(record_list) logging.debug('<<') def refreshAthleteView(self): logging.debug('>>') self.athlete.refresh() self.windowmain.actualize_athleteview(self.athlete) logging.debug('<<') def refreshStatsView(self): logging.debug('>>') self.stats.refresh() self.windowmain.actualize_statsview(self.stats, self.record.getAllRecordList()) logging.debug('<<') def refreshListView(self,condition=None): logging.debug('>>') record_list = self.record.getRecordListByCondition(condition) self.windowmain.actualize_listview(record_list) logging.debug('<<') def refreshWaypointView(self,default_waypoint=None,redrawmap=1): logging.debug('>>') waypoint_list = self.waypoint.getAllWaypoints() self.windowmain.actualize_waypointview(waypoint_list,default_waypoint,redrawmap) logging.debug('<<') def editExtensions(self): logging.debug('>>') before = self.extension.getActiveExtensions() self.extension.manageExtensions() after = self.extension.getActiveExtensions() self.setExtensions(before, after) logging.debug('<<') def importData(self): logging.debug('>>') activeplugins_before = self.plugins.getActivePlugins() self.importdata.runImportdata() activeplugins_after = self.plugins.getActivePlugins() #Need to check for plugins that have been disabled (were active and now are not) self.setMenuPlugins(activeplugins_before, activeplugins_after) self.refreshListRecords() self.refreshGraphView(self.windowmain.selected_view) logging.debug('<<') def editGpsPlugins(self): logging.debug('>>') activeplugins_before = self.plugins.getActivePlugins() self.plugins.managePlugins() activeplugins_after = self.plugins.getActivePlugins() #Need to check for plugins that have been disabled (were active and now are not) self.setMenuPlugins(activeplugins_before, activeplugins_after) logging.debug('<<') def setMenuPlugins(self, activeplugins_before, activeplugins_after): logging.debug('>>') #Need to check for plugins that have been disabled (were active and now are not) for plugin in activeplugins_before: if plugin not in activeplugins_after: #disabled plugin -> need to unload plugin txtbutton = self.plugins.loadPlugin(plugin) self.windowmain.removeImportPlugin(txtbutton) #Need to check for plugins that have been enabled (were not active and now are) for plugin in activeplugins_after: if plugin not in activeplugins_before: #new active plugin -> need to load plugin txtbutton = self.plugins.loadPlugin(plugin) self.windowmain.addImportPlugin(txtbutton) logging.debug('<<') def setExtensions(self, before, after): logging.debug('>>') #Need to check for extensions that have been disabled (were active and now are not) for extension in before: if extension not in after: #disabled extension -> need to unload extension print "Need to disable extension %s " % extension txtbutton = self.extension.loadExtension(extension) self.windowmain.removeExtension(txtbutton) #Need to check for plugins that have been enabled (were not active and now are) for extension in after: if extension not in before: #new active extension -> need to load extension logging.debug("Enabling extension %s " % extension) txtbutton = self.extension.loadExtension(extension) self.windowmain.addExtension(txtbutton) logging.debug('<<') def newRecord(self,title=None,distance=None,time=None,upositive=None,unegative=None,bpm=None,calories=None,date=None,comment=None,view=None): logging.debug('>>') if date == None: date = self.date.getDate() self.record.newRecord(date, title, distance, time, upositive, unegative, bpm, calories, comment) self.refreshListRecords() if view is not None: self.refreshGraphView(view) logging.debug('<<') def editRecord(self, id_record, view=None): logging.debug("Editing record with id: '%s'", id_record) self.record.editRecord(id_record) self.refreshListRecords() if view is not None: self.refreshGraphView(view) logging.debug('<<') def removeRecord(self, id_record, confirm = False, view=None): logging.debug('>>') if confirm: self.record.removeRecord(id_record) else: msg = _("Delete this database entry?") params = [id_record,True] warning = Warning(self.data_path,self.removeRecord,params) warning.set_text(msg) warning.run() self.refreshListRecords() if view is not None: self.refreshGraphView(view) logging.debug('<<') def removeWaypoint(self,id_waypoint, confirm = False): logging.debug('>>') if confirm: self.waypoint.removeWaypoint(id_waypoint) self.refreshWaypointView() else: msg = _("Delete this waypoint?") params = [id_waypoint,True] warning = Warning(self.data_path,self.removeWaypoint,params) warning.set_text(msg) warning.run() logging.debug('<<') def updateWaypoint(self,id_waypoint,lat,lon,name,desc,sym): logging.debug('>>') self.waypoint.updateWaypoint(id_waypoint,lat,lon,name,desc,sym) self.refreshWaypointView(id_waypoint) logging.debug('<<') def exportCsv(self): logging.debug('>>') from save import Save save = Save(self.data_path, self.record) save.run() logging.debug('<<') def editProfile(self): logging.debug('>>') self.profile.editProfile(self._sport_service) self.activitypool.clear_pool() self.windowmain.setup() logging.debug('<<')
class pyTrainer: def __init__(self, filename=None, data_path=None): #Version constants self.version = "1.9.2-dev" #Process command line options self.startup_options = self.get_options() #Setup logging self.environment = Environment(platform.get_platform(), self.startup_options.conf_dir) self.environment.create_directories() self.set_logging(self.startup_options.log_level, self.startup_options.log_type) logging.debug('>>') logging.debug("PyTrainer version %s" % (self.version)) self.data_path = data_path self.date = Date() self.ddbb = None # Checking profile logging.debug('Checking configuration and profile...') self.profile = Profile(self.environment, self.data_path, self) self.uc = UC() self.windowmain = None self.ddbb = DDBB(self.profile, self) logging.debug('connecting to DDBB') self.ddbb.connect() initialize_data(self.ddbb, self.environment.conf_dir) self._sport_service = SportService(self.ddbb) self.record = Record(self._sport_service, data_path, self) self.athlete = Athlete(data_path, self) self.stats = Stats(self._sport_service, self) pool_size = self.profile.getIntValue("pytraining", "activitypool_size", default=1) self.activitypool = ActivityPool(self, size=pool_size) #preparamos la ventana principal self.windowmain = Main(self._sport_service, data_path, self, self.version, gpxDir=self.profile.gpxdir) self.date = Date(self.windowmain.calendar) self.waypoint = Waypoint(data_path, self) self.extension = Extension(data_path, self) self.plugins = Plugins(data_path, self) self.importdata = Importdata(self._sport_service, data_path, self, self.profile) self.loadPlugins() self.loadExtensions() self.windowmain.setup() self.windowmain.on_calendar_selected(None) self.refreshMainSportList() self.windowmain.run() logging.debug('<<') def get_options(self): ''' Define usage and accepted options for command line startup returns: options - dict with option: value pairs ''' usage = '''usage: %prog [options] For more help on valid options try: %prog -h ''' parser = OptionParser(usage=usage) parser.set_defaults(log_level=logging.ERROR, validate=False, equip=False, newgraph=True, conf_dir=None, log_type="file") parser.add_option("-d", "--debug", action="store_const", const=logging.DEBUG, dest="log_level", help="enable logging at debug level") parser.add_option("-i", "--info", action="store_const", const=logging.INFO, dest="log_level", help="enable logging at info level") parser.add_option("-w", "--warn", action="store_const", const=logging.WARNING, dest="log_level", help="enable logging at warning level") parser.add_option( "--valid", action="store_true", dest="validate", help= "enable validation of files imported by plugins (details at info or debug logging level) - note plugin must support validation" ) parser.add_option("--oldgraph", action="store_false", dest="newgraph", help="Turn off new graphing approach") parser.add_option( "--newgraph", action="store_true", dest="newgraph", help="Deprecated Option: Turn on new graphing approach") parser.add_option( "--confdir", dest="conf_dir", help= "Specify the directory where application configuration will be stored." ) parser.add_option( "--logtype", dest="log_type", metavar="TYPE", type="choice", choices=["file", "console"], help= "Specify where logging should be output to. TYPE is one of 'file' (default), or 'console'." ) (options, args) = parser.parse_args() return options def set_logging(self, level, log_type): '''Setup rotating log file with customized format''' if ("console" == log_type): handler = logging.StreamHandler(sys.stdout) else: handler = logging.handlers.RotatingFileHandler( self.environment.log_file, maxBytes=100000, backupCount=5) formatter = logging.Formatter( '%(asctime)s|%(levelname)s|%(module)s|%(funcName)s|%(message)s') handler.setFormatter(formatter) logging.getLogger('').addHandler(handler) self.set_logging_level(self.startup_options.log_level) def set_logging_level(self, level): '''Set level of information written to log''' logging.debug("Setting logger to level: " + str(level)) logging.getLogger('').setLevel(level) def quit(self): logging.debug('--') logging.info("Exit!") #self.webservice.stop() self.windowmain.gtk_main_quit() logging.shutdown() sys.exit( ) # Any nonzero value is considered "abnormal termination" by shells and the like def loadPlugins(self): logging.debug('>>') activeplugins = self.plugins.getActivePlugins() if (len(activeplugins) < 1): logging.info("No active plugins") else: for plugin in activeplugins: txtbutton = self.plugins.loadPlugin(plugin) self.windowmain.addImportPlugin(txtbutton) logging.debug('<<') def loadExtensions(self): logging.debug('>>') activeextensions = self.extension.getActiveExtensions() if (len(activeextensions) < 1): logging.info("No active extensions") else: for extension in activeextensions: txtbutton = self.extension.loadExtension(extension) self.windowmain.addExtension(txtbutton) logging.debug('<<') def runPlugin(self, widget, pathPlugin): logging.debug('>>') self.pluginClass = self.plugins.importClass(pathPlugin) pluginFiles = self.pluginClass.run() if pluginFiles is not None: logging.debug("Plugin returned %d files" % (len(pluginFiles))) #process returned GPX files for (pluginFile, sport) in pluginFiles: if os.path.isfile(pluginFile): logging.info('File exists. Size: %d. Sport: %s' % (os.path.getsize(pluginFile), sport)) if self.record.importFromGPX(pluginFile, sport) is None: logging.error("Error importing file " + pluginFile) else: logging.error('File ' + pluginFile + ' not valid') else: logging.debug("No files returned from Plugin") self.refreshListRecords() self.refreshGraphView("day") logging.debug('<<') def runExtension(self, extension, id): logging.debug('>>') #print("Extension id: %s" % str(id)) activity = self.activitypool.get_activity(id) txtbutton, pathExtension, type = extension self.extensionClass = self.extension.importClass(pathExtension) self.extensionClass.run(id, activity) #if type == "record": # #Si es record le tenemos que crear el googlemaps, el gpx y darle el id de la bbdd # alert = self.extension.runExtension(pathExtension,id) logging.debug('<<') def refreshMainSportList(self): logging.debug('>>') sports = self._sport_service.get_all_sports() self.windowmain.updateSportList(sports) logging.debug('<<') def refreshGraphView(self, view, sport=None): logging.debug('>>') if self.windowmain is None: logging.debug("First call to refreshGraphView") logging.debug('<<') return date_selected = self.date.getDate() if view == "record": logging.debug('record view') if self.windowmain.recordview.get_current_page() == 0: self.refreshRecordGraphView("info") elif self.windowmain.recordview.get_current_page() == 1: self.refreshRecordGraphView("graphs") elif self.windowmain.recordview.get_current_page() == 2: self.refreshRecordGraphView("map") elif self.windowmain.recordview.get_current_page() == 3: self.refreshRecordGraphView("heartrate") elif self.windowmain.recordview.get_current_page() == 4: self.refreshRecordGraphView("analytics") elif view == "day": logging.debug('day view') sport = self.windowmain.activeSport sport_id = self.record.getSportId(sport) record_list = self.record.getrecordList(date_selected, sport_id) self.windowmain.actualize_dayview(record_list=record_list) #selected,iter = self.windowmain.recordTreeView.get_selection().get_selected() elif view == "week": logging.debug('week view') date_ini, date_end = self.date.getWeekInterval( date_selected, self.profile.prf_us_system) sport = self.windowmain.activeSport sport_id = self.record.getSportId(sport) record_list = self.record.getrecordPeriod(date_ini, date_end, sport_id) self.windowmain.actualize_weekview(record_list, date_ini, date_end) elif view == "month": logging.debug('month view') date_ini, date_end = self.date.getMonthInterval(date_selected) sport = self.windowmain.activeSport sport_id = self.record.getSportId(sport) # record_list = self.record.getrecordPeriodSport(date_ini, date_end,sport_id) record_list = self.record.getrecordPeriod(date_ini, date_end, sport_id) nameMonth, daysInMonth = self.date.getNameMonth(date_selected) self.windowmain.actualize_monthview(record_list, nameMonth) self.windowmain.actualize_monthgraph(record_list, daysInMonth) elif view == "year": logging.debug('year view') date_ini, date_end = self.date.getYearInterval(date_selected) sport = self.windowmain.activeSport sport_id = self.record.getSportId(sport) year = self.date.getYear(date_selected) # record_list = self.record.getrecordPeriodSport(date_ini, date_end,sport_id) record_list = self.record.getrecordPeriod(date_ini, date_end, sport_id) self.windowmain.actualize_yearview(record_list, year) self.windowmain.actualize_yeargraph(record_list) elif view == "listview": logging.debug('list view') self.refreshListView() elif view == "athlete": logging.debug('athlete view') self.windowmain.on_athleteview_activate() elif view == "stats": logging.debug('stats view') self.windowmain.on_statsview_activate() else: print "Unknown view %s" % view logging.debug('<<') def refreshRecordGraphView(self, view, id_record=None): logging.debug('>>') logging.info('Working on ' + view + ' graph') if id_record is not None: #Refresh called for a specific record #Select correct record in treeview model = self.windowmain.recordTreeView.get_model() #Loop through all records in treeview looking for the correct one to highlight for i, row in enumerate(model): if row[0] == id_record: self.windowmain.recordTreeView.set_cursor(i) else: selected, iter = self.windowmain.recordTreeView.get_selection( ).get_selected() if iter: id_record = selected.get_value(iter, 0) else: id_record = None view = "info" activity = self.activitypool.get_activity(id_record) if view == "info": self.windowmain.actualize_recordview(activity) if view == "graphs": self.windowmain.actualize_recordgraph(activity) if view == "map": self.refreshMapView() if view == "heartrate": self.windowmain.actualize_heartrategraph(activity) self.windowmain.actualize_hrview(activity) if view == "analytics": self.windowmain.actualize_analytics(activity) logging.debug('<<') def refreshMapView(self, full_screen=False): logging.debug('>>') if self.windowmain is None: logging.debug('Called before windowmain initialisation') logging.debug('<<') return selected, iter = self.windowmain.recordTreeView.get_selection( ).get_selected() id_record = selected.get_value(iter, 0) activity = self.activitypool.get_activity(id_record) logging.debug('Trying to show map for record ' + str(id_record)) self.windowmain.actualize_map(activity, full_screen) logging.debug('<<') def refreshListRecords(self): logging.debug('>>') #Refresh list view #self.refreshListView() # old variant self.refreshListView(self.windowmain.listsearch.condition) #Refresh list records date = self.date.getDate() sport = self.windowmain.activeSport id_sport = self.record.getSportId(sport) record_ids = self.record.getrecordList(date, id_sport) self.windowmain.actualize_recordTreeView(record_ids) #Mark the monthly calendar to show which days have activity? record_list = self.record.getRecordDayList(date, id_sport) self.windowmain.actualize_calendar(record_list) logging.debug('<<') def refreshAthleteView(self): logging.debug('>>') self.athlete.refresh() self.windowmain.actualize_athleteview(self.athlete) logging.debug('<<') def refreshStatsView(self): logging.debug('>>') self.stats.refresh() self.windowmain.actualize_statsview(self.stats, self.record.getAllRecordList()) logging.debug('<<') def refreshListView(self, condition=None): logging.debug('>>') record_list = self.record.getRecordListByCondition(condition) self.windowmain.actualize_listview(record_list) logging.debug('<<') def refreshWaypointView(self, default_waypoint=None, redrawmap=1): logging.debug('>>') waypoint_list = self.waypoint.getAllWaypoints() self.windowmain.actualize_waypointview(waypoint_list, default_waypoint, redrawmap) logging.debug('<<') def editExtensions(self): logging.debug('>>') before = self.extension.getActiveExtensions() self.extension.manageExtensions() after = self.extension.getActiveExtensions() self.setExtensions(before, after) logging.debug('<<') def importData(self): logging.debug('>>') activeplugins_before = self.plugins.getActivePlugins() self.importdata.runImportdata() activeplugins_after = self.plugins.getActivePlugins() #Need to check for plugins that have been disabled (were active and now are not) self.setMenuPlugins(activeplugins_before, activeplugins_after) self.refreshListRecords() self.refreshGraphView(self.windowmain.selected_view) logging.debug('<<') def editGpsPlugins(self): logging.debug('>>') activeplugins_before = self.plugins.getActivePlugins() self.plugins.managePlugins() activeplugins_after = self.plugins.getActivePlugins() #Need to check for plugins that have been disabled (were active and now are not) self.setMenuPlugins(activeplugins_before, activeplugins_after) logging.debug('<<') def setMenuPlugins(self, activeplugins_before, activeplugins_after): logging.debug('>>') #Need to check for plugins that have been disabled (were active and now are not) for plugin in activeplugins_before: if plugin not in activeplugins_after: #disabled plugin -> need to unload plugin txtbutton = self.plugins.loadPlugin(plugin) self.windowmain.removeImportPlugin(txtbutton) #Need to check for plugins that have been enabled (were not active and now are) for plugin in activeplugins_after: if plugin not in activeplugins_before: #new active plugin -> need to load plugin txtbutton = self.plugins.loadPlugin(plugin) self.windowmain.addImportPlugin(txtbutton) logging.debug('<<') def setExtensions(self, before, after): logging.debug('>>') #Need to check for extensions that have been disabled (were active and now are not) for extension in before: if extension not in after: #disabled extension -> need to unload extension print "Need to disable extension %s " % extension txtbutton = self.extension.loadExtension(extension) self.windowmain.removeExtension(txtbutton) #Need to check for plugins that have been enabled (were not active and now are) for extension in after: if extension not in before: #new active extension -> need to load extension logging.debug("Enabling extension %s " % extension) txtbutton = self.extension.loadExtension(extension) self.windowmain.addExtension(txtbutton) logging.debug('<<') def newRecord(self, title=None, distance=None, time=None, upositive=None, unegative=None, bpm=None, calories=None, date=None, comment=None, view=None): logging.debug('>>') if date == None: date = self.date.getDate() self.record.newRecord(date, title, distance, time, upositive, unegative, bpm, calories, comment) self.refreshListRecords() if view is not None: self.refreshGraphView(view) logging.debug('<<') def editRecord(self, id_record, view=None): logging.debug("Editing record with id: '%s'", id_record) self.record.editRecord(id_record) self.refreshListRecords() if view is not None: self.refreshGraphView(view) logging.debug('<<') def removeRecord(self, id_record, confirm=False, view=None): logging.debug('>>') if confirm: self.record.removeRecord(id_record) else: msg = _("Delete this database entry?") params = [id_record, True] warning = Warning(self.data_path, self.removeRecord, params) warning.set_text(msg) warning.run() self.refreshListRecords() if view is not None: self.refreshGraphView(view) logging.debug('<<') def removeWaypoint(self, id_waypoint, confirm=False): logging.debug('>>') if confirm: self.waypoint.removeWaypoint(id_waypoint) self.refreshWaypointView() else: msg = _("Delete this waypoint?") params = [id_waypoint, True] warning = Warning(self.data_path, self.removeWaypoint, params) warning.set_text(msg) warning.run() logging.debug('<<') def updateWaypoint(self, id_waypoint, lat, lon, name, desc, sym): logging.debug('>>') self.waypoint.updateWaypoint(id_waypoint, lat, lon, name, desc, sym) self.refreshWaypointView(id_waypoint) logging.debug('<<') def exportCsv(self): logging.debug('>>') from save import Save save = Save(self.data_path, self.record) save.run() logging.debug('<<') def editProfile(self): logging.debug('>>') self.profile.editProfile(self._sport_service) self.activitypool.clear_pool() self.windowmain.setup() logging.debug('<<')