|
| 1 | +import os |
| 2 | + |
| 3 | +import click |
| 4 | + |
| 5 | +from ctfcli.core.api import API |
| 6 | +from ctfcli.core.config import Config |
| 7 | + |
| 8 | + |
| 9 | +class MediaCommand: |
| 10 | + def add(self, path): |
| 11 | + """Add local media file to config file and remote instance""" |
| 12 | + config = Config() |
| 13 | + if config.config.has_section("media") is False: |
| 14 | + config.config.add_section("media") |
| 15 | + |
| 16 | + api = API() |
| 17 | + |
| 18 | + new_file = ("file", open(path, mode="rb")) |
| 19 | + filename = os.path.basename(path) |
| 20 | + location = f"media/{filename}" |
| 21 | + file_payload = { |
| 22 | + "type": "page", |
| 23 | + "location": location, |
| 24 | + } |
| 25 | + |
| 26 | + # Specifically use data= here to send multipart/form-data |
| 27 | + r = api.post("/api/v1/files", files=[new_file], data=file_payload) |
| 28 | + r.raise_for_status() |
| 29 | + resp = r.json() |
| 30 | + server_location = resp["data"][0]["location"] |
| 31 | + |
| 32 | + # Close the file handle |
| 33 | + new_file[1].close() |
| 34 | + |
| 35 | + config.config.set("media", location, f"/files/{server_location}") |
| 36 | + |
| 37 | + with open(config.config_path, "w+") as f: |
| 38 | + config.write(f) |
| 39 | + |
| 40 | + def rm(self, path): |
| 41 | + """Remove local media file from remote server and local config""" |
| 42 | + config = Config() |
| 43 | + api = API() |
| 44 | + |
| 45 | + local_location = config["media"][path] |
| 46 | + |
| 47 | + remote_files = api.get("/api/v1/files?type=page").json()["data"] |
| 48 | + for remote_file in remote_files: |
| 49 | + if f"/files/{remote_file['location']}" == local_location: |
| 50 | + # Delete file from server |
| 51 | + r = api.delete(f"/api/v1/files/{remote_file['id']}") |
| 52 | + r.raise_for_status() |
| 53 | + |
| 54 | + # Update local config file |
| 55 | + del config["media"][path] |
| 56 | + with open(config.config_path, "w+") as f: |
| 57 | + config.write(f) |
| 58 | + |
| 59 | + def url(self, path): |
| 60 | + """Get server URL for a file key""" |
| 61 | + config = Config() |
| 62 | + api = API() |
| 63 | + |
| 64 | + if config.config.has_section("media") is False: |
| 65 | + config.config.add_section("media") |
| 66 | + |
| 67 | + try: |
| 68 | + location = config["media"][path] |
| 69 | + except KeyError: |
| 70 | + click.secho(f"Could not locate local media '{path}'", fg="red") |
| 71 | + return 1 |
| 72 | + |
| 73 | + remote_files = api.get("/api/v1/files?type=page").json()["data"] |
| 74 | + for remote_file in remote_files: |
| 75 | + if f"/files/{remote_file['location']}" == location: |
| 76 | + base_url = config["config"]["url"] |
| 77 | + base_url = base_url.rstrip("/") |
| 78 | + return f"{base_url}{location}" |
| 79 | + click.secho(f"Could not locate remote media '{path}'", fg="red") |
| 80 | + return 1 |
0 commit comments