示例#1
0
def is_tf2_install(log: logger.Log, exe_location: str) -> bool:
    if not os.path.isfile(exe_location):
        log.debug(f"No TF2 installation found at {exe_location}")
        return False

    is_tf2: bool = False
    appid_path: str = os.path.join(os.path.dirname(exe_location),
                                   'steam_appid.txt')

    if os.path.isfile(appid_path):
        with open(appid_path, 'rb') as appid_file:
            appid_read: bytes = appid_file.read()

            if appid_read.startswith(b'440\n'):
                is_tf2 = True
            else:
                log.debug(f"steam_appid.txt contains \"{appid_read}\" ")
    else:
        log.debug(
            f"steam_appid.txt doesn't exist (install folder: {os.listdir(os.path.dirname(exe_location))})"
        )

    if is_tf2:
        log.debug(f"Found TF2 hl2.exe at {exe_location}")
        return True
    else:
        log.error(f"Found non-TF2 hl2.exe at {exe_location}")
        return False
示例#2
0
 def _browser_exit(self, exit_status=0):
     if self._browser is not None:
         self._browser.close()
         if exit_status is not 0:
             Log.error(self._exit_msg)
         else:
             Log.info(self._exit_msg)
         sys.exit(exit_status)
示例#3
0
def set_window_icon(log: logger.Log, window: Union[tk.Tk, tk.Toplevel],
                    wrench: bool):
    filename: str = 'tf2_logo_blurple_wrench.ico' if wrench else 'tf2_logo_blurple.ico'
    path: str = filename if launcher.DEBUG else os.path.join(
        'resources', filename)

    try:
        window.iconbitmap(path)
    except tk.TclError:
        log.error(traceback.format_exc())
示例#4
0
class DB:
    def __init__(self):
        self.log = Log()
        try:
            self.conn = connect(host=host,
                                port=port,
                                user=user,
                                password=password,
                                db=db,
                                charset='utf8',
                                cursorclass=cursors.DictCursor)
        except OperationalError as e:
            self.log.error("Mysql Error %d: %s" (e.args[0], e.args[1]))

    #封装select语句
    def select(self, table_name, table_data):
        if table_data['where'] == '':
            #print("无where子句")
            real_sql = "select " + table_data['fields'] + " from " + table_name
        else:
            keys = table_data['where']
            #print(keys)
            str = 'where'
            for key, value in keys.items():
                str = str + ' ' + key + ' =' + ' ' + '\'' + value + '\'' + 'and'
            str = str[:-3]
            real_sql = "select " + table_data[
                'fields'] + " from " + table_name + ' ' + str

        self.log.info(real_sql)
        #print(table_name)
        cur = self.conn.cursor()
        cur.execute(real_sql)
        results = cur.fetchall()
        return results

    #封装insert语句
    def insert(self, table_name, table_data):
        keys = table_data
        #print(keys)
        str1, str2 = '', ''
        for key, value in keys.items():
            str1 = str1 + key + ','
            str2 = str2 + value + ','
        str1 = str1[:-1]
        str2 = str2[:-1]
        real_sql = "insert into " + table_name + " (" + str1 + ")" + " values " + "(" + str2 + ")"
        self.log.info(real_sql)
        #print(table_name)
        cur = self.conn.cursor()
        cur.execute(real_sql)
示例#5
0
def get_map_gamemode(
        log: logger.Log,
        map_filename: str) -> Union[Tuple[str, str, str, bool], list]:
    if map_filename == '':
        log.error("Map filename is blank")
        return map_filename, 'unknown', 'Unknown gamemode', False

    map_gamemodes: Dict[str, List[str]] = load_maps_db()

    if map_filename in map_gamemodes:
        map_data: list = map_gamemodes[map_filename]
        map_data.append(False)

        # add some formatting for maps with multiple gamemodes
        if map_filename in game_state.ambiguous_maps:
            if map_data[1] in modes_short:
                map_data[0] = f'{map_data[0]} ({modes_short[map_data[1]]})'
            else:
                map_data[0] = f'{map_data[0]} ({map_data[2]})'

        return map_data
    elif not map_gamemodes:
        log.error("maps.json failed to load")

    log.debug(f"Finding gamemode for custom map: {map_filename}")

    # determine based on common substrings
    for gamemode_substring in substrings:
        if gamemode_substring in map_filename:
            gamemode: str = substrings[gamemode_substring]
            gamemode_fancy: str = modes[gamemode]
            log.debug(
                f"Determined gamemode to be {(gamemode, gamemode_fancy)}) based on substring ({gamemode_substring}_)"
            )
            return map_filename, gamemode, gamemode_fancy, True

    # determine based on the map prefix
    map_prefix: str = map_filename.split('_')[0]
    if map_prefix in prefixes and '_' in map_filename:
        gamemode = prefixes[map_prefix]
        gamemode_fancy = modes[gamemode]
        log.debug(
            f"Determined gamemode to be {(gamemode, gamemode_fancy)}) based on prefix ({map_prefix}_)"
        )
        return map_filename, gamemode, gamemode_fancy, True

    log.debug(
        "Couldn't determine map gamemode from filename")  # probably trading
    return map_filename, 'unknown', 'Unknown gamemode', True
示例#6
0
def _getRequest(url):
    """Send HTTP request to url and return the response."""

    try:
        request_result = requests.get(url, headers={
            'Connection': 'close'
        }).json()
        Log.info('Sent request to: %s' % url)
        time.sleep(0.01)

    except:
        Log.error('URL not found!')
        sys.exit()

    return request_result
示例#7
0
def detect_system_language(log: logger.Log):
    db: Dict[str, Union[bool, list, str]] = utils.access_db()

    if not db['has_asked_language']:
        language_codes: dict = {
            read_localization_files()[lang]['code']: lang
            for lang in langs[1:]
        }
        system_locale: str = locale.windows_locale[
            ctypes.windll.kernel32.GetUserDefaultUILanguage()]
        system_language_code: str = system_locale.split('_')[0]
        is_brazilian_port: bool = system_locale == 'pt_BR'

        if system_language_code in language_codes or is_brazilian_port:
            system_language: str = language_codes[system_language_code]
            can_localize: bool = True
        else:
            if system_language_code != 'en':
                log.error(f"System locale {system_locale} is not localizable")

            can_localize = False

        if can_localize and settings.get('language') != system_language:
            log.info(
                f"System language ({system_locale}, {system_language}) != settings language ({settings.get('language')}), asking to change"
            )
            db['has_asked_language'] = True
            utils.access_db(db)
            system_language_display: str = 'Português Brasileiro' if is_brazilian_port else system_language
            # this is intentionally not localized
            changed_language: str = messagebox.askquestion(
                f"TF2 Rich Presence {launcher.VERSION}",
                f"Change language to your system's default ({system_language_display})?"
            )
            log.debug(f"Changed language: {changed_language}")

            if changed_language == 'yes':
                settings.change('language', system_language)
示例#8
0
文件: crontab.py 项目: espengjerde/DF
data = Data()
log = Log(conf.files.limitlog)

if action.upper() == "UPDATE_STATS":

    for row in Data().getIpUser():
        User = row[0]
        ip = row[1]
        stats = Statistics().get_iptables_io(ip)
        if stats:
            tx = stats['bytes_sent']
            rx = stats['bytes_received']
            Connections = Statistics().get_active_connections(ip)
            Data().updateStats(User,Connections, tx, rx)
        else:
            log.error("something went wrong updatings stats, user: "******" at "+ip )

if action.upper() == "CHECK_LIMITS":

    soft = bw.is_violating(False)
    hard = bw.is_violating(True)
    
    if(soft[0]):
        print "SOFTLIMIT DOWNSTREAM VIOLATED"
        limitTopFiveDown()
        if(hard[0]):
            print "HARDLIMIT."
            limitAllDown()
    if(soft[1]):
        print "SOFTLIMIT UPSTREAM VIOLATED"
        if(hard[1]):
class Excel:
    def __init__(self):
        self.log = Log()
        try:
            self.el = xlrd.open_workbook(file_path)
        except Exception as e:
            self.log.error('[Excel]filepath is wrong:%s' % e)

    #获取指定sheet所有值,行循环
    def GetAllExcelData(self, sheet_name):
        try:
            table = self.el.sheet_by_name(sheet_name)
            #获取总行数
            nrows = table.nrows
            for i in range(nrows):
                #print(table.row_values(i))
                return table.row_values(i)
        except Exception as e:
            self.log.error('[Excel]GetAllExcelData:%s' % e)

    #获取某一行所有值
    def GetRowsData(self, sheet_name, row_num):
        try:
            table = self.el.sheet_by_name(sheet_name)
            try:
                #print(table.col_values(row_num))
                return table.row_values(row_num)
            except Exception as e:
                self.log.error('[Excel]GetRowsData:%s' % e)
        except Exception as e:
            self.log.error('[Excel]GetRowsData:%s' % e)

    #获取某一列所有值
    def GetColsData(self, sheet_name, col_num):
        try:
            table = self.el.sheet_by_name(sheet_name)
            try:
                #print(table.col_values(col_num))
                return table.col_values(col_num)
            except Exception as e:
                self.log.error('[Excel]GetColsData:%s' % e)
        except Exception as e:
            self.log.error('[Excel]GetColsData:%s' % e)

    def GetDetialData(self, sheet_name, row_num, col_num):
        try:
            table = self.el.sheet_by_name(sheet_name)
            try:
                nrows = table.row(row_num)[col_num].value
                #print(table.row(row_num)[col_num])
                return nrows
            except Exception as e:
                self.log.error('[Excel]GetDetialData:%s' % e)
        except Exception as e:
            self.log.error('[Excel]GetDetialData:%s' % e)
示例#10
0
# coding:utf-8
from weChat import WeChat
from logger import Log

if __name__ == "__main__":
    logging =Log()

    try:
        weChat = WeChat(logging)
        account_id="5742"
        weChat.prepare_chrome(account_id)
        weChat.spider_articles()
    except Exception as e:
        logging.error(e)
    finally:
        weChat.update_to_server()
        weChat.close()
示例#11
0
class Runner(RunnerInterface):
    def __init__(self):
        super().__init__()
        self.store = Store()
        self.torr_searcher = TorrSearch()
        self.loop = asyncio.get_event_loop()
        self.queue = asyncio.Queue()
        self.bot = TgBot(self.queue)
        self.log = Log(__name__)

    async def background_updater(self):
        await asyncio.sleep(5.0)
        self.log.debug(f"Start update after 5 seconds")
        while True:
            await asyncio.sleep(10)
            movies = await self.store.get_movies()
            self.log.debug(f"Search for {movies}")
            for movie in movies:
                self.log.debug(f"Find '{movie['title']}' for users: {movie['watchers']}")
                result = await self.torr_searcher.search_word(movie['title'])
                self.log.debug(f"Result: {result}")
                if result:
                    message = self.format_films(movie['title'], result)
                    for watcher in movie['watchers']:
                        await self.bot.send_message(watcher, message)
                    await self.store.create_or_update_movie(movie=movie['title'], is_active=False)

    @staticmethod
    def format_films(search_str, films):
        msg = f'По запросу: "{search_str}" найдены следущие раздачи:\n'
        for i in films[:6]:
            msg += f"---\n{i['date']}  |  {i['size']}  |  {i['name']}\n"
        return msg

    async def process_messages(self):
        while True:
            item = await self.queue.get()
            if item is not None:
                self.log.info(item)
                if not isinstance(item, dict) or 'type' not in item.keys():
                    self.log.error(f"Get incorrect object from tgbot: {item}")
                if item['type'] == 'start':
                    await self.store.create_or_update_user(item['content']['from'])
                elif item['type'] == 'deactivate':
                    await self.store.create_or_update_user(item['content']['from'], is_active=False)
                elif item['type'] == 'ignore':
                    watcher = item['content']['from']['id']
                    movie = item['content']['text'][8:].strip()
                    self.log.debug(f"User {watcher} trying ignore: {movie}")
                    await self.store.ignore_movie(movie=movie, watcher=watcher)
                    answer = f"You are unsubscribed from '{movie}' search."
                    await self.bot.send_message(watcher, answer)
                elif item['type'] == 'list':
                    watcher = item['content']['from']['id']
                    movies = await self.store.get_movies(telegram_id=watcher)
                    results = '\n'.join([i['title'] for i in movies])
                    answer = f"You are waiting for:\n" \
                             f"{results}"
                    await self.bot.send_message(watcher, answer)
                elif item['type'] == 'message':
                    movie = item['content']['text'].strip()
                    watcher = item['content']['from']['id']
                    if movie.startswith('/'):
                        answer = f"Incorrect command. Use /help for additional information."
                    else:
                        if await self.store.get_users(telegram_id=watcher):
                            await self.store.create_or_update_movie(movie=movie, watcher=watcher)
                            answer = f"Title '{movie}' was added"
                        else:
                            answer = f'You need /start chatting with bot before make requests.'
                    await self.bot.send_message(watcher, answer)
                else:
                    self.log.error(f"Unknown type from item: {item}")

    def prepare(self):
        self.loop.create_task(self.process_messages())
        self.loop.create_task(self.background_updater())

    def run(self):
        self.prepare()
        # Bot exec run loop forever
        self.bot.run()

    async def search_digital(self, keywords):
        pass

    async def search_bd(self):
        pass

    async def search_torrent(self, keywords):
        return await self.torr_searcher.search_word(keywords)
示例#12
0
class SendEmail:
    def __init__(self):
        # 发送邮件服务器
        self.smtpserver = smtpserver
        # 发送邮箱用户/密码
        self.user = user
        self.password = password
        # 发送邮箱
        self.sender = sender
        # 接收邮箱
        self.receiver = receiver
        #抄送
        self.cc = cc
        #标题
        self.subject = subject
        #发送方式
        self.subtype = subtype
        #SMTP初始化
        self.smtp = smtplib.SMTP()
        #打印日志
        self.log = Log()

    #连接服务器connect
    def __Connect(self, smtpserver):
        try:
            self.smtp.connect(self.smtpserver)
            return True
        except Exception as e:
            self.log.error("[SendEmail:]you got wrong server connect %s" % e)

    #登陆login
    def __Login(self, username, password):
        try:
            self.smtp.login(username, password)
        except Exception as e:
            self.log.error("[SendEmail]username or password is wrong %s" % e)

    #退出quit
    def __Quit(self):
        self.smtp.quit()

    #整合发送邮件
    def __SendEmail(self, sender, receviver, message):
        self.smtp.sendmail(sender, receviver, message)

    #读取报告
    def __GetFile(self, fp):
        try:
            f = open(fp, 'rb')
            filepath = f.read()
            return filepath
            f.close()
        except Exception as e:
            self.log.error('[SendEmail]you got wrong filepath %s' % e)

    #发送测试报告
    def sendemail(self, file_new):
        try:
            mail_body = self.__GetFile(file_new)
            if self.subtype == 'html' or self.subtype == 'plain':  #发送html或者text格式的邮件
                msg = MIMEText(mail_body, self.subtype, 'utf-8')
                msg['Subject'] = Header(self.subject, 'utf-8')
                msg['From'] = Header(self.sender, 'utf-8')
                msg['To'] = ",".join(self.receiver)
                msg['cc'] = ",".join(self.cc)
            elif self.subtype == 'base64':
                #附件部分
                disposition = 'attachment;filename="' + file_new[3:] + '\"'
                att = MIMEText(mail_body, 'base64', 'utf-8')
                att['Content-Type'] = 'application/octet-stream'
                att['Content-Disposition'] = disposition
                #正文部分
                txt = MIMEText("您好!具体内容见附件", 'plain', 'utf-8')

                msg = MIMEMultipart('related')
                msg['Subject'] = Header(self.subject, 'utf-8')
                msg['From'] = Header(self.sender, 'utf-8')
                msg['To'] = ",".join(self.receiver)
                msg['cc'] = ",".join(self.cc)
                msg.attach(att)
                msg.attach(txt)
            else:
                raise IOError('you got wrong subtype')
        except Exception as e:
            self.log.error('[SendEmail]%s' % e)
        else:
            # 连接发送邮件
            if self.__Connect(self.smtpserver) == True:
                self.__Login(self.user, self.password)
                #存在多个收件人时候进行需要拆分
                self.__SendEmail(self.sender, self.receiver, msg.as_string())
                self.__Quit()
示例#13
0
if __name__ == '__main__':
    log.info('program started:------------------------------------')
    info_url = config.httpInfo + 'info'
    finish_url = config.httpInfo + 'finish'
    while (True):
        person_info = {}
        # body_info = {}
        try:
            result = get(info_url)
            if result['has_record'] == 1:
                log.info('process record: %s' % result['data'])
                record_id = result['data']['id']
                person_info['person_id'] = result['data']['bbiid']
                person_info['height'] = result['data']['height']
                person_info['weight'] = result['data']['weight']
                person_info['name'] = result['data']['name']
                person_info['body_id'] = result['data']['body_id']
                save_person_info(result['data']['folder'], person_info)
                download_files(result['data']['folder'],
                               result['data']['body_id'],
                               result['data']['status'])

                result = get('%s/%d' % (finish_url, record_id))
                print(result)
            else:
                time.sleep(2)
        except Exception as e:
            log.error('exception occured:' + str(e))
            time.sleep(2)