raannakasturi commited on
Commit
03339dc
·
verified ·
1 Parent(s): f02e0aa

Upload 7 files

Browse files
Files changed (5) hide show
  1. app.py +33 -32
  2. getScreenshot.py +86 -117
  3. getStatus.py +2 -2
  4. main.py +44 -39
  5. saveDataSendMail.py +135 -133
app.py CHANGED
@@ -1,33 +1,34 @@
1
- import gradio as gr
2
- from main import getData, installGC
3
-
4
- def run(URL, email):
5
- domain, URL, code, status, webStatus, moreDetails, img, imgurl, email, downcount = getData(URL, email)
6
- return domain, URL, code, status, webStatus, moreDetails, img, imgurl, email, downcount
7
-
8
- app = gr.Interface(
9
- fn=run,
10
- inputs=[
11
- gr.Textbox(label="Enter URL", placeholder="https://google.com", type="text", interactive=True),
12
- gr.Textbox(label="Enter Email", placeholder="example@gmail.com", type="text", interactive=True)
13
- ],
14
- outputs=[
15
- gr.Textbox(label="Domain", type="text", interactive=False),
16
- gr.Textbox(label="URL", type="text", interactive=False),
17
- gr.Textbox(label="Code", type="text", interactive=False),
18
- gr.Textbox(label="Status", type="text", interactive=False),
19
- gr.Textbox(label="Web Status", type="text", interactive=False),
20
- gr.Textbox(label="More Details", type="text", interactive=False),
21
- gr.Image(label="Website Screenshot"),
22
- gr.Textbox(label="Email", type="text", interactive=False),
23
- gr.Textbox(label="Download Count", type="text", interactive=False),
24
- ],
25
- title="Website Monitor<br> by <a href='https://nayankasturi.eu.org'>Nayan Kasturi</a> aka Raanna.<br> Checkout the <a href='https://github.com/raannakasturi'>Github</a> for more projects and contact info.",
26
- description="This app captures website status and its screenshot and displays it, along with sending mail to the person, in case website is down.",
27
- api_name="get",
28
- concurrency_limit=10
29
- )
30
-
31
- if __name__ == "__main__":
32
- installGC()
 
33
  app.launch()
 
1
+ import gradio as gr
2
+ from main import getData, installGC
3
+
4
+ def run(URL, email):
5
+ domain, URL, code, status, webStatus, moreDetails, img, imgurl, email, downcount = getData(URL, email)
6
+ return domain, URL, code, status, webStatus, moreDetails, img, imgurl, email, downcount
7
+
8
+ app = gr.Interface(
9
+ fn=run,
10
+ inputs=[
11
+ gr.Textbox(label="Enter URL", placeholder="https://google.com", type="text", interactive=True),
12
+ gr.Textbox(label="Enter Email", placeholder="example@gmail.com", type="email", interactive=True)
13
+ ],
14
+ outputs=[
15
+ gr.Textbox(label="Domain", type="text", interactive=False, allow_copy=True),
16
+ gr.Textbox(label="URL", type="text", interactive=False, allow_copy=True),
17
+ gr.Textbox(label="Code", type="text", interactive=False),
18
+ gr.Textbox(label="Status", type="text", interactive=False),
19
+ gr.Textbox(label="Web Status", type="text", interactive=False),
20
+ gr.Textbox(label="More Details", type="text", interactive=False, allow_copy=True),
21
+ gr.Image(label="Website Screenshot"),
22
+ gr.Textbox(label="Screenshot URL/Error", type="text", interactive=False, allow_copy=True),
23
+ gr.Textbox(label="Email", type="email", interactive=False),
24
+ gr.Textbox(label="Download Count", type="text", interactive=False),
25
+ ],
26
+ title="Website Monitor<br> by <a href='https://nayankasturi.eu.org'>Nayan Kasturi</a> aka Raanna.<br> Checkout the <a href='https://github.com/raannakasturi'>Github</a> for more projects and contact info.",
27
+ description="This app captures website status and its screenshot and displays it, along with sending mail to the person, in case website is down.",
28
+ api_name="get",
29
+ concurrency_limit=10
30
+ )
31
+
32
+ if __name__ == "__main__":
33
+ #installGC()
34
  app.launch()
getScreenshot.py CHANGED
@@ -1,117 +1,86 @@
1
- import os
2
- import sys
3
- import json
4
- import base64
5
- import time
6
- import requests
7
- from selenium import webdriver
8
- from selenium.webdriver.chrome.service import Service
9
- from selenium.webdriver.chrome.options import Options
10
- from selenium_stealth import stealth
11
- from webdriver_manager.chrome import ChromeDriverManager
12
- from dotenv import load_dotenv
13
- import checkinstallGC
14
-
15
- def driverSetup():
16
- options = Options()
17
- options.add_argument("--no-sandbox")
18
- options.add_argument("--disable-dev-shm-usage")
19
- options.add_argument("--disable-gpu")
20
- options.add_argument("--start-maximized")
21
- options.add_argument("--headless=new")
22
- options.add_experimental_option("excludeSwitches", ["enable-automation"])
23
- options.add_experimental_option('useAutomationExtension', False)
24
- options.add_argument("--window-size=1366,768")
25
- service = Service(ChromeDriverManager().install())
26
- driver = webdriver.Chrome(service=service, options=options)
27
-
28
- stealth(driver,
29
- languages=["en-US", "en"],
30
- vendor="Google Inc.",
31
- platform="Linux",
32
- webgl_vendor="MesaLib",
33
- renderer="Mesa DRI Intel(R) HD Graphics 5500",
34
- fix_hairline=True,
35
- )
36
- return driver
37
-
38
- def screenshotName(url):
39
- timestr = time.strftime("%Y%m%d_%H%M%S")
40
- url = url.replace('https://', '').replace('http://', '').replace('www.', '')
41
- if url.endswith('/'):
42
- url = url[:-1]
43
- return f"{url.replace('/', '')}_{timestr}.png"
44
-
45
- def getScreenshots(driver, url):
46
- try:
47
- driver.get(url)
48
- ssname = screenshotName(url)
49
- driver.save_screenshot(ssname)
50
- return ssname
51
- except Exception as e:
52
- print(f"Error: {e}")
53
- ssname = "1366-768.png"
54
- return ssname
55
-
56
- def saveScreenshot(url):
57
- driver = driverSetup()
58
- screenshot_file = getScreenshots(driver, url)
59
- driver.quit()
60
- return screenshot_file
61
-
62
- def uploadandDelSS(file):
63
- load_dotenv()
64
- api = os.getenv("IMGBBAPI")
65
- url = os.getenv("IMGBBURL")
66
- filename = file
67
- try:
68
- with open(f"{filename}", "rb") as file:
69
- name = file.name[:-4]
70
- payload = {
71
- "key": api,
72
- "image": base64.b64encode(file.read()),
73
- "name": name,
74
- "expiration": "15552000"
75
- }
76
- r = requests.post(url, data=payload)
77
- view_url = json.loads(r.text)["data"]["display_url"]
78
- return view_url, view_url
79
- except Exception as e:
80
- print(f"Error: {e}")
81
- return "https://i.ibb.co/s5c9QpD/1366x768.png", "Error in uploading the image. Please try again."
82
-
83
- def getScreenshot(url):
84
- if url == "":
85
- img = "https://i.ibb.co/s5c9QpD/1366x768.png"
86
- imgurl = "Please Enter the URL to capture the screenshot."
87
- return img, imgurl
88
- else:
89
- ss = saveScreenshot(url)
90
- img, imgurl = uploadandDelSS(ss)
91
- if ss == "1366-768.png":
92
- return img, imgurl
93
- else:
94
- os.remove(ss)
95
- return img, imgurl
96
-
97
- def checkSystem():
98
- OS = sys.platform
99
- if OS.startswith('linux'):
100
- print("Linux OS detected.")
101
- return "linux"
102
- elif OS.startswith('win32') or OS.startswith('cygwin'):
103
- print("Windows OS detected.")
104
- return "windows"
105
- else:
106
- print("Unsupported OS. We are currently supported on Windows and Linux only.")
107
- return "unsupported"
108
-
109
- def checkinstallChrome():
110
- OS = checkSystem()
111
- if OS == "linux":
112
- return checkinstallGC.checkGC("linux")
113
- elif OS == "windows":
114
- return checkinstallGC.checkGC("windows")
115
- else:
116
- print("Can't check for Chrome installation or install Chrome. Exiting..")
117
- return False
 
1
+ import os
2
+ import sys
3
+ import json
4
+ import base64
5
+ import time
6
+ import requests
7
+ from selenium import webdriver
8
+ from selenium.webdriver.chrome.service import Service
9
+ from selenium.webdriver.chrome.options import Options
10
+ from selenium_stealth import stealth
11
+ from webdriver_manager.chrome import ChromeDriverManager
12
+ from dotenv import load_dotenv
13
+
14
+ def driverSetup():
15
+ options = Options()
16
+ options.add_argument("--no-sandbox")
17
+ options.add_argument("--disable-dev-shm-usage")
18
+ options.add_argument("--disable-gpu")
19
+ options.add_argument("--start-maximized")
20
+ options.add_argument("--headless=new")
21
+ options.add_experimental_option("excludeSwitches", ["enable-automation"])
22
+ options.add_experimental_option('useAutomationExtension', False)
23
+ options.add_argument("--window-size=1366,768")
24
+ service = Service(ChromeDriverManager().install())
25
+ driver = webdriver.Chrome(service=service, options=options)
26
+
27
+ stealth(driver,
28
+ languages=["en-US", "en"],
29
+ vendor="Google Inc.",
30
+ platform="Linux",
31
+ webgl_vendor="MesaLib",
32
+ renderer="Mesa DRI Intel(R) HD Graphics 5500",
33
+ fix_hairline=True,
34
+ )
35
+ return driver
36
+
37
+ def screenshotName(url):
38
+ timestr = time.strftime("%Y%m%d_%H%M%S")
39
+ url = url.replace('https://', '').replace('http://', '').replace('www.', '')
40
+ if url.endswith('/'):
41
+ url = url[:-1]
42
+ return f"{url.replace('/', '')}_{timestr}.png"
43
+
44
+ def getScreenshots(driver, url):
45
+ driver.get(url)
46
+ ssname = screenshotName(url)
47
+ driver.save_screenshot(ssname)
48
+ return ssname
49
+
50
+ def saveScreenshot(url):
51
+ driver = driverSetup()
52
+ screenshot_file = getScreenshots(driver, url)
53
+ driver.quit()
54
+ return screenshot_file
55
+
56
+ def uploadandDelSS(file):
57
+ load_dotenv()
58
+ api = os.getenv("IMGBBAPI")
59
+ url = os.getenv("IMGBBURL")
60
+ filename = file
61
+ try:
62
+ with open(f"{filename}", "rb") as file:
63
+ name = file.name[:-4]
64
+ payload = {
65
+ "key": api,
66
+ "image": base64.b64encode(file.read()),
67
+ "name": name,
68
+ "expiration": "15552000"
69
+ }
70
+ r = requests.post(url, data=payload)
71
+ view_url = json.loads(r.text)["data"]["display_url"]
72
+ return view_url, view_url
73
+ except Exception as e:
74
+ print(f"Error: {e}")
75
+ return "https://i.ibb.co/s5c9QpD/1366x768.png", "Error in uploading the image. Please try again."
76
+
77
+ def getScreenshot(url):
78
+ if url == "":
79
+ img = "https://i.ibb.co/s5c9QpD/1366x768.png"
80
+ imgurl = "Please Enter the URL to capture the screenshot."
81
+ return img, imgurl
82
+ else:
83
+ ss = saveScreenshot(url)
84
+ img, imgurl = uploadandDelSS(ss)
85
+ os.remove(ss)
86
+ return img, imgurl
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
getStatus.py CHANGED
@@ -2,8 +2,8 @@ import requests
2
 
3
  def getStatus(URL):
4
  try:
5
- headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
6
- webResponse = requests.get(URL, headers=headers)
7
  webCode = str(webResponse.status_code)
8
  code, status, webStatus, moreDetails = statusCodes(webCode)
9
  return code, status, webStatus, moreDetails
 
2
 
3
  def getStatus(URL):
4
  try:
5
+ headers = {'User-Agent': 'Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; Googlebot/2.1; +https://www.google.com/bot.html) Safari/537.36'}
6
+ webResponse = requests.get(URL, headers=headers, timeout=10)
7
  webCode = str(webResponse.status_code)
8
  code, status, webStatus, moreDetails = statusCodes(webCode)
9
  return code, status, webStatus, moreDetails
main.py CHANGED
@@ -1,40 +1,45 @@
1
- import tldextract
2
- from getStatus import getStatus
3
- from getScreenshot import getScreenshot
4
- from saveDataSendMail import saveDataSendMail
5
- import subprocess
6
- import sys
7
-
8
- def cleanURL(inputURL):
9
- url = tldextract.extract(inputURL)
10
- if url.subdomain == "":
11
- domain = url.domain + "." + url.suffix
12
- URL = "http://" + domain
13
- else:
14
- domain = url.subdomain + "." + url.domain + "." + url.suffix
15
- URL = "http://" + domain
16
- return domain, URL
17
-
18
- def getData(url, email):
19
- domain, URL = cleanURL(url)
20
- code, status, webStatus, moreDetails = getStatus(URL)
21
- if status.startswith("2") or status.startswith("3"):
22
- img, imgurl = getScreenshot(URL)
23
- else:
24
- img = "1366-768.png"
25
- imgurl = "Website Down. Can't capture screenshot."
26
- email, downcount = saveDataSendMail(URL, email)
27
- return domain, URL, code, status, webStatus, moreDetails, img, imgurl, email, downcount
28
-
29
- def installGC():
30
- OS = sys.platform
31
- print(OS)
32
- if OS == 'linux':
33
- subprocess.run(['apt-get', 'update'])
34
- subprocess.run(['apt-get', 'install', '-y', 'wget', 'unzip'])
35
- subprocess.run(['wget', 'https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb'])
36
- subprocess.run(['apt-get', 'install', '-y', './google-chrome-stable_current_amd64.deb'])
37
- subprocess.run(['rm', 'google-chrome-stable_current_amd64.deb'])
38
- subprocess.run(['apt-get', 'clean'])
39
- else:
 
 
 
 
 
40
  subprocess.run(['powershell', '-command', 'winget', 'install', 'Google.Chrome', '--force'])
 
1
+ import tldextract
2
+ from getStatus import getStatus
3
+ from getScreenshot import getScreenshot
4
+ from saveDataSendMail import saveDataSendMail
5
+ import subprocess
6
+ import sys
7
+
8
+ def cleanURL(inputURL):
9
+ url = tldextract.extract(inputURL)
10
+ if url.subdomain == "":
11
+ domain = url.domain + "." + url.suffix
12
+ URL = "https://" + domain
13
+ else:
14
+ domain = url.subdomain + "." + url.domain + "." + url.suffix
15
+ URL = "https://" + domain
16
+ return domain, URL
17
+
18
+ def getData(url, email):
19
+ domain, URL = cleanURL(url)
20
+ code, status, webStatus, moreDetails = getStatus(URL)
21
+ if code.startswith("2"):
22
+ img, imgurl = getScreenshot(URL)
23
+ else:
24
+ img = "1366-768.png"
25
+ imgurl = "Website is down. No screenshot available."
26
+ email, downcount = saveDataSendMail(URL, email)
27
+ return domain, URL, code, status, webStatus, moreDetails, img, imgurl, email, downcount
28
+
29
+ def installGC():
30
+ OS = sys.platform
31
+ if OS == 'linux':
32
+ subprocess.run(['apt-get', 'update'])
33
+ subprocess.run(['apt-get', 'install', '-y', 'wget', 'unzip'])
34
+ subprocess.run(['wget', 'https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb'])
35
+ subprocess.run(['apt-get', 'install', '-y', './google-chrome-stable_current_amd64.deb'])
36
+ subprocess.run(['rm', 'google-chrome-stable_current_amd64.deb'])
37
+ subprocess.run(['apt-get', 'clean'])
38
+ subprocess.run(['sudo', 'apt-get', 'update'])
39
+ subprocess.run(['sudo', 'apt-get', 'install', '-y', 'wget', 'unzip'])
40
+ subprocess.run(['wget', 'https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb'])
41
+ subprocess.run(['sudo', 'apt-get', 'install', '-y', './google-chrome-stable_current_amd64.deb'])
42
+ subprocess.run(['sudo', 'rm', 'google-chrome-stable_current_amd64.deb'])
43
+ subprocess.run(['sudo', 'apt-get', 'clean'])
44
+ else:
45
  subprocess.run(['powershell', '-command', 'winget', 'install', 'Google.Chrome', '--force'])
saveDataSendMail.py CHANGED
@@ -1,133 +1,135 @@
1
- import psycopg2
2
- from psycopg2 import sql
3
- from dotenv import load_dotenv
4
- import os
5
- from fetchWebsiteInfo import dispStatus
6
- import tldextract
7
- import smtplib
8
- from email.mime.text import MIMEText
9
- import ssl
10
-
11
- load_dotenv()
12
- database = os.getenv('POSTGRES_DATABASE')
13
- user = os.getenv('POSTGRES_USER')
14
- password = os.getenv('POSTGRES_PASSWORD')
15
- host = os.getenv('POSTGRES_HOST')
16
- port = os.getenv('POSTGRES_DATABASE_PORT')
17
- endpoint_id = os.getenv('ENDPOINT_ID')
18
- sender_email = os.getenv('EMAIL_ADDRESS')
19
- sender_password = os.getenv('EMAIL_PASSWORD')
20
- smtp_server = os.getenv('SMTP_SERVER')
21
- smtp_port = os.getenv('SMTP_PORT')
22
-
23
- databaseConn = f"postgresql://{user}:{password}@{host}:{port}/{database}?options=endpoint%3D{endpoint_id}&sslmode=require"
24
-
25
- def insert(domain, email, status, downcount):
26
- try:
27
- conn = psycopg2.connect(databaseConn)
28
- cursor = conn.cursor()
29
- insertData = """
30
- INSERT INTO USERDATA (DOMAIN, EMAIL, STATUS, DOWNCOUNT)
31
- VALUES (%s, %s, %s, %s);
32
- """
33
- cursor.execute(insertData, (domain, email, status, downcount))
34
- conn.commit()
35
- print(f"Data for {domain} inserted successfully.")
36
- cursor.close()
37
- conn.close()
38
- except Exception as e:
39
- print(f"Error inserting data for {domain}: {e}")
40
-
41
-
42
- def get(domain):
43
- try:
44
- conn = psycopg2.connect(databaseConn)
45
- cursor = conn.cursor()
46
- getData = """
47
- SELECT STATUS, DOWNCOUNT FROM USERDATA WHERE DOMAIN = %s;
48
- """
49
- cursor.execute(getData, (domain,))
50
- existing_data = cursor.fetchone()
51
- if existing_data:
52
- return existing_data[1]
53
- else:
54
- return None
55
- cursor.close()
56
- conn.close()
57
- except Exception as e:
58
- print(f"Error retrieving data for {domain}: {e}")
59
- return None
60
-
61
- def update(domain, status, downcount):
62
- try:
63
- conn = psycopg2.connect(databaseConn)
64
- cursor = conn.cursor()
65
- updateData = """
66
- UPDATE USERDATA SET STATUS = %s, DOWNCOUNT = %s WHERE DOMAIN = %s;
67
- """
68
- cursor.execute(updateData, (status, downcount, domain))
69
- conn.commit()
70
- cursor.close()
71
- conn.close()
72
- print(f"Data for {domain} updated successfully.")
73
- except Exception as e:
74
- print(f"Error updating data for {domain}: {e}")
75
-
76
- def getData(EMAIL, URL, downcount):
77
- data = dispStatus(URL)
78
- if data[0].startswith("2") or data[0].startswith("3"):
79
- status = "Up"
80
- downcount = 0
81
- else:
82
- status = "Down"
83
- downcount += 1
84
- domainData = tldextract.extract(URL)
85
- if domainData.subdomain == "":
86
- domain = domainData.domain + "." + domainData.suffix
87
- else:
88
- domain = domainData.subdomain + "." + domainData.domain + "." + domainData.suffix
89
- email = EMAIL
90
- return domain, email, status, downcount
91
-
92
- def saveDataSendMail(URL, email):
93
- domain, email, status, downcount = getData(email, URL, 0)
94
- existing_downcount = get(domain)
95
-
96
- if existing_downcount is None:
97
- existing_downcount = 0
98
- if status == "Up":
99
- downcount = 0
100
- else:
101
- downcount = existing_downcount + 1
102
- sendMail(email, domain, status)
103
- insert(domain, email, status, downcount)
104
- else:
105
- if status == "Up":
106
- downcount = 0
107
- else:
108
- downcount = existing_downcount + 1
109
- sendMail(email, domain, status)
110
- update(domain, status, downcount)
111
- print(f"{domain} is currently {status}")
112
- return email, downcount,
113
-
114
- def sendMail(recipient_email, website_domain, status):
115
- """Sends an email notification to the user when the website is down."""
116
- subject = f"Website Alert: {website_domain} is currently {status}"
117
- body = f"The website {website_domain} is currently unavailable.\nPlease check it as soon as possible.\nIf you think this is a mistake, Contact Us."
118
-
119
- message = MIMEText(body, 'plain')
120
- message['Subject'] = subject
121
- message['From'] = sender_email
122
- message['To'] = recipient_email
123
-
124
- context = ssl.create_default_context()
125
-
126
- try:
127
- with smtplib.SMTP_SSL(smtp_server, smtp_port, context=context) as server:
128
- server.login(sender_email, sender_password)
129
- server.sendmail(sender_email, recipient_email, message.as_string())
130
- return f"Sent email notification for {website_domain} to {recipient_email}"
131
- except Exception as e:
132
- return f"Error sending email: {e}"
133
-
 
 
 
1
+ import psycopg2
2
+ from psycopg2 import sql
3
+ from dotenv import load_dotenv
4
+ import os
5
+ from getStatus import getStatus
6
+ import tldextract
7
+ import smtplib
8
+ from email.mime.text import MIMEText
9
+ import ssl
10
+
11
+ load_dotenv()
12
+ database = os.getenv('POSTGRES_DATABASE')
13
+ user = os.getenv('POSTGRES_USER')
14
+ password = os.getenv('POSTGRES_PASSWORD')
15
+ host = os.getenv('POSTGRES_HOST')
16
+ port = os.getenv('POSTGRES_DATABASE_PORT')
17
+ endpoint_id = os.getenv('ENDPOINT_ID')
18
+ sender_email = os.getenv('EMAIL_ADDRESS')
19
+ sender_password = os.getenv('EMAIL_PASSWORD')
20
+ smtp_server = os.getenv('SMTP_SERVER')
21
+ smtp_port = os.getenv('SMTP_PORT')
22
+
23
+ databaseConn = f"postgresql://{user}:{password}@{host}:{port}/{database}?options=endpoint%3D{endpoint_id}"
24
+
25
+ def insert(domain, email, status, downcount):
26
+ try:
27
+ conn = psycopg2.connect(databaseConn)
28
+ cursor = conn.cursor()
29
+ insertData = """
30
+ INSERT INTO USERDATA (DOMAIN, EMAIL, STATUS, DOWNCOUNT)
31
+ VALUES (%s, %s, %s, %s);
32
+ """
33
+ cursor.execute(insertData, (domain, email, status, downcount))
34
+ conn.commit()
35
+ print(f"Data for {domain} inserted successfully.")
36
+ except Exception as e:
37
+ print(f"Error inserting data for {domain}: {e}")
38
+ finally:
39
+ cursor.close()
40
+ conn.close()
41
+
42
+ def get(domain):
43
+ try:
44
+ conn = psycopg2.connect(databaseConn)
45
+ cursor = conn.cursor()
46
+ getData = """
47
+ SELECT STATUS, DOWNCOUNT FROM USERDATA WHERE DOMAIN = %s;
48
+ """
49
+ cursor.execute(getData, (domain,))
50
+ existing_data = cursor.fetchone()
51
+ if existing_data:
52
+ return existing_data[1]
53
+ else:
54
+ return None
55
+ except Exception as e:
56
+ print(f"Error retrieving data for {domain}: {e}")
57
+ return None
58
+ finally:
59
+ cursor.close()
60
+ conn.close()
61
+
62
+ def update(domain, status, downcount):
63
+ try:
64
+ conn = psycopg2.connect(databaseConn)
65
+ cursor = conn.cursor()
66
+ updateData = """
67
+ UPDATE USERDATA SET STATUS = %s, DOWNCOUNT = %s WHERE DOMAIN = %s;
68
+ """
69
+ cursor.execute(updateData, (status, downcount, domain))
70
+ conn.commit()
71
+ print(f"Data for {domain} updated successfully.")
72
+ except Exception as e:
73
+ print(f"Error updating data for {domain}: {e}")
74
+ finally:
75
+ cursor.close()
76
+ conn.close()
77
+
78
+ def getData(EMAIL, URL, downcount):
79
+ data = getStatus(URL)
80
+ if data[0].startswith("2") or data[0].startswith("3"):
81
+ status = "Up"
82
+ downcount = 0
83
+ else:
84
+ status = "Down"
85
+ downcount += 1
86
+ domainData = tldextract.extract(URL)
87
+ if domainData.subdomain == "":
88
+ domain = domainData.domain + "." + domainData.suffix
89
+ else:
90
+ domain = domainData.subdomain + "." + domainData.domain + "." + domainData.suffix
91
+ email = EMAIL
92
+ return domain, email, status, downcount
93
+
94
+ def saveDataSendMail(URL, email):
95
+ domain, email, status, downcount = getData(email, URL, 0)
96
+ existing_downcount = get(domain)
97
+
98
+ if existing_downcount is None:
99
+ existing_downcount = 0
100
+ if status == "Up":
101
+ downcount = 0
102
+ else:
103
+ downcount = existing_downcount + 1
104
+ sendMail(email, domain, status)
105
+ insert(domain, email, status, downcount)
106
+ else:
107
+ if status == "Up":
108
+ downcount = 0
109
+ else:
110
+ downcount = existing_downcount + 1
111
+ sendMail(email, domain, status)
112
+ update(domain, status, downcount)
113
+ print(f"{domain} is currently {status}")
114
+ return email, downcount
115
+
116
+ def sendMail(recipient_email, website_domain, status):
117
+ """Sends an email notification to the user when the website is down."""
118
+ subject = f"Website Alert: {website_domain} is currently {status}"
119
+ body = f"The website {website_domain} is currently unavailable.\nPlease check it as soon as possible.\nIf you think this is a mistake, Contact Us."
120
+
121
+ message = MIMEText(body, 'plain')
122
+ message['Subject'] = subject
123
+ message['From'] = sender_email
124
+ message['To'] = recipient_email
125
+
126
+ context = ssl.create_default_context()
127
+
128
+ try:
129
+ with smtplib.SMTP_SSL(smtp_server, smtp_port, context=context) as server:
130
+ server.login(sender_email, sender_password)
131
+ server.sendmail(sender_email, recipient_email, message.as_string())
132
+ return f"Sent email notification for {website_domain} to {recipient_email}"
133
+ except Exception as e:
134
+ return f"Error sending email: {e}"
135
+