Skip to content

Commit

Permalink
feat: 🎸 Enhanced, update online clipboard code completed
Browse files Browse the repository at this point in the history
✅ Closes: #449
  • Loading branch information
yashksaini-coder committed Nov 10, 2024
1 parent d413b36 commit e1e849d
Show file tree
Hide file tree
Showing 17 changed files with 717 additions and 0 deletions.
Empty file.
Empty file.
64 changes: 64 additions & 0 deletions pysnippets/clipboard_online/package/clip.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import os
import subprocess
import sys
import shutil
from datetime import datetime
import glob


def display(snippet_name, password):
current_time = datetime.now().strftime("%H%M")
if str(password).zfill(4) != current_time:
raise ValueError("Invalid password")

base_dir = os.path.dirname(__file__)
snippets_dir = os.path.join(base_dir, "stash")
pattern = os.path.join(snippets_dir, f"{snippet_name}.*")

matching_files = glob.glob(pattern)

if not matching_files:
raise FileNotFoundError("No file found with the name.")
elif len(matching_files) > 1:
raise ValueError("Multiple files found with the given name.")

snippet_path = os.path.join(snippets_dir, matching_files[0])

try:
with open(snippet_path, "r") as file:
source_code = file.read()

# Call the copy to clipboard function
copy_to_clipboard(source_code)

except FileNotFoundError:
print("File not found")
raise


def copy_to_clipboard(text):
# Linux
if "linux" in sys.platform:
# Check if xclip is installed
if shutil.which("xclip") is None:
print("Error: xclip not found. Install it.", file=sys.stderr)
return
# If xclip is installed, proceed with copying text
subprocess.run(
["xclip", "-selection", "clipboard"],
input=text.strip().encode(),
check=True,
)

# Windows
elif "win32" in sys.platform:
subprocess.run(
["C:\\Windows\\System32\\clip.exe"], input=text.strip().encode(), check=True
)

# macOS
elif "darwin" in sys.platform:
subprocess.run(["/usr/bin/pbcopy"], input=text.strip().encode(), check=True)

else:
raise OSError("Unsupported operating system")
94 changes: 94 additions & 0 deletions pysnippets/clipboard_online/package/create.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import asyncio
import requests
import subprocess
import platform


def get_clipboard_content() -> str:
# Detect the operating system
current_os = platform.system()

try:
if current_os == "Linux":
# Use xclip to get clipboard content
result = subprocess.run(
["xclip", "-selection", "clipboard", "-o"], stdout=subprocess.PIPE
)
return result.stdout.decode("utf-8")
elif current_os == "Darwin": # macOS
# Use pbpaste to get clipboard content
result = subprocess.run(["pbpaste"], stdout=subprocess.PIPE)
return result.stdout.decode("utf-8")
elif current_os == "Windows":
# Use PowerShell to get clipboard content on Windows
result = subprocess.run(
["powershell", "-command", "Get-Clipboard"], stdout=subprocess.PIPE
)
return result.stdout.decode("utf-8")
else:
print(f"Unsupported OS: {current_os}")
return ""
except subprocess.CalledProcessError:
print("Failed to get clipboard content.")
return ""


async def create(url_id, lifetime="60s"):
text = get_clipboard_content()
base_url = "https://cl1p.net"
convert_lifetime_to_seconds(lifetime)

async def create_clip():
url = f"{base_url}/{url_id}"
data = {"content": text}
try:
response = await asyncio.to_thread(requests.post, url, data=data)
if response.status_code == 200:
return True
else:
print(f"Failed to create clip: Status code {response.status_code}")
return False
except requests.exceptions.RequestException as e:
print(f"Failed to create clip: {e}")
return False

create_success = await create_clip()
if create_success:
print(f"Clip created successfully: https://cl1p.net/{url_id}")
else:
print("Failed to create the clip.")


def convert_lifetime_to_seconds(lifetime):
parts = lifetime.split()
if len(parts) != 2:
raise ValueError(
"Lifetime must be in the format '<number> <unit>' (e.g., '1 day')."
)

value, unit = parts
try:
value = int(value)
except ValueError:
raise ValueError("The first part of lifetime must be an integer.")

if "second" in unit or "seconds" in unit:
return value
elif "minute" in unit or "minutes" in unit:
return value * 60
elif "hour" in unit or "hours" in unit:
return value * 3600
elif "day" in unit or "days" in unit:
return value * 86400
elif "week" in unit or "weeks" in unit:
return value * 604800
else:
raise ValueError(
"Invalid time unit provided. Use seconds, minutes, hours, days, or weeks."
)


if __name__ == "__main__":
asyncio.run(
create("yash1", "This clip will self-destruct!", "1 day")
) # Example usage
10 changes: 10 additions & 0 deletions pysnippets/clipboard_online/package/display.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from package.show import display
from package.write import plot


def write(snippet_name, password):
return plot(snippet_name, password)


def show(snippet_name, password, clipboard=None):
return display(snippet_name, password, clipboard=None)
6 changes: 6 additions & 0 deletions pysnippets/clipboard_online/package/password.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from datetime import datetime


def valid_password(password: int) -> bool:
current_time = int(datetime.now().strftime("%H%M"))
return password == current_time
88 changes: 88 additions & 0 deletions pysnippets/clipboard_online/package/scrap/grab.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import urllib.request
import re
import html
import subprocess
import sys
import shutil


def copy_to_clipboard(text):
# Linux
if "linux" in sys.platform:
if shutil.which("xclip") is None:
print("Error: xclip not found. Install it.", file=sys.stderr)
return
subprocess.run(
["xclip", "-selection", "clipboard"],
input=text.strip().encode(),
check=True,
)

# Windows
elif "win32" in sys.platform:
subprocess.run(
["C:\\Windows\\System32\\clip.exe"], input=text.strip().encode(), check=True
)

# macOS
elif "darwin" in sys.platform:
subprocess.run(["/usr/bin/pbcopy"], input=text.strip().encode(), check=True)

else:
raise OSError("Unsupported operating system")


def grab_content(url_name):
url = f"https://cl1p.net/{url_name}"
try:
with urllib.request.urlopen(url) as response:
html_content = response.read().decode("utf-8")
match = re.search(
r'<textarea[^>]*id="cl1pTextArea"[^>]*>(.*?)</textarea>',
html_content,
re.DOTALL,
)
if match:
content = html.unescape(match.group(1)).strip()
if content:
return content
except (urllib.error.HTTPError, urllib.error.URLError):
pass
return content


def show(url_name):
try:
content = grab_content(url_name)
if content:
print("The content is: ", content)
else:
print(
"Nothing found. The clipboard might be empty or you have entered a wrong URL."
)
except Exception as e:
print(f"Error occurred: {e}")


def clip(url_name):
try:
content = grab_content(url_name)
if content:
copy_to_clipboard(content)
print("Content copied to clipboard.")
else:
print(
"Nothing found. The clipboard might be empty or you have entered a wrong URL."
)
except Exception as e:
print(f"Error occurred: {e}")


def write(url_name, file):
try:
content = grab_content(url_name)
with open(file, "w") as file:
file.write(content)
print("Content written to file successfully.")
except IOError as e:
print(f"Error writing to file: {e}")
84 changes: 84 additions & 0 deletions pysnippets/clipboard_online/package/show.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import os
import shutil
import subprocess
import sys
from datetime import datetime
import glob


def display(snippet_name=None, password=None, clipboard=None):

if snippet_name is None and password is None and clipboard is None:
ls("/package/stash") # Enter stash directory
return

current_time = datetime.now().strftime("%H%M")

if snippet_name is None or password is None:
print("Both snippet_name and password must be provided")
return

if str(password).zfill(4) != current_time:
raise ValueError("syntax error: incorrect password")
try:
base_dir = os.path.dirname(__file__)
snippets_dir = os.path.join(base_dir, "stash")
pattern = os.path.join(snippets_dir, f"{snippet_name}.*")

matching_files = glob.glob(pattern)

if not matching_files:
raise FileNotFoundError("No file found with the name.")
elif len(matching_files) > 1:
raise ValueError("Multiple files found with the given name.")

snippet_path = os.path.join(snippets_dir, matching_files[0])

# If clipboard argument is passed as 1, copy content to clipboard
if clipboard == 1:
with open(snippet_path, "r") as file:
content = file.read()
copy_to_clipboard(content)
print("Content copied to clipboard.")
else:
# regular
with open(snippet_path, "r") as file:
content = file.read()
print(content)

except Exception as e:
print(f"Syntax Error: {e}")


def copy_to_clipboard(text):
# Linux
if "linux" in sys.platform:
# Check if xclip is installed
if shutil.which("xclip") is None:
print("Error: xclip not found. Install it.", file=sys.stderr)
return
# If xclip is installed, proceed with copying text
subprocess.run(
["xclip", "-selection", "clipboard"],
input=text.strip().encode(),
check=True,
)

# Windows
elif "win32" in sys.platform:
subprocess.run(
["C:\\Windows\\System32\\clip.exe"], input=text.strip().encode(), check=True
)

# macOS
elif "darwin" in sys.platform:
subprocess.run(["/usr/bin/pbcopy"], input=text.strip().encode(), check=True)

else:
raise OSError("Unsupported operating system")


def ls(directory_path):
contents = os.listdir(directory_path)
for files in contents:
print(files)
Empty file.
1 change: 1 addition & 0 deletions pysnippets/clipboard_online/package/stash/test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
print("If it's visible, then it's good to go!")
5 changes: 5 additions & 0 deletions pysnippets/clipboard_online/package/test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from scrap.grab import write, show, clip

write("fghd", "text.txt")
show("fghd")
clip("fghd")
36 changes: 36 additions & 0 deletions pysnippets/clipboard_online/package/write.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import os
import shutil
from datetime import datetime
import glob


def plot(snippet_name, password):
current_time = datetime.now().strftime("%H%M")
if str(password).zfill(4) != current_time:
raise ValueError("syntax error: incorrect password")

try:
base_dir = os.path.dirname(__file__)
snippets_dir = os.path.join(base_dir, "stash")
pattern = os.path.join(snippets_dir, f"{snippet_name}.*")

matching_files = glob.glob(pattern)

if not matching_files:
raise FileNotFoundError("No file found with the name.")
elif len(matching_files) > 1:
raise ValueError("Multiple files found with the given name.")

snippet_path = matching_files[0]
snippet_extension = os.path.splitext(snippet_path)[1]
output_path = os.path.join(base_dir, f"{snippet_name}{snippet_extension}")

shutil.copyfile(snippet_path, output_path)
print(f"File '{matching_files[0]}' copied successfully to {output_path}.")

except FileNotFoundError:
print("File is not found")
except ValueError:
print("The given values are not supported")
except Exception as e:
print(f"Error: {e}")
Loading

0 comments on commit e1e849d

Please sign in to comment.