Skip to content

Commit

Permalink
Merge pull request #167 from pythonpune/issue-155
Browse files Browse the repository at this point in the history
Improvements to code for validating the url
  • Loading branch information
ganeshhubale authored Oct 17, 2024
2 parents 2623ed6 + 31579a5 commit 627b9ad
Show file tree
Hide file tree
Showing 3 changed files with 83 additions and 64 deletions.
95 changes: 59 additions & 36 deletions readit/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,50 +56,49 @@ def main(
Readit - Command-line bookmark manager tool.
"""
if add:
for url_to_add in add:
url = url_to_add.strip() # Strip any leading/trailing whitespace
for url in add:
try:
validate_url = requests.get(url)
validate_code = validate_url.status_code
validate_code = check_url_validation(url)

if validate_code == 200:
is_url_added = database_connection.add_url(url)
if is_url_added:
print(f"\nSuccess: The URL '{url}' has been added to the database.")
print(f"\033[92m\nSuccess: The URL '{url}' has been added to the database.\033[0m")
else:
print("*" * 12, "\nInvalid URL\n", "*" * 11)
print("\033[93m\nWarning: The URL seems to be inaccessible at the moment.\033[0m") # Warning in yellow
if option_yes_no():
is_url_added = database_connection.add_url(url)
if is_url_added:
print(f"\nSuccess: The URL '{url}' has been added to the database.")
print(f"\033[92m\nSuccess: The URL '{url}' has been added to the database.\033[0m")
except Exception:
print("*" * 12, "\nInvalid URL\n", "*" * 11)
print("\033[93m\nWarning: The URL seems to be inaccessible at the moment.\033[0m") # Warning in yellow
if option_yes_no():
is_url_added = database_connection.add_url(url)
if is_url_added:
print(f"\nSuccess: The URL '{url}' has been added to the database.")
print(f"\033[92m\nSuccess: The URL '{url}' has been added to the database.\033[0m")
elif delete:
database_connection.delete_url(delete)
elif update:
url_list = []
for update_to_url in update:
url_list.append(update_to_url)
url_id = url_list[0]
url = url_list[1].strip() # Strip any leading/trailing whitespace
url = url_list[1]
try:
validate_url = requests.get(url)
validate_code = validate_url.status_code
validate_code = check_url_validation(url)

if validate_code == 200:
database_connection.update_url(url_id, url)
else:
print("*" * 12, "\nInvalid URL\n", "*" * 11)
print("\033[93m\nWarning: The URL seems to be inaccessible at the moment.\033[0m") # Warning in yellow
if option_yes_no():
database_connection.update_url(url_id, url)
except Exception:
print("*" * 12, "\nInvalid URL\n", "*" * 11)
print("\033[93m\nWarning: The URL seems to be inaccessible at the moment.\033[0m") # Warning in yellow
if option_yes_no():
is_url_updated = database_connection.update_url(url_id, url)
if is_url_updated:
print(f"\nSuccess: URL of ID {url_id} updated.")
print(f"\033[92m\nSuccess: URL of ID {url_id} updated.\033[0m")
elif view:
output.print_bookmarks(database_connection.show_urls())
elif openurl:
Expand All @@ -113,66 +112,90 @@ def main(
for tag_to_url in tag:
tag_list.append(tag_to_url)
tag_name = tag_list[0]
tagged_url = tag_list[1].strip() # Strip any leading/trailing whitespace
tagged_url = tag_list[1]
try:
validate_url = requests.get(tagged_url)
validate_code = validate_url.status_code
validate_code = check_url_validation(tagged_url)
if validate_code == 200:
is_url_tagged = database_connection.tag_url(tag_name, tagged_url)
if is_url_tagged:
print(f"\nSuccess: Bookmarked URL `{tagged_url}` with tag `{tag_name}`.")
print(f"\033[92m\nSuccess: Bookmarked URL `{tagged_url}` with tag `{tag_name}`.\033[0m")
else:
print("*" * 12, "\nInvalid URL\n", "*" * 11)
print("\033[93m\nWarning: The URL seems to be inaccessible at the moment.\033[0m") # Warning in yellow
if option_yes_no():
is_url_tagged = database_connection.tag_url(tag_name, tagged_url)
if is_url_tagged:
print(f"\nSuccess: Bookmarked URL `{tagged_url}` with tag `{tag_name}`.")
print(f"\033[92m\nSuccess: Bookmarked URL `{tagged_url}` with tag `{tag_name}`.\033[0m")
except Exception:
print("*" * 12, "\nInvalid URL\n", "*" * 11)
print("\033[93m\nWarning: The URL seems to be inaccessible at the moment.\033[0m") # Warning in yellow
if option_yes_no():
is_url_tagged = database_connection.tag_url(tag_name, tagged_url)
if is_url_tagged:
print(f"\nSuccess: Bookmarked URL `{tagged_url}` with tag `{tag_name}`.")
print(f"\033[92m\nSuccess: Bookmarked URL `{tagged_url}` with tag `{tag_name}`.\033[0m")
elif taglist:
output.print_all_tags(database_connection.list_all_tags())
elif version:
print("readit v0.3")
print("\033[92m\nreadit v0.3 \033[0m")
elif export:
path = database_connection.export_urls()
if path:
print(f"\nExported bookmarks available at `{path}`")
print(f"\033[92m\nSuccess: Exported bookmarks available at `{path}`.\033[0m")
else:
print("\nError: Bookmarks are not exported in csv file.")
print("\033[91m\nError: Bookmarks are not exported in csv file.\033[0m")
else:
for url_to_add in insert:
url = url_to_add.strip() # Strip any leading/trailing whitespace
for url in insert:
try:
validate_url = requests.get(url)
validate_code = validate_url.status_code
validate_code = check_url_validation(url)

if validate_code == 200:
is_url_added = database_connection.add_url(url)
if is_url_added:
print(f"\nSuccess: The URL '{url}' has been added to the database.")
print(f"\033[92m\nSuccess: The URL '{url}' has been added to the database.\033[0m")
else:
print("*" * 12, "\nInvalid URL\n", "*" * 11)
print("\033[93m\nWarning: The URL seems to be inaccessible at the moment.\033[0m") # Warning in yellow
if option_yes_no():
is_url_added = database_connection.add_url(url)
if is_url_added:
print(f"\nSuccess: The URL '{url}' has been added to the database.")
print(f"\033[92m\nSuccess: The URL '{url}' has been added to the database.\033[0m")

except Exception:
print("*" * 12, "\nInvalid URL\n", "*" * 11)
print("\033[93m\nWarning: The URL seems to be inaccessible at the moment.\033[0m") # Warning in yellow
if option_yes_no():
is_url_added = database_connection.add_url(url)
if is_url_added:
print(f"\nSuccess: The URL '{url}' has been added to the database.")
print(f"\033[92m\nSuccess: The URL '{url}' has been added to the database.\033[0m")

def option_yes_no():
"""
Asks whether to bookmark invalid URLs or Offline URLs to database.
"""
option = input("Still you want to bookmark: Yes/No ? ")
option = input("\033[96m\nAre you sure you want to bookmark this URL? (Yes/No) \033[0m")
if option.lower() in ["yes", "y"]:
return True
else:
sys.exit(0)

def check_url_validation(url_given):
url = url_given.strip() # Strip any leading/trailing whitespace
if not url:
print("\033[91m\nError: Cannot add an empty URL.\033[0m")
sys.exit(0)

# Initialize the validation code
validate_code = 0

if not url.startswith(("http://", "https://")):
# First try with http, if it fails, try https
for prefix in ["http://", "https://"]:
full_url = prefix + url
response = requests.get(full_url)
if response.status_code == 200:
validate_code = 200
url = full_url # Update URL with valid prefix
break
else:
validate_code = 0
else:
# If URL starts with http or https, validate directly
response = requests.get(url)
validate_code = response.status_code
return validate_code
45 changes: 20 additions & 25 deletions readit/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def init_db(self):
else:
raise IOError("\nDirectory does not exists")
except sqlite3.OperationalError as e:
print("\nERROR: Failed to create table in the database.")
print("\033[91m\nERROR: Failed to create table in the database.\033[0m")
print(f"\nSQLite Error: {str(e)}")
sys.exit(1)

Expand All @@ -103,11 +103,6 @@ def add_url(self, url):
start = datetime.datetime.now()
time = start.strftime("%H:%M:%S")

# Check if the URL is empty or invalid before attempting to add
if not self.url:
print("\nError: Cannot add an empty URL.")
return False

self.cursor.execute(
"""
INSERT INTO bookmarks(url, date, time) VALUES (?, ?, ?)
Expand All @@ -119,7 +114,7 @@ def add_url(self, url):

except sqlite3.IntegrityError as e:
if 'UNIQUE constraint failed' in str(e):
print(f"\nError: The URL '{self.url}' already exists in the database.")
print(f"\033[91m\nError: The URL '{self.url}' already bookmarked.\033[0m")
return False
else:
print(f"\nDatabase error: {str(e)}")
Expand Down Expand Up @@ -182,7 +177,7 @@ def tag_url(self, tag_name, tagged_url):

except sqlite3.IntegrityError as e:
if 'UNIQUE constraint failed' in str(e):
print(f"\nError: The URL '{self.url}' has already been taggedwith '{self.tag}'.")
print(f"\033[91m\nError: The URL '{self.url}' has already been taggedwith '{self.tag}'.\033[0m")
return False
else:
print(f"\nDatabase error: {str(e)}")
Expand Down Expand Up @@ -236,10 +231,10 @@ def delete_url(self, url_id):
# Commit the transaction
self.db.commit()

print(f"\nSuccessfully deleted URL '{deleted_url[0]}' and its associated tags.")
print(f"\033[92m\nSuccessfully deleted URL '{deleted_url[0]}' and its associated tags.\033[0m")
return True
else:
print(f"\nError: No URL found with ID `{self.url_id}`. Nothing was deleted.")
print(f"\033[91m\nError: No URL found with ID `{self.url_id}`. Nothing was deleted.\033[0m")
return False

except sqlite3.OperationalError as e:
Expand Down Expand Up @@ -269,13 +264,13 @@ def update_url(self, url_id, new_url):
"""UPDATE bookmarks SET url=? WHERE id=?""", (self.new_url, self.url_id)
)
self.db.commit()
print(f"\nSuccess: URL updated to '{self.new_url}'.")
print(f"\033[92m\nSuccess: URL updated to '{self.new_url}'.\033[0m")
return True
else:
print("\nNo changes: The provided URL is already bookmarked. No update needed.")
print("\033[92m\nNo changes: The provided URL is already bookmarked. No update needed.\033[0m")
return False
else:
print(f"\nError: No URL found with ID `{self.url_id}`. Update failed.")
print(f"\033[91m\nError: No URL found with ID `{self.url_id}`. Update failed.\033[0m")
return False

except sqlite3.OperationalError as e:
Expand Down Expand Up @@ -367,10 +362,10 @@ def delete_all_url(self):
self.cursor.execute("""DELETE FROM url_tags""") # Delete all associations in the junction table
self.cursor.execute("""DELETE FROM tags WHERE tag_name NOT IN (SELECT tag_name FROM url_tags)""") # Delete orphaned tags
self.db.commit()
print(f"\nSuccess: All {url_count} URLs and their associated tags have been successfully deleted.")
print(f"\033[92m\nSuccess: All {url_count} URLs and their associated tags have been successfully deleted.\033[0m")
return True
else:
print("\nSuccess: No URLs found in the database to delete.")
print("\033[92m\nSuccess: No URLs found in the database to delete.\033[0m")
return False

except sqlite3.OperationalError as e:
Expand All @@ -388,10 +383,10 @@ def open_url(self, part_of_url):
urls = self.search_url(part_of_url)
if urls:
# Prompt the user before opening multiple URLs
print(f"\nFound {len(urls)} URLs. Do you want to open them all? (yes/no)")
print(f"\033[96m\nFound {len(urls)} URLs. Do you want to open them all? (yes/no) \033[0m")
user_confirmation = input().strip().lower()

if user_confirmation == 'yes':
if user_confirmation in ["yes", "y"]:
for url in urls:
url_to_open = url[1] # Assuming url[1] contains the actual URL
try:
Expand All @@ -400,11 +395,11 @@ def open_url(self, part_of_url):
except Exception as e:
print(f"Could not open {url_to_open}: {str(e)}")
else:
print("\nOperation cancelled. No URLs were opened.")
print("\033[92m\nOperation cancelled. No URLs were opened.\033[0m")
self.db.commit()
return True
else:
print("\nError: Please enter a valid URL substring to proceed.")
print("\033[91m\nError: Please enter a valid URL substring to proceed.\033[0m")

except sqlite3.OperationalError as e:
print(f"\nDatabase error occurred: {str(e)}")
Expand All @@ -422,9 +417,9 @@ def select_directory():
folder_path = filedialog.askdirectory(title="Select a folder")

if folder_path:
print(f"\nSelected folder: {folder_path}")
print(f"\n\033[92mSelected folder: {folder_path}.\033[0m")
else:
print("\nNo folder selected")
print("\n\033[92mNo folder selected.\033[0m")
return folder_path

def export_urls(self):
Expand All @@ -438,19 +433,19 @@ def export_urls(self):
folder_path = os.path.expanduser("~/.config/readit")

if not os.path.exists(folder_path):
msg = "File path does not exist: " + folder_path
msg = f"\033[91m\nFile path does not exist: {folder_path}.\033[0m"
return False, msg

except OSError as e:
msg = f"Error: Finding directory: {str(e)}"
msg = f"\033[91m\nError: Finding directory: {str(e)}.\033[0m"
return False, msg

database_file = os.path.join(os.path.expanduser("~/.config/readit"), "bookmarks.db")
try:
# Ensure the database file exists
db_file_paths = glob(os.path.expanduser(database_file))
if not db_file_paths:
return False, f"Error: Database file not found at: {database_file}"
return False, f"\033[91mError: Database file not found at: {database_file}.\033[0m"

# Open the database connection and export to CSV
with sqlite3.connect(db_file_paths[0]) as conn:
Expand Down Expand Up @@ -479,4 +474,4 @@ def export_urls(self):
if isinstance(result, tuple) and result[0] is False:
print(result[1]) # Print error message
else:
print(f"Bookmarks exported successfully to: {result}")
print(f"\033[92m\nSuccess: Bookmarks exported successfully to: {result}.\033[0m")
7 changes: 4 additions & 3 deletions readit/view.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,18 @@ def __init__(self):

def print_all_tags(self, tag_list):
if tag_list:
print("\033[34m\n*Collection of associated Tags.*\033[0m\n")
for tag_in_list in tag_list:
table_tag.rows.append([tag_in_list])
print(table_tag)
else:
print("\nTags list is empty.")
print("\033[92m\nSuccess: Tags list is empty.\033[0m")

def print_bookmarks(self, all_bookmarks):
if all_bookmarks:
print("*" * 24, "\nAlready bookmarked URLs.\n", "*" * 23)
print("\033[34m\n*Collection of Bookmarked Links*\033[0m\n")
for bookmark in all_bookmarks:
table.rows.append([bookmark[0], bookmark[1], bookmark[2], bookmark[3], bookmark[4]])
print(table)
else:
print("\nNo bookmarks found.")
print("\033[92m\nSuccess: No bookmarks found.\033[0m")

0 comments on commit 627b9ad

Please sign in to comment.