|
| 1 | +import os |
| 2 | + |
| 3 | +from ctfcli.core.api import API |
| 4 | +from ctfcli.core.config import Config |
| 5 | + |
| 6 | + |
| 7 | +class MediaCommand: |
| 8 | + def add(self, path): |
| 9 | + """Add local media file to config file and remote instance""" |
| 10 | + config = Config() |
| 11 | + if config.config.has_section("media") is False: |
| 12 | + config.config.add_section("media") |
| 13 | + |
| 14 | + api = API() |
| 15 | + |
| 16 | + new_file = ("file", open(path, mode="rb")) |
| 17 | + filename = os.path.basename(path) |
| 18 | + location = f"media/{filename}" |
| 19 | + file_payload = { |
| 20 | + "type": "page", |
| 21 | + "location": location, |
| 22 | + } |
| 23 | + |
| 24 | + # Specifically use data= here to send multipart/form-data |
| 25 | + r = api.post("/api/v1/files", files=[new_file], data=file_payload) |
| 26 | + r.raise_for_status() |
| 27 | + resp = r.json() |
| 28 | + server_location = resp["data"][0]["location"] |
| 29 | + |
| 30 | + # Close the file handle |
| 31 | + new_file[1].close() |
| 32 | + |
| 33 | + config.config.set("media", location, f"/files/{server_location}") |
| 34 | + |
| 35 | + with open(config.config_path, "w+") as f: |
| 36 | + config.write(f) |
| 37 | + |
| 38 | + def rm(self, path): |
| 39 | + """Remove local media file from remote server and local config""" |
| 40 | + config = Config() |
| 41 | + api = API() |
| 42 | + |
| 43 | + local_location = config["media"][path] |
| 44 | + |
| 45 | + remote_files = api.get("/api/v1/files?type=page").json()["data"] |
| 46 | + for remote_file in remote_files: |
| 47 | + if f"/files/{remote_file['location']}" == local_location: |
| 48 | + # Delete file from server |
| 49 | + r = api.delete(f"/api/v1/files/{remote_file['id']}") |
| 50 | + r.raise_for_status() |
| 51 | + |
| 52 | + # Update local config file |
| 53 | + del config["media"][path] |
| 54 | + with open(config.config_path, "w+") as f: |
| 55 | + config.write(f) |
0 commit comments