-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshellmfs.py
More file actions
164 lines (135 loc) · 5.12 KB
/
Copy pathshellmfs.py
File metadata and controls
164 lines (135 loc) · 5.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
import os
import argparse
import readline
import glob
import getpass
from prettytable import PrettyTable
import humanize
import datetime
from libmfs import MatrixFs
def get_completions(text, state, options):
opts = list(options) if not isinstance(options, (list, tuple)) else options
matches = [x for x in opts if x.startswith(text)]
return matches[state] if state < len(matches) else None
def print_help():
print("Available commands:")
print(" put [filename] Upload a local file")
print(" get [filename] [dest] Download a file to dest or current dir")
print(" del [filename] Delete a remote file")
print(" ls List remote files")
print(" help Show this help")
print(" exit Exit the shell")
def print_error(e):
print(f"Error: {e}")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--server_url", help="Matrix homeserver URL")
parser.add_argument("--username", help="Username")
parser.add_argument("--password", help="Password")
parser.add_argument("--room_name", help="Room name")
parser.add_argument("--encryption_key", default="", help="Encryption key")
parser.add_argument("--max_file_size", type=int, default=1 * 1024 * 1024)
parser.add_argument("--variance", type=float, default=0.10, help="Chunk size variance (e.g. 0.10 for ±10%)")
args = parser.parse_args()
if not args.server_url:
args.server_url = input("Server URL: ")
if not args.username:
args.username = input("Username: ")
if not args.password:
args.password = getpass.getpass("Password: ")
if not args.room_name:
args.room_name = input("Room name: ")
fs = MatrixFs(
server_url=args.server_url,
username=args.username,
password=args.password,
room_name=args.room_name,
encryption_key=args.encryption_key,
max_file_size=args.max_file_size,
variance=args.variance,
)
def completer(text, state):
buffer = readline.get_line_buffer()
line = buffer.strip().split()
if not line:
return None
cmd = line[0]
if cmd == "put":
return get_completions(text, state, glob.glob(text + "*"))
elif cmd in {"get", "del", "delete"}:
try:
return get_completions(text, state, list(fs.list_files().keys()))
except Exception:
return None
else:
return get_completions(text, state, ["put", "get", "del", "ls", "exit", "help"])
readline.set_completer(completer)
readline.parse_and_bind("tab: complete")
print_help()
while True:
try:
cmd_line = input(f"MatrixFS@{args.username}:{args.server_url}> ").strip()
except (EOFError, KeyboardInterrupt):
print("\nExiting.")
break
if not cmd_line:
continue
parts = cmd_line.split()
command = parts[0]
if command == "put" and len(parts) == 2:
print("Uploading...")
try:
fs.send_file(parts[1])
except Exception as e:
print_error(e)
elif command == "get" and len(parts) >= 2:
filename = parts[1]
dest = parts[2] if len(parts) == 3 else os.path.join(".", filename)
try:
print("Downloading...")
content = fs.find_file(filename)
with open(dest, "wb") as f:
f.write(content)
print(f"Downloaded to {dest}")
except Exception as e:
print_error(e)
elif command in {"del", "delete"} and len(parts) == 2:
try:
fs.delete(parts[1])
print(f"{parts[1]} deleted.")
except Exception as e:
print_error(e)
elif command == "ls":
try:
files = fs.list_files()
table = PrettyTable()
table.field_names = [
"Filename",
"Size",
"# Chunks",
"Date Added",
"ID",
]
table.border = True
table.header = True
for col in table.field_names:
table.align[col] = "l"
for filename, info in files.items():
size = humanize.naturalsize(info.get("size", "N/A"), binary=False)
chunks = info.get("chunks", "N/A")
date = humanize.naturaltime(
datetime.datetime.fromtimestamp(int(info.get("date_added", 0)))
)
media_id = info.get("media_id", "N/A")
table.add_row([filename, size, chunks, date, media_id])
print(table)
except Exception as e:
print_error(e)
elif command in {"exit", "quit"}:
break
elif command == "help":
print_help()
else:
print(f"Unknown command: {command}")
if __name__ == "__main__":
main()