diff --git a/pysnippets/clipboard_online/__init__.py b/pysnippets/clipboard_online/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/pysnippets/clipboard_online/package/__init__.py b/pysnippets/clipboard_online/package/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/pysnippets/clipboard_online/package/clip.py b/pysnippets/clipboard_online/package/clip.py new file mode 100644 index 0000000..11524a8 --- /dev/null +++ b/pysnippets/clipboard_online/package/clip.py @@ -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") diff --git a/pysnippets/clipboard_online/package/create.py b/pysnippets/clipboard_online/package/create.py new file mode 100644 index 0000000..e2738d1 --- /dev/null +++ b/pysnippets/clipboard_online/package/create.py @@ -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 ' ' (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 diff --git a/pysnippets/clipboard_online/package/display.py b/pysnippets/clipboard_online/package/display.py new file mode 100644 index 0000000..acc3190 --- /dev/null +++ b/pysnippets/clipboard_online/package/display.py @@ -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) diff --git a/pysnippets/clipboard_online/package/password.py b/pysnippets/clipboard_online/package/password.py new file mode 100644 index 0000000..4d2a73a --- /dev/null +++ b/pysnippets/clipboard_online/package/password.py @@ -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 diff --git a/pysnippets/clipboard_online/package/scrap/grab.py b/pysnippets/clipboard_online/package/scrap/grab.py new file mode 100644 index 0000000..a5b8bb6 --- /dev/null +++ b/pysnippets/clipboard_online/package/scrap/grab.py @@ -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']*id="cl1pTextArea"[^>]*>(.*?)', + 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}") diff --git a/pysnippets/clipboard_online/package/show.py b/pysnippets/clipboard_online/package/show.py new file mode 100644 index 0000000..3d8315f --- /dev/null +++ b/pysnippets/clipboard_online/package/show.py @@ -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) diff --git a/pysnippets/clipboard_online/package/stash/__init__.py b/pysnippets/clipboard_online/package/stash/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/pysnippets/clipboard_online/package/stash/test.py b/pysnippets/clipboard_online/package/stash/test.py new file mode 100644 index 0000000..9d01c84 --- /dev/null +++ b/pysnippets/clipboard_online/package/stash/test.py @@ -0,0 +1 @@ +print("If it's visible, then it's good to go!") diff --git a/pysnippets/clipboard_online/package/test.py b/pysnippets/clipboard_online/package/test.py new file mode 100644 index 0000000..edc06f5 --- /dev/null +++ b/pysnippets/clipboard_online/package/test.py @@ -0,0 +1,5 @@ +from scrap.grab import write, show, clip + +write("fghd", "text.txt") +show("fghd") +clip("fghd") diff --git a/pysnippets/clipboard_online/package/write.py b/pysnippets/clipboard_online/package/write.py new file mode 100644 index 0000000..d984697 --- /dev/null +++ b/pysnippets/clipboard_online/package/write.py @@ -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}") diff --git a/pysnippets/clipboard_online/test_clip.py b/pysnippets/clipboard_online/test_clip.py new file mode 100644 index 0000000..3f759f6 --- /dev/null +++ b/pysnippets/clipboard_online/test_clip.py @@ -0,0 +1,27 @@ +import pytest +from package.clip import display +from datetime import datetime +import subprocess +from package.clip import copy_to_clipboard + + +def test_display_right_password(): + current_time = datetime.now().strftime("%H%M") + assert display("test", current_time) is None + + +def test_display_wrong_password(): + with pytest.raises(ValueError, match="Invalid password"): + display("test", 1111) + + +def test_copy_to_clipboard(monkeypatch): + def mock_run(*args, **kwargs): + pass + + monkeypatch.setattr(subprocess, "run", mock_run) + + try: + copy_to_clipboard("Whatever test") + except Exception: + pytest.fail("Unexpected error raised: {e}") diff --git a/pysnippets/clipboard_online/test_display.py b/pysnippets/clipboard_online/test_display.py new file mode 100644 index 0000000..0d4addb --- /dev/null +++ b/pysnippets/clipboard_online/test_display.py @@ -0,0 +1,119 @@ +import pytest +from datetime import datetime +from package.display import show, write + + +# Mock datetime class +class MockDateTime(datetime): + @classmethod + def now(cls): + return datetime.strptime("1234", "%H%M") # Mock time to 12:34 + + +# Mock file operations +def mock_glob_single_file(*args, **kwargs): + return ["test_file.txt"] + + +def mock_glob_no_file(*args, **kwargs): + return [] + + +def mock_glob_multiple_files(*args, **kwargs): + return ["test1.txt", "test2.txt"] + + +def mock_open_file_content(*args, **kwargs): + class MockFile: + def __enter__(self): + return self + + def __exit__(self, *args): + pass + + def read(self): + return "Sample content" + + return MockFile() + + +# Mock subprocess for clipboard operations +def mock_subprocess_run(*args, **kwargs): + return None + + +# Test cases for show function +def test_show_correct_password(monkeypatch): + monkeypatch.setattr("package.show.datetime", MockDateTime) + monkeypatch.setattr("glob.glob", mock_glob_single_file) + monkeypatch.setattr("builtins.open", mock_open_file_content) + + # Should not raise any exception + show("test_snippet", "1234") + + +def test_show_incorrect_password(monkeypatch): + monkeypatch.setattr("package.show.datetime", MockDateTime) + + with pytest.raises(ValueError, match="syntax error: incorrect password"): + show("test_snippet", "5678") + + +# Test cases for clipboard functionality +def test_show_with_clipboard_linux(monkeypatch): + monkeypatch.setattr("package.show.datetime", MockDateTime) + monkeypatch.setattr("glob.glob", mock_glob_single_file) + monkeypatch.setattr( + "package.show.glob.glob", mock_glob_single_file + ) # Added this line + monkeypatch.setattr("builtins.open", mock_open_file_content) + monkeypatch.setattr("sys.platform", "linux") + monkeypatch.setattr("shutil.which", lambda x: "/usr/bin/xclip") + monkeypatch.setattr("subprocess.run", mock_subprocess_run) + + show("test_snippet", "1234", clipboard=1) + + +def test_show_with_clipboard_windows(monkeypatch): + monkeypatch.setattr("package.show.datetime", MockDateTime) + monkeypatch.setattr("glob.glob", mock_glob_single_file) + monkeypatch.setattr( + "package.show.glob.glob", mock_glob_single_file + ) # Added this line + monkeypatch.setattr("builtins.open", mock_open_file_content) + monkeypatch.setattr("sys.platform", "win32") + monkeypatch.setattr("subprocess.run", mock_subprocess_run) + + show("test_snippet", "1234", clipboard=1) + + +def test_show_with_clipboard_macos(monkeypatch): + monkeypatch.setattr("package.show.datetime", MockDateTime) + monkeypatch.setattr("glob.glob", mock_glob_single_file) + monkeypatch.setattr( + "package.show.glob.glob", mock_glob_single_file + ) # Added this line + monkeypatch.setattr("builtins.open", mock_open_file_content) + monkeypatch.setattr("sys.platform", "darwin") + monkeypatch.setattr("subprocess.run", mock_subprocess_run) + + show("test_snippet", "1234", clipboard=1) + + +# Test cases for write function +def test_write_correct_password(monkeypatch): + monkeypatch.setattr("package.write.datetime", MockDateTime) + monkeypatch.setattr("glob.glob", mock_glob_single_file) + monkeypatch.setattr( + "package.write.glob.glob", mock_glob_single_file + ) # Added this line + monkeypatch.setattr("shutil.copyfile", lambda x, y: None) + + write("test_snippet", "1234") + + +def test_write_incorrect_password(monkeypatch): + monkeypatch.setattr("package.write.datetime", MockDateTime) + + with pytest.raises(ValueError, match="syntax error: incorrect password"): + write("test_snippet", "5678") diff --git a/pysnippets/clipboard_online/test_scrap.py b/pysnippets/clipboard_online/test_scrap.py new file mode 100644 index 0000000..706e89f --- /dev/null +++ b/pysnippets/clipboard_online/test_scrap.py @@ -0,0 +1,69 @@ +import unittest +from unittest.mock import patch, mock_open +from package.scrap.grab import copy_to_clipboard, grab_content, show, clip, write + + +class TestGrabFunctions(unittest.TestCase): + def setUp(self): + """Set up test data that will be used across test methods""" + self.sample_html = """ + + + + + + """ + self.test_content = "Test content" + + @patch("subprocess.run") + def test_copy_to_clipboard_linux(self, mock_run): + # Mock platform to test Linux clipboard + with patch("sys.platform", "linux"), patch( + "shutil.which", return_value="/usr/bin/xclip" + ): + copy_to_clipboard("test content") + + mock_run.assert_called_once_with( + ["xclip", "-selection", "clipboard"], input=b"test content", check=True + ) + + @patch("subprocess.run") + def test_copy_to_clipboard_windows(self, mock_run): + with patch("sys.platform", "win32"): + copy_to_clipboard("test text") + mock_run.assert_called_once_with( + ["C:\\Windows\\System32\\clip.exe"], input=b"test text", check=True + ) + + @patch("subprocess.run") + def test_copy_to_clipboard_macos(self, mock_run): + with patch("sys.platform", "darwin"): + copy_to_clipboard("test text") + mock_run.assert_called_once_with( + ["/usr/bin/pbcopy"], input=b"test text", check=True + ) + + @patch("builtins.print") + @patch("package.scrap.grab.grab_content", return_value="test content") + def test_show(self, mock_grab_content, mock_print): + show("test-url") + mock_print.assert_called_once_with("The content is: ", "test content") + + @patch("builtins.print") + @patch("package.scrap.grab.grab_content", return_value="test content") + @patch("package.scrap.grab.copy_to_clipboard") + def test_clip(self, mock_copy_to_clipboard, mock_grab_content, mock_print): + clip("test-url") + mock_copy_to_clipboard.assert_called_once_with("test content") + mock_print.assert_called_once_with("Content copied to clipboard.") + + @patch("builtins.open", new_callable=mock_open) + @patch("package.scrap.grab.grab_content", return_value="test content") + def test_write(self, mock_grab_content, mock_open): + write("test-url", "test.txt") + mock_open.assert_called_once_with("test.txt", "w") + mock_open().write.assert_called_once_with("test content") + + +if __name__ == "__main__": + unittest.main() diff --git a/pysnippets/clipboard_online/test_show.py b/pysnippets/clipboard_online/test_show.py new file mode 100644 index 0000000..405174b --- /dev/null +++ b/pysnippets/clipboard_online/test_show.py @@ -0,0 +1,47 @@ +import pytest +import sys +from datetime import datetime +from package.show import display, copy_to_clipboard + + +# Mock datetime class +class MockDateTime(datetime): + @classmethod + def now(cls): + return datetime.strptime("1234", "%H%M") # Mock time to 12:34 + + +# Mock functions for clipboard operations +def mock_subprocess_run(*args, **kwargs): + return None # Assume successful run + + +def mock_open_file_content(*args, **kwargs): + class MockFile: + def __enter__(self): + return self + + def __exit__(self, *args): + pass + + def read(self): + return "Sample content" + + return MockFile() + + +def test_display_incorrect_password(monkeypatch): + monkeypatch.setattr("package.show.datetime", MockDateTime) # Mock datetime + + snippet_name = "test" + incorrect_password = "1111" # Different from "1234" + + with pytest.raises(ValueError, match="syntax error: incorrect password"): + display(snippet_name, incorrect_password) + + +def test_copy_to_clipboard_unsupported_os(monkeypatch): + monkeypatch.setattr(sys, "platform", "unsupported_os") + + with pytest.raises(OSError, match="Unsupported operating system"): + copy_to_clipboard("test content") diff --git a/pysnippets/clipboard_online/test_write.py b/pysnippets/clipboard_online/test_write.py new file mode 100644 index 0000000..dd2354e --- /dev/null +++ b/pysnippets/clipboard_online/test_write.py @@ -0,0 +1,67 @@ +import shutil +import glob +from datetime import datetime +from package.write import plot + + +# we cannot mock this function, so mocking the whole class +class MockDateTime(datetime): + @classmethod + def now(cls): + return datetime.strptime("1234", "%H%M") + + +def mock_copyfile(src, dst): + pass + + +def mock_glob_single(pattern): + return ["stash/test.py"] + + +def mock_glob_none(pattern): + return [] + + +def mock_glob_multiple(pattern): + return ["stash/test.py", "stash/test2.py"] + + +def test_plot_success(monkeypatch, capfd): + monkeypatch.setattr("package.write.datetime", MockDateTime) + monkeypatch.setattr(shutil, "copyfile", mock_copyfile) + monkeypatch.setattr(glob, "glob", mock_glob_single) + + snippet_name = "test" + password = "1234" + plot(snippet_name, password) + + # Verify output + captured = capfd.readouterr() + assert "File 'stash/test.py' copied successfully" in captured.out + + +def test_plot_no_file_found(monkeypatch, capfd): + monkeypatch.setattr("package.write.datetime", MockDateTime) + monkeypatch.setattr(glob, "glob", mock_glob_none) + + snippet_name = "nonexistent" + password = "1234" + plot(snippet_name, password) + + # Verify output + captured = capfd.readouterr() + assert "File is not found" in captured.out + + +def test_plot_multiple_files_found(monkeypatch, capfd): + monkeypatch.setattr("package.write.datetime", MockDateTime) + monkeypatch.setattr(glob, "glob", mock_glob_multiple) + + snippet_name = "test" + password = "1234" + plot(snippet_name, password) + + # Verify output + captured = capfd.readouterr() + assert "The given values are not supported" in captured.out