Commits

Konstantine Rybnikov committed cbb6276

can't remember, it was long time ago. But I'm rewriting it to be more clear

Comments (0)

Files changed (5)

 #!/usr/bin/python
 # -*- coding: utf-8 -*-
 
-import sys
-import xmpp
+# configuration
+DEBUG = True
+JID = 'openju@example.com'
+PASSWORD = 'FasengEntoabApJo'
 
-# you should kind a just skip this file
-# and go to message_cb.py, it's like routes
-from openju.messagecb import message_cb
-
-from openju.config import set_config_profile, get_conf_val
-from openju.util import *
-
-def StepOn(conn):
-    try:
-        conn.Process(1)
-    except KeyboardInterrupt: return 0
-    return 1
-
-def main():
-    set_config_profile('dev')
-    
-    jid = xmpp.JID(get_conf_val('jid'))
-    user, server, password = jid.getNode(), jid.getDomain(), get_conf_val('pwd')
-    
-    conn = xmpp.Client(server, debug=[])
-    conres = conn.connect()
-    if not conres:
-        print "> Unable to connect to server %s!" % server
-        sys.exit(1)
-    if conres != 'tls':
-        print "> Warning: unable to estabilish secure connection - TLS failed!"
-    authres = conn.auth(user,password)
-    if not authres:
-        print "> Unable to authorize on %s - check login/password." % server
-        sys.exit(1)
-    conn.RegisterHandler('message', message_cb)
-    conn.sendInitPresence()
-    print "> Bot started."
-    while StepOn(conn):
-        pass
+from openju import OpenJu
+app = OpenJu(__name__)
+app.config.from_object(__name__)
 
 if __name__ == '__main__':
-    main()
+    app.run()
+
+# from openju.messagecb import message_cb
+
+# from openju.config import set_config_profile, get_conf_val
+# from openju.util import *
+
+# def StepOn(conn):
+#     try:
+#         conn.Process(1)
+#     except KeyboardInterrupt: return 0
+#     return 1
+
+# def main():
+#     set_config_profile('dev')
     
+#     jid = xmpp.JID(get_conf_val('jid'))
+#     user, server, password = jid.getNode(), jid.getDomain(), get_conf_val('pwd')
+    
+#     conn = xmpp.Client(server, debug=[])
+#     conres = conn.connect()
+#     if not conres:
+#         print "> Unable to connect to server %s!" % server
+#         sys.exit(1)
+#     if conres != 'tls':
+#         print "> Warning: unable to estabilish secure connection - TLS failed!"
+#     authres = conn.auth(user,password)
+#     if not authres:
+#         print "> Unable to authorize on %s - check login/password." % server
+#         sys.exit(1)
+#     conn.RegisterHandler('message', message_cb)
+#     conn.sendInitPresence()
+#     print "> Bot started."
+#     while StepOn(conn):
+#         pass
+
+# if __name__ == '__main__':
+#     main()
+    

openju/__init__.py

-import threading
+# -*- coding: utf-8 -*-
 
-_ = lambda x: x
+from .globals import g
+from .app import OpenJu
 
-class MetaObject:
-    def __setattr__(self, key, value):
-        setattr(meta_store, key, value)
+# _ = lambda x: x
+
+# class MetaObject:
+#     def __setattr__(self, key, value):
+#         setattr(meta_store, key, value)
     
-    def __getattr__(self, key):
-        value = getattr(meta_store, key)
-        # delattr(meta_store, key)
-        return value
+#     def __getattr__(self, key):
+#         value = getattr(meta_store, key)
+#         # delattr(meta_store, key)
+#         return value
 
-meta_store = threading.local()
-g = MetaObject()
+# meta_store = threading.local()
 
-import messagecb
-import bl
+# import messagecb
+# import bl
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+import os
+import sys
+from flask.config import Config, ConfigAttribute
+from threading import Lock
+
+import xmpp
+
+# a lock used for logger initialization
+_logger_lock = Lock()
+
+def _get_package_path(name):
+    """Returns the path to a package or cwd if that cannot be found."""
+    try:
+        return os.path.abspath(os.path.dirname(sys.modules[name].__file__))
+    except (KeyError, AttributeError):
+        return os.getcwd()
+
+class OpenJu():
+    #: The logging format used for the debug logger.  This is only used when
+    #: the application is in debug mode, otherwise the attached logging
+    #: handler does the formatting.
+    #:
+    #: .. versionadded:: 0.3
+    debug_log_format = (
+        '-' * 80 + '\n' +
+        '%(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n' +
+        '%(message)s\n' +
+        '-' * 80
+    )
+    
+    #: The debug flag.  Set this to `True` to enable debugging of the
+    #: application.  In debug mode the debugger will kick in when an unhandled
+    #: exception ocurrs and the integrated server will automatically reload
+    #: the application if changes in the code are detected.
+    #:
+    #: This attribute can also be configured from the config with the `DEBUG`
+    #: configuration key.  Defaults to `False`.
+    debug = ConfigAttribute('DEBUG')
+    
+    # TODO: make it werkzeug.ImmutableDict
+    default_config = {
+        'DEBUG': False,
+        'JID': None,
+        'PWD': None,
+        'MONGO_DBNAME': 'openju',
+        'LOGGER_NAME': None,
+    }
+    
+    def __init__(self, import_name):
+        #: The name of the package or module.  Do not change this once
+        #: it was set by the constructor.
+        self.import_name = import_name
+        
+        #: Where is the app root located?
+        self.root_path = _get_package_path(self.import_name)
+        
+        self._logger = None
+        self.logger_name = self.import_name
+        
+        self.config = Config(self.root_path, self.default_config)
+    
+    @property
+    def logger(self):
+        """A :class:`logging.Logger` object for this application.  The
+        default configuration is to log to stderr if the application is
+        in debug mode.  This logger can be used to (surprise) log messages.
+        Here some examples::
+
+            app.logger.debug('A value for debugging')
+            app.logger.warning('A warning ocurred (%d apples)', 42)
+            app.logger.error('An error occoured')
+
+        .. versionadded:: 0.3
+        """
+        if self._logger and self._logger.name == self.logger_name:
+            return self._logger
+        with _logger_lock:
+            if self._logger and self._logger.name == self.logger_name:
+                return self._logger
+            from flask.logging import create_logger
+            self._logger = rv = create_logger(self)
+            return rv
+        
+    def run(self):
+        jid = xmpp.JID(self.config['JID'])
+        user, server, password = jid.getNode(), jid.getDomain(), self.config['PASSWORD']
+        if self.config['DEBUG']:
+            conn = xmpp.Client(server, debug=[])
+        else:
+            conn = xmpp.Client(server)
+        conres = conn.connect()
+        if not conres:
+            raise Exception("Unable to connect to server %s!" % server)
+        if conres != 'tls':
+            self.logger.warning("Unable to estabilish secure connection - TLS failed!")
+        authres = conn.auth(user, password)
+        if not authres:
+            raise Exception("Unable to authorize on %s - check login/password." % server)
+        
+        from openju.messagecb import message_cb
+        conn.RegisterHandler('message', message_cb)
+        conn.sendInitPresence()
+        self.logger.info('Bot started')
+        
+        def step_on(conn):
+            try:
+                conn.Process(1)
+            except KeyboardInterrupt:
+                return False
+            return True
+        
+        # step on
+        while step_on(conn):
+            pass
+        

openju/globals.py

+# -*- coding: utf-8 -*-
+
+from werkzeug import LocalStack, LocalProxy
+
+_request_ctx_stack = LocalStack()
+g = LocalProxy(lambda: _request_ctx_stack.top.g)
 # -*- coding: utf-8 -*-
 
 from pymongo import Connection
-from openju.config import get_conf_val
 
 class mongo_connection_wrapper(object):
     def __init__(self):