Exemplo n.º 1
0
def qrLogin():
    headers= {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36",
        "X-Line-Application": "CHROMEOS\t2.3.2\tChrome OS\t1",
        "x-lal": "en_ID",
        "X-Line-Carrier": "51010,1-0"
    }
    sys_name = "BE-Team"
    transport = THttpClient("https://ga2.line.naver.jp" + '/api/v4/TalkService.do')
    transport.setCustomHeaders(headers)
    protocol = TCompactProtocol(transport)
    talk = BoteaterService.Client(protocol)
    qr_code = talk.getAuthQrcode(keepLoggedIn=True, systemName=sys_name, returnCallbackUrl=True)
    transport.close()
    print(qr_code.callbackUrl)
    headers["X-Line-Access"] = qr_code.verifier
    transport = THttpClient("https://ga2.line.naver.jp" + '/api/v4p/rs')
    transport.setCustomHeaders(headers)
    protocol = TCompactProtocol(transport)
    auth = BoteaterService.Client(protocol)
    get_access = json.loads(requests.get("https://ga2.line.naver.jp" + '/Q', headers=headers).text)
    login_request = LoginRequestStruct()
    login_request.type = 1
    login_request.identityProvider = 1
    login_request.keepLoggedIn = True
    login_request.systemName = sys_name
    login_request.verifier = get_access['result']['verifier']
    result = auth.loginZ(login_request)
    transport.close()
    return result.authToken
Exemplo n.º 2
0
 def qrLogin(self, headers):
     sys_name = "BE-Team"
     transport = THttpClient(self.lineServer + '/api/v4/TalkService.do')
     transport.setCustomHeaders(headers)
     protocol = TCompactProtocol(transport)
     talk = TalkService.Client(protocol)
     qr_code = talk.getAuthQrcode(keepLoggedIn=True,
                                  systemName=sys_name,
                                  returnCallbackUrl=True)
     transport.close()
     print(qr_code.callbackUrl)
     headers["X-Line-Access"] = qr_code.verifier
     transport = THttpClient(self.lineServer + '/api/v4p/rs')
     transport.setCustomHeaders(headers)
     protocol = TCompactProtocol(transport)
     auth = TalkService.Client(protocol)
     get_access = json.loads(
         requests.get(self.lineServer + '/Q', headers=headers).text)
     login_request = LoginRequest()
     login_request.type = 1
     login_request.identityProvider = 1
     login_request.keepLoggedIn = True
     login_request.systemName = sys_name
     login_request.verifier = get_access['result']['verifier']
     result = auth.loginZ(login_request)
     transport.close()
     return result.authToken
Exemplo n.º 3
0
            async def g(*args, **kwargs):
                service = args[0]
                key = f'{interfaceName}:{version}'
                if id_index is not None:
                    key = f'{key}:{args[id_index]}'
                objs = []

                if service is None:
                    # recommend service is down, resort to redis
                    try:
                        redis = await self.connect()
                        robjs = await redis.lrange(key, 0, -1)
                        robjs = robjs or []
                        for robj in robjs:
                            if robj is None:
                                continue

                            obj = creator()
                            mobj = TMemoryBuffer(lz4.frame.decompress(robj))
                            cobj = TCompactProtocol(mobj)
                            obj.read(cobj)
                            objs.append(obj)

                        logger.debug(f'[REDIS] Get list of {key} from cache')
                    except Exception as e:
                        log.print_excp(e)
                else:
                    objs = await f(*args, **kwargs)
                    # save obj to redis randomly
                    if self.lucky() and objs is not None and len(objs) > 0:
                        try:
                            redis = await self.connect(True)
                            vals = []
                            for obj in objs:
                                mobj = TMemoryBuffer()
                                cobj = TCompactProtocol(mobj)
                                obj.write(cobj)
                                vals.append(lz4.frame.compress(
                                    mobj.getvalue()))

                            if len(vals) > 0:
                                tr = redis.multi_exec()
                                tr.ltrim(key, 1, 0)
                                tr.rpush(key, *vals)
                                tr.expire(key, RECO_TTL)

                                await tr.execute()
                                logger.debug(
                                    f'[REDIS] Set list of {key} to cache')
                        except Exception as e:
                            log.print_excp(e)

                return objs
Exemplo n.º 4
0
    async def cache_set(self, f, creator, prefix, id_index, *args, **kwargs):
        capacity = 10
        service = args[0]
        version = self.get_reco_version(creator)
        key = f'{prefix}:{version}'
        if id_index is not None:
            key = f'{key}:{args[id_index]}'
        obj = None

        if service is None:
            # recommend service is down, fetch one from redis randomly
            try:
                redis = await self.connect()
                robj = await redis.srandmember(key)
                if robj is not None:
                    obj = creator()
                    mobj = TMemoryBuffer(lz4.frame.decompress(robj))
                    cobj = TCompactProtocol(mobj)
                    obj.read(cobj)

                    logger.debug(
                        f'[REDIS] Get Response obj of {key} from cache')
            except Exception as e:
                log.print_excp(e)
        else:
            obj = await f(*args, **kwargs)

            # save obj to redis randomly
            if self.lucky() and obj is not None:
                try:
                    redis = await self.connect(True)
                    # del some randomly when total number is more than {capacity}
                    total = await redis.scard(key)
                    if total > capacity * 1.25:
                        await redis.execute('spop', key,
                                            int(total - capacity * 0.75))
                    else:
                        tr = redis.multi_exec()
                        mobj = TMemoryBuffer()
                        cobj = TCompactProtocol(mobj)
                        obj.write(cobj)
                        tr.sadd(key, lz4.frame.compress(mobj.getvalue()))
                        tr.expire(key, RECO_TTL)
                        await tr.execute()
                        logger.debug(
                            f'[REDIS] Set Response obj of {key} to cache')
                except Exception as e:
                    log.print_excp(e)

        return obj
Exemplo n.º 5
0
    def post(self, request):
        out_format = request.POST.get('OutFormat', 'json')

        info = CouponInfo(
                cid=coupon['cid'],
                name=coupon['name'],
                amount=coupon['amount'],
                progress=coupon['progress'],
                start_time=coupon['start_time'],
                expired_time=coupon['expired_time'],
                ctype=coupon['ctype'],
                use_type=coupon['use_type'],
                min_invest_time=coupon['min_invest_time'],
                max_invest_time=coupon['max_invest_time'],
                min_amount=coupon['min_amount'],
                des=coupon['desc'],
        )
        res = CouponInfoResponse(code=0, message='success', info=info)
        tMemory_b = TMemoryBuffer()
        if out_format == 'binary':
            tBinaryProtocol_b = TCompactProtocol(tMemory_b)
            content_type = 'application/octet-stream'
        elif out_format == 'tjson':
            tBinaryProtocol_b = TJSONProtocol(tMemory_b)
            content_type = 'application/json'
        else:
            tBinaryProtocol_b = TSimpleJSONProtocol(tMemory_b)
            content_type = 'application/json'

        res.write(tBinaryProtocol_b)

        memory_buffer = tMemory_b.getvalue()
        return HttpResponse(content=memory_buffer, content_type=content_type)
Exemplo n.º 6
0
def main(argv):
    p = argparse.ArgumentParser()
    add_common_args(p)
    # Since THeaderTransport acts as framed transport when detected frame, we
    # cannot use --transport=framed as it would result in 2 layered frames.
    p.add_argument('--override-transport')
    p.add_argument('--override-protocol')
    args = p.parse_args()
    assert args.protocol == 'header'
    assert args.transport == 'buffered'
    assert not args.ssl

    sock = TSocket(args.host, args.port, socket_family=socket.AF_INET)
    if not args.override_transport or args.override_transport == 'buffered':
        trans = TBufferedTransport(sock)
    elif args.override_transport == 'framed':
        print('TFRAMED')
        trans = TFramedTransport(sock)
    else:
        raise ValueError('invalid transport')
    trans.open()

    if not args.override_protocol or args.override_protocol == 'binary':
        proto = TBinaryProtocol(trans)
    elif args.override_protocol == 'compact':
        proto = TCompactProtocol(trans)
    else:
        raise ValueError('invalid transport')

    test_void(proto)
    test_void(proto)

    trans.close()
Exemplo n.º 7
0
def make_ver_req(peer_ip, peer_port, node_id):
    m = TMemoryBuffer()
    # p = TBinaryProtocol(m)
    p = TCompactProtocol(m)
    msg_name = "ver_req"
    nonce = "0"  #get_random_id()
    head = ttypes_header.msg_header(0, msg_name, nonce)
    head.write(p)
    # print("nonce:%s, node_id:%s" %(nonce,  node_id))
    addr_me = network_address("127.0.0.1", 1)
    addr_you = network_address(peer_ip, peer_port)
    time_stamp = int(time.time())
    req = ver_req_body(node_id, 0, 0, time_stamp, addr_me, addr_you, 1)

    # p.writeMessageBegin()
    req.write(p)
    # p.writeMessageEnd()
    m.flush()

    v = m.getvalue()
    # print v
    # print [hex(ord(i)) for i in v]

    c = pack_head(m)
    # pprint(c)

    # print [hex(ord(i)) for i in c]
    return c
Exemplo n.º 8
0
    def decode_compact(self, bs):
        m = TMemoryBuffer(bs)  # skip packet header
        p = TCompactProtocol(m)
        try:
            # h = msg_header()
            h = ttypes_header.msg_header()
            h.read(p)
        except EOFError:
            print "Error: msg header decode failure"
            return

        self.header = h

        # print m._buffer.tell()  # buffer offset
        s = h.msg_name + "_body"
        if s in globals():
            t = globals()[s]
        else:
            t = empty

        try:
            body = t()
            body.read(p)
        except EOFError:
            print "Error: msg body decode failure"
            return

        self.body = body
Exemplo n.º 9
0
 def _connect(self, host, port) -> Client:
     socket = TSocket(host, port)
     transport = TFramedTransport(socket)
     protocol = TCompactProtocol(transport)
     client = Client(protocol)
     transport.open()
     return client
Exemplo n.º 10
0
def write_thrift(fobj, thrift):
    """Write binary compact representation of thiftpy structured object

    Parameters
    ----------
    fobj: open file-like object (binary mode)
    thrift: thriftpy object to write

    Returns
    -------
    Number of bytes written
    """
    t0 = fobj.tell()
    pout = TCompactProtocol(fobj)
    try:
        thrift.write(pout)
        fail = False
    except TProtocolException as e:
        typ, val, tb = sys.exc_info()
        frames = []
        while tb is not None:
            frames.append(tb)
            tb = tb.tb_next
        frame = [
            tb for tb in frames if 'write_struct' in str(tb.tb_frame.f_code)
        ]
        variables = frame[0].tb_frame.f_locals
        obj = variables['obj']
        name = variables['fname']
        fail = True
    if fail:
        raise ParquetException('Thrift parameter validation failure %s'
                               ' when writing: %s-> Field: %s' %
                               (val.args[0], obj, name))
    return fobj.tell() - t0
Exemplo n.º 11
0
 def test_primitive_serialization(self):
     val = int(12)
     buf = TMemoryBuffer()
     proto = TCompactProtocol(buf)
     proto.writeI32(val)
     reader = TCompactProtocol(StringIO(buf.getvalue()))
     self.assertEqual(reader.readI32(), val)
Exemplo n.º 12
0
 def openTransport(self, endPoint, pool=False):
     if pool:
         #transport = THttpClientPool(self.lineServer + endPoint)
         transport = THttpClient(self.lineServer + endPoint)
     else:
         transport = THttpClient(self.lineServer + endPoint)
     transport.setCustomHeaders(self.thisHeaders)
     protocol = TCompactProtocol(transport)
     return BEService.Client(protocol)
Exemplo n.º 13
0
    def Shop(self, isopen=True):
        self.transport = THttpClient(self.host, customThrift=self.customThrift)
        self.transport.setCustomHeaders(self.headers)

        self.protocol = TCompactProtocol(self.transport)
        self._shop = ShopService.Client(self.protocol)

        if isopen:
            self.transport.open()

        return self._shop
Exemplo n.º 14
0
def getMid(my_token):
    headers= {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36",
        "X-Line-Application": "CHROMEOS\t2.3.2\tChrome OS\t1",
        "x-lal": "en_ID",
        "X-Line-Carrier": "51010,1-0"
    }
    headers["X-Line-Access"] = my_token
    transport = THttpClient("https://ga2.line.naver.jp" + '/api/v4/TalkService.do')
    transport.setCustomHeaders(headers)
    protocol = TCompactProtocol(transport)
    talk = BoteaterService.Client(protocol)
    mid = talk.getProfile().mid
    transport.close()
    return mid
Exemplo n.º 15
0
    async def get_details_from_cache(self, idts, prefix):
        obj = dittypes.DIResponse(typeList=[idt.type for idt in idts])
        idts_left = None
        try:
            # 先从Redis拿数据
            redis = await self.connect()
            idts_left = []

            for idt in idts:
                typ = idt.type
                ids = idt.ids

                version = self.get_di_version(typ)
                key_prefix = f'{prefix}:{typ}:{version}'
                keys = [f'{key_prefix}:{i}' for i in ids]
                # 一次从多个key读取数据
                items = await redis.mget(*keys)
                logger.debug(
                    f'[REDIS] Get {len(items)} DIResponse objs of {typ} from redis'
                )

                ids = [ids[i] for i, v in enumerate(items) if v is None]
                items = [it for it in items if it is not None]

                if len(ids) > 0:
                    idts_left.append(dittypes.IdsWithType(ids=ids, type=typ))

                vals = []
                for item in items:
                    if item is None:
                        continue

                    # 从Redis中的二进制数据恢复成所需结构
                    creator = self.di_creator(typ)
                    if creator is None:
                        continue

                    val = creator()
                    mval = TMemoryBuffer(lz4.frame.decompress(item))
                    cval = TCompactProtocol(mval)
                    val.read(cval)
                    vals.append(val)

                self.di_setlist(obj, typ, vals)
        except Exception as e:
            log.print_excp(e)

        return obj, idts_left
Exemplo n.º 16
0
def _marshall_span(span):
    class TestTrans(TMemoryBuffer):
        def now_reading(self):
            """
            Thrift TMemoryBuffer is not read-able AND write-able,
            it's one or the other (really? yes.). This will convert
            us from write-able to read-able.
            """
            self._buffer = BytesIO(self.getvalue())

    spans = thrift.make_zipkin_spans([span])

    # write and read them to test encoding
    args = Agent.emitZipkinBatch_args(spans)
    t = TestTrans()
    prot = TCompactProtocol(t)
    args.write(prot)
    t.now_reading()
    args.read(prot)
Exemplo n.º 17
0
def _marshall_span(span):
    class TestTrans(TMemoryBuffer):
        def now_reading(self):
            """
            Thrift TMemoryBuffer is not read-able AND write-able,
            it's one or the other (really? yes.). This will convert
            us from write-able to read-able.
            """
            self._buffer = BytesIO(self.getvalue())

    batch = thrift.make_jaeger_batch(
        spans=[span], process=ttypes.Process(serviceName='x', tags={}))

    # write and read them to test encoding
    args = Agent.emitBatch_args(batch)
    t = TestTrans()
    prot = TCompactProtocol(t)
    args.write(prot)
    t.now_reading()
    args.read(prot)
Exemplo n.º 18
0
	async def loginWithQrcode(self, path=None):
		self.url(config.MAIN_PATH)
		qr = await self.call('getAuthQrcode', True, "AsyncLine", "")
		p_key = generate_asymmetric_keypair()
		secret_query = create_secret_query(p_key.public_key)
		print(f"line://au/q/{qr.verifier}?secret={secret_query}&e2eeVersion=1")
		r = self.waitForPhoneConfirm(qr.verifier)
		vr = r.json()
	
		key_chain = vr['result']['metadata']['encryptedKeyChain']
		public_key = vr['result']['metadata']['publicKey']
		data_key = decrypt_keychain(p_key, key_chain, public_key)
		keychain = E2EEKeyChain()
		tbuffer = TMemoryBuffer(data_key)
		protocol = TCompactProtocol(tbuffer)
		keychain.read(protocol)
		
		self.url(config.AUTH_PATH)
		rq = LoginRequest(
			type=LoginType.QRCODE,
			identityProvider=IdentityProvider.LINE,
			keepLoggedIn=True,
			accessLocation=config.LOGIN_LOCATION,
			systemName="AsyncLine",
			verifier=vr["result"]["verifier"],
			secret=p_key.public_key,
			e2eeVersion=2
		)
		lr = await self.call('loginZ', rq)
		self.updateHeaders({
			'X-Line-Access': lr.authToken
		})
		self.authToken = lr.authToken
		self.cert = lr.certificate
		if path:
			with open(path, "w") as fp:
				fp.write(lr.authToken)
		await self.afterLogin()
Exemplo n.º 19
0
 def _connect(self):
     try:
         self._current_host_port = random.choice(
             self._host_ports_pool).split(':')
         self._sock = TSocket.TSocket(host=self._current_host_port[0],
                                      port=self._current_host_port[1])
         self._transport = TTransport.TFramedTransport(self._sock)
         self._protocol = TCompactProtocol(self._transport)
         self._client = THBaseService.Client(self._protocol)
         self._transport.open()
     except Exception, e:
         TDDCLogging.error(e)
         current_host_port = ':'.join(self._current_host_port)
         self._host_ports_pool.remove(current_host_port)
         if len(self._host_ports_pool) > 0:
             TDDCLogging.warning(
                 'HBase Server Exception. Now Is Reconnecting.')
         else:
             TDDCLogging.warning(
                 'HBase Server Fatal Error. Please Check It.')
             gevent.sleep(30)
             self._host_ports_pool = list(self._host_ports)
             TDDCLogging.warning('Retry Connecting HHase.')
         self._reconnect()
Exemplo n.º 20
0
def read_thrift(file_obj, ttype):
    """Read a thrift structure from the given fo."""
    from thrift.transport.TTransport import TFileObjectTransport, TBufferedTransport
    starting_pos = file_obj.tell()

    # set up the protocol chain
    ft = TFileObjectTransport(file_obj)
    bufsize = 2 ** 16
    # for accelerated reading ensure that we wrap this so that the CReadable transport can be used.
    bt = TBufferedTransport(ft, bufsize)
    pin = TCompactProtocol(bt)

    # read out type
    obj = ttype()
    obj.read(pin)

    # The read will actually overshoot due to the buffering that thrift does. Seek backwards to the correct spot,.
    buffer_pos = bt.cstringio_buf.tell()
    ending_pos = file_obj.tell()
    blocks = ((ending_pos - starting_pos) // bufsize) - 1
    if blocks < 0:
        blocks = 0
    file_obj.seek(starting_pos + blocks * bufsize + buffer_pos)
    return obj
Exemplo n.º 21
0
    async def set_details_to_cache(self, obj_left, prefix):
        try:
            redis = await self.connect(write=True)

            pairs = []
            keys = []
            types = obj_left.typeList

            for typ in types:
                version = self.get_di_version(typ)
                key_prefix = f'{prefix}:{typ}:{version}'
                items = self.di_getlist(obj_left, typ)

                for it in items:
                    key = f'{key_prefix}:{self.di_id(typ, it)}'
                    mval = TMemoryBuffer()
                    cval = TCompactProtocol(mval)
                    it.write(cval)
                    pairs.extend((key, lz4.frame.compress(mval.getvalue())))
                    keys.append(key)

            # 一次性向Redis中存储多个数据
            if len(pairs) > 0:
                tr = redis.multi_exec()
                tr.mset(*pairs)

                for key in keys:
                    tr.expire(key, DI_TTL)

                await tr.execute()
                logger.debug(
                    f'[REDIS] Set {len(items)} DIResponse objs of type:{typ} to redis'
                )

        except Exception as e:
            log.print_excp(e)
Exemplo n.º 22
0
from thrift import Thrift
from thrift.protocol.TCompactProtocol import TCompactProtocol

from thrift.transport import TSocket, TTransport

from py.thrift.generated import PersonService, ttypes

try:
    tSocket = TSocket.TSocket("localhost", 8899)
    tSocket.setTimeout(600)
    transport = TTransport.TFramedTransport(tSocket)
    protocol = TCompactProtocol(transport)
    client = PersonService.Client(protocol)
    transport.open()
    person = client.getPersonByUsername("张三")

    print(person.username)
    print(person.age)
    print(person.married)

    print('-------------------------')

    newPerson = ttypes.Person()
    newPerson.username = "******"
    newPerson.age = 30
    newPerson.married = True

    client.savePerson(newPerson)
    transport.close()

except Exception as e:
Exemplo n.º 23
0
 def openTransport(self, endPoint):
     transport = THttpClient(self.lineServer + endPoint)
     transport.setCustomHeaders(self.thisHeaders)
     protocol = TCompactProtocol(transport)
     return TalkService.Client(protocol)
Exemplo n.º 24
0
    def __init__(self, my_app, my_token=None):
        self.lineServer = "https://ga2.line.naver.jp"
        self.lineOBS = "https://obs-sg.line-apps.com"
        self.boteaterApi = "https://api.boteater.us"
        self.liffServer = "https://api.line.me/message/v3/share"
        self.stickerLink = "https://stickershop.line-scdn.net/stickershop/v1/sticker/{}/iPhone/[email protected]"
        self.stickerLinkAnimation = "https://stickershop.line-scdn.net/stickershop/v1/sticker/{}/iPhone/[email protected]"
        self.dataHeaders = {
            "android_lite": {
                "User-Agent": "LLA/2.11.1 samsung 5.1.1",
                "X-Line-Application": "ANDROIDLITE\t2.11.1\tAndroid OS\t5.1.1",
                "x-lal": "en_ID",
                "X-Line-Carrier": "51010,1-0"
            },
            "android": {
                "User-Agent": "Line/10.1.1",
                "X-Line-Application": "ANDROID\t10.1.1\tAndroid OS\t5.1.1",
                "x-lal": "en_ID",
                "X-Line-Carrier": "51010,1-0"
            },
            "ios_ipad": {
                "User-Agent": "Line/10.1.1",
                "X-Line-Application": "IOSIPAD\t10.1.1\tiPhone 8\t11.2.5",
                "x-lal": "en_ID",
                "X-Line-Carrier": "51010,1-0"
            },
            "ios": {
                "User-Agent": "Line/10.1.1",
                "X-Line-Application": "IOS\t10.1.1\tiPhone 8\t11.2.5",
                "x-lal": "en_ID",
                "X-Line-Carrier": "51010,1-0"
            },
            "chrome": {
                "User-Agent":
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36",
                "X-Line-Application": "CHROMEOS\t2.3.2\tChrome OS\t1",
                "x-lal": "en_ID",
                "X-Line-Carrier": "51010,1-0"
            },
            "desktopwin": {
                "User-Agent": "Line/5.12.3",
                "X-Line-Application": "DESKTOPWIN\t5.21.3\tWindows\t10",
                "x-lal": "en_ID",
                "X-Line-Carrier": "51010,1-0"
            },
            "desktopmac": {
                "User-Agent": "Line/5.12.3",
                "X-Line-Application": "DESKTOPMAC\t5.21.3\tMAC\t10.15",
                "x-lal": "en_ID",
                "X-Line-Carrier": "51010,1-0"
            }
        }
        if my_app in self.dataHeaders:
            self.headers = self.dataHeaders[my_app]
            if my_token != None:
                self.headers["X-Line-Access"] = my_token
            else:
                self.headers["X-Line-Access"] = self.qrLogin(self.headers)
        else:
            raise Exception('APP not found!!!')

        ### CONNECT TO POOL ###
        transport = THttpClient(self.lineServer + '/P4')
        transport.setCustomHeaders(self.headers)
        transport.open()
        protocol = TCompactProtocol(transport)
        self.pool = OperationService.Client(protocol)

        ### CONNECT TO TALK ###
        transport = THttpClient(self.lineServer + '/api/v4/TalkService.do')
        transport.setCustomHeaders(self.headers)
        transport.open()
        protocol = TCompactProtocol(transport)
        self.talk = TalkService.Client(protocol)

        ### CONNECT TO CHANNEL ###
        transport = THttpClient(self.lineServer + '/CH4')
        transport.setCustomHeaders(self.headers)
        transport.open()
        protocol = TCompactProtocol(transport)
        self.channel = ChannelService.Client(protocol)

        ### CONNECT TO CALL ###
        transport = THttpClient(self.lineServer + '/V4')
        transport.setCustomHeaders(self.headers)
        transport.open()
        protocol = TCompactProtocol(transport)
        self.call = CallService.Client(protocol)

        ### CONNECT TO SHOP ###
        transport = THttpClient(self.lineServer + '/TSHOP4')
        transport.setCustomHeaders(self.headers)
        transport.open()
        protocol = TCompactProtocol(transport)
        self.shop = ShopService.Client(protocol)

        ### CONNECT TO LIFF ###
        transport = THttpClient(self.lineServer + '/LIFF1')
        transport.setCustomHeaders(self.headers)
        transport.open()
        protocol = TCompactProtocol(transport)
        self.liff = LiffService.Client(protocol)

        self.profile = self.getProfile()
        self.lastOP = self.getLastOpRevision()
        self.liffPermision()
        self.tokenOBS = self.acquireEncryptedAccessToken()
        print("[ Login ] Display Name: " + self.profile.displayName)
        print("[ Login ] Auth Token: " + self.headers["X-Line-Access"])

        ### TIMELINE HEADERS ###
        self.tl_headers = copy.deepcopy(self.headers)
        self.tl_headers["X-Line-ChannelToken"] = self.issueChannelToken(
            '1341209950').channelAccessToken
        self.tl_headers["X-Line-Mid"] = self.profile.mid
        self.tl_headers["X-Line-AcceptLanguage"] = 'en'
        self.tl_headers[
            "X-Requested-With"] = 'jp.naver.line.android.LineApplication'
        self.tl_headers["Content-Type"] = 'application/json'
Exemplo n.º 25
0
 def get_protocol(host, endpoint, headers={}):
     transport = THttpClient(host + endpoint)
     transport.setCustomHeaders(headers)
     protocol = TCompactProtocol(transport)
     return protocol
Exemplo n.º 26
0
    def __init__(self, my_app, my_token=None):
        self.lineServer = "https://ga2.line.naver.jp"
        self.lineOBS = "https://obs-sg.line-apps.com"
        self.boteaterApi = "https://api.boteater.us"
        self.liffServer = "https://api.line.me/message/v3/share"
        self.stickerLink = "https://stickershop.line-scdn.net/stickershop/v1/sticker/{}/iPhone/[email protected]"
        self.stickerLinkAnimation = "https://stickershop.line-scdn.net/stickershop/v1/sticker/{}/iPhone/[email protected]"
        self.dataHeaders = self.readJson("headers.json")
        if my_app in self.dataHeaders:
            self.headers = self.dataHeaders[my_app]
            if my_token != None:
                self.headers["X-Line-Access"] = my_token
            else:
                del self.headers["X-Line-Access"]
                self.headers["X-Line-Access"] = self.qrLogin(self.headers)
                #self.headers["X-Line-Access"] = self.qrLoginRotate("ios_ipad")
        else:
            raise Exception('APP not found!!!')

        ### CONNECT TO POOL ###
        transport = THttpClient(self.lineServer + '/P4')
        transport.setCustomHeaders(self.headers)
        transport.open()
        protocol = TCompactProtocol(transport)
        self.pool = BoteaterService.Client(protocol)
        
        ### CONNECT TO TALK ###
        transport = THttpClient(self.lineServer + '/api/v4/TalkService.do')
        transport.setCustomHeaders(self.headers)
        transport.open()
        protocol = TCompactProtocol(transport)
        self.talk = BoteaterService.Client(protocol)

        ### CONNECT TO CHANNEL ###
        transport = THttpClient(self.lineServer + '/CH4')
        transport.setCustomHeaders(self.headers)
        transport.open()
        protocol = TCompactProtocol(transport)
        self.channel = BoteaterService.Client(protocol)

        ### CONNECT TO CALL ###
        transport = THttpClient(self.lineServer + '/V4')
        transport.setCustomHeaders(self.headers)
        transport.open()
        protocol = TCompactProtocol(transport)
        self.call = BoteaterService.Client(protocol)

        ### CONNECT TO SHOP ###
        transport = THttpClient(self.lineServer + '/TSHOP4')
        transport.setCustomHeaders(self.headers)
        transport.open()
        protocol = TCompactProtocol(transport)
        self.shop = BoteaterService.Client(protocol)

        ### CONNECT TO LIFF ###
        transport = THttpClient(self.lineServer + '/LIFF1')
        transport.setCustomHeaders(self.headers)
        transport.open()
        protocol = TCompactProtocol(transport)
        self.liff = BoteaterService.Client(protocol)

        self.profile = self.getProfile()
        self.lastOP = self.getLastOpRevision()
        self.liffPermision()
        self.tokenOBS = self.acquireEncryptedAccessToken()
        print("[ Login ] Display Name: " + self.profile.displayName)

        ### TIMELINE HEADERS ###
        self.tl_headers= copy.deepcopy(self.headers)
        self.tl_headers["X-Line-ChannelToken"] = self.issueChannelToken('1341209950').channelAccessToken
        self.tl_headers["X-Line-Mid"] = self.profile.mid
        self.tl_headers["X-Line-AcceptLanguage"] = 'en'
        self.tl_headers["X-Requested-With"] = 'jp.naver.line.android.LineApplication'
        self.tl_headers["Content-Type"] = 'application/json'
Exemplo n.º 27
0
    def __init__(self, my_app, my_token=None, server=None):
        if server == "japan":
            self.line_server = "https://ga2.line.naver.jp"  #Japan
        elif server == "sg":
            self.line_server = "https://ga2s.line.naver.jp"  #Indo/Singapure
        else:
            self.line_server = "https://gd2.line.naver.jp"  #Japan
        self.line_obs = "https://obs-sg.line-apps.com"
        self.boteater_api = "https://api.boteater.us"
        self.liff_url = "https://api.line.me/message/v3/share"
        self.sticker_link = "https://stickershop.line-scdn.net/stickershop/v1/sticker/{}/iPhone/[email protected]"
        self.sticker_link_animation = "https://stickershop.line-scdn.net/stickershop/v1/sticker/{}/iPhone/[email protected]"
        self.data_headers = self.read_json("headers.json")
        if my_app in self.data_headers:
            self.headers = self.data_headers[my_app]
            if my_token != None:
                self.headers["X-Line-Access"] = my_token
            else:
                del self.headers["X-Line-Access"]
                self.headers["X-Line-Access"] = self.qr_login(self.headers)
        else:
            raise Exception('APP not found!!!')

        ### CONNECT TO POOL ###
        transport = THttpClient(self.line_server + '/P4')
        transport.setCustomHeaders(self.headers)
        transport.open()
        protocol = TCompactProtocol(transport)
        self.pool = BoteaterService.Client(protocol)

        ### CONNECT TO TALK ###
        transport = THttpClient(self.line_server + '/api/v4/TalkService.do')
        transport.setCustomHeaders(self.headers)
        transport.open()
        protocol = TCompactProtocol(transport)
        self.talk = BoteaterService.Client(protocol)

        ### CONNECT TO CHANNEL ###
        transport = THttpClient(self.line_server + '/CH4')
        transport.setCustomHeaders(self.headers)
        transport.open()
        protocol = TCompactProtocol(transport)
        self.channel = BoteaterService.Client(protocol)

        ### CONNECT TO CALL ###
        transport = THttpClient(self.line_server + '/V4')
        transport.setCustomHeaders(self.headers)
        transport.open()
        protocol = TCompactProtocol(transport)
        self.call = BoteaterService.Client(protocol)

        ### CONNECT TO SHOP ###
        transport = THttpClient(self.line_server + '/TSHOP4')
        transport.setCustomHeaders(self.headers)
        transport.open()
        protocol = TCompactProtocol(transport)
        self.shop = BoteaterService.Client(protocol)

        ### CONNECT TO LIFF ###
        transport = THttpClient(self.line_server + '/LIFF1')
        transport.setCustomHeaders(self.headers)
        transport.open()
        protocol = TCompactProtocol(transport)
        self.liff = BoteaterService.Client(protocol)

        self.profile_data = self.talk.getProfile()
        self.my_mid = self.profile_data.mid
        self.last_op = self.pool.getLastOpRevision()
        self.issue_liff_view()
        self.tl_channel = self.issue_channel_token(
            '1341209950').channelAccessToken
        self.tl_headers = copy.deepcopy(self.headers)
        self.tl_headers["X-Line-ChannelToken"] = self.tl_channel
        self.tl_headers["X-Line-Mid"] = self.my_mid
        self.tl_headers["X-Line-AcceptLanguage"] = 'en'
        self.tl_headers[
            "X-Requested-With"] = 'jp.naver.line.android.LineApplication'
        self.tl_headers["Content-Type"] = 'application/json'

        self.my_OBStoken = self.gen_obs_token()
        print("[ Login ] Display Name: " + self.profile_data.displayName)
        self.temp_data = self.read_json("tmp.json")