def _logClsend(self, senderId, dataStr): msgStream = StringStream() simbase.air.describeMessage(msgStream, '', dataStr) readableStr = msgStream.getData() sstream = StringStream() PyDatagram(dataStr).dumpHex(sstream) hexDump = sstream.getData() self.clsendNotify.info( '%s [%s]: %s%s' % (self.doId, self._clsendCounter, readableStr, hexDump))
def _logClsend(self, senderId, dataStr): msgStream = StringStream() simbase.air.describeMessage(msgStream, '', dataStr) readableStr = msgStream.getData() sstream = StringStream() PyDatagram(dataStr).dumpHex(sstream) hexDump = sstream.getData() self.clsendNotify.info('%s [%s]: %s%s' % (self.doId, self._clsendCounter, readableStr, hexDump))
def create_miraidata(self): # Create a temporary _miraidata.py and throw it on the path somewhere... # First, we need the minified DC file contents: from panda3d.core import StringStream dcStream = StringStream() self.dcf.write(dcStream, True) dcData = dcStream.getData() # Next we need config files... configData = [] with open(self.config_file) as f: fd = f.read() fd = fd.replace('SERVER_VERSION_HERE', self.version) fd = fd.replace('LANGUAGE_HERE', self.language) configData.append(fd) md = 'CONFIG = %r\nDC = %r\n' % (configData, dcData) # Now we use tempfile to dump md: td = tempfile.mkdtemp() with open(os.path.join(td, '_miraidata.py'), 'w') as f: f.write(md) self.mf.path.append(td) atexit.register(shutil.rmtree, td)
def __test_loader(self, filename, use_loader_class): store = DNAStorage() if use_loader_class: np = self.loader.loadDNAFile(store, filename) expected_repr = '''PandaNode dna PandaNode test PandaNode 1000 PandaNode subgroup ModelNode prop_test T:(pos -12 5 7 hpr 180 15 0) S:(ColorScaleAttrib) PandaNode tb3:test_block [DNACode] PandaNode sb3:test_block''' else: np = NodePath(loadDNAFile(store, filename)) expected_repr = '''PandaNode test PandaNode 1000 PandaNode subgroup ModelNode prop_test T:(pos -12 5 7 hpr 180 15 0) S:(ColorScaleAttrib) PandaNode tb3:test_block [DNACode] PandaNode sb3:test_block''' self.check_store(store) ss = StringStream() np.ls(ss) self.assertEqual(ss.getData().strip(), expected_repr)
def getScreenshot(p3dApp): p3dApp.taskMgr.step() p3dApp.taskMgr.step() pnmss = PNMImage() p3dApp.win.getScreenshot(pnmss) resulting_ss = StringStream() pnmss.write(resulting_ss, "screenshot.png") screenshot_buffer = resulting_ss.getData() pilimage = Image.open(StringIO(screenshot_buffer)) pilimage.load() #pnmimage will sometimes output as palette mode for 8-bit png so convert pilimage = pilimage.convert('RGBA') return pilimage
def takePictureRaw(self): img = PNMImage() tex = self.takePicture() tex.store(img) ss = StringStream() img.write(ss, 'jpg') if 1: # Test it img2 = PNMImage() img2.read(ss) img2.write(Filename("test_viewfinder.jpg")) return ss.getData()
def test_loader(self): store = DNAStorage() np = self.loader.loadDNAFile(store, Filename('test.pdna')) self.check_store(store) expected_repr = '''PandaNode dna PandaNode root PandaNode test PandaNode 1000 PandaNode subgroup ModelNode prop_test T:(pos -12 5 7 hpr 180 15 0) S:(ColorScaleAttrib) PandaNode tb3:test_block [DNACode] PandaNode sb3:test_block''' ss = StringStream() np.ls(ss) self.assertEqual(ss.getData().strip(), expected_repr)
class ToontownRPCMethod: def __init__(self, client, name): self.client = client self.name = name self.notify = directNotify.newCategory('ToontownRPCMethod[%s]' % name) self.channel = None self.stream = StringStream() self.callback = None self.errback = None self.extraArgs = None def __call__(self, *args, **kwargs): self.callback = kwargs.pop('_callback', None) self.errback = kwargs.pop('_errback', None) self.extraArgs = kwargs.pop('_extraArgs', []) if (len(args) > 0) and (len(kwargs) > 0): raise ProtocolError('Cannot use both positional and keyword arguments.') token = self.generateToken(700) if kwargs: kwargs['token'] = token self.send(kwargs) else: self.send((token,) + args) @staticmethod def generateToken(accessLevel): data = json.dumps({'timestamp': int(time.mktime(time.gmtime())), 'accesslevel': accessLevel}) iv = os.urandom(AES.block_size) webRpcSecret = config.GetString('web-rpc-secret', '6163636f756e7473') cipher = AES.new(webRpcSecret, mode=AES.MODE_CBC, IV=iv) data += '\x00' * (16 - (len(data) % AES.block_size)) token = cipher.encrypt(data) return base64.b64encode(iv + token) def send(self, params): if not self.client.url.hasServer(): if self.errback is not None: self.errback(*self.extraArgs) return self.channel = self.client.http.makeChannel(False) self.channel.sendExtraHeader('Accept', 'application/json') self.channel.sendExtraHeader('Content-Type', 'application/json') self.channel.sendExtraHeader('User-Agent', 'RPCClient (Toontown Infinite; src)') data = json.dumps({'jsonrpc': '2.0', 'method': self.name, 'params': params, 'id': id(self)}) ds = DocumentSpec(self.client.url) self.channel.beginPostForm(ds, data) self.channel.downloadToStream(self.stream) self.client.channels[self.channel] = self def finish(self): if not self.channel.isValid(): self.notify.warning('Failed to make HTTP request.') if self.errback is not None: self.errback(*self.extraArgs) return if not self.channel.isDownloadComplete(): self.notify.warning('Received an incomplete response.') if self.errback is not None: self.errback(*self.extraArgs) return data = self.stream.getData() try: response = json.loads(data) except ValueError: self.notify.warning('Received an invalid response.') if self.errback is not None: self.errback(*self.extraArgs) return error = response.get('error') if error is not None: self.notify.warning('Resulted in error: ' + repr(error)) if self.errback is not None: self.errback(*self.extraArgs) return if self.callback: self.callback(response['result'], *self.extraArgs)
class Interpreter(InteractiveConsole): def __init__(self, *args): InteractiveConsole.__init__(self, *args) self.stream = StringStream() self.stringio = StringIO() self.input_string = "" self.output_string = "" self.more = 0 self.prompt = ">>> " def runline(self, line): self.output_string = "" self.input_string = self.prompt + line + "\n" self.write(self.input_string) if self.push(line): self.prompt = "... " else: self.prompt = ">>> " def showsyntaxerror(self, filename=None): type, value, tb = sys.exc_info() sys.last_type = type sys.last_value = value sys.last_traceback = tb if filename and type is SyntaxError: # Work hard to stuff the correct filename in the exception try: msg, (dummy_filename, lineno, offset, line) = value.args except ValueError: # Not the format we expect; leave it alone pass else: # Stuff in the right filename value = SyntaxError(msg, (filename, lineno, offset, line)) sys.last_value = value lines = traceback.format_exception_only(type, value) self.write(''.join(lines)) def runcode(self, code): # Empty buffers self.stringio.truncate(0) self.stringio.seek(0) self.stream.clearData() try: # Swap buffers notify = Notify.ptr() old_notify = notify.get_ostream_ptr() notify.set_ostream_ptr(self.stream, False) with redirect_stdout(self.stringio): # Exec, writing output to buffers exec(code, self.locals) # Write buffers to output string. io_data = self.stringio.getvalue() stream_data = self.stream.getData().decode("utf-8") self.write(io_data + stream_data) # Restore buffers notify.set_ostream_ptr(old_notify, False) except: self.showtraceback() def showtraceback(self): sys.last_type, sys.last_value, last_tb = ei = sys.exc_info() sys.last_traceback = last_tb try: # Normally, if someone has set sys.excepthook, we let that take # precedence over self.write; but cefpython sets sys.excepthook # making this behavior undesirable lines = traceback.format_exception(ei[0], ei[1], last_tb.tb_next) self.write(''.join(lines)) finally: last_tb = ei = None def write(self, output_string): self.output_string += output_string
class ToontownRPCMethod: def __init__(self, client, name): self.client = client self.name = name self.notify = directNotify.newCategory('ToontownRPCMethod[%s]' % name) self.channel = None self.stream = StringStream() self.callback = None self.errback = None self.extraArgs = None def __call__(self, *args, **kwargs): self.callback = kwargs.pop('_callback', None) self.errback = kwargs.pop('_errback', None) self.extraArgs = kwargs.pop('_extraArgs', []) if (len(args) > 0) and (len(kwargs) > 0): raise ProtocolError( 'Cannot use both positional and keyword arguments.') token = self.generateToken(700) if kwargs: kwargs['token'] = token self.send(kwargs) else: self.send((token, ) + args) @staticmethod def generateToken(accessLevel): data = json.dumps({ 'timestamp': int(time.mktime(time.gmtime())), 'accesslevel': accessLevel }) iv = os.urandom(AES.block_size) webRpcSecret = config.GetString('web-rpc-secret', '6163636f756e7473') cipher = AES.new(webRpcSecret, mode=AES.MODE_CBC, IV=iv) data += '\x00' * (16 - (len(data) % AES.block_size)) token = cipher.encrypt(data) return base64.b64encode(iv + token) def send(self, params): if not self.client.url.hasServer(): if self.errback is not None: self.errback(*self.extraArgs) return self.channel = self.client.http.makeChannel(False) self.channel.sendExtraHeader('Accept', 'application/json') self.channel.sendExtraHeader('Content-Type', 'application/json') self.channel.sendExtraHeader('User-Agent', 'RPCClient (Toontown Infinite; src)') data = json.dumps({ 'jsonrpc': '2.0', 'method': self.name, 'params': params, 'id': id(self) }) ds = DocumentSpec(self.client.url) self.channel.beginPostForm(ds, data) self.channel.downloadToStream(self.stream) self.client.channels[self.channel] = self def finish(self): if not self.channel.isValid(): self.notify.warning('Failed to make HTTP request.') if self.errback is not None: self.errback(*self.extraArgs) return if not self.channel.isDownloadComplete(): self.notify.warning('Received an incomplete response.') if self.errback is not None: self.errback(*self.extraArgs) return data = self.stream.getData() try: response = json.loads(data) except ValueError: self.notify.warning('Received an invalid response.') if self.errback is not None: self.errback(*self.extraArgs) return error = response.get('error') if error is not None: self.notify.warning('Resulted in error: ' + repr(error)) if self.errback is not None: self.errback(*self.extraArgs) return if self.callback: self.callback(response['result'], *self.extraArgs)