diff --git a/.gitignore b/.gitignore index 45b4278..f774a56 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,10 @@ *.pyc .idea/* /logs -/conf/levels.db* +levels.db* /build /dist /libs +/conf *.spec *.log diff --git a/conf/blacklist.cfg b/conf/blacklist.cfg deleted file mode 100644 index 25a7b58..0000000 --- a/conf/blacklist.cfg +++ /dev/null @@ -1,26 +0,0 @@ -[gui_information] -category = messaging -id = 30 - -[main] -message = Пытаеться что-то сказать, но у него лалка во рту - -[users__gui] -for = users_hide, users_block -view = list -addable = true - -[users_hide] - -[users_block] -announce - -[words__gui] -for = words_hide, words_block -addable = true -view = list - -[words_hide] - -[words_block] - diff --git a/conf/c2b.cfg b/conf/c2b.cfg deleted file mode 100644 index 8386b77..0000000 --- a/conf/c2b.cfg +++ /dev/null @@ -1,15 +0,0 @@ -[gui_information] -category = messaging -id = 10 - -[config__gui] -for = config -view = list_dual -addable = true - -[config] -sc2tv = funstream, адольф -gnomoria = игра, которую нельзя называть -гномория = игра, которая не нужна -czt = lalka - diff --git a/conf/chat_modules.cfg b/conf/chat_modules.cfg deleted file mode 100644 index 5ab8adb..0000000 --- a/conf/chat_modules.cfg +++ /dev/null @@ -1,15 +0,0 @@ -[gui_information] -category = main - -[chats] -goodgame -sc2tv -twitch - -[chats__gui] -for = chats -view = choose_multiple -check_type = files -check = modules/chats -file_extension = False - diff --git a/conf/config.cfg b/conf/config.cfg deleted file mode 100644 index 3bf341c..0000000 --- a/conf/config.cfg +++ /dev/null @@ -1,18 +0,0 @@ -[gui_information] -category = main - -[language__gui] -check = translations -check_type = folder -for = language -view = choose_single - -[gui] -on_top = True -gui = True -show_hidden = True -reload - -[language] -en - diff --git a/conf/df.cfg b/conf/df.cfg deleted file mode 100644 index c1c7f83..0000000 --- a/conf/df.cfg +++ /dev/null @@ -1,32 +0,0 @@ -[gui_information] -category = messaging - -[grep] -symbol = # -file = logs/df.txt - -[prof__gui] -for = prof -view = list_dual -addable = true - -[prof] -archer = ([Лл]учник|[Aa]rcher) -carpenter = ([Пп]лотник|[Cc]arpenter|[Ll]umberjack) -child = ([Дд]итя|[Cc]hild) -clothemaker = ([Шш]ве[яй]|[Cc]lothemaker) -craftsdwarf = ([Кк]рафтер|[Cc]raft(er|sdwarf)) -engraver = ([Шш]лифов(щик|альщик)|[Ee]ngraver]) -farmer = ([Фф]ермер|[Пп]овар|[Бб]ухлодел|[Ff]armer|[Bb]rewer|[Cc]ook) -fisher = ([Рр]ыбак|[Ff]isher) -hunter = ([Оо]хотник|[Hh]unter) -jeweler = ([Юю]велир|[Сс]аша|[Jj]eweler) -mason = ([Кк]аменьщик|[Мм]асон|[Mm]ason) -mechanic = ([Мм]еханик|[Mm]echanic) -medic = ([Мм]едик|[Дд]октор|[Вв]рач|[Кк]оновал|[Хх]ирург|[Mm]edic|[Dd]octor) -miner = ([Шш]ахтер|[Кк]опатель|[Mm]iner) -noble = ([Мм]удак|[Бб]лагородный|[Дд]ворянин|[Нн]обл|[Nn]oble) -smith = ([Кк]узнец|[Ss]mith) -warrior = ([Вв]оин|[Вв]а(р)?риор|[Ww]arrior) -nothing = ([Нн]икто|[Nn]othing|\w*) - diff --git a/conf/goodgame.cfg b/conf/goodgame.cfg deleted file mode 100644 index 1e0ab5b..0000000 --- a/conf/goodgame.cfg +++ /dev/null @@ -1,11 +0,0 @@ -[gui_information] -category = chat - -[config__gui] -for = config -hidden = socket - -[config] -socket = ws://chat.goodgame.ru:8081/chat/websocket -channel_name = CzT - diff --git a/conf/levels.cfg b/conf/levels.cfg deleted file mode 100644 index 97f401d..0000000 --- a/conf/levels.cfg +++ /dev/null @@ -1,10 +0,0 @@ -[gui_information] -category = messaging - -[config] -experience = random -exp_for_level = 50 -file = conf/levels.xml -db = levels.db -message = {0} засунули в соковыжималку, выжали, и он теперь {1} - diff --git a/conf/logger.cfg b/conf/logger.cfg deleted file mode 100644 index cb51e89..0000000 --- a/conf/logger.cfg +++ /dev/null @@ -1,10 +0,0 @@ -[gui_information] -category = messaging -id = 20 - -[config] -logging = true -rotation = daily -file_format = %Y-%m-%d -message_date_format = %Y-%m-%d %H:%M:%S - diff --git a/conf/mentions.cfg b/conf/mentions.cfg deleted file mode 100644 index d324a2d..0000000 --- a/conf/mentions.cfg +++ /dev/null @@ -1,12 +0,0 @@ -[gui_information] -category = messaging - -[config__gui] -for = mentions, address -view = list -addable = true - -[mentions] - -[address] - diff --git a/conf/messaging.cfg b/conf/messaging.cfg deleted file mode 100644 index 496247d..0000000 --- a/conf/messaging.cfg +++ /dev/null @@ -1,19 +0,0 @@ -[gui_information] -category = main - -[messaging__gui] -for = messaging -view = choose_multiple -check_type = files -check = modules/messaging -file_extension = False - -[messaging] -blacklist -df -logger -webchat -c2b -levels -mentions - diff --git a/conf/sc2tv.cfg b/conf/sc2tv.cfg deleted file mode 100644 index 52a1dc6..0000000 --- a/conf/sc2tv.cfg +++ /dev/null @@ -1,11 +0,0 @@ -[gui_information] -category = chat - -[config__gui] -for = config -hidden = socket - -[config] -socket = ws://funstream.tv/socket.io/ -nick = CzT - diff --git a/conf/twitch.cfg b/conf/twitch.cfg deleted file mode 100644 index 3c21b88..0000000 --- a/conf/twitch.cfg +++ /dev/null @@ -1,13 +0,0 @@ -[gui_information] -category = chat - -[config__gui] -for = config -hidden = host, port - -[config] -host = irc.twitch.tv -port = 6667 -channel = CzT1 -bttv = true - diff --git a/conf/webchat.cfg b/conf/webchat.cfg deleted file mode 100644 index 39f1052..0000000 --- a/conf/webchat.cfg +++ /dev/null @@ -1,17 +0,0 @@ -[gui_information] -category = main -id = 9001 - -[style__gui] -for = style -view = choose_single -check_type = dir -check = http - -[style] -czt - -[server] -host = 127.0.0.1 -port = 14589 - diff --git a/http/czt/img/levels/default/0.png b/http/czt/img/levels/0.png similarity index 100% rename from http/czt/img/levels/default/0.png rename to http/czt/img/levels/0.png diff --git a/http/czt/img/levels/default/1.png b/http/czt/img/levels/1.png similarity index 100% rename from http/czt/img/levels/default/1.png rename to http/czt/img/levels/1.png diff --git a/http/czt/img/levels/10.png b/http/czt/img/levels/10.png new file mode 100644 index 0000000..1ea1251 Binary files /dev/null and b/http/czt/img/levels/10.png differ diff --git a/http/czt/img/levels/11.png b/http/czt/img/levels/11.png new file mode 100644 index 0000000..a22762c Binary files /dev/null and b/http/czt/img/levels/11.png differ diff --git a/http/czt/img/levels/12.png b/http/czt/img/levels/12.png new file mode 100644 index 0000000..8c94a59 Binary files /dev/null and b/http/czt/img/levels/12.png differ diff --git a/http/czt/img/levels/13.png b/http/czt/img/levels/13.png new file mode 100644 index 0000000..6878638 Binary files /dev/null and b/http/czt/img/levels/13.png differ diff --git a/http/czt/img/levels/14.png b/http/czt/img/levels/14.png new file mode 100644 index 0000000..c08dd39 Binary files /dev/null and b/http/czt/img/levels/14.png differ diff --git a/http/czt/img/levels/15.png b/http/czt/img/levels/15.png new file mode 100644 index 0000000..64353ec Binary files /dev/null and b/http/czt/img/levels/15.png differ diff --git a/http/czt/img/levels/16.png b/http/czt/img/levels/16.png new file mode 100644 index 0000000..eaab90e Binary files /dev/null and b/http/czt/img/levels/16.png differ diff --git a/http/czt/img/levels/17.png b/http/czt/img/levels/17.png new file mode 100644 index 0000000..682e71e Binary files /dev/null and b/http/czt/img/levels/17.png differ diff --git a/http/czt/img/levels/18.png b/http/czt/img/levels/18.png new file mode 100644 index 0000000..246369a Binary files /dev/null and b/http/czt/img/levels/18.png differ diff --git a/http/czt/img/levels/19.png b/http/czt/img/levels/19.png new file mode 100644 index 0000000..af9497d Binary files /dev/null and b/http/czt/img/levels/19.png differ diff --git a/http/czt/img/levels/default/2.png b/http/czt/img/levels/2.png similarity index 100% rename from http/czt/img/levels/default/2.png rename to http/czt/img/levels/2.png diff --git a/http/czt/img/levels/20.png b/http/czt/img/levels/20.png new file mode 100644 index 0000000..0216450 Binary files /dev/null and b/http/czt/img/levels/20.png differ diff --git a/http/czt/img/levels/21.png b/http/czt/img/levels/21.png new file mode 100644 index 0000000..d4b185e Binary files /dev/null and b/http/czt/img/levels/21.png differ diff --git a/http/czt/img/levels/22.png b/http/czt/img/levels/22.png new file mode 100644 index 0000000..6939a2f Binary files /dev/null and b/http/czt/img/levels/22.png differ diff --git a/http/czt/img/levels/23.png b/http/czt/img/levels/23.png new file mode 100644 index 0000000..9db3a5d Binary files /dev/null and b/http/czt/img/levels/23.png differ diff --git a/http/czt/img/levels/24.png b/http/czt/img/levels/24.png new file mode 100644 index 0000000..3dcb03e Binary files /dev/null and b/http/czt/img/levels/24.png differ diff --git a/http/czt/img/levels/25.png b/http/czt/img/levels/25.png new file mode 100644 index 0000000..db09752 Binary files /dev/null and b/http/czt/img/levels/25.png differ diff --git a/http/czt/img/levels/26.png b/http/czt/img/levels/26.png new file mode 100644 index 0000000..a492bad Binary files /dev/null and b/http/czt/img/levels/26.png differ diff --git a/http/czt/img/levels/27.png b/http/czt/img/levels/27.png new file mode 100644 index 0000000..75e398d Binary files /dev/null and b/http/czt/img/levels/27.png differ diff --git a/http/czt/img/levels/28.png b/http/czt/img/levels/28.png new file mode 100644 index 0000000..2d01db2 Binary files /dev/null and b/http/czt/img/levels/28.png differ diff --git a/http/czt/img/levels/29.png b/http/czt/img/levels/29.png new file mode 100644 index 0000000..9e78222 Binary files /dev/null and b/http/czt/img/levels/29.png differ diff --git a/http/czt/img/levels/default/3.png b/http/czt/img/levels/3.png similarity index 100% rename from http/czt/img/levels/default/3.png rename to http/czt/img/levels/3.png diff --git a/http/czt/img/levels/30.png b/http/czt/img/levels/30.png new file mode 100644 index 0000000..33ab473 Binary files /dev/null and b/http/czt/img/levels/30.png differ diff --git a/http/czt/img/levels/31.png b/http/czt/img/levels/31.png new file mode 100644 index 0000000..b71b907 Binary files /dev/null and b/http/czt/img/levels/31.png differ diff --git a/http/czt/img/levels/32.png b/http/czt/img/levels/32.png new file mode 100644 index 0000000..6282eea Binary files /dev/null and b/http/czt/img/levels/32.png differ diff --git a/http/czt/img/levels/33.png b/http/czt/img/levels/33.png new file mode 100644 index 0000000..ad748bb Binary files /dev/null and b/http/czt/img/levels/33.png differ diff --git a/http/czt/img/levels/34.png b/http/czt/img/levels/34.png new file mode 100644 index 0000000..fa98e40 Binary files /dev/null and b/http/czt/img/levels/34.png differ diff --git a/http/czt/img/levels/35.png b/http/czt/img/levels/35.png new file mode 100644 index 0000000..a620df4 Binary files /dev/null and b/http/czt/img/levels/35.png differ diff --git a/http/czt/img/levels/36.png b/http/czt/img/levels/36.png new file mode 100644 index 0000000..4f1db46 Binary files /dev/null and b/http/czt/img/levels/36.png differ diff --git a/http/czt/img/levels/37.png b/http/czt/img/levels/37.png new file mode 100644 index 0000000..d216a83 Binary files /dev/null and b/http/czt/img/levels/37.png differ diff --git a/http/czt/img/levels/38.png b/http/czt/img/levels/38.png new file mode 100644 index 0000000..600785d Binary files /dev/null and b/http/czt/img/levels/38.png differ diff --git a/http/czt/img/levels/39.png b/http/czt/img/levels/39.png new file mode 100644 index 0000000..c3524f5 Binary files /dev/null and b/http/czt/img/levels/39.png differ diff --git a/http/czt/img/levels/default/4.png b/http/czt/img/levels/4.png similarity index 100% rename from http/czt/img/levels/default/4.png rename to http/czt/img/levels/4.png diff --git a/http/czt/img/levels/40.png b/http/czt/img/levels/40.png new file mode 100644 index 0000000..5108e46 Binary files /dev/null and b/http/czt/img/levels/40.png differ diff --git a/http/czt/img/levels/41.png b/http/czt/img/levels/41.png new file mode 100644 index 0000000..0088095 Binary files /dev/null and b/http/czt/img/levels/41.png differ diff --git a/http/czt/img/levels/42.png b/http/czt/img/levels/42.png new file mode 100644 index 0000000..3a48399 Binary files /dev/null and b/http/czt/img/levels/42.png differ diff --git a/http/czt/img/levels/43.png b/http/czt/img/levels/43.png new file mode 100644 index 0000000..a68a199 Binary files /dev/null and b/http/czt/img/levels/43.png differ diff --git a/http/czt/img/levels/5.png b/http/czt/img/levels/5.png new file mode 100644 index 0000000..1887163 Binary files /dev/null and b/http/czt/img/levels/5.png differ diff --git a/http/czt/img/levels/6.png b/http/czt/img/levels/6.png new file mode 100644 index 0000000..60d5b33 Binary files /dev/null and b/http/czt/img/levels/6.png differ diff --git a/http/czt/img/levels/7.png b/http/czt/img/levels/7.png new file mode 100644 index 0000000..85df85b Binary files /dev/null and b/http/czt/img/levels/7.png differ diff --git a/http/czt/img/levels/8.png b/http/czt/img/levels/8.png new file mode 100644 index 0000000..68ace6e Binary files /dev/null and b/http/czt/img/levels/8.png differ diff --git a/http/czt/img/levels/9.png b/http/czt/img/levels/9.png new file mode 100644 index 0000000..8b33420 Binary files /dev/null and b/http/czt/img/levels/9.png differ diff --git a/http/czt/img/levels/cube.png b/http/czt/img/levels/cube.png new file mode 100644 index 0000000..7d05d56 Binary files /dev/null and b/http/czt/img/levels/cube.png differ diff --git a/conf/levels.xml b/http/czt/levels.xml similarity index 100% rename from conf/levels.xml rename to http/czt/levels.xml diff --git a/main.py b/main.py index 9eca9fb..eb4a1a3 100644 --- a/main.py +++ b/main.py @@ -14,16 +14,17 @@ if hasattr(sys, 'frozen'): - python_folder = os.path.dirname(sys.executable) + PYTHON_FOLDER = os.path.dirname(sys.executable) else: - python_folder = os.path.dirname(os.path.abspath('__file__')) -TRANSLATION_FOLDER = os.path.join(python_folder, "translations") -CONF_FOLDER = os.path.join(python_folder, "conf") -MODULE_FOLDER = os.path.join(python_folder, "modules") + PYTHON_FOLDER = os.path.dirname(os.path.abspath('__file__')) +TRANSLATION_FOLDER = os.path.join(PYTHON_FOLDER, "translations") +CONF_FOLDER = os.path.join(PYTHON_FOLDER, "conf") +MODULE_FOLDER = os.path.join(PYTHON_FOLDER, "modules") MAIN_CONF_FILE = os.path.join(CONF_FOLDER, "config.cfg") +HTTP_FOLDER = os.path.join(PYTHON_FOLDER, "http") GUI_TAG = 'gui' -LOG_FOLDER = os.path.join(python_folder, "logs") +LOG_FOLDER = os.path.join(PYTHON_FOLDER, "logs") LOG_FILE = os.path.join(LOG_FOLDER, 'chat_log.log') LOG_FORMAT = logging.Formatter("%(asctime)s [%(name)s] [%(levelname)s] %(message)s") @@ -46,7 +47,7 @@ def init(): gui_settings = {} # Creating dict with folder settings - main_config = {'root_folder': python_folder, + main_config = {'root_folder': PYTHON_FOLDER, 'conf_folder': CONF_FOLDER, 'main_conf_file': MAIN_CONF_FILE, 'main_conf_file_loc': MAIN_CONF_FILE, @@ -68,21 +69,27 @@ def init(): logger.info("Loading basic configuration") main_config_dict = [ - {'gui_information': { - 'category': 'main'}}, - {'language__gui': { - 'for': 'language', - 'view': 'choose_single', - 'check_type': 'dir', - 'check': 'translations' - }}, - {'gui': { - 'show_hidden': True, - 'gui': True, - 'on_top': True, - 'reload': None - }}, - {'language': 'english'} + {'gui_information': { + 'category': 'main'}}, + {'language__gui': { + 'for': 'language', + 'view': 'choose_single', + 'check_type': 'dir', + 'check': 'translations' + }}, + {'gui': { + 'show_hidden': True, + 'gui': True, + 'on_top': True, + 'reload': None + }}, + {'style__gui': { + 'check': 'http', + 'check_type': 'dir', + 'for': 'style', + 'view': 'choose_single'}}, + {'style': 'czt'}, + {'language': 'en'} ] config = self_heal(MAIN_CONF_FILE, main_config_dict) # Adding config for main module @@ -97,6 +104,18 @@ def init(): gui_settings['on_top'] = config.get(GUI_TAG, 'gui') gui_settings['language'], null_element = config.items('language')[0] gui_settings['show_hidden'] = config.get(GUI_TAG, 'show_hidden') + # Fallback if style folder not found + fallback_style = 'czt' + if len(config.items('style')) > 0: + style, null_element = config.items('style')[0] + path = os.path.abspath(os.path.join(HTTP_FOLDER, style)) + if os.path.exists(path): + gui_settings['style'] = style + else: + gui_settings['style'] = fallback_style + else: + gui_settings['style'] = fallback_style + loaded_modules['config']['http_folder'] = os.path.join(HTTP_FOLDER, gui_settings['style']) logger.info("Loading Messaging Handler") logger.info("Loading Queue for message handling") @@ -105,7 +124,7 @@ def init(): queue = Queue.Queue() # Loading module for message processing... msg = messaging.Message(queue) - loaded_modules.update(msg.load_modules(main_config)) + loaded_modules.update(msg.load_modules(main_config, loaded_modules['config'])) msg.start() logger.info("Loading Chats") @@ -142,7 +161,7 @@ def init(): tmp = imp.load_source(module, module_location) chat_init = getattr(tmp, module) - class_module = chat_init(queue, python_folder) + class_module = chat_init(queue, PYTHON_FOLDER) loaded_modules[module] = class_module.conf_params loaded_modules[module]['class'] = class_module else: diff --git a/messaging.py b/messaging.py index 72e12ee..e89dd4f 100644 --- a/messaging.py +++ b/messaging.py @@ -1,13 +1,13 @@ # This Python file uses the following encoding: utf-8 # -*- coding: utf-8 -*- import os -import ConfigParser import threading import imp import operator import logging from modules.helpers.system import ModuleLoadException +from modules.helpers.parser import self_heal log = logging.getLogger('messaging') MODULE_PRI_DEFAULT = '100' @@ -23,18 +23,27 @@ def __init__(self, queue): self.queue = queue self.module_tag = "modules.messaging" - def load_modules(self, config_dict): + def load_modules(self, config_dict, settings): log.info("Loading configuration file for messaging") modules_list = {} conf_file = os.path.join(config_dict['conf_folder'], "messaging.cfg") - config = ConfigParser.RawConfigParser(allow_no_value=True) - + conf_dict = [ + {'gui_information': { + 'category': 'main'}}, + {'messaging__gui': {'check': 'modules/messaging', + 'check_type': 'files', + 'file_extension': False, + 'for': 'messaging', + 'view': 'choose_multiple'}}, + {'messaging': { + 'webchat': None}} + ] + config = self_heal(conf_file, conf_dict) modules_list['messaging_modules'] = {'folder': config_dict['conf_folder'], 'file': conf_file, 'filename': ''.join(os.path.basename(conf_file).split('.')[:-1]), 'parser': config} - config.read(conf_file) modules = {} # Loading modules from cfg. if config.items("messaging") > 0: @@ -49,7 +58,8 @@ def load_modules(self, config_dict): try: tmp = imp.load_source(module, file_path) class_init = getattr(tmp, module) - class_module = class_init(config_dict['conf_folder'], root_folder=config_dict['root_folder']) + class_module = class_init(config_dict['conf_folder'], root_folder=config_dict['root_folder'], + main_settings=settings) if 'id' in class_module.conf_params: priority = class_module.conf_params['id'] diff --git a/modules/chats/goodgame.py b/modules/chats/goodgame.py index 87110f4..5612338 100644 --- a/modules/chats/goodgame.py +++ b/modules/chats/goodgame.py @@ -12,11 +12,22 @@ log = logging.getLogger('goodgame') SOURCE = 'gg' SOURCE_ICON = 'http://goodgame.ru/images/icons/favicon.png' +CONF_DICT = [ + {'gui_information': { + 'category': 'chat'}}, + {'config__gui': { + 'for': 'config', + 'hidden': 'socket'}}, + {'config': { + 'channel_name': 'CHANGE_ME', + 'socket': 'ws://chat.goodgame.ru:8081/chat/websocket'}} + ] class GoodgameMessageHandler(threading.Thread): - def __init__(self, queue, gg_queue, **kwargs): + def __init__(self, ws_class, queue, gg_queue, **kwargs): super(self.__class__, self).__init__() + self.ws_class = ws_class # type: GGChat self.daemon = True self.message_queue = queue self.gg_queue = gg_queue @@ -77,16 +88,21 @@ def process_message(self, msg): if re.match('^{0},'.format(self.nick).lower(), comp['text'].lower()): comp['pm'] = True self.message_queue.put(comp) + elif msg['type'] == 'error': + log.info("Received error message: {0}".format(msg)) + if msg['data']['errorMsg'] == 'Invalid channel id': + self.ws_class.close(reason='INV_CH_ID') + log.error("Failed to find channel on GoodGame, please check channel name") -class ggChat(WebSocketClient): +class GGChat(WebSocketClient): def __init__(self, ws, protocols=None, queue=None, ch_id=None, nick=None, **kwargs): super(self.__class__, self).__init__(ws, protocols=protocols) # Received value setting. self.ch_id = ch_id self.gg_queue = Queue.Queue() - message_handler = GoodgameMessageHandler(queue, self.gg_queue, nick=nick, **kwargs) + message_handler = GoodgameMessageHandler(self, queue, self.gg_queue, nick=nick, **kwargs) message_handler.start() def opened(self): @@ -99,7 +115,10 @@ def opened(self): def closed(self, code, reason=None): log.info("Connection Closed Down") - self.connect() + if 'INV_CH_ID' in reason: + pass + else: + self.connect() def received_message(self, mes): # Deserialize message to json for easier parsing @@ -107,7 +126,7 @@ def received_message(self, mes): self.gg_queue.put(message) -class ggThread(threading.Thread): +class GGThread(threading.Thread): def __init__(self, queue, address, nick): threading.Thread.__init__(self) # Basic value setting. @@ -121,7 +140,6 @@ def __init__(self, queue, address, nick): self.kwargs = {} def load_config(self): - error = False try: self.kwargs['smiles'] = {} smile_request = requests.get("http://api2.goodgame.ru/smiles") @@ -155,12 +173,12 @@ def load_config(self): except Exception as exc: log.warning("Unable to get channel name, error {0}\nArgs: {1}".format(exc.message, exc.args)) - return error + return True def run(self): - if not self.load_config(): + if self.load_config(): # Connecting to goodgame websocket - ws = ggChat(self.address, protocols=['websocket'], queue=self.queue, ch_id=self.ch_id, nick=self.nick, + ws = GGChat(self.address, protocols=['websocket'], queue=self.queue, ch_id=self.ch_id, nick=self.nick, **self.kwargs) ws.connect() ws.run_forever() @@ -173,17 +191,7 @@ def __init__(self, queue, python_folder, **kwargs): log.info("Initializing goodgame chat") conf_file = os.path.join(conf_folder, "goodgame.cfg") - conf_dict = [ - {'gui_information': { - 'category': 'chat'}}, - {'config__gui': { - 'for': 'config', - 'hidden': 'socket'}}, - {'config': { - 'channel_name': 'CzT', - 'socket': 'ws://chat.goodgame.ru:8081/chat/websocket'}} - ] - config = self_heal(conf_file, conf_dict) + config = self_heal(conf_file, CONF_DICT) self.conf_params = {'folder': conf_folder, 'file': conf_file, 'filename': ''.join(os.path.basename(conf_file).split('.')[:-1]), 'parser': config} @@ -195,5 +203,5 @@ def __init__(self, queue, python_folder, **kwargs): # ch_id # Creating new thread with queue in place for messaging transfers - gg = ggThread(queue, address, channel_name) + gg = GGThread(queue, address, channel_name) gg.start() diff --git a/modules/chats/sc2tv.py b/modules/chats/sc2tv.py index 155c709..634cd15 100644 --- a/modules/chats/sc2tv.py +++ b/modules/chats/sc2tv.py @@ -12,17 +12,27 @@ log = logging.getLogger('sc2tv') SOURCE = 'fs' SOURCE_ICON = 'http://funstream.tv/build/images/icon_home.png' +CONF_DICT = [ + {'gui_information': { + 'category': 'chat'}}, + {'config__gui': { + 'for': 'config', + 'hidden': 'socket'}}, + {'config': { + 'channel_name': 'CHANGE_ME', + 'socket': 'ws://funstream.tv/socket.io/'}} + ] -class fsChat(WebSocketClient): - def __init__(self, ws, queue, nick, protocols=None, smiles=None): - super(self.__class__, self).__init__(ws, protocols=None) +class FsChat(WebSocketClient): + def __init__(self, ws, queue, channel_name, protocols=None, smiles=None): + super(self.__class__, self).__init__(ws, protocols=protocols) # Received value setting. self.source = SOURCE self.queue = queue - self.nick = nick + self.channel_name = channel_name - self.channel_id = self.fsGetId() + self.channel_id = self.fs_get_id() self.smiles = smiles self.smile_regex = ':(\w+|\d+):' @@ -30,7 +40,7 @@ def __init__(self, ws, queue, nick, protocols=None, smiles=None): # Because funstream API is fun, we have to iterate the # requests in "proper" format: # - # 42Iterator["command",{"params":"param"}] + # 42Iterator["command",{"params":"param"}] # ex: 420["/chat/join",{'channel':"stream/30000"} # ex: 421["/chat/join",{'channel':"stream/30000"} # ex: 429["/chat/join",{'channel':"stream/30000"} @@ -51,7 +61,8 @@ def opened(self): def closed(self, code, reason=None): log.info("Websocket Connection Closed Down") - def allow_smile(self, smile, subscriptions): + @staticmethod + def allow_smile(smile, subscriptions): allow = False if smile['user']: @@ -88,12 +99,12 @@ def received_message(self, mes): # "Funstream" has some interesting infrastructure, so # we first need to find the channel ID from # nickname of streamer we need to connect to. - self.fsJoin() - self.fsPing() + self.fs_join() + self.fs_ping() elif dict_item == 'id': try: self.duplicates.index(message[dict_item]) - except: + except IndexError: comp = {'source': self.source, 'source_icon': SOURCE_ICON, 'user': message['from']['name'], @@ -101,7 +112,7 @@ def received_message(self, mes): 'emotes': []} if message['to'] is not None: comp['to'] = message['to']['name'] - if comp['to'] == self.nick: + if comp['to'] == self.channel_name: comp['pm'] = True else: comp['to'] = None @@ -118,10 +129,10 @@ def received_message(self, mes): if len(self.duplicates) > self.bufferForDup: self.duplicates.pop(0) - def fsGetId(self): + def fs_get_id(self): # We get ID from POST request to funstream API, and it hopefuly # answers us the correct ID of the channel we need to connect to - payload = "{'id': null, 'name': \"" + self.nick + "\"}" + payload = "{'id': null, 'name': \"" + self.channel_name + "\"}" request = requests.post("http://funstream.tv/api/user", data=payload) if request.status_code == 200: channel_id = json.loads(re.findall('{.*}', request.text)[0])['id'] @@ -134,19 +145,20 @@ def fsGetId(self): channel_id = None return channel_id - def fsJoin(self): + def fs_join(self): # Because we need to iterate each message we iterate it! - iter = "42"+str(self.iter) + iter_sio = "42"+str(self.iter) self.iter += 1 # Then we send the message acording to needed format and # hope it joins us if self.channel_id: - join = str(iter) + "[\"/chat/join\", " + json.dumps({'channel': "stream/" + str(self.channel_id)}, sort_keys=False) + "]" + join = str(iter_sio) + "[\"/chat/join\", " + json.dumps({'channel': "stream/" + str(self.channel_id)}, + sort_keys=False) + "]" self.send(join) log.info("Joined channel {0}".format(self.channel_id)) - def fsPing(self): + def fs_ping(self): # Because funstream is not your normal websocket they # have own "ping/pong" algorithm, and WE have to send ping. # Yes, I don't know why. @@ -154,11 +166,11 @@ def fsPing(self): # disconnect us. So we have to create separate thread for it. # Dont understand why server is not sending his own pings, it # would be sooooo easier. - pingThr = pingThread(self) - pingThr.start() + ping_thread = FsPingThread(self) + ping_thread.start() -class pingThread(threading.Thread): +class FsPingThread(threading.Thread): def __init__(self, ws): threading.Thread.__init__(self) self.daemon = "True" @@ -181,8 +193,8 @@ def run(self): time.sleep(30) -class fsThread(threading.Thread): - def __init__(self, queue, socket, nick): +class FsThread(threading.Thread): + def __init__(self, queue, socket, channel_name): threading.Thread.__init__(self) # Basic value setting. # Daemon is needed so when main programm exits @@ -190,7 +202,7 @@ def __init__(self, queue, socket, nick): self.daemon = "True" self.queue = queue self.socket = socket - self.nick = nick + self.channel_name = channel_name self.smiles = [] def run(self): @@ -201,11 +213,11 @@ def run(self): smiles_answer = smiles.json() for smile in smiles_answer: self.smiles.append(smile) - except: + except requests.ConnectionError: log.error("Unable to get smiles") # Connecting to funstream websocket - ws = fsChat(self.socket, self.queue, self.nick, protocols=['websocket'], smiles=self.smiles,) + ws = FsChat(self.socket, self.queue, self.channel_name, protocols=['websocket'], smiles=self.smiles) ws.connect() ws.run_forever() @@ -217,29 +229,19 @@ def __init__(self, queue, python_folder, **kwargs): # Reading config from main directory. conf_folder = os.path.join(python_folder, "conf") conf_file = os.path.join(conf_folder, "sc2tv.cfg") - conf_dict = [ - {'gui_information': { - 'category': 'chat'}}, - {'config__gui': { - 'for': 'config', - 'hidden': 'socket'}}, - {'config': { - 'nick': 'CzT', - 'socket': 'ws://funstream.tv/socket.io/'}} - ] - config = self_heal(conf_file, conf_dict) + config = self_heal(conf_file, CONF_DICT) self.conf_params = {'folder': conf_folder, 'file': conf_file, 'filename': ''.join(os.path.basename(conf_file).split('.')[:-1]), 'parser': config} # Checking config file for needed variables config_tag = 'config' socket = config.get(config_tag, 'socket') - nick = config.get(config_tag, 'nick') + channel_name = config.get(config_tag, 'channel_name') # If any of the value are non-existent then exit the programm with error. - if (socket is None) or (nick is None): + if (socket is None) or (channel_name is None): log.critical("Config for funstream is not correct!") # Creating new thread with queue in place for messaging tranfers - fs = fsThread(queue, socket, nick) + fs = FsThread(queue, socket, channel_name) fs.start() diff --git a/modules/chats/twitch.py b/modules/chats/twitch.py index 2d8085f..68e9414 100644 --- a/modules/chats/twitch.py +++ b/modules/chats/twitch.py @@ -19,6 +19,18 @@ NOT_FOUND = 'none' SOURCE = 'tw' SOURCE_ICON = 'https://www.twitch.tv/favicon.ico' +CONF_DICT = [ + {'gui_information': { + 'category': 'chat'}}, + {'config__gui': { + 'for': 'config', + 'hidden': 'host, port'}}, + {'config': { + 'bttv': 'true', + 'channel': 'CHANGE_ME', + 'host': 'irc.twitch.tv', + 'port': '6667'}} + ] class TwitchMessageHandler(threading.Thread): @@ -170,15 +182,23 @@ def __init__(self, queue, host, port, channel, bttv_smiles, anon=True): self.nickname += str(random.randint(0, 9)) def run(self): - self.load_config() - - # We are connecting via IRC handler. - irc_client = IRC(self.queue, self.channel, **self.kwargs) - irc_client.connect(self.host, self.port, self.nickname) - irc_client.start() + if self.load_config(): + # We are connecting via IRC handler. + irc_client = IRC(self.queue, self.channel, **self.kwargs) + irc_client.connect(self.host, self.port, self.nickname) + irc_client.start() def load_config(self): - error = False + try: + request = requests.get("https://api.twitch.tv/kraken/channels/{0}".format(self.channel), headers=headers) + if request.status_code == 200: + log.info("Channel found, continuing") + else: + raise Exception("Not successful status code: {0}".format(request.status_code)) + except Exception as exc: + log.error("Unable to get channel ID, error: {0}\nArgs: {1}".format(exc.message, exc.args)) + return False + try: # Getting random IRC server to connect to request = requests.get("http://tmi.twitch.tv/servers?channel={0}".format(self.channel)) @@ -188,7 +208,7 @@ def load_config(self): raise Exception("Not successful status code: {0}".format(request.status_code)) except Exception as exc: log.error("Unable to get server list, error: {0}\nArgs: {1}".format(exc.message, exc.args)) - error = True + return False try: # Getting Better Twitch TV smiles @@ -224,7 +244,7 @@ def load_config(self): log.warning("Unable to get twitch undocumented api badges, error {0}\n" "Args: {1}".format(exc.message, exc.args)) - return error + return True class twitch: @@ -234,19 +254,8 @@ def __init__(self, queue, python_folder, **kwargs): # Reading config from main directory. conf_folder = os.path.join(python_folder, "conf") conf_file = os.path.join(conf_folder, "twitch.cfg") - conf_dict = [ - {'gui_information': { - 'category': 'chat'}}, - {'config__gui': { - 'for': 'config', - 'hidden': 'host, port'}}, - {'config': { - 'bttv': 'true', - 'channel': 'CzT1', - 'host': 'irc.twitch.tv', - 'port': '6667'}} - ] - config = self_heal(conf_file, conf_dict) + + config = self_heal(conf_file, CONF_DICT) self.conf_params = {'folder': conf_folder, 'file': conf_file, 'filename': ''.join(os.path.basename(conf_file).split('.')[:-1]), 'parser': config} diff --git a/modules/messaging/levels.py b/modules/messaging/levels.py index 37ae272..0b14e17 100644 --- a/modules/messaging/levels.py +++ b/modules/messaging/levels.py @@ -11,13 +11,6 @@ from modules.helpers.system import system_message, ModuleLoadException logger = logging.getLogger('levels') -TEMPLATE = """ - -{% for name, url in levels -%} - -{% endfor -%} - -""" class levels: @@ -34,24 +27,18 @@ def create_db(db_location): def __init__(self, conf_folder, **kwargs): # Creating filter and replace strings. + main_settings = kwargs.get('main_settings') + conf_file = os.path.join(conf_folder, "levels.cfg") conf_dict = [ {'gui_information': { 'category': u'messaging'}}, {'config': { 'message': u'{0} has leveled up, now he is {1}', - 'file': u'conf/levels.xml', 'db': u'levels.db', 'experience': u'geometrical', 'exp_for_level': 200}} ] - levels_dict = [ - ("Ghost", "img/levels/default/0.png"), - ("Baby", "img/levels/default/1.png"), - ("Child", "img/levels/default/2.png"), - ("Mystical Person", "img/levels/default/3.png"), - ("King", "img/levels/default/4.png"), - ] config = self_heal(conf_file, conf_dict) self.conf_params = {'folder': conf_folder, 'file': conf_file, @@ -63,7 +50,7 @@ def __init__(self, conf_folder, **kwargs): self.experience = config.get(tag_config, 'experience') self.exp_for_level = int(config.get(tag_config, 'exp_for_level')) self.exp_for_message = 1 - self.filename = os.path.abspath(config.get(tag_config, 'file')) + self.filename = os.path.abspath(os.path.join(main_settings['http_folder'], 'levels.xml')) self.levels = [] self.special_levels = {} self.db_location = os.path.join(conf_folder, config.get(tag_config, 'db')) @@ -72,10 +59,7 @@ def __init__(self, conf_folder, **kwargs): # Load levels if not os.path.exists(self.filename): logger.error("{0} not found, generating from template".format(self.filename)) - if not os.path.exists(os.path.dirname(self.filename)): - os.makedirs(os.path.dirname(self.filename)) - with open(self.filename, 'w') as levels_file: - levels_file.write(jinja2.Template(TEMPLATE).render(levels=levels_dict)) + raise ModuleLoadException("{0} not found, generating from template".format(self.filename)) if self.experience == 'random': self.db_location += '.random' diff --git a/modules/messaging/webchat.py b/modules/messaging/webchat.py index c15a698..bedb6ef 100644 --- a/modules/messaging/webchat.py +++ b/modules/messaging/webchat.py @@ -128,7 +128,7 @@ def __init__(self, host, port, root_folder, **kwargs): cherrypy.tools.websocket = WebSocketTool() def run(self): - http_folder = os.path.join(self.root_folder, '..', 'http', self.style) + http_folder = self.style cherrypy.log.access_file = '' cherrypy.log.error_file = '' cherrypy.log.screen = False @@ -150,22 +150,15 @@ def run(self): class webchat(): def __init__(self, conf_folder, **kwargs): + main_settings = kwargs.get('main_settings') conf_file = os.path.join(conf_folder, "webchat.cfg") conf_dict = [ {'gui_information': { 'category': 'main', 'id': DEFAULT_PRIORITY}}, - {'style__gui': { - 'check': 'http', - 'check_type': 'dir', - 'for': 'style', - 'view': 'choose_single'}}, - {'style': 'czt'}, {'server': { 'host': '127.0.0.1', 'port': '8080'}}] - root_folder = kwargs.get('root_folder') - http_folder = 'http' config = self_heal(conf_file, conf_dict) self.conf_params = {'folder': conf_folder, 'file': conf_file, @@ -176,16 +169,7 @@ def __init__(self, conf_folder, **kwargs): tag_server = 'server' host = config.get(tag_server, 'host') port = config.get(tag_server, 'port') - - # Fallback if style folder not found - fallback_style = 'czt' - if len(config.items('style')) > 0: - style, null_element = config.items('style')[0] - path = os.path.abspath(os.path.join(root_folder, http_folder, style)) - if not os.path.exists(path): - style = fallback_style - else: - style = fallback_style + style = main_settings['http_folder'] self.conf_params['port'] = port diff --git a/translations/en/goodgame.key b/translations/en/goodgame.key index 2890e94..45bd609 100644 --- a/translations/en/goodgame.key +++ b/translations/en/goodgame.key @@ -1,4 +1,4 @@ goodgame = GoodGame -goodgame.main = Main Settings -goodgame.main.socket = WebSocket parameters -goodgame.main.channelname = Channel name \ No newline at end of file +goodgame.config = Main Settings +goodgame.config.socket = WebSocket parameters +goodgame.config.channel_name = Channel name \ No newline at end of file diff --git a/translations/en/main.key b/translations/en/main.key index 8c39901..a5172ab 100644 --- a/translations/en/main.key +++ b/translations/en/main.key @@ -20,6 +20,9 @@ config.gui.reload.button = Reload config.language = Program Language config.language.list_box = +config.style = +config.style.list_box = Available styles + messaging_modules = Message modules messaging_modules.messaging = messaging_modules.messaging.list_box = List of available modules diff --git a/translations/en/sc2tv.key b/translations/en/sc2tv.key index 1db3268..8f7cba9 100644 --- a/translations/en/sc2tv.key +++ b/translations/en/sc2tv.key @@ -1,4 +1,4 @@ sc2tv = sc2tv -sc2tv.main = Main settings -sc2tv.main.socket = WebSocket parameters -sc2tv.main.nick = Channel name \ No newline at end of file +sc2tv.config = Main settings +sc2tv.config.socket = WebSocket parameters +sc2tv.config.channel_name = Channel name \ No newline at end of file diff --git a/translations/en/twitch.key b/translations/en/twitch.key index 64816f4..90d0d58 100644 --- a/translations/en/twitch.key +++ b/translations/en/twitch.key @@ -1,5 +1,5 @@ twitch = Twitch.TV -twitch.main.host = IRC hostname -twitch.main.port = IRC port -twitch.main.channel = Channel name -twitch.main.bttv = Show BTTV smiles \ No newline at end of file +twitch.config.host = IRC hostname +twitch.config.port = IRC port +twitch.config.channel = Channel name +twitch.config.bttv = Show BTTV smiles \ No newline at end of file diff --git a/translations/en/webchat.key b/translations/en/webchat.key index b8f4394..2b4a758 100644 --- a/translations/en/webchat.key +++ b/translations/en/webchat.key @@ -1,6 +1,4 @@ webchat = WebChat -webchat.style = -webchat.style.list_box = Available styles webchat.server = Local server settings webchat.server.host = Host diff --git a/translations/ru/goodgame.key b/translations/ru/goodgame.key index 25b32bb..3956511 100644 --- a/translations/ru/goodgame.key +++ b/translations/ru/goodgame.key @@ -1,4 +1,4 @@ goodgame = GoodGame -goodgame.main = Основные параметры GoodGame -goodgame.main.socket = Настройки WebSocket -goodgame.main.channelname = Название канала \ No newline at end of file +goodgame.config = Основные параметры GoodGame +goodgame.config.socket = Настройки WebSocket +goodgame.config.channel_name = Название канала \ No newline at end of file diff --git a/translations/ru/main.key b/translations/ru/main.key index e3cd0d7..0b003dd 100644 --- a/translations/ru/main.key +++ b/translations/ru/main.key @@ -20,6 +20,9 @@ config.gui.reload.button = Перезагрузить config.language = Язык Интерфейса config.language.list_box = +config.style = +config.style.list_box = Доступные Стили + messaging_modules = Модули Сообщений messaging_modules.messaging = messaging_modules.messaging.list_box = Список доступных модулей diff --git a/translations/ru/sc2tv.key b/translations/ru/sc2tv.key index d1286ca..cd0b1e4 100644 --- a/translations/ru/sc2tv.key +++ b/translations/ru/sc2tv.key @@ -1,4 +1,4 @@ sc2tv = sc2tv -sc2tv.main = Основные параметры -sc2tv.main.socket = WS параметры -sc2tv.main.nick = Название канала \ No newline at end of file +sc2tv.config = Основные параметры +sc2tv.config.socket = WS параметры +sc2tv.config.channel_name = Название канала \ No newline at end of file diff --git a/translations/ru/twitch.key b/translations/ru/twitch.key index d2cd1fe..bdfead4 100644 --- a/translations/ru/twitch.key +++ b/translations/ru/twitch.key @@ -1,5 +1,5 @@ twitch = Twitch.TV -twitch.main.host = IRC хостнейм -twitch.main.port = IRC порт -twitch.main.channel = Имя канала -twitch.main.bttv = Показать BTTV смайлы \ No newline at end of file +twitch.config.host = IRC хостнейм +twitch.config.port = IRC порт +twitch.config.channel = Имя канала +twitch.config.bttv = Показать BTTV смайлы \ No newline at end of file diff --git a/translations/ru/webchat.key b/translations/ru/webchat.key index a0b22c9..26c74e4 100644 --- a/translations/ru/webchat.key +++ b/translations/ru/webchat.key @@ -1,6 +1,4 @@ webchat = Веб Чат -webchat.style = -webchat.style.list_box = Доступные Стили webchat.server = Настройки локального сервера webchat.server.host = Хост