Exemple #1
0
 def send_chars(self, chars):
     log.i('Sending chars: {}'.format(chars))
     if len(chars) > 255:
         log.w("Text length exceeds calc's buffer size (255 chars).")
     parity_bytes = util.set_parity(bytearray(chars),
                                    int(self.config['parity'].value))
     self.transport.write_bytes(parity_bytes)
    def get_port(self, device_type):
        if device_type == "vr":
            card_port_product_name_regex = self.config.audio_card_port_vr_product_name_regex()
        elif device_type == "normal":
            card_port_product_name_regex = self.config.audio_card_port_normal_product_name_regex()
        else:
            raise NotImplementedError()

        if card_port_product_name_regex is None:
            log.d(
                "Skipping port selection for {device_type} device because card_port_{device_type}_product_name_regex is not set.".format(
                    device_type=device_type))
            return None

        cards = pactl_interface.Card.get_all_cards()
        for card in cards:
            for port in card.ports:
                if port.product_name is not None:
                    if re.match(card_port_product_name_regex, port.product_name):
                        return port

        debug_output = ''
        for card in cards:
            debug_output += card.name + '\n'
            for port in card.ports:
                debug_output += '    {}\n'.format(port.product_name if port.product_name is not None else '-')
        log.w('Failed to find any port on any card matching "{}". Name of the product at every port:\n{}'.format(
            card_port_product_name_regex, debug_output
        ))

        return None
Exemple #3
0
def read(args):
    """
    Read configuration (possibly pointed by args)
    """

    if debug:
        log.w("DEBUGGING ENABLED! YOUR DATA MAY BE EXPOSED!")

    v = vars(args)

    global verbose
    if 'verbose' in v:
        verbose = v['verbose']

    user_config_parser = ConfigParser.ConfigParser()
    try:
        if 'config' in v and v['config'] != None:
            f = open(v['config'])
            user_config_parser.readfp(f)
        else:
            try:
                f = open('.cryptoboxrc')
                user_config_parser.readfp(f)
            except:
                try:
                    f = open('~/.cryptoboxrc')
                    user_config_parser.readfp(f)
                except:
                    pass
    except Exception as e:
        log.e("Could not load user config!")
        log.e(str(e))
        sys.exit(1)

    return read_user_config(user_config_parser)
Exemple #4
0
    def fetch_cna(self):
        def quote_cna(val):
            if '%' in val:
                return val
            return urllib.parse.quote(val)

        cook = cookiejar.CookieJar()
        if cookies:
            for cookie in cook:
                if cookie.name == 'cna' and cookie.domain == '.youku.com':
                    log.i('Found cna in imported cookies. Use it')
                    return quote_cna(cookie.value)
        url = 'http://log.mmstat.com/eg.js'
        #url = 'http://gm.mmstat.com/yt/ykcomment.play.commentInit?cna='
        req = urllib.request.urlopen(url)
        headers = req.getheaders()
        for header in headers:
            if header[0].lower(
            ) == 'set-cookie':  #元组中第0项字符串转换为小写对比是不是'set-cookie'
                n_v = header[1].split(';')[0]  #根据分好分割出cna
                name, value = n_v.split('=')  #根据分好分割出cna字段
                if name == 'cna':
                    return quote_cna(value)
        log.w(
            'It seems that the client failed to fetch a cna cookie. Please load your own cookie if possible'
        )
        return quote_cna('DOG4EdW4qzsCAbZyXbU+t7Jt')
 def getMovieListByKeyword(self, keyword):
     log.d("getMovieListByKeyword: " + keyword)
     if (not keyword):
         log.w("search request with empty keyword")
         return []
     else:
         json_str = self.requestSearch(keyword)
         return self.getMovieList(json_str)
Exemple #6
0
    def audio_card_port_vr_product_name_regex(self):
        if 'audio' in self.data and 'card_port_vr_product_name_regex' in self.data['audio']:
            return self.data['audio']['card_port_vr_product_name_regex']

        if 'audio' in self.data and 'card_port_product_name_regex' in self.data['audio']:
            log.w(
                "Using deprecated config value audio:card_port_product_name_regex, use audio:card_port_vr_product_name_regex instead!")
            return self.data['audio']['card_port_product_name_regex']

        return '(Index HMD)|(VIVE)'
Exemple #7
0
    def set_profile(self, config, profile):
        if config.dry_run():
            log.w('Skipping because of dry run')
            return

        arguments = ['pactl', 'set-card-profile', self.name, profile.name]
        return_code, stdout, stderr = utlis.run(arguments)

        if return_code != 0:
            log.e('\'{}\' () failed, stderr:\n{}'.format(
                " ".join(arguments), stderr))
Exemple #8
0
    def set_suspend_state(self, config, state):
        if config.dry_run():
            log.w('Skipping because of dry run')
            return

        if state:
            state = "true"
        else:
            state = "false"

        arguments = ['pactl', 'suspend-sink', self.name, state]
        log.d('set_suspend_state {}'.format(' '.join(arguments)))
        return_code, stdout, stderr = utlis.run(arguments)

        if return_code != 0:
            log.e('\'{}\' () failed, stderr:\n{}'.format(" ".join(arguments), stderr))
Exemple #9
0
    def set_sink_for_all_sink_inputs(self, sink):
        if self.config.dry_run():
            log.w('Skipping because of dry run')
            return

        # verify sink name exists before proceeding
        sinks = pactl_interface.Sink.get_all_sinks(self)
        found = False
        for s in sinks:
            if s.name == sink.name:
                found = True

        if not found:
            log.w(
                'Skipping move-sink-input since the sink name does not exist')
            return

        sink_inputs = pactl_interface.SinkInput.get_all_sink_inputs(self)
        pactl_interface.Client.get_client_names(sink_inputs)
        sink_inputs = self.filter_by_client_name(sink_inputs)

        for sink_input in sink_inputs:
            failure = \
                ([failure for failure in self.failed_sink_inputs if failure.sink_input_id == sink_input.id] + [None])[0]
            if failure is not None and not failure.try_again():
                continue

            arguments = [
                'pactl', 'move-sink-input',
                str(sink_input.id), sink.name
            ]
            return_code, stdout, stderr = pactl_interface.utlis.run(arguments)

            if return_code != 0:
                if failure is None:
                    failure = self.Failure(sink_input.id)
                    self.failed_sink_inputs.append(failure)
                else:
                    failure.add_attempt()

                log.e(
                    '\'{}\' (client_name: {}) failed (count: {}), stderr:\n{}'.
                    format(" ".join(arguments), sink_input.client_name,
                           failure.failure_count, stderr))
                self.log_state()
Exemple #10
0
def backup(path, backup_files):
    if len(backup_files) <= 0:
        return

    saved_cwd = os.getcwd()
    tar = tarfile.open(path, "w")
    for p in backup_files:
        abspath = os.path.abspath(p)

        try:
            os.chdir(os.path.dirname(abspath))
            tar.add(os.path.basename(abspath))
        except:
            log.w("Couldn't add %s file to backup!" % abspath)

    os.chdir(saved_cwd)

    tar.close()
Exemple #11
0
    def __handle_node(search_paths, tp, v):
        for path in search_paths:
            f = path + '/' + tp
            try:
                data = pp(f, v)
            except:
                log.v("Tried " + f)
                continue

            log.v("Read " + f)

            try:
                jdata = json.loads(data)
            except Exception as e:
                raise Exception("Invalid JSON data in '" + f + "':\n" + str(e))

            jdata['type'] = tp.split('/')[0]

            if jdata['type'] == 'login':
                jdata['vars'] = v

            if len(v['tag']) == 0:
                jdata['tag'] = '__default__'
            else:
                jdata['tag'] = v['tag']

            return jdata

        if tp.split('/')[0] == 'login':
            log.w("Not found entry type '%s'" % tp)
            jdata = {}
            jdata['vars'] = v
            jdata['tag'] = '__default__'
            jdata['type'] = 'login'
            jdata['name'] = '/'.join(tp.split('/')[1:])
            jdata['address'] = 'http://' + jdata['name']
            jdata['form'] = {}

            return jdata
        else:
            raise Exception("Not found entry type '%s'" % tp)
Exemple #12
0
 def get_current_user( self ) :
     try:
         uuid = self.get_cookie( etc.cookie_uuid )
         if not uuid :
             log.i( 'no uuid' )
             expires = datetime.datetime.utcnow() + datetime.timedelta(days=365)
             uuid = generate_uuid()
             domain = util.get_domain_from_host( self.request.host )
             self.set_cookie( etc.cookie_uuid, uuid, domain=domain, expires=expires )
         self.uuid = uuid
         usr_ss_id = self.get_secure_cookie( etc.cookie_name )
         usr_ss_id_hmac = self.get_secure_cookie( etc.cookie_verify )
         if not usr_ss_id or not usr_ss_id_hmac :
             log.i( 'no cookie' )
             self.clear_cookie( etc.cookie_name )
             self.clear_cookie( etc.cookie_verify )
             self.ss_data = None
             return None
         check_hmac = session_base.generate_hmac( usr_ss_id )
         if usr_ss_id_hmac != check_hmac :
             log.w("evil session : %s %s"%(usr_ss_id,usr_ss_id_hmac))
             self.clear_cookie( etc.cookie_name )
             self.clear_cookie( etc.cookie_verify )
             self.ss_data = None
             return None
         old_ss_data = self.ss_store.get( usr_ss_id )
         if old_ss_data == None :
             log.i("session expired")
             self.clear_cookie( etc.cookie_name )
             self.clear_cookie( etc.cookie_verify )
             self.ss_data = None
             return None
         self.ss_data = old_ss_data
         return self.ss_data
     except Exception as e :
         log.exp(e)
         self.clear_cookie( etc.cookie_name )
         self.clear_cookie( etc.cookie_verify )
         self.ss_data = None
         return self.ss_data
Exemple #13
0
 def get( self ) :
     try:
         vid = self.get_argument( 'vid', default=None )
         log.i('vid=%s' % vid)
         domain = util.get_domain_from_host( self.request.host )
         #reset = data_user.get_reset( mongo.db_pool[domain].reset, vid )
         reset = NOne
         if not reset:
             log.w('no such reset pwd')
             return self.redirect( etc.url['user_main'] )
         else:
             log.i( 'verify success' )
             return self.render( "user_reset_pwd.html",
                     p_url = etc.url,
                     p_session = self.ss_data,
                     p_pwsecret = etc.pw_secret,
                     p_next = None,
                     p_email = reset['email'],
                     p_vid = reset['vid'],
                 )
     except Exception as e :
         log.exp( e )
         self.redirect( etc.url['user_main'] )
Exemple #14
0
    def action_attempt(self, action):
        address = 0x12  # location of the byte which sets the power state

        for device in self.devices:
            basestation = bluepy.btle.Peripheral(
                iface=self.config.basestation_bluetooth_interface())
            log.i('Connecting to {}'.format(device))
            basestation.connect(device, addrType=bluepy.btle.ADDR_TYPE_RANDOM)

            if action == self.Action.ON:
                if not self.config.dry_run():
                    basestation.writeCharacteristic(address, b'\x01')
                else:
                    log.w('Skipping because of dry run:')
                log.i('Turning on')
            elif action == self.Action.OFF:
                if not self.config.dry_run():
                    basestation.writeCharacteristic(address, b'\x00')
                else:
                    log.w('Skipping because of dry run:')
                log.i('Turning off')

            basestation.disconnect()
Exemple #15
0
        def __init__(self, in_dict, card):
            self.product_name = None
            self.profiles = []
            self.card = card

            if isinstance(in_dict, str):
                key, contents = in_dict, []
            else:
                key, contents = list(in_dict.items())[0]

            match = re.match('^(.*): ', key)
            self.name = match.group(1)

            for content in contents:
                if 'Properties:' in content:
                    for property_item in content['Properties:']:
                        if isinstance(property_item, dict):
                            property_item, _ = list(property_item.items())[0]
                        match = re.match('^device.product.name = \"(.*)\"$',
                                         property_item)
                        if match is not None:
                            self.product_name = match.group(1)
                else:
                    match = re.match(r'^Part of profile\(s\): (.*)$', content)
                    if match is not None:
                        profile_names = match.group(1).split(', ')
                        for profile_name in profile_names:
                            matching_profiles = [
                                profile for profile in card.profiles
                                if profile.name == profile_name
                            ]
                            if len(matching_profiles) == 1:
                                self.profiles.append(matching_profiles[0])
                            else:
                                log.w('Did not find profile {}'.format(
                                    profile_name))
Exemple #16
0
 def Process( handler, *args ) :
     #请求前重建Session数据的过程
     try :
         email = handler.get_argument( 'email',default=None )
         passwd = handler.get_argument( 'passwd',default=None )
         rememberme = handler.get_argument( 'rememberme',default=None )
         log.i( 'email=%s , passwd=%s , rememberme=%s' % (email,passwd,rememberme) )
         expires = None
         if rememberme == "on" :
             expires = datetime.datetime.utcnow() + datetime.timedelta(days=365)
         if not email or not passwd:
             log.w( 'empty email or passwd' )
             res = { 'op':False, 'msg':'邮箱和密码不能为空' }
             handler.write( json.dumps(res) )
             handler.finish()
             return
         email = email.strip().lower()
         domain = util.get_domain_from_host( handler.request.host )
         #user = data_user.get_user_by_email( mongo.db_pool[domain].user, email, passwd )
         user = None
         handler.ss_id = None
         if not user:
             log.w( 'no such user' )
             res = { 'op':False, 'msg':'邮箱或密码错误' }
             handler.write( json.dumps(res) )
             handler.finish()
             return
         if passwd != user['pw'] :
             log.w( 'passwd err'+' '+ user['pw'] )
             res = { 'op':False, 'msg':'邮箱或密码错误' }
             handler.write( json.dumps(res) )
             handler.finish()
             return
         if user['ss']['ssid'] :
             old_ss_id = str( user['ss']['ssid'] )
             old_ss_data = handler.ss_store.get( old_ss_id )
             if old_ss_data :
                 log.i( "old session : uid=%s , ssid=%s" % (user['uid'],old_ss_id) )
                 handler.ss_id = old_ss_id
         if not handler.ss_id :
             handler.ss_id = generate_id()
             log.i( "new session : uid=%s , ssid=%s" % (user['uid'],handler.ss_id) )
         handler.ss_id_hmac = generate_hmac( handler.ss_id )
         handler.set_secure_cookie( etc.cookie_name, handler.ss_id, domain=domain, expires=expires )
         handler.set_secure_cookie( etc.cookie_verify, handler.ss_id_hmac, domain=domain, expires=expires )
         #data_user.set_login( mongo.db_pool[domain].user, user['uid'], handler.ss_id )
         handler.ss_user = user
         #执行原本请求的方法
         request( handler, *args )
     except Exception as e :
         log.exp(e)
         res = { 'op':False, 'msg':etc.err_500 }
         handler.write( json.dumps(res) )
         handler.finish()
         return
    def set_stream_for_all_stream_connections(self, stream):
        if self.config.dry_run():
            log.w('Skipping because of dry run')
            return

        # verify stream name exists before proceeding
        streams = self.get_all_streams()
        found = False
        for s in streams:
            if s.name == stream.name:
                found = True

        if not found:
            log.w('Skipping {} since the {} name does not exist'.format(
                self.get_move_stream_connection_command(),
                self.get_stream_type_name()))
            return

        stream_connections = self.get_all_stream_connections()
        pactl_interface.Client.get_client_names(stream_connections)
        stream_connections = self.filter_by_client_name(stream_connections)

        for stream_connection in stream_connections:
            failure = \
                ([failure for failure in self.failed_stream_connections if
                  failure.stream_connection_id == stream_connection.id] + [
                     None])[0]
            if failure is not None and not failure.try_again():
                continue

            arguments = [
                'pactl',
                self.get_move_stream_connection_command(),
                str(stream_connection.id), stream.name
            ]
            log.w("move {}".format(" ".join(arguments)))
            return_code, stdout, stderr = pactl_interface.utlis.run(
                arguments, assert_success=False)

            if return_code != 0:
                if failure is None:
                    failure = self.Failure(stream_connection.id)
                    self.failed_stream_connections.append(failure)
                else:
                    failure.add_attempt()

                log.e(
                    '\'{}\' (client_name: {}) failed (count: {}), stderr:\n{}'.
                    format(" ".join(arguments), stream_connection.client_name,
                           failure.failure_count, stderr))
                self.output_logger.log_all()
Exemple #18
0
#!/usr/bin/env python
#coding: utf-8

import sys

sys.path.append('./common')
import log
log.logger.setLevel(log.ERROR)

if __name__ == '__main__':
    log.initLogger('./logs/log.txt')
    log.d('this is a debug message')
    log.i("info 1+1=%d", 1 + 1)
    log.w('warning: %s', 'xxxxxx')
    log.e('error message')
    log.c("critical message, exit!")
    log.i("xxx")