Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
_write method from msrplib session.py to send a file in chunks.
def _write_file(self):
outgoing_file = self.outgoing_files.items[0][0]
number_of_chunks = 0
while outgoing_file.position < outgoing_file.size:
try:
piece = outgoing_file.fileobj.read(self.FILE_PIECE_SIZE)
except Exception:
self.logger.err('error while reading file %r\n%s' % (outgoing_file, traceback.format_exc()))
return
self.logger.debug('_write_file: read %s bytes from %s' % (len(piece), outgoing_file))
number_of_chunks +=1
chunk = self.msrp.make_chunk(data=piece, start=outgoing_file.position+1, end=(outgoing_file.position+len(piece)), length=outgoing_file.size, message_id=outgoing_file.message_id)
chunk.headers.update(outgoing_file.headers)
# Need to rewrite the Byte-Range header
chunk.add_header(protocol.ByteRangeHeader((outgoing_file.position+1, (outgoing_file.position+len(piece)), outgoing_file.size)))
id = chunk.transaction_id
assert id not in self.expected_responses, "MSRP transaction %r is already in progress" % id
cb_and_timer = [outgoing_file.on_transaction_response, None]
self.expected_responses[id] = cb_and_timer
try:
trailer = chunk.encode_start()
self.msrp.write(trailer)
self.logger.sent_new_chunk(trailer, self.msrp, chunk=chunk)
self.logger.debug('_write_file: wrote header %r' % chunk)
print('%s wrote header %r' % (number_of_chunks, chunk))
self.msrp.write(piece)
outgoing_file.position += len(piece)
if not piece or outgoing_file.position == outgoing_file.size:
contflag = '$'
if self.outgoing_files:
self.outgoing_files.wait()
else:
contflag = '+'
footer = chunk.encode_end(contflag)
self.msrp.write(footer)
self.logger.sent_chunk_end(footer, self.msrp, transaction_id=chunk.transaction_id)
self.logger.debug('_write_file: wrote chunk end %s' % contflag)
timeout_error = Response408Timeout if chunk.failure_report=='yes' else Response200OK
timer = api.get_hub().schedule_call_global(self.RESPONSE_TIMEOUT, self._response_timeout, id, timeout_error)
self.last_expected_response = time() + self.RESPONSE_TIMEOUT
cb_and_timer[1] = timer
except:
self.expected_responses.pop(id, None)
raise
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment