Beispiel #1
0
 def __init__(self):
     super().__init__()
     self.running = True
     config = load_config()
     self.webapp = Application(config)
     self.webapp.bot.api = DummyTelegramApi()
     self.webapp.bot.evernote = DummyEvernoteApi()
 def test_base(self):
     request = Request({})
     request.app = Application(self.config)
     request.app.bot.api.sendMessage = MockMethod(result={'message_id': 1})
     request.app.bot.api.editMessageReplyMarkup = MockMethod()
     fake_oauth_data = {
         'oauth_url': 'url',
         'oauth_token': 'token',
         'oauth_token_secret': 'secret',
         'callback_key': 'key',
     }
     request.app.bot.evernote.get_oauth_data = MockMethod(
         result=fake_oauth_data)
     data = self.fixtures['start_command']
     update = TelegramUpdate(data)
     start_command(request.app.bot, update.message)
     self.assertEqual(request.app.bot.api.sendMessage.call_count, 1)
     users = request.app.bot.get_storage(User).get_all({})
     self.assertEqual(len(users), 1)
     oauth = users[0].evernote.oauth
     self.assertIsNotNone(oauth.token)
     self.assertIsNotNone(oauth.secret)
     self.assertIsNotNone(oauth.callback_key)
     self.assertEqual(request.app.bot.api.editMessageReplyMarkup.call_count,
                      1)
     self.assertEqual(request.app.bot.evernote.get_oauth_data.call_count, 1)
 def __init__(self):
     super().__init__()
     self.running = True
     config = load_config()
     self.webapp = Application(config)
     self.webapp.bot.api = DummyTelegramApi()
     self.webapp.bot.evernote = DummyEvernoteApi()
    def test_base(self):
        request = Request({})
        request.app = Application(self.config)
        request.app.bot.api.sendMessage = MockMethod(result={'message_id': 1})
        request.app.bot.api.editMessageReplyMarkup = MockMethod()
        update = TelegramUpdate(self.fixtures['start_command'])
        start_command(request.app.bot, update.message)
        self.assertEqual(request.app.bot.api.sendMessage.call_count, 1)
        self.assertEqual(request.app.bot.api.editMessageReplyMarkup.call_count, 1)

        update = TelegramUpdate(self.fixtures['switch_mode_command'])
        switch_mode_command(request.app.bot, update.message)
        users = request.app.bot.get_storage(User).get_all({})
        user_id = users[0].id
        callback_key = users[0].evernote.oauth.callback_key
        self.assertEqual(users[0].state, 'switch_mode')
        self.assertEqual(request.app.bot.api.sendMessage.call_count, 2)
        self.assertEqual(request.app.bot.api.editMessageReplyMarkup.call_count, 1)

        fake_oauth_data = {
            'oauth_url': 'url',
            'oauth_token': 'token',
            'oauth_token_secret': 'secret',
            'callback_key': callback_key,
        }
        request.app.bot.evernote.get_oauth_data = MockMethod(result=fake_oauth_data)
        update = TelegramUpdate(self.fixtures['one_note_mode_text'])
        request.app.bot.handle_message(update.message)
        self.assertEqual(request.app.bot.evernote.get_oauth_data.call_count, 1)
        self.assertEqual(request.app.bot.api.sendMessage.call_count, 4)
        user = request.app.bot.get_storage(User).get(user_id)
        self.assertEqual(user.state, None)
        self.assertEqual(user.bot_mode, 'multiple_notes')

        request.app.bot.evernote.get_access_token = MockMethod(result='token')
        request.app.bot.evernote.get_note_link = MockMethod()
        Note = namedtuple('Note', ['guid', 'content'])
        request.app.bot.evernote.create_note = MockMethod(result=Note(guid='guid:123', content=''))
        oauth_request = Request({'QUERY_STRING': 'key={key}&oauth_verifier=x&access=full'.format(key=callback_key)})
        oauth_request.app = request.app
        response = evernote_oauth(oauth_request)
        self.assertIsNotNone(response)
        self.assertEqual(request.app.bot.evernote.create_note.call_count, 1)
        user = request.app.bot.get_storage(User).get(user_id)
        self.assertEqual(user.bot_mode, 'one_note')
        self.assertEqual(user.evernote.shared_note_id, 'guid:123')

        # NOTE: try save text
        request.app.bot.api.editMessageText = MockMethod()
        request.app.bot.evernote.update_note = MockMethod(result=Note(content='', guid='guid:123'))
        data = self.fixtures['simple_text']
        update = TelegramUpdate(data)
        handle_text(request.app.bot, update.message)
        self.assertEqual(request.app.bot.evernote.update_note.call_count, 1)
        args = request.app.bot.evernote.update_note.calls[0]['args']
        self.assertTrue(args[1] == 'guid:123')
        self.assertEqual(request.app.bot.api.editMessageText.call_count, 1)
Beispiel #5
0
 def test_base(self):
     request = Request({})
     request.app = Application(self.config)
     request.app.bot.handle_telegram_update = MockMethod()
     data = self.fixtures['simple_text']
     request.body = json.dumps(data).encode()
     telegram_hook(request)
     method = request.app.bot.handle_telegram_update
     self.assertEqual(method.call_count, 1)
     arg = method.calls[0]['args'][0]
     self.assertEqual(arg.__class__.__name__, 'TelegramUpdate')
 def test_base(self):
     request = Request({
         'QUERY_STRING':
         'key=secret&oauth_verifier=verifier&access=basic'
     })
     request.app = Application(self.config)
     request.app.bot.oauth_callback = MockMethod()
     response = evernote_oauth(request)
     self.assertIsNotNone(response)
     self.assertEqual(response.headers[0][0], 'Location')
     method = request.app.bot.oauth_callback
     self.assertEqual(method.call_count, 1)
     args = method.calls[0]['args']
     self.assertEqual(len(args), 3)
     self.assertEqual(args[0], 'secret')
     self.assertEqual(args[1], 'verifier')
     self.assertEqual(args[2], 'basic')
class DevServer(Thread):
    def __init__(self):
        super().__init__()
        self.running = True
        config = load_config()
        self.webapp = Application(config)
        self.webapp.bot.api = DummyTelegramApi()
        self.webapp.bot.evernote = DummyEvernoteApi()

    def run(self):
        def app(environ, start_response):
            status, response_headers, response_body = self.webapp.handle_request(environ)
            start_response(status, response_headers)
            return [response_body]

        server = make_server('', 8080, app)
        while self.running:
            server.handle_request()

    def stop(self):
        print('Stopping server...', end='')
        self.running = False
        print('OK')
Beispiel #8
0
class DevServer(Thread):
    def __init__(self):
        super().__init__()
        self.running = True
        config = load_config()
        self.webapp = Application(config)
        self.webapp.bot.api = DummyTelegramApi()
        self.webapp.bot.evernote = DummyEvernoteApi()

    def run(self):
        def app(environ, start_response):
            status, response_headers, response_body = self.webapp.handle_request(
                environ)
            start_response(status, response_headers)
            return [response_body]

        server = make_server('', 8080, app)
        while self.running:
            server.handle_request()

    def stop(self):
        print('Stopping server...', end='')
        self.running = False
        print('OK')
Beispiel #9
0
    # init logging
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG if config.debug else logging.INFO)
    channel = logging.StreamHandler(sys.stdout)
    channel.setFormatter(tornado.log.LogFormatter())
    logger.addHandler(channel)

    if not config.debug:
        channel = logging.StreamHandler(sys.stderr)
        channel.setFormatter(tornado.log.LogFormatter())
        channel.setLevel(logging.WARNING)
        logger.addHandler(channel)

    if len(sys.argv) > 2 and sys.argv[1] == '-p' and sys.argv[2].isdigit():
        port = int(sys.argv[2])
    else:
        port = config.port
    converter = sqlite3_db_task_converter.DBconverter()
    converter.ConvertNewType()

    http_server = HTTPServer(Application(), xheaders=True)
    http_server.bind(port, config.bind)
    http_server.start()

    worker = MainWorker()
    PeriodicCallback(worker, config.check_task_loop).start()
    worker()

    logging.info("http server started on %s:%s", config.bind, port)
    IOLoop.instance().start()
Beispiel #10
0
#!/usr/bin/env python
import os
import sys
import tornado.wsgi
from web.app import Application

sys.path.append(
    os.path.join(os.path.dirname(os.path.abspath(__file__)), 'lib', 'python'))

app = tornado.wsgi.WSGIAdapter(Application().make_app())
from www import register_blueprint

base_dir = os.path.abspath(os.path.dirname(__file__))

if win:
    template_folder = os.path.join(base_dir, f"web\\templates\\")
    static_folder = os.path.join(base_dir, f"web\\static\\")
    # todo 考虑配置文件导入,放在Application类之中
    base_config = os.path.join(base_dir, f"config\\base_setting.py")
    env_config = os.path.join(base_dir, f"config\\{os.getenv('FLASK_CONFIG', 'local_setting')}.py")
else:
    template_folder = os.path.join(base_dir, f"web/templates/")
    static_folder = os.path.join(base_dir, f"web/static/")
    base_config = os.path.join(base_dir, f"config/base_setting.py")
    env_config = os.path.join(base_dir, f"config/{os.getenv('FLASK_CONFIG', 'local_setting')}.py")

app = Application(__name__, template_folder=template_folder, root_path=os.getcwd(), static_folder=static_folder)
app.config.from_pyfile(base_config)
app.config.from_pyfile(env_config)
db.init_app(app)
register_blueprint(app)
app.before_request(check_auth)
register_error(app)

app.add_template_global(UrlManager.buildUrl, 'buildUrl')
app.add_template_global(UrlManager.buildStaticUrl, 'buildStaticUrl')
app.add_template_global(UrlManager.buildImageUrl, 'buildImageUrl')

# Manager 没有init__app() 方法
manager = Manager(app)
Beispiel #12
0
    channel = logging.StreamHandler(sys.stdout)
    channel.setFormatter(tornado.log.LogFormatter())
    logger.addHandler(channel)

    if not config.debug:
        channel = logging.StreamHandler(sys.stderr)
        channel.setFormatter(tornado.log.LogFormatter())
        channel.setLevel(logging.WARNING)
        logger.addHandler(channel)

    if len(sys.argv) > 2 and sys.argv[1] == '-p' and sys.argv[2].isdigit():
        port = int(sys.argv[2])
    else:
        port = config.port

    http_server = HTTPServer(Application(), xheaders=True)
    http_server.bind(port, config.bind)
    http_server.start()

    https_enable = False
    if os.path.exists(config.certfile) & os.path.exists(config.keyfile):
        https_enable = True
        https_server = HTTPServer(Application(), ssl_options={
            "certfile": os.path.abspath(config.certfile),
            "keyfile": os.path.abspath(config.keyfile),
        }, xheaders=True)
        https_server.bind(config.https_port, config.bind)
        https_server.start()

    converter = sqlite3_db_task_converter.DBconverter()
    converter.ConvertNewType() 
Beispiel #13
0
from web.app import Application
from config import load_config

config = load_config()
webapp = Application(config)
webapp.bot.api.setWebhook(config['webhook_url'])


def app(environ, start_response):
    status, response_headers, response_body = webapp.handle_request(environ)
    start_response(status, response_headers)
    return [response_body]