From 76bc290623af2a62ec02b1440de2e1c1059f23c2 Mon Sep 17 00:00:00 2001
From: Rudi Grinberg <rudi.grinberg@sourcefabric.org>
Date: Thu, 9 Aug 2012 18:24:50 -0400
Subject: [PATCH] cc-4105: modularized mm2.py. fixed little bug where proper
 last ran time wasn't being used

---
 .../media-monitor2/media/monitor/airtime.py   |   3 +-
 python_apps/media-monitor2/mm2.py             | 135 ++++++++++--------
 2 files changed, 73 insertions(+), 65 deletions(-)

diff --git a/python_apps/media-monitor2/media/monitor/airtime.py b/python_apps/media-monitor2/media/monitor/airtime.py
index 56725aaeb..9a43ee39c 100644
--- a/python_apps/media-monitor2/media/monitor/airtime.py
+++ b/python_apps/media-monitor2/media/monitor/airtime.py
@@ -3,7 +3,6 @@ from kombu.messaging import Exchange, Queue, Consumer
 from kombu.connection import BrokerConnection
 import json
 import os
-import time
 import copy
 import traceback
 
@@ -105,7 +104,7 @@ class AirtimeMessageReceiver(Loggable):
         if directory == None: directory = sdb.to_directory(directory_id)
         try:
             bs = Bootstrapper( sdb, self.manager.watch_signal() )
-            bs.flush_watch( directory=directory, last_ran=time.time() )
+            bs.flush_watch( directory=directory, last_ran=self.cfg.last_ran() )
         except Exception as e:
             self.logger.info( "Exception bootstrapping: (dir,id)=(%s,%s)" %
                     (directory, directory_id) )
diff --git a/python_apps/media-monitor2/mm2.py b/python_apps/media-monitor2/mm2.py
index 76c41beb4..7da586d9e 100644
--- a/python_apps/media-monitor2/mm2.py
+++ b/python_apps/media-monitor2/mm2.py
@@ -18,82 +18,91 @@ import media.monitor.pure as mmp
 
 from api_clients import api_client as apc
 
-base_path = u'/home/rudi/Airtime/python_apps/media-monitor2/tests'
-global_config = os.path.join(base_path,u'live_client.cfg')
-api_client_config = global_config
 
-# MMConfig is a proxy around ConfigObj instances. it does not allow itself
-# users of MMConfig instances to modify any config options directly through the
-# dictionary. Users of this object muse use the correct methods designated for
-# modification
-try: config = MMConfig(global_config)
-except NoConfigFile as e:
-    print("Cannot run mediamonitor2 without configuration file.")
-    print("Current config path: '%s'" % global_config)
-    sys.exit(1)
-except Exception as e:
-    print("Unknown error reading configuration file: '%s'" % global_config)
-    print(str(e))
+def main(global_config, api_client_config):
+    for cfg in [global_config, api_client_config]:
+        if not os.path.exists(cfg): raise NoConfigFile(cfg)
+    # MMConfig is a proxy around ConfigObj instances. it does not allow
+    # itself users of MMConfig instances to modify any config options
+    # directly through the dictionary. Users of this object muse use the
+    # correct methods designated for modification
+    try: config = MMConfig(global_config)
+    except NoConfigFile as e:
+        print("Cannot run mediamonitor2 without configuration file.")
+        print("Current config path: '%s'" % global_config)
+        sys.exit(1)
+    except Exception as e:
+        print("Unknown error reading configuration file: '%s'" % global_config)
+        print(str(e))
 
-logfile = unicode( config['logpath'] )
-setup_logging(logfile)
-log = get_logger()
-log.info("Attempting to set the locale...")
+    logfile = unicode( config['logpath'] )
+    setup_logging(logfile)
+    log = get_logger()
+    log.info("Attempting to set the locale...")
 
-try:
-    mmp.configure_locale(mmp.get_system_locale())
-except FailedToSetLocale as e:
-    log.info("Failed to set the locale...")
-    sys.exit(1)
-except FailedToObtainLocale as e:
-    log.info("Failed to obtain the locale form the default path: \
-            '/etc/default/locale'")
-    sys.exit(1)
-except Exception as e:
-    log.info("Failed to set the locale for unknown reason. Logging exception.")
-    log.info(str(e))
+    try:
+        mmp.configure_locale(mmp.get_system_locale())
+    except FailedToSetLocale as e:
+        log.info("Failed to set the locale...")
+        sys.exit(1)
+    except FailedToObtainLocale as e:
+        log.info("Failed to obtain the locale form the default path: \
+                '/etc/default/locale'")
+        sys.exit(1)
+    except Exception as e:
+        log.info("Failed to set the locale for unknown reason. \
+                Logging exception.")
+        log.info(str(e))
 
-watch_syncer = WatchSyncer(signal='watch',
-                           chunking_number=config['chunking_number'],
-                           timeout=config['request_max_wait'])
+    watch_syncer = WatchSyncer(signal='watch',
+                            chunking_number=config['chunking_number'],
+                            timeout=config['request_max_wait'])
 
-apiclient = apc.AirtimeApiClient.create_right_config(log=log,
-        config_path=api_client_config)
+    apiclient = apc.AirtimeApiClient.create_right_config(log=log,
+            config_path=api_client_config)
 
-ReplayGainUpdater.start_reply_gain(apiclient)
+    ReplayGainUpdater.start_reply_gain(apiclient)
 
-sdb = AirtimeDB(apiclient)
+    sdb = AirtimeDB(apiclient)
 
-manager = Manager()
+    manager = Manager()
 
-airtime_receiver = AirtimeMessageReceiver(config,manager)
-airtime_notifier = AirtimeNotifier(config, airtime_receiver)
+    airtime_receiver = AirtimeMessageReceiver(config,manager)
+    airtime_notifier = AirtimeNotifier(config, airtime_receiver)
 
-store = apiclient.setup_media_monitor()
-airtime_receiver.change_storage({ 'directory':store[u'stor'] })
+    store = apiclient.setup_media_monitor()
+    airtime_receiver.change_storage({ 'directory':store[u'stor'] })
 
-for watch_dir in store[u'watched_dirs']:
-    if not os.path.exists(watch_dir):
-        # Create the watch_directory here
-        try: os.makedirs(watch_dir)
-        except Exception as e:
-            log.error("Could not create watch directory: '%s' \
-                    (given from the database)." % watch_dir)
-    if os.path.exists(watch_dir):
-        airtime_receiver.new_watch({ 'directory':watch_dir })
+    for watch_dir in store[u'watched_dirs']:
+        if not os.path.exists(watch_dir):
+            # Create the watch_directory here
+            try: os.makedirs(watch_dir)
+            except Exception as e:
+                log.error("Could not create watch directory: '%s' \
+                        (given from the database)." % watch_dir)
+        if os.path.exists(watch_dir):
+            airtime_receiver.new_watch({ 'directory':watch_dir })
 
-last_ran=config.last_ran()
-bs = Bootstrapper( db=sdb, watch_signal='watch' )
+    last_ran=config.last_ran()
+    bs = Bootstrapper( db=sdb, watch_signal='watch' )
 
-#bs.flush_all( config.last_ran() )
+    #bs.flush_all( config.last_ran() )
 
-ed = EventDrainer(airtime_notifier.connection,
-        interval=float(config['rmq_event_wait']))
+    ed = EventDrainer(airtime_notifier.connection,
+            interval=float(config['rmq_event_wait']))
 
-# Launch the toucher that updates the last time when the script was ran every n
-# seconds.
-tt = ToucherThread(path=config['index_path'],
-        interval=int(config['touch_interval']))
+    # Launch the toucher that updates the last time when the script was
+    # ran every n seconds.
+    tt = ToucherThread(path=config['index_path'],
+            interval=int(config['touch_interval']))
 
-pyi = manager.pyinotify()
-pyi.loop()
+    pyi = manager.pyinotify()
+    pyi.loop()
+
+if __name__ == '__main__':
+    # TODO : parse these from command line arguments
+    # TODO : add log config stuff
+    base_path = u'/home/rudi/Airtime/python_apps/media-monitor2/tests'
+    global_config = os.path.join(base_path, u'live_client.cfg')
+    api_client_config = global_config
+    main(global_config, api_client_config)