Skip to content

Commit 31579a5

Browse files
committed
Improvements to code to validate the url
Signed-off-by: Ganesh Hubale <[email protected]>
1 parent 2623ed6 commit 31579a5

File tree

3 files changed

+83
-64
lines changed

3 files changed

+83
-64
lines changed

readit/cli.py

Lines changed: 59 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -56,50 +56,49 @@ def main(
5656
Readit - Command-line bookmark manager tool.
5757
"""
5858
if add:
59-
for url_to_add in add:
60-
url = url_to_add.strip() # Strip any leading/trailing whitespace
59+
for url in add:
6160
try:
62-
validate_url = requests.get(url)
63-
validate_code = validate_url.status_code
61+
validate_code = check_url_validation(url)
62+
6463
if validate_code == 200:
6564
is_url_added = database_connection.add_url(url)
6665
if is_url_added:
67-
print(f"\nSuccess: The URL '{url}' has been added to the database.")
66+
print(f"\033[92m\nSuccess: The URL '{url}' has been added to the database.\033[0m")
6867
else:
69-
print("*" * 12, "\nInvalid URL\n", "*" * 11)
68+
print("\033[93m\nWarning: The URL seems to be inaccessible at the moment.\033[0m") # Warning in yellow
7069
if option_yes_no():
7170
is_url_added = database_connection.add_url(url)
7271
if is_url_added:
73-
print(f"\nSuccess: The URL '{url}' has been added to the database.")
72+
print(f"\033[92m\nSuccess: The URL '{url}' has been added to the database.\033[0m")
7473
except Exception:
75-
print("*" * 12, "\nInvalid URL\n", "*" * 11)
74+
print("\033[93m\nWarning: The URL seems to be inaccessible at the moment.\033[0m") # Warning in yellow
7675
if option_yes_no():
7776
is_url_added = database_connection.add_url(url)
7877
if is_url_added:
79-
print(f"\nSuccess: The URL '{url}' has been added to the database.")
78+
print(f"\033[92m\nSuccess: The URL '{url}' has been added to the database.\033[0m")
8079
elif delete:
8180
database_connection.delete_url(delete)
8281
elif update:
8382
url_list = []
8483
for update_to_url in update:
8584
url_list.append(update_to_url)
8685
url_id = url_list[0]
87-
url = url_list[1].strip() # Strip any leading/trailing whitespace
86+
url = url_list[1]
8887
try:
89-
validate_url = requests.get(url)
90-
validate_code = validate_url.status_code
88+
validate_code = check_url_validation(url)
89+
9190
if validate_code == 200:
9291
database_connection.update_url(url_id, url)
9392
else:
94-
print("*" * 12, "\nInvalid URL\n", "*" * 11)
93+
print("\033[93m\nWarning: The URL seems to be inaccessible at the moment.\033[0m") # Warning in yellow
9594
if option_yes_no():
9695
database_connection.update_url(url_id, url)
9796
except Exception:
98-
print("*" * 12, "\nInvalid URL\n", "*" * 11)
97+
print("\033[93m\nWarning: The URL seems to be inaccessible at the moment.\033[0m") # Warning in yellow
9998
if option_yes_no():
10099
is_url_updated = database_connection.update_url(url_id, url)
101100
if is_url_updated:
102-
print(f"\nSuccess: URL of ID {url_id} updated.")
101+
print(f"\033[92m\nSuccess: URL of ID {url_id} updated.\033[0m")
103102
elif view:
104103
output.print_bookmarks(database_connection.show_urls())
105104
elif openurl:
@@ -113,66 +112,90 @@ def main(
113112
for tag_to_url in tag:
114113
tag_list.append(tag_to_url)
115114
tag_name = tag_list[0]
116-
tagged_url = tag_list[1].strip() # Strip any leading/trailing whitespace
115+
tagged_url = tag_list[1]
117116
try:
118-
validate_url = requests.get(tagged_url)
119-
validate_code = validate_url.status_code
117+
validate_code = check_url_validation(tagged_url)
120118
if validate_code == 200:
121119
is_url_tagged = database_connection.tag_url(tag_name, tagged_url)
122120
if is_url_tagged:
123-
print(f"\nSuccess: Bookmarked URL `{tagged_url}` with tag `{tag_name}`.")
121+
print(f"\033[92m\nSuccess: Bookmarked URL `{tagged_url}` with tag `{tag_name}`.\033[0m")
124122
else:
125-
print("*" * 12, "\nInvalid URL\n", "*" * 11)
123+
print("\033[93m\nWarning: The URL seems to be inaccessible at the moment.\033[0m") # Warning in yellow
126124
if option_yes_no():
127125
is_url_tagged = database_connection.tag_url(tag_name, tagged_url)
128126
if is_url_tagged:
129-
print(f"\nSuccess: Bookmarked URL `{tagged_url}` with tag `{tag_name}`.")
127+
print(f"\033[92m\nSuccess: Bookmarked URL `{tagged_url}` with tag `{tag_name}`.\033[0m")
130128
except Exception:
131-
print("*" * 12, "\nInvalid URL\n", "*" * 11)
129+
print("\033[93m\nWarning: The URL seems to be inaccessible at the moment.\033[0m") # Warning in yellow
132130
if option_yes_no():
133131
is_url_tagged = database_connection.tag_url(tag_name, tagged_url)
134132
if is_url_tagged:
135-
print(f"\nSuccess: Bookmarked URL `{tagged_url}` with tag `{tag_name}`.")
133+
print(f"\033[92m\nSuccess: Bookmarked URL `{tagged_url}` with tag `{tag_name}`.\033[0m")
136134
elif taglist:
137135
output.print_all_tags(database_connection.list_all_tags())
138136
elif version:
139-
print("readit v0.3")
137+
print("\033[92m\nreadit v0.3 \033[0m")
140138
elif export:
141139
path = database_connection.export_urls()
142140
if path:
143-
print(f"\nExported bookmarks available at `{path}`")
141+
print(f"\033[92m\nSuccess: Exported bookmarks available at `{path}`.\033[0m")
144142
else:
145-
print("\nError: Bookmarks are not exported in csv file.")
143+
print("\033[91m\nError: Bookmarks are not exported in csv file.\033[0m")
146144
else:
147-
for url_to_add in insert:
148-
url = url_to_add.strip() # Strip any leading/trailing whitespace
145+
for url in insert:
149146
try:
150-
validate_url = requests.get(url)
151-
validate_code = validate_url.status_code
147+
validate_code = check_url_validation(url)
148+
152149
if validate_code == 200:
153150
is_url_added = database_connection.add_url(url)
154151
if is_url_added:
155-
print(f"\nSuccess: The URL '{url}' has been added to the database.")
152+
print(f"\033[92m\nSuccess: The URL '{url}' has been added to the database.\033[0m")
156153
else:
157-
print("*" * 12, "\nInvalid URL\n", "*" * 11)
154+
print("\033[93m\nWarning: The URL seems to be inaccessible at the moment.\033[0m") # Warning in yellow
158155
if option_yes_no():
159156
is_url_added = database_connection.add_url(url)
160157
if is_url_added:
161-
print(f"\nSuccess: The URL '{url}' has been added to the database.")
158+
print(f"\033[92m\nSuccess: The URL '{url}' has been added to the database.\033[0m")
162159

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

170167
def option_yes_no():
171168
"""
172169
Asks whether to bookmark invalid URLs or Offline URLs to database.
173170
"""
174-
option = input("Still you want to bookmark: Yes/No ? ")
171+
option = input("\033[96m\nAre you sure you want to bookmark this URL? (Yes/No) \033[0m")
175172
if option.lower() in ["yes", "y"]:
176173
return True
177174
else:
178175
sys.exit(0)
176+
177+
def check_url_validation(url_given):
178+
url = url_given.strip() # Strip any leading/trailing whitespace
179+
if not url:
180+
print("\033[91m\nError: Cannot add an empty URL.\033[0m")
181+
sys.exit(0)
182+
183+
# Initialize the validation code
184+
validate_code = 0
185+
186+
if not url.startswith(("http://", "https://")):
187+
# First try with http, if it fails, try https
188+
for prefix in ["http://", "https://"]:
189+
full_url = prefix + url
190+
response = requests.get(full_url)
191+
if response.status_code == 200:
192+
validate_code = 200
193+
url = full_url # Update URL with valid prefix
194+
break
195+
else:
196+
validate_code = 0
197+
else:
198+
# If URL starts with http or https, validate directly
199+
response = requests.get(url)
200+
validate_code = response.status_code
201+
return validate_code

readit/database.py

Lines changed: 20 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ def init_db(self):
8484
else:
8585
raise IOError("\nDirectory does not exists")
8686
except sqlite3.OperationalError as e:
87-
print("\nERROR: Failed to create table in the database.")
87+
print("\033[91m\nERROR: Failed to create table in the database.\033[0m")
8888
print(f"\nSQLite Error: {str(e)}")
8989
sys.exit(1)
9090

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

106-
# Check if the URL is empty or invalid before attempting to add
107-
if not self.url:
108-
print("\nError: Cannot add an empty URL.")
109-
return False
110-
111106
self.cursor.execute(
112107
"""
113108
INSERT INTO bookmarks(url, date, time) VALUES (?, ?, ?)
@@ -119,7 +114,7 @@ def add_url(self, url):
119114

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

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

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

245240
except sqlite3.OperationalError as e:
@@ -269,13 +264,13 @@ def update_url(self, url_id, new_url):
269264
"""UPDATE bookmarks SET url=? WHERE id=?""", (self.new_url, self.url_id)
270265
)
271266
self.db.commit()
272-
print(f"\nSuccess: URL updated to '{self.new_url}'.")
267+
print(f"\033[92m\nSuccess: URL updated to '{self.new_url}'.\033[0m")
273268
return True
274269
else:
275-
print("\nNo changes: The provided URL is already bookmarked. No update needed.")
270+
print("\033[92m\nNo changes: The provided URL is already bookmarked. No update needed.\033[0m")
276271
return False
277272
else:
278-
print(f"\nError: No URL found with ID `{self.url_id}`. Update failed.")
273+
print(f"\033[91m\nError: No URL found with ID `{self.url_id}`. Update failed.\033[0m")
279274
return False
280275

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

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

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

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

424419
if folder_path:
425-
print(f"\nSelected folder: {folder_path}")
420+
print(f"\n\033[92mSelected folder: {folder_path}.\033[0m")
426421
else:
427-
print("\nNo folder selected")
422+
print("\n\033[92mNo folder selected.\033[0m")
428423
return folder_path
429424

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

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

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

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

455450
# Open the database connection and export to CSV
456451
with sqlite3.connect(db_file_paths[0]) as conn:
@@ -479,4 +474,4 @@ def export_urls(self):
479474
if isinstance(result, tuple) and result[0] is False:
480475
print(result[1]) # Print error message
481476
else:
482-
print(f"Bookmarks exported successfully to: {result}")
477+
print(f"\033[92m\nSuccess: Bookmarks exported successfully to: {result}.\033[0m")

readit/view.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,17 +31,18 @@ def __init__(self):
3131

3232
def print_all_tags(self, tag_list):
3333
if tag_list:
34+
print("\033[34m\n*Collection of associated Tags.*\033[0m\n")
3435
for tag_in_list in tag_list:
3536
table_tag.rows.append([tag_in_list])
3637
print(table_tag)
3738
else:
38-
print("\nTags list is empty.")
39+
print("\033[92m\nSuccess: Tags list is empty.\033[0m")
3940

4041
def print_bookmarks(self, all_bookmarks):
4142
if all_bookmarks:
42-
print("*" * 24, "\nAlready bookmarked URLs.\n", "*" * 23)
43+
print("\033[34m\n*Collection of Bookmarked Links*\033[0m\n")
4344
for bookmark in all_bookmarks:
4445
table.rows.append([bookmark[0], bookmark[1], bookmark[2], bookmark[3], bookmark[4]])
4546
print(table)
4647
else:
47-
print("\nNo bookmarks found.")
48+
print("\033[92m\nSuccess: No bookmarks found.\033[0m")

0 commit comments

Comments
 (0)