-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
312 lines (269 loc) · 10.2 KB
/
main.py
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
import os
import time
import platform
import psutil
import json
import pyperclip
import random
import string
import threading
import time
import subprocess
import pyttsx3
from datetime import datetime
from rich.console import Console
from rich.prompt import Prompt
from rich.text import Text
# dependencies
from weather import Weather
from task import Task
from linux_commands import Commands
from git_commands import Git
from terminals import Terminal
from song import Song
from equations import Equations
import config
console = Console()
USER_FILE = "users.json"
lock = threading.Lock()
scheduled_jobs = {}
commands = {}
stop_scheduler = False
prompt_flag = True
# Load users
def load_users():
with lock:
if os.path.exists(USER_FILE):
with open(USER_FILE, "r") as file:
return json.load(file)
return {}
def save_users(users):
with lock:
with open(USER_FILE, "w") as file:
json.dump(users, file, indent=4)
def clipboard_copy(text):
with lock:
pyperclip.copy(text)
console.print("Text copied to clipboard!", style="bold green")
def clipboard_paste():
with lock:
console.print(f"Clipboard Content: {pyperclip.paste()}", style="bold yellow")
# User Authentication
def register_user():
users = load_users()
username = Prompt.ask("Enter new username")
role = Prompt.ask("Assign role (admin/user)", choices=["admin", "user"], default="user")
if username in users:
console.print("User already exists!", style="bold red")
return register_user()
password = Prompt.ask("Enter password", password=True)
users[username] = {"password": password, "role": role}
save_users(users)
console.print("User registered successfully!", style="bold green")
return username, role
def login_user():
users = load_users()
username = Prompt.ask("Enter username")
password = Prompt.ask("Enter password", password=True)
if username in users and users[username]["password"] == password:
console.print("Login successful!", style="bold green")
return username, users[username]["role"]
else:
console.print("Invalid credentials!", style="bold red")
return login_user()
# Synchronization
def list_processes(*args):
for proc in psutil.process_iter(['pid', 'name']):
console.print(f"{proc.info['pid']} - {proc.info['name']}")
def kill_process(args):
if not args:
console.print("Usage: kill <PID>", style="bold red")
return
try:
psutil.Process(int(args[0])).terminate()
console.print(f"Process {args[0]} terminated", style="bold red")
except Exception as e:
console.print(str(e), style="bold red")
def generate_password(*args):
length = Prompt.ask("Enter password length (default 12)", default="12")
try:
length = int(length)
except ValueError:
console.print("Invalid input. Using default length (12)", style="bold red")
length = 12
display_prompt(username)
return
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for _ in range(length))
console.print(f"Generated Password: {password}", style="bold green")
clipboard_copy(password)
# changing and displaying terminal
terminal = Terminal()
def display_prompt(username):
if terminal.get_prompt_flag():
hostname = platform.node()
cwd = os.getcwd().split(os.sep)
time_str = datetime.now().strftime("%H:%M")
mem = psutil.virtual_memory()
mem_percent = mem.percent
mem_total_gb = round(mem.total / (1024 ** 3))
mem_used_gb = round(mem.used / (1024 ** 3))
left_prompt = Text()
left_prompt.append("\n # ", style="black on white")
left_prompt.append(" shell ", style="white on blue")
left_prompt.append("", style="blue on black")
left_prompt.append("", style="black on blue")
left_prompt.append(f" MEM: {mem_percent}% ↑ {mem_used_gb}/{mem_total_gb}GB ", style="white on blue")
left_prompt.append("", style="blue on grey15")
left_prompt.append(" code ", style="white on grey15")
left_prompt.append("", style="grey15 on black")
left_prompt.append(f" {time_str} ", style="white on black")
left_prompt.append("", style="black")
for part in cwd:
if part:
left_prompt.append(" // ", style="white")
left_prompt.append("📁", style="white")
left_prompt.append(f" {part} ", style="white")
right_prompt = Text()
right_prompt.append("", style="black on medium_sea_green")
right_prompt.append(" ", style="black on medium_sea_green")
try:
branch = subprocess.check_output(
["git", "rev-parse", "--abbrev-ref", "HEAD"],
stderr=subprocess.DEVNULL
).decode("utf-8").strip()
except subprocess.CalledProcessError:
branch = "no-branch"
right_prompt.append(f" {branch} ≡ ⎔ ~1 ", style="black on medium_sea_green")
console.print(left_prompt + Text(" " * (console.width - len(left_prompt.plain) - len(right_prompt.plain))) + right_prompt)
else:
if config.current_terminal_layout == 1:
Terminal().terminal_1()
elif config.current_terminal_layout == 2:
Terminal().terminal_2()
elif config.current_terminal_layout == 3:
Terminal().terminal_3()
elif config.current_terminal_layout == 4:
Terminal().terminal_4()
elif config.current_terminal_layout == 5:
Terminal().terminal_5()
elif config.current_terminal_layout == 6:
Terminal().terminal_6()
elif config.current_terminal_layout == 7:
Terminal().terminal_7()
elif config.current_terminal_layout == 8:
Terminal().terminal_8()
console.print(terminal.get_prompt()) # Use prompt returned from Terminal
# clear console
def clear(*args):
os.system('cls' if os.name == 'nt' else 'clear')
def main():
console.clear()
console.print("="*70, style="bold blue")
console.print("Welcome to PyShell", style="bold yellow", end=" ")
console.print("{Python CLI by @ansh.mn.soni}", style="white")
console.print(f"System: {platform.system()} {platform.release()} ", style="bold cyan")
console.print("="*70, style="bold blue")
# Welcome message
engine = pyttsx3.init()
engine.say("Welcome to Ansh Soni's Terminal")
engine.runAndWait()
global username
username, role = register_user() if Prompt.ask("New user?", choices=["y", "n"]) == "y" else login_user()
# Objects
cmds = Commands()
task = Task()
weather = Weather()
terminl = Terminal()
git = Git()
eq = Equations()
commands = {
"rename": cmds.rename_item,
"move": cmds.move_file,
"copy": cmds.copy_file,
"processes": list_processes,
"kill": kill_process,
"network": cmds.network_info,
"copytext": clipboard_copy,
"paste": clipboard_paste,
"password": generate_password,
"calc": cmds.calculator,
"equation": eq.solve_equation,
# "diffequation": eq.solve_differential,
"math-help": cmds.math_help,
"weather": weather.get_weather,
"schedule": task.schedule_task,
"tasks": task.list_scheduled_tasks,
"unschedule": task.remove_scheduled_task,
"stop": task.stop_running_tasks,
"cls": clear,
"terminal": terminl.change_terminal,
"exit": lambda _: exit(),
# Git Commands (Using Git Class)
"git-status": git.git_status,
"git-branches": git.git_branches,
"git-create": git.git_create_branch,
"git-switch": git.git_switch_branch,
"git-push": git.git_push,
"git-pull": git.git_pull,
"git-merge": git.git_merge,
"git-delete": git.git_delete_branch,
"git-clone": git.git_clone,
"git-add": git.git_add,
"git-commit": git.git_commit,
# Unique Git Features
"play": lambda args: Song.play_song(" ".join(args)),
"git-smart": git.git_smart_commit,
"git-help": git.git_help,
"git-history": git.git_history,
"git-undo": git.git_undo,
"git-stash": git.git_stash,
"git-recover": git.git_recover,
"git-dashboard": git.git_dashboard,
"git-auto_merge": git.git_auto_merge,
"git-voice": git.git_voice_command,
"git-reminder": git.git_reminder,
"git-offline_sync": git.git_offline_sync,
}
scheduler_thread = threading.Thread(target=Task().run_scheduler, daemon=True)
scheduler_thread.start()
while True:
display_prompt(username)
command = input().strip().lower().split()
if not command:
continue
cmd, *args = command
start_time = time.time()
if not command:
continue
cmd, *args = command
start_time = time.time()
if cmd in commands:
commands[cmd](args)
else:
if cmd == "ls":
cmds.list_files()
elif cmd == "touch" and args:
cmds.create_file(args[0])
elif cmd == "rm" and args:
cmds.delete_file(args[0])
elif cmd == "mkdir" and args:
cmds.create_folder(args[0])
elif cmd == "rmdir" and args:
cmds.delete_folder(args[0])
elif cmd == "cd" and args:
cmds.change_directory(args[0])
elif cmd == "edit" and args:
cmds.text_editor(args[0])
elif cmd == "sysinfo":
cmds.system_info()
elif cmd == "exit":
console.print("Exiting PyShell...", style="bold red")
break
else:
console.print("Invalid command!", style="bold red")
exec_time = time.time() - start_time
console.print(f"Execution time: {exec_time:.4f} seconds", style="bold yellow")
time.sleep(1)
if __name__ == "__main__":
main()