MCPcopy
hub / github.com/HelloZeroNet/ZeroNet / handleGetFile

Method handleGetFile

src/File/FileRequest.py:210–282  ·  view source on GitHub ↗
(self, params, streaming=False)

Source from the content-addressed store, hash-verified

208
209 # Send file content request
210 def handleGetFile(self, params, streaming=False):
211 site = self.sites.get(params["site"])
212 if not site or not site.isServing(): # Site unknown or not serving
213 self.response({"error": "Unknown site"})
214 self.connection.badAction(5)
215 return False
216 try:
217 file_path = site.storage.getPath(params["inner_path"])
218 if streaming:
219 file_obj = site.storage.open(params["inner_path"])
220 else:
221 file_obj = Msgpack.FilePart(file_path, "rb")
222
223 with file_obj as file:
224 file.seek(params["location"])
225 read_bytes = params.get("read_bytes", FILE_BUFF)
226 file_size = os.fstat(file.fileno()).st_size
227
228 if file_size > read_bytes: # Check if file is readable at current position (for big files)
229 if not self.isReadable(site, params["inner_path"], file, params["location"]):
230 raise RequestError("File not readable at position: %s" % params["location"])
231 else:
232 if params.get("file_size") and params["file_size"] != file_size:
233 self.connection.badAction(2)
234 raise RequestError("File size does not match: %sB != %sB" % (params["file_size"], file_size))
235
236 if not streaming:
237 file.read_bytes = read_bytes
238
239 if params["location"] > file_size:
240 self.connection.badAction(5)
241 raise RequestError("Bad file location")
242
243 if streaming:
244 back = {
245 "size": file_size,
246 "location": min(file.tell() + read_bytes, file_size),
247 "stream_bytes": min(read_bytes, file_size - params["location"])
248 }
249 self.response(back)
250 self.sendRawfile(file, read_bytes=read_bytes)
251 else:
252 back = {
253 "body": file,
254 "size": file_size,
255 "location": min(file.tell() + file.read_bytes, file_size)
256 }
257 self.response(back, streaming=True)
258
259 bytes_sent = min(read_bytes, file_size - params["location"]) # Number of bytes we going to send
260 site.settings["bytes_sent"] = site.settings.get("bytes_sent", 0) + bytes_sent
261 if config.debug_socket:
262 self.log.debug("File %s at position %s sent %s bytes" % (file_path, params["location"], bytes_sent))
263
264 # Add peer to site if not added before
265 connected_peer = site.addPeer(self.connection.ip, self.connection.port, source="request")
266 if connected_peer: # Just added
267 connected_peer.connect(self.connection) # Assign current connection to peer

Callers 2

actionGetFileMethod · 0.95
actionStreamFileMethod · 0.95

Calls 14

responseMethod · 0.95
isReadableMethod · 0.95
sendRawfileMethod · 0.95
RequestErrorClass · 0.85
isServingMethod · 0.80
badActionMethod · 0.80
getPathMethod · 0.80
openMethod · 0.80
addPeerMethod · 0.80
errorMethod · 0.80
getMethod · 0.45
seekMethod · 0.45

Tested by

no test coverage detected