示例#1
0
 async def on_message(self, message: object):
     d("New message: {} from {}".format(message,
                                        self.connection.remote_address))
     type = message_type(message)
     if not self.registered:
         if type != "Register":
             await self.connection.close()
             raise ConnectionClosed
         await self.connection.send(registered_message(uuid4()))
         self.registered = True
     else:
         if type == "Stream":
             file = Path(get_payload_element(message, "path"))
             if file.is_file():
                 global start_port
                 port = start_port
                 start_port += 1
                 self.player = start_streaming_player(port, file.absolute())
                 await self.connection.send(
                     start_streaming_message(
                         "rtp://127.0.0.1:{}".format(port)))
             else:
                 await self.connection.send(error_message())
         else:
             # just echo
             await self.connection.send(message)
示例#2
0
def main():
    # 解析命令行选项
    import optparse
    parser = optparse.OptionParser()
    parser.add_option(
        '-m',
        '--mode',
        dest='mode',
        default='random',
        help='登录模式:random 随机账号登录,config 配置信息中的账号登录,filter 筛选可用的账号')
    parser.add_option('-s',
                      '--stayon',
                      dest='stayon',
                      action='store_true',
                      default=False,
                      help='保持在线')
    parser.add_option('--checktime',
                      dest='checktime',
                      type='int',
                      default=3,
                      help='检查在线状态的时间间隔')
    parser.add_option('--accountdatafile',
                      dest='accountdatafile',
                      default='UCASAccounts.data',
                      help='指定账号数据文件,默认是 %default')
    parser.add_option('--configfile',
                      dest='configfile',
                      default='Config.json',
                      help='指定账号数据文件,默认是 %default')
    opts, args = parser.parse_args()

    accountDataFile = opts.accountdatafile
    configFile = opts.configfile
    mode = opts.mode.lower()

    if mode == 'random':
        result, info, aInfo = loginWithRandom(accountDataFile,
                                              minFlowWithGB=5,
                                              onlineDevice=1)
    elif mode == 'config':
        result, info, aInfo = loginWithConfileFile(configFile)
    elif mode == 'filter':
        filterUsableAccount(accountDataFile, accountDataFile)

    if mode in ('random', 'config'):
        userInfo = getOnlineUserInfo(info)
        print(userInfo)
        msg = getInfoString(userInfo) if result else ''
        title = '登陆成功' if result else '登陆失败'
        showMessage(title, msg)
        if opts.stayon:
            while (True):
                try:
                    if not isOnline():
                        result, info, *ignore = login(*aInfo)
                        d((result, info))
                    time.sleep(opts.checktime)
                except Exception as e:
                    logging.error(e)
示例#3
0
def logoutByUserIdAndPass(userId, password):
    """使用用户名密码下线所有用户"""
    url = r'http://210.77.16.21/eportal/InterFace.do?method=logoutByUserIdAndPass&userId={}&pass={password}'.format(
        userId, password)
    d(url)
    try:
        urlopen(url)
    except:
        pass
示例#4
0
    def parserTime(self, response):
        d('parserTime')

        meta = response.meta

        startTime = response.xpath(
            '//div[@class="qbx_2"]/p[1]/text()').extract_first()
        startTime = " ".join(startTime.split())  # 截去中间夹的\xa0 空格符&npsp

        meta['match'].update({'startTime': startTime})

        print(meta['match'])
        resultData.append(meta['match'])
示例#5
0
def start_streaming_player(port: int, file: str):
    cmd = [
        "file://{}".format(file),
        "sout=#duplicate{dst=rtp{dst=127.0.0.1,port=" + str(port) + "}}",
        "no-sout-rtp-sap", "no-sout-standard-sap", "sout-keep"
    ]
    d("start streaming with arguments: {}".format(cmd))
    vlc = VLC()
    media = vlc.media_new(*cmd)
    media.get_mrl()

    player = vlc.media_player_new()
    player.set_media(media)
    player.play()

    return player
示例#6
0
def main():
    # 解析命令行选项
    import optparse
    parser = optparse.OptionParser()
    parser.add_option('-m', '--mode', dest='mode', default='random',
                      help='登录模式:random 随机账号登录,config 配置信息中的账号登录,filter 筛选可用的账号')
    parser.add_option('-s', '--stayon', dest='stayon',
                      action='store_true', default=False,
                      help='保持在线')
    parser.add_option('--checktime', dest='checktime',
                      type='int', default=3,
                      help='检查在线状态的时间间隔')
    parser.add_option('--accountdatafile', dest='accountdatafile',
                      default='UCASAccounts.data',
                      help='指定账号数据文件,默认是 %default')
    parser.add_option('--configfile', dest='configfile',
                      default='Config.json',
                      help='指定账号数据文件,默认是 %default')
    opts, args = parser.parse_args()

    accountDataFile = opts.accountdatafile
    configFile = opts.configfile
    mode = opts.mode.lower()

    if mode == 'random':
        result, info, aInfo = loginWithRandom(accountDataFile, minFlowWithGB=5, onlineDevice=1)
    elif mode == 'config':
        result, info, aInfo = loginWithConfileFile(configFile)
    elif mode == 'filter':
        filterUsableAccount(accountDataFile, accountDataFile)

    if mode in ('random', 'config'):
        userInfo = getOnlineUserInfo(info)
        print(userInfo)
        msg = getInfoString(userInfo) if result else ''
        title = '登陆成功' if result else '登陆失败'
        showMessage(title, msg)
        if opts.stayon:
            while(True):
                try:
                    if not isOnline():
                        result, info, *ignore = login(*aInfo)
                        d((result, info))
                    time.sleep(opts.checktime)
                except Exception as e:
                    logging.error(e)
示例#7
0
    def parse(self, response):
        d('parse')

        for i in range(roundWantStart, roundWantStart + roundWantget):
            round_url = 'http://www.okooo.com/soccer/league/%s/schedule/%s/1-1-%s/' % (
                leagueCode, seasonCode, i)

            headers = {
                'User-Agent': userAgent,
                'Connection': 'keep-alive',
                'Referer': round_url,
                'Cookie': cookie
            }

            meta = {'match': {}}

            meta['match'].update({'round': i})

            d('Round %s' % (i))
            yield Request(url=round_url,
                          headers=headers,
                          callback=self.parseRound,
                          meta=meta)
示例#8
0
def loginWithRandom(accountFileName, defaultPassword='******', minFlowWithGB=0, onlineDevice=0):
    """使用配置文件中的账号随机登录"""
    logout()

    configChanged = False
    config = None
    noFlowAccounts = []
    noMeetFlowAccounts = []
    try:
        curMonthConfig = getCurrentMonthConfigFile(accountFileName)
        config = readConfig(curMonthConfig) if path.isfile(curMonthConfig) else None
        if config:
            noFlowAccounts = config.get('NoFlow', [])
            noMeetFlowAccounts = config.get(str(minFlowWithGB), [])
    except Exception as e:
        print("错误", e, '结束')

    try:
        # read all accounts
        with open(accountFileName, encoding='utf8') as fh:
            accountSet = set(fh.read().splitlines())
            accounts = list(accountSet - set(noFlowAccounts) - set(noMeetFlowAccounts))
        # d(accounts)
        modifyAccounysSet = False
        logined = []
        lResult, lMsg, aInfo = None, None, None
        while len(accounts) > 0:
            i = random.randint(0, len(accounts) - 1)
            account = accounts.pop(i)
            meetCondition, msg, loginSuccess, userInfo = meet(
                account, defaultPassword, minFlowWithGB, onlineDevice)
            if meetCondition:
                lResult, lMsg, aInfo = login(account, defaultPassword)
                break
            else:

                if loginSuccess and userInfo:
                    noMeetFlowAccounts.append(account)
                    configChanged = True
                    logined.append((account, float(userInfo['flow'])))
                    d('添加了不满足流量账号' + account)
                elif msg in ('NoUser', 'NoPassword'):
                    d("密码被修改:" + account)
                    accountSet.discard(account)
                    modifyAccounysSet = True
                elif msg == 'NoFlow':
                    configChanged = True
                    d('添加了无流量账号')
                    noFlowAccounts.append(account)
        else:
            # 没有一个满足条件的
            # 从登录成功的账号中和挑选一个登录
            d('矬子里面拔将军')
            d(logined)
            for account in noMeetFlowAccounts:
                loginSuccess, info, aInfo = login(account, defaultPassword)
                if loginSuccess:
                    userInfo = getOnlineUserInfo(info)
                    if userInfo and 'flow' in userInfo:
                        logined.append((account, float(userInfo['flow'])))
                    logout(info)
            if len(logined):
                d(logined)
                logined.sort(key=lambda x: x[1], reverse=True)
                account = logined[0][0]
                lResult, lMsg, aInfo = login(account, defaultPassword)

        # 从原文件中剔除被修改了密码的账号
        if modifyAccounysSet:
            d('有被修改了密码的存在')
            with open(accountFileName, 'w', encoding='utf8') as fh:
                for a in accountSet:
                    fh.write(a + '\n')

        # 把这个月没流量的和不满足流量要求的账号记录下来
        if configChanged:
            config = config or {}
            config['NoFlow'] = list(set(noFlowAccounts))
            config[minFlowWithGB] = list(set(noMeetFlowAccounts))
            writeConfig(curMonthConfig, config)
        return lResult, lMsg, aInfo
    except Exception as e:
        print(e)
示例#9
0
    def parseHoddsDetail(self, response):
        d('parseHoddsDetail')

        meta = response.meta

        hodd = str(meta['match']['hoddNum'])

        oddLine = response.xpath(
            '//tr[contains(@id,"%s") and td[3]/span/text()="%s"]' %
            (labBrokes, hodd))

        print(oddLine)
        print(oddLine.extract())

        if oddLine == []:
            print('no LabBrokes hodd')
            oddLine = response.xpath(
                '//tr[contains(@id,"%s") and td[3]/span/text()="%s"]' %
                (williamHill, hodd))
            print(oddLine)
            print(oddLine.extract())
            hoddFrom = williamHill
        else:
            hoddFrom = labBrokes

        if oddLine != []:
            hodd3 = oddLine.xpath('td[7]/a/span/text()').extract_first()
            hodd1 = oddLine.xpath('td[8]/a/span/text()').extract_first()
            hodd0 = oddLine.xpath('td[9]/a/span/text()').extract_first()

            hoddStart3 = oddLine.xpath('td[4]/a/span/text()').extract_first()
            hoddStart1 = oddLine.xpath('td[5]/a/span/text()').extract_first()
            hoddStart0 = oddLine.xpath('td[6]/a/span/text()').extract_first()

            meta['match'].update({
                'hodd3': hodd3,
                'hodd1': hodd1,
                'hodd0': hodd0,
                'hoddStart3': hoddStart3,
                'hoddStart1': hoddStart1,
                'hoddStart0': hoddStart0,
                'hoddFrom': hoddFrom
            })
        else:
            w('no hodd found')

        # 最后再去取一下精确时间
        match_url = 'http://www.okooo.com/soccer/match/%s/odds/' % (
            meta['match']['matchId'])
        round_url = 'http://www.okooo.com/soccer/league/%s/schedule/%s/1-1-%s/' % (
            leagueCode, seasonCode, i)

        headers = {
            'User-Agent': userAgent,
            'Connection': 'keep-alive',
            'Referer': round_url,
            'Cookie': cookie
        }

        yield scrapy.Request(url=match_url,
                             headers=headers,
                             cookies=cookie,
                             callback=self.parserTime,
                             meta=meta)
示例#10
0
    def parseOddsDetail(self, response):
        d('parseOddsDetail')

        meta = response.meta

        sel = Selector(response)
        oddLine = sel.xpath('//tr[@id="tr82"]')

        if len(oddLine.extract()) > 0:
            odd3 = oddLine.xpath('td[6]/a/span/text()').extract_first()
            odd1 = oddLine.xpath('td[7]/a/span/text()').extract_first()
            odd0 = oddLine.xpath('td[8]/div/a/span/text()').extract_first()

            oddStart3 = oddLine.xpath('td[3]/span/text()').extract_first()
            oddStart1 = oddLine.xpath('td[4]/span/text()').extract_first()
            oddStart0 = oddLine.xpath('td[5]/span/text()').extract_first()

            prob3 = oddLine.xpath('td[10]/span/text()').extract_first()
            prob1 = oddLine.xpath('td[11]/span/text()').extract_first()
            prob0 = oddLine.xpath('td[12]/span/text()').extract_first()

            kelly3 = oddLine.xpath('td[13]/span/text()').extract_first()
            kelly1 = oddLine.xpath('td[14]/span/text()').extract_first()
            kelly0 = oddLine.xpath('td[15]/span/text()').extract_first()

            returnProb = oddLine.xpath('td[16]/span/text()').extract_first()

            hoddNum = -1
            if float(oddStart3) > float(oddStart0):
                hoddNum = 1

            goal_h = meta['match']['goalHome'] + hoddNum
            goal_a = meta['match']['goalAway']

            hResultCode = -1
            if goal_h > goal_a:
                hResultCode = 3
            elif goal_h < goal_a:
                hResultCode = 0
            else:
                hResultCode = 1

            meta['match'].update({
                'hoddNum': hoddNum,
                'hResultCode': hResultCode,
                'odd3': odd3,
                'odd1': odd1,
                'odd0': odd0,
                'prob3': prob3,
                'prob1': prob1,
                'prob0': prob0,
                'kelly3': kelly3,
                'kelly1': kelly1,
                'kelly0': kelly0,
                'returnProb': returnProb,
                'oddStart3': oddStart3,
                'oddStart1': oddStart1,
                'oddStart0': oddStart0,
            })

            headers = {
                'User-Agent':
                userAgent,
                'Connection':
                'keep-alive',
                'Referer':
                'http://www.okooo.com/soccer/match/%s/' %
                (meta['match']['matchId']),
                'X-Requested-With':
                'XMLHttpRequest',
            }

            # 获取让球详细赔率 ajax
            url = 'http://www.okooo.com/soccer/match/%s/hodds/ajax/?page=0&trnum=0&companytype=BaijiaBooks' % (
                meta['match']['matchId'])
            yield scrapy.Request(url=url,
                                 headers=headers,
                                 cookies=cookie,
                                 callback=self.parseHoddsDetail,
                                 meta=meta)
        else:
            w('no LabBroke odd')
示例#11
0
    def parseRound(self, response):
        d('parseRound')
        roundIndex = response.meta['match']['round']
        matches = response.xpath('//*[@id="team_fight_table"]/tr')

        matchIndex = 0
        for i in range(1, len(matches)):
            matchPath = matches[i]

            scoreText = matchPath.xpath(
                'td[4]/a/strong/text()').extract_first()

            # 延期比赛会当做一场全新的比赛来看待
            if scoreText == None and matchPath.xpath(
                    'td[4]/text()').extract_first().find('延期') > -1:
                d('延期')
                continue

            matchId = matchPath.xpath('@matchid').extract_first()
            startTime = matchPath.xpath('td[1]/text()').extract_first()
            teamHome = matchPath.xpath('td[3]/text()').extract_first()
            teamAway = matchPath.xpath('td[5]/text()').extract_first().strip()
            goalHome = int(scoreText.split('-')[0])
            goalAway = int(scoreText.split('-')[1])

            resultCode = -1
            if goalHome > goalAway:
                resultCode = 3
            elif goalHome < goalAway:
                resultCode = 0
            else:
                resultCode = 1

            meta = {}

            matchIndex += 1
            meta['match'] = {
                'matchId': matchId,
                'leagueCode': leagueCode,
                'leagueName': leagueName,
                'seasonCode': seasonCode,
                'seasonName': seasonName,
                'round': roundIndex,
                'vsText': '%s %s %s' % (teamHome, scoreText, teamAway),
                'matchIndex': matchIndex,
                'startTime': startTime,
                'teamHome': teamHome,
                'teamAway': teamAway,
                'goalHome': goalHome,
                'goalAway': goalAway,
                'scoreText': scoreText,
                'resultCode': resultCode
            }

            # 获取立博详细赔率 ajax
            url = 'http://www.okooo.com/soccer/match/%s/odds/ajax/?page=0&trnum=0&companytype=BaijiaBooks&type=1' % (
                matchId)
            headers = {
                'User-Agent': userAgent,
                'Connection': 'keep-alive',
                'Referer':
                'http://www.okooo.com/soccer/match/%s/odds/' % (matchId),
                'X-Requested-With': 'XMLHttpRequest',
                'Accept-Language':
                'zh-CN,zh;q=0.9,ja;q=0.8,en;q=0.7,zh-TW;q=0.6',
                'Accept': 'text/html, */*',
                'Pragma': 'no-cache',
                'Proxy-Connection': 'keep-alive'
            }
            yield scrapy.Request(url=url,
                                 headers=headers,
                                 cookies=cookie,
                                 callback=self.parseOddsDetail,
                                 meta=meta)
示例#12
0
 def __init__(self, connection: Connection):
     d("Client connected: {}".format(connection.remote_address))
     self.connection = connection
     self.registered = False
     self.player = None
示例#13
0
async def client_connected(connection: Connection, path):
    try:
        await Client(connection).run()
    except ConnectionClosed:
        d("Client {} closed the connection".format(connection.remote_address))
示例#14
0
    async def run(self):
        async for message in self.connection:
            decoded = loads(message)

            if message_source(decoded) != "slave" or not message_type(decoded):
                await self.connection.close()
                raise ConnectionClosed
            await self.on_message(decoded)


async def client_connected(connection: Connection, path):
    try:
        await Client(connection).run()
    except ConnectionClosed:
        d("Client {} closed the connection".format(connection.remote_address))


if __name__ == "__main__":
    basicConfig(level=DEBUG, handlers=[StreamHandler()])

    host = ""
    port = 5678

    try:
        get_event_loop().run_until_complete(serve(client_connected, host,
                                                  port))
        d("Started game server: {}:{}".format(host, port))
        get_event_loop().run_forever()
    except KeyboardInterrupt:
        d("The game server was shut")
示例#15
0
import SoccerUtil as su
import logging
from logging import debug as d,info as i,warning as w,error as e,critical as c


#
logging.basicConfig(level=logging.DEBUG)
print(su.LEAGUE)
# debug('a')
# info('b')
# error('c')
# warning('d')
# critical('e')
# critical(su.LEAGUE)

d('a')
i('b')
e('c')
w('d')
c('e')
c(su.LEAGUE)
#


#
# f = open("const.json",encoding="utf-8")
#
# setting = json.load(f)
#
# print(setting)
#