├── Notify_Magnet.png ├── howtousepreview.gif ├── endpoints.py ├── regex_pattern_date.txt ├── notice.py ├── LICENSE.txt ├── .github ├── LICENSE.txt └── CODE_OF_CONDUCT.md ├── mftp.py ├── CODE_OF_CONDUCT.md ├── README.md ├── ntfy.py └── mailcopy.py /Notify_Magnet.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XylenSky/notify-magnet/HEAD/Notify_Magnet.png -------------------------------------------------------------------------------- /howtousepreview.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XylenSky/notify-magnet/HEAD/howtousepreview.gif -------------------------------------------------------------------------------- /endpoints.py: -------------------------------------------------------------------------------- 1 | # ERP Endpoints 2 | TPSTUDENT_URL = 'https://erp.iitkgp.ac.in/TrainingPlacementSSO/TPStudent.jsp' 3 | COMPANIES_URL = 'https://erp.iitkgp.ac.in/TrainingPlacementSSO/ERPMonitoring.htm?action=fetchData&jqqueryid=37&_search=false&nd=1448725351715&rows=20&page=1&sidx=&sord=asc&totalrows=50' 4 | NOTICEBOARD_URL = 'https://erp.iitkgp.ac.in/TrainingPlacementSSO/Notice.jsp' 5 | NOTICES_URL = 'https://erp.iitkgp.ac.in/TrainingPlacementSSO/ERPMonitoring.htm?action=fetchData&jqqueryid=54&_search=false&nd=1448884994803&rows=20&page=1&sidx=&sord=asc&totalrows=50' 6 | ATTACHMENT_URL = 'https://erp.iitkgp.ac.in/TrainingPlacementSSO/AdmFilePDF.htm?type=NOTICE&year={}&id={}' 7 | NOTICE_CONTENT_URL = 'https://erp.iitkgp.ac.in/TrainingPlacementSSO/ShowContent.jsp?year={}&id={}' 8 | 9 | # NTFY Endpoints 10 | SERVER_URL = 'http://10.105.34.28/' -------------------------------------------------------------------------------- /regex_pattern_date.txt: -------------------------------------------------------------------------------- 1 | \b.*?(\d{1,2}[a-z]{2} [A-Za-z]+ \d{4},? \d{1,2}[:.]\d{2} [APMapm]{2}).*?\b| 2 | \b.*?(\d{1,2}[\/.-]\d{1,2}[\/.-]\d{4},? \d{1,2}[:.]\d{2} [APMapm]{2}).*?\b| 3 | \b.*?(\d{1,2}[:.]\d{2} [APMapm]{2},? \d{1,2}[\/.-]\d{1,2}[\/.-]\d{4}).*?\b| 4 | \b.*?(\d{1,2}[a-z]{2} [A-Za-z]+,? \d{1,2}[:.]\d{2} [APMapm]{2}).*?\b| 5 | \b.*?(\d{1,2} [APMapm]{2},? \d{1,2}[-]\d{2}[-]\d{4}).*?\b| 6 | \b.*?(\d{1,2}[\/]\d{1,2}[\/]\d{4},? \d{1,2}[:.]\d{2} [APMapm]{2}).*?\b| 7 | \b.*?(\d{1,2}[:.]\d{2} [APMapm]{2},? \d{1,2}[a-z]{2} [A-Za-z]+ \d{4}).*?\b| 8 | \b.*?(\d{2}:\d{2} [APap][Mm], \d{1,2}(?:st|nd|rd|th) [A-Za-z]+, \d{4}).*?\b| 9 | \b.*?(\d{1,2} [APap][Mm], \d{1,2}(?:st|nd|rd|th) [A-Za-z]+ \d{4}).*?\b| 10 | \b.*?(\d{2}:\d{2} [APap][Mm], \d{1,2}(?:st|nd|rd|th) [A-Za-z]+, \d{4}).*?\b| 11 | \b.*?(\d{1,2}\.\d{2} [AP]M, \d{1,2} [A-Za-z]+ \d{4}).*?\b| 12 | \b.*?(\d{1,2}:\d{2} [APap][Mm], \d{1,2}-[A-Za-z]{3,9}-\d{2,4}).*?\b| 13 | \b.*?(\d{1,2}(?::|\.)?\d{0,2}\s*[APap][Mm],\s\d{1,2}\s\w+\s\d{4}).*?\b| 14 | -------------------------------------------------------------------------------- /notice.py: -------------------------------------------------------------------------------- 1 | import os 2 | import logging 3 | from endpoints import * 4 | import xml.etree.ElementTree as ET 5 | from bs4 import BeautifulSoup as bs 6 | 7 | def fetch(headers, session, ssoToken, lsnif): 8 | print('[FETCHING NOTICES]', flush=True) 9 | try: 10 | r = session.post(TPSTUDENT_URL, data=dict(ssoToken=ssoToken, menu_id=11, module_id=26), headers=headers) 11 | r = session.get(NOTICEBOARD_URL, headers=headers) 12 | r = session.get(NOTICES_URL, headers=headers) 13 | except Exception as e: 14 | logging.error(f" Failed to navigate to Noticeboard ~ {str(e)}") 15 | 16 | try: 17 | soup = bs(r.text, features="xml") 18 | xml = soup.prettify().encode('utf-8') 19 | root = ET.fromstring(xml) 20 | except Exception as e: 21 | logging.error(f" Failed to extract data from Noticeboard ~ {str(e)}") 22 | 23 | latest_index = get_latest_index(lsnif) 24 | logging.info(f" Latest Saved Notice Index ~ {latest_index}") 25 | 26 | notices = [] 27 | for row in root.findall('row'): 28 | id_ = row.find('cell[1]').text.strip() 29 | year = root.findall('row')[0].find('cell[8]').text.split('"')[1].strip() 30 | notice = { 31 | 'UID': f'{id_}_{year}', 32 | 'Time': row.find('cell[7]').text.strip(), 33 | 'Type': row.find('cell[2]').text.strip(), 34 | 'Subject': row.find('cell[3]').text.strip(), 35 | 'Company': row.find('cell[4]').text.strip(), 36 | } 37 | 38 | if int(id_) > latest_index: 39 | notices.append(notice) 40 | logging.info(f" [NEW NOTICE]: #{id_} | {notice['Type']} | {notice['Subject']} | {notice['Company']} | {notice['Time']}") 41 | else: 42 | break 43 | 44 | return notices 45 | 46 | 47 | def get_latest_index(lsnif): 48 | try: 49 | with open(lsnif, 'r') as file: 50 | file_content = file.read().strip() 51 | latest_index = int(file_content) 52 | except FileNotFoundError: 53 | latest_index = 0 54 | 55 | return latest_index 56 | 57 | 58 | def update_lsni(lsnif, notices, i): 59 | lsni = notices[-i]['UID'].split('_')[0] # Latest Sent Notice Index 60 | 61 | # Create file if it doesn't exist 62 | if not os.path.exists(lsnif): 63 | open(lsnif, 'w').close() 64 | 65 | # Save the value of Latest Sent Notice Index 66 | try: 67 | with open(lsnif, 'w') as file: 68 | file.write(lsni) 69 | except Exception as e: 70 | logging.error(f" Failed to Save Notice ~ #{lsni}") 71 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Custom License - No Commercial Use Without Written Permission 2 | 3 | Copyright (c) 2023, Rishabh Sonkar 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without modification, are permitted for non-commercial purposes only, provided that the following conditions are met: 7 | 8 | 1. Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer. 9 | 10 | 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions, and the following disclaimer in the documentation and/or other materials provided with the distribution. 11 | 12 | 3. Commercial use of this software, or any derivative works based on this software, is strictly prohibited without prior written permission from the copyright holder. 13 | 14 | 4. To request permission for commercial use, please contact the copyright holder at xylensky@proton.me. 15 | 16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 17 | 18 | For any code or components used from projects under the Apache License 2.0 or the BSD 2-Clause License, the terms and conditions of those respective licenses apply. 19 | 20 | mftp.py and notice.py are licensed as follows: 21 | 22 | BSD 2-Clause License 23 | 24 | Copyright (c) 2022, Arpit Bhardwaj 25 | All rights reserved. 26 | 27 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 28 | 29 | 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 30 | 31 | 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 32 | 33 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 34 | -------------------------------------------------------------------------------- /.github/LICENSE.txt: -------------------------------------------------------------------------------- 1 | Custom License - No Commercial Use Without Written Permission 2 | 3 | Copyright (c) 2023, Rishabh Sonkar 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without modification, are permitted for non-commercial purposes only, provided that the following conditions are met: 7 | 8 | 1. Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer. 9 | 10 | 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions, and the following disclaimer in the documentation and/or other materials provided with the distribution. 11 | 12 | 3. Commercial use of this software, or any derivative works based on this software, is strictly prohibited without prior written permission from the copyright holder. 13 | 14 | 4. To request permission for commercial use, please contact the copyright holder at [Your Contact Email]. 15 | 16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 17 | 18 | For any code or components used from projects under the Apache License 2.0 or the BSD 2-Clause License, the terms and conditions of those respective licenses apply. 19 | 20 | mftp.py and notice.py are licensed as follows: 21 | 22 | BSD 2-Clause License 23 | 24 | Copyright (c) 2022, Arpit Bhardwaj 25 | All rights reserved. 26 | 27 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 28 | 29 | 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 30 | 31 | 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 32 | 33 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 34 | -------------------------------------------------------------------------------- /mftp.py: -------------------------------------------------------------------------------- 1 | import env 2 | import mailcopy as mail 3 | import time 4 | import notice 5 | import requests 6 | import argparse 7 | import random 8 | from datetime import datetime 9 | import iitkgp_erp_login.erp as erp 10 | import logging 11 | 12 | global_var = 1 13 | 14 | def run_hold_session(): 15 | global_var = global_var + 1 16 | # Set up a loop to make the request periodically 17 | while not(global_var % 27): 18 | 19 | # Make the request after the delay 20 | url = "https://erp.iitkgp.ac.in/IIT_ERP3/holdSession.htm?rand_id=" 21 | 22 | with open(".session", 'r') as file: 23 | jsid = file.readline() 24 | ssotoken = file.readline() 25 | 26 | headers = { 27 | # 'Accept': 'application/xml, text/xml, */*; q=0.01', 28 | # 'Accept-Language': 'en-GB,en;q=0.5', 29 | # 'Connection': 'keep-alive', 30 | 'Cookie': f'ssoToken={ssotoken}; JSID#/TrainingPlacementSSO={jsid}', 31 | 'Referer': 'https://erp.iitkgp.ac.in/TrainingPlacementSSO/TPStudent.jsp', 32 | # 'Sec-Fetch-Dest': 'empty', 33 | # 'Sec-Fetch-Mode': 'cors', 34 | # 'Sec-Fetch-Site': 'same-origin', 35 | # 'Sec-GPC': '1', 36 | 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/51.0.2704.79 Chrome/51.0.2704.79 Safari/537.36', 37 | 'X-Requested-With': 'XMLHttpRequest', 38 | # 'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Brave";v="120"', 39 | # 'sec-ch-ua-mobile': '?0', 40 | # 'sec-ch-ua-platform': '"macOS"' 41 | } 42 | 43 | random_int = str(random.randint(10**14, (10**15)-1)) 44 | # print(random_int) 45 | response = requests.get(url+random_int, headers=headers) 46 | # Check the response 47 | 48 | if response.text == "SUCCESS": 49 | logging.info(f"Session hold request successful") 50 | else: 51 | # print(f"Session hold request failed with status code: {response.status_code}") 52 | logging.error(f" Request failed : {response.status_code} and response \n{response.text}\n" ) 53 | 54 | 55 | global_var = 1 56 | 57 | 58 | lsnif = "lsnif" 59 | headers = { 60 | 'timeout': '20', 61 | 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/51.0.2704.79 Chrome/51.0.2704.79 Safari/537.36', 62 | } 63 | session = requests.Session() 64 | 65 | parser = argparse.ArgumentParser(description='One stop mailing solution for CDC NoticeBoard at IIT KGP') 66 | parser.add_argument('--smtp', action="store_true", help='Use SMTP for sending the mails', required=False) 67 | parser.add_argument('--gmail-api', action="store_true", help='Use GMAIL API for sending the mails', required=False) 68 | args = parser.parse_args() 69 | 70 | 71 | 72 | while True: 73 | print(f"================ <<: {datetime.now()} :>> ================", flush=True) 74 | print('[ERP LOGIN]', flush=True) 75 | _, ssoToken = erp.login(headers, session, ERPCREDS=env, OTP_CHECK_INTERVAL=2, LOGGING=True, SESSION_STORAGE_FILE='.session') 76 | 77 | notices = notice.fetch(headers, session, ssoToken, lsnif) 78 | mails = mail.format_notice(notices, session) 79 | mail.send(mails, lsnif, notices) 80 | 81 | print("[PAUSED FOR 2 MINUTES]", flush=True) 82 | time.sleep(60) 83 | run_hold_session() 84 | time.sleep(60) 85 | run_hold_session() 86 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | xylensky@proton.me. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /.github/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | xylensky@proton.me. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
4 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
27 | Key Features • 28 | How To Use • 29 | Download • 30 | Known Issues • 31 | Credits • 32 | License 33 |
34 | 35 |  36 | 37 | ## Vision 38 | 39 | The primary purpose of this service is to expeditiously inform and remind students participating in CDC internship and placement activities about critical CDC notices. Any inappropriate utilization of this service for unethical purposes may result in disciplinary actions. 40 | 41 | ## Known Issues 42 | 43 | - Date formatting issue: Dates like "17/09/2023, 11.59 PM" may be recognized as "17/09/2023, 11.00 PM" due to non-standard formatting. 44 | - Service Restricted to Campus Network: This service can only be accessed within the campus network, and you will not receive notifications when using mobile data. 45 | - Notification Priority: Notification order may depend on priority when a large number of notifications are missed. 46 | - Expiring Attachments: Attachment links have an expiration time; please download them promptly to avoid loss. 47 | - Cache Limits: Notifications are cached for a limited time; if you exceed this limit (while not connected to the campus network), some notifications may not be delivered. 48 | - Allow background running and auto launch for this application; otherwise, notifications will be missed or delayed. 49 | - Cache Deletion Caution: Avoid clearing the app's cache or using phone manager tools, as it may delete downloaded PDFs of existing messages. 50 | - Mobile Apps: The Android and iPhone apps are not developed by us; if some features don't work, it's beyond our control. 51 | - Restrictions: The service provider disclaims any liability for actions or conduct with the intent of interfering with or obstructing the service's functionality through unethical means. 52 | - Official Directive: Official representatives' instructions may lead to service discontinuation, possibly without notice. 53 | - Infrastructure Issues: Power or network infrastructure failures may affect the service. 54 | 55 | ## Key Features 56 | 57 | - Five Priority Levels: Notifications have five priority levels; most are set to the highest priority. Customize ringtones and notification settings (notify even in DND mode) accordingly. 58 | - No data is collected by the mobile app, and the current setup doesn't even include any third party in the loop to send the notification; notifications are sent directly to your phone via Local Area Network. 59 | 60 | ## Amazing Features 61 | 62 | - Scheduled Notifications: Schedule notifications for recognized dates and times, sent 30 minutes before deadlines to ensure you never miss important events. 63 | - Separate Channels: Internship, Placement, and Error notifications are delivered through separate channels, allowing you to subscribe to error notifications for missed updates. 64 | 65 | - Cross-Platform: Compatible with Android, iOS. 66 | 67 | ## How To Use 68 | 69 | **For Android and iOS:** 70 | 71 | 1. Connect to the any of the campus network. 72 | 2. Open the application. 73 | 3. Click on the "+" to add a topic (internship, placement, error) [case-sensitive] [do not put any spaces]. 74 | 4. Select "Use Another Server." 75 | 5. Enter the current server address: `http://10.105.34.28` 76 | 6. Repeat the above steps for error notifications as well. 77 | 7. You can directly open this URL in your browser as well to see all the notifications. 78 | 8. If you encounter issues, check back here for any updated IP addresses or port numbers. 79 | 9. If you're still experiencing issues, please fill out our [issue reporting form](https://forms.gle/B55UbUkG6fv7246i9). 80 | 81 | Current address: 82 | ``` 83 | http://10.105.34.28 84 | ``` 85 | 86 | 87 | > **Note:** 88 | > All the claims about the application may change based on their owner's consent. 89 | > We kindly request users to carefully read and adhere to the aforementioned risks and conditions associated with this service before proceeding with its use. 90 | 91 | ## Download 92 | 93 | You can download the app from the following platforms: 94 | - **Play Store**: [](https://play.google.com/store/apps/details?id=io.heckel.ntfy&pcampaignid=web_share) 95 | - **App Store**: [](https://apps.apple.com/in/app/ntfy/id1625396347) 96 | 97 | ## Join Us 98 | 99 | If you are excited about this project, you can contribute or encourage your fellow students to maintain and enhance it, making it even more feature-rich. [Email us](mailto:xylensky@proton.me). 100 | 101 | ## Credits 102 | 103 | This software utilizes the following open-source packages: 104 | 105 | - [MFTP](https://github.com/metakgp/mftp) 106 | - [NTFY](https://github.com/binwiederhier/ntfy) 107 | 108 | ## License 109 | 110 | Made with ❤️ for KGP 111 | 112 | The project is dual-licensed under the Custom License. To know more, check out the corresponding project licenses used here for more information. 113 | -------------------------------------------------------------------------------- /ntfy.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from time import sleep 3 | import base64 4 | from endpoints import SERVER_URL 5 | from env import DEBUG, CHANNEL1, CHANNEL2 6 | import os 7 | import logging 8 | 9 | 10 | if DEBUG: 11 | CHANNEL1 = "o13srdbtydg55Sjc3h_testing" 12 | CHANNEL2 = "xhoxnvpun6lvjj23er_debug" 13 | 14 | 15 | def send_to_ntfy(message): 16 | url = SERVER_URL + message['Type'].lower() 17 | token = os.getenv('MAINSTREAM_TOKEN') 18 | if DEBUG: 19 | url = SERVER_URL + CHANNEL1 20 | token = os.getenv('TESTING_TOKEN') 21 | 22 | try: 23 | more_headers = beautify_message(message['Subject'].strip()) 24 | 25 | headers={ 26 | "Authorization": f'Bearer {token}', 27 | "Title": message['Title'].strip(), 28 | "Message": encode_rfc_2047_base64(message['body']), 29 | "Tags": more_headers['Tags'], 30 | "Priority": more_headers['Priority'], 31 | # "Icon": more_headers['Icon'], 32 | } 33 | 34 | if 'attachment' in message: 35 | headers["Filename"] = "notice.pdf" 36 | details = requests.put(url, 37 | data=message['attachment'], 38 | headers=headers 39 | ) 40 | else: 41 | details = requests.put(url, 42 | headers=headers 43 | ) 44 | 45 | details.raise_for_status() 46 | 47 | 48 | except Exception as e: 49 | logging.error(f" Failed to Send Notice3 : {message['Subject']} ~ {str(e)}") 50 | message['Title'] = f" Failed to Send : {message['Title']}" 51 | error_ntfy(message) 52 | 53 | 54 | def schedule_ntfy(message): 55 | url = SERVER_URL + message['Type'].lower() 56 | token = os.getenv('MAINSTREAM_TOKEN') 57 | if DEBUG: 58 | url = SERVER_URL + CHANNEL1 59 | token = os.getenv('TESTING_TOKEN') 60 | 61 | try: 62 | headers={ 63 | "Authorization": f'Bearer {token}', 64 | "Title": message['Title'].strip(), 65 | "Message": encode_rfc_2047_base64(message['body']), 66 | "Tags": 'hourglass_flowing_sand,bell', 67 | "Priority": '4', 68 | 'Delay': message['Delay'], 69 | # "Icon": more_headers['Icon'], 70 | } 71 | 72 | if 'attachment' in message: 73 | headers["Filename"] = "notice.pdf" 74 | details = requests.put(url, 75 | data=message['attachment'], 76 | headers=headers 77 | ) 78 | 79 | else: 80 | details = requests.put(url, 81 | headers=headers 82 | ) 83 | details.raise_for_status() 84 | 85 | except Exception as e: 86 | logging.error(f" Failed to Send Notice3 : {message['Subject']} ~ {str(e)}") 87 | message['Title'] = f" Failed to Schedule : {message['Title']}" 88 | error_ntfy(message) 89 | 90 | 91 | ## NO ERROR ZONE EXPLICITY CHECK 92 | def error_ntfy(message): 93 | url = SERVER_URL + CHANNEL2 94 | token = os.getenv('ERROR_TOKEN') 95 | if DEBUG: 96 | url = SERVER_URL + CHANNEL2 97 | token = os.getenv('DEBUG_TOKEN') 98 | 99 | try: 100 | details = requests.put(f"{url}", 101 | data="There is an error in sending the notice please check the notice board", 102 | headers={ 103 | "Authorization": f'Bearer {token}', 104 | "Title": encode_rfc_2047_base64(message['Title'].strip()), #remove whitespace error 105 | "Tags": "warning,lady_beetle", 106 | "Priority": "5", 107 | # "Icon": "https://styles.redditmedia.com/t5_32uhe/styles/communityIcon_xnt6chtnr2j21.png", 108 | } 109 | ) 110 | details.raise_for_status() 111 | 112 | except Exception as e: 113 | logging.error(f" Failed to Send Notice4 : {message['Subject']} ~ {str(e)}") 114 | sleep(120) 115 | 116 | try: 117 | details = requests.put(f"{url}", 118 | data="There is an error in sending the notice please check the notice board", 119 | headers={ 120 | "Authorization": f'Bearer {token}', 121 | "Title": encode_rfc_2047_base64(message['Title'].strip()), #remove whitespace error 122 | "Tags": "warning,lady_beetle", 123 | "Priority": "5", 124 | # "Icon": "https://styles.redditmedia.com/t5_32uhe/styles/communityIcon_xnt6chtnr2j21.png", 125 | } 126 | ) 127 | details.raise_for_status() 128 | 129 | except Exception as e: 130 | logging.error(f" Failed to Send Notice5 : {message['Subject']} ~ {str(e)}") 131 | 132 | 133 | 134 | def beautify_message(subject): 135 | headers = {} 136 | if subject == 'PPO': 137 | headers['Priority'] = '3' 138 | headers['Tags'] = 'love_letter' 139 | headers['Icon'] = '❤️' 140 | 141 | elif subject == 'Urgent': 142 | headers['Priority'] = '5' 143 | headers['Tags'] = 'exclamation, stop_sign' 144 | headers['Icon'] = '🚨' 145 | 146 | elif subject == 'PPT/Workshop/Seminars etc': 147 | headers['Priority'] = '2' 148 | headers['Tags'] = 'popcorn' 149 | headers['Icon'] = '📊' 150 | 151 | elif subject == 'Result': 152 | headers['Priority'] = '4' 153 | headers['Tags'] = 'bowing_man,cup_with_straw' 154 | headers['Icon'] = '✅' 155 | 156 | elif subject == 'Schedule': 157 | headers['Priority'] = '5' 158 | headers['Tags'] = 'calendar' 159 | headers['Icon'] = '📅' 160 | 161 | elif subject == 'CV Submission': 162 | headers['Priority'] = '5' 163 | headers['Tags'] = 'briefcase' 164 | headers['Icon'] = '📄' 165 | 166 | elif subject == 'Shortlist': 167 | headers['Priority'] = '5' 168 | headers['Tags'] = 'chart_with_upwards_trend' 169 | headers['Icon'] = '📋' 170 | 171 | elif subject == 'Postponement': 172 | headers['Priority'] = '5' 173 | headers['Tags'] = 'alarm_clock,arrow_forward' 174 | headers['Icon'] = 'ℹ️' 175 | 176 | 177 | else: 178 | headers['Priority'] = '5' 179 | headers['Tags'] = 'arrow_forward' 180 | headers['Icon'] = 'ℹ️' 181 | 182 | return headers 183 | 184 | 185 | def encode_rfc_2047_base64(input_string): 186 | # Encode the input string to bytes using UTF-8 and then to Base64 187 | base64_encoded = base64.b64encode(input_string.encode('utf-8')).decode('ascii') 188 | 189 | # Format the RFC 2047 string 190 | rfc2047_encoded = f'=?UTF-8?B?{base64_encoded}?=' 191 | 192 | return rfc2047_encoded 193 | 194 | # def raise_error(message="An error occurred"): 195 | # raise Exception(message) 196 | -------------------------------------------------------------------------------- /mailcopy.py: -------------------------------------------------------------------------------- 1 | import re 2 | import logging 3 | from ntfy import send_to_ntfy, error_ntfy, schedule_ntfy 4 | from bs4 import BeautifulSoup as bs 5 | from endpoints import NOTICE_CONTENT_URL, ATTACHMENT_URL 6 | from notice import update_lsni, get_latest_index 7 | import ntfy 8 | import dateutil.parser 9 | import datetime 10 | import copy 11 | from time import sleep 12 | 13 | 14 | def send(mails, smtp, gmail_api, lsnif, notices): 15 | if mails: 16 | print(f"[SENDING MAILS]", flush=True) 17 | for i, mail in enumerate(mails, 1): 18 | if has_idx_mutated(lsnif, notices, i): 19 | logging.error(f" Mutated index found ~ {i}") 20 | # break 21 | 22 | try: 23 | send_to_ntfy(mail) 24 | logging.info(f" [MAIL SENT] ~ {mail['Subject']}") 25 | update_lsni(lsnif, notices, i) 26 | except Exception as e: 27 | logging.error(f" Failed to Send Mail1 : {mail['Subject']} ~ {str(e)}") 28 | mail['Title'] = f" Failed to Send Notice : {mail['Title']}" 29 | error_ntfy(mail) 30 | sleep(.1) 31 | 32 | 33 | def format_notice(notices, session): 34 | if notices: print('[FORMATTING MAILS]', flush=True) 35 | 36 | mails = [] 37 | i = 0 38 | for notice in (notices): 39 | id_, year = notice['UID'].split('_') 40 | message = {} 41 | message['Type'] = notice['Type'] 42 | message['Subject'] = notice['Subject'] 43 | message["Title"] = f"#{id_} | {notice['Subject']} | {notice['Company']}" 44 | 45 | try: 46 | body = parseBody(session, year, id_) 47 | except Exception as e: 48 | logging.error(f" Failed to parse mail body ~ {str(e)}") 49 | message['Title'] = f"Failed to Send : {message['Subject']}" 50 | error_ntfy(message) 51 | continue 52 | 53 | lines = body.split('\n') # Split the text into lines 54 | # Take a slice starting from the fourth line 55 | cleaned_text = '\n'.join(lines[6:]) 56 | processed_text = '\n'+cleaned_text+'\n' 57 | 58 | 59 | body = cleaned_text.rstrip() + ' ' + re.sub(r'\s+', ' ', notice['Time']) 60 | 61 | message['body']=body 62 | 63 | 64 | # Handling attachment 65 | try: 66 | attachment = parseAttachment(session, year, id_) 67 | if len(attachment) == 0 and ('Please find attached' in processed_text or 'PFA' in processed_text): 68 | z = 0 69 | while len(attachment) == 0 and z < 3: 70 | sleep(30) 71 | attachment = parseAttachment(session, year, id_) 72 | z = z + 1 73 | logging.info(f" Waited till to parse mail attachment ~ {z}") 74 | 75 | except Exception as e: 76 | logging.error(f" Failed to parse mail attachment ~ {str(e)}") 77 | message['Title'] = f" Failed to Send : {message['Title']}" 78 | error_ntfy(message) 79 | continue 80 | 81 | if len(attachment) != 0: 82 | message['attachment'] = attachment 83 | logging.info(f" [PDF ATTACHED] On notice #{id_} of length ~ {len(attachment)}") 84 | 85 | 86 | if notice['Subject'].strip() not in ['PPO', 'Result']: # No reminders for the PPO and Result 87 | message_remainder = copy.deepcopy(message) 88 | try: 89 | dates = extract_date_time_formats(processed_text.replace('noon','PM')) 90 | # print('message data', dates) 91 | if dates: 92 | message['body'] += '\n' 93 | dates = sorted(dates) 94 | logging.info(f" Dates parsed On notice #{id_} ~ {dates}") 95 | for date in dates: 96 | date_for_rem = date - datetime.timedelta(minutes=30) 97 | remainder_date = int(datetime.datetime.timestamp(date_for_rem)) 98 | 99 | if date - datetime.timedelta(hours=12) > datetime.datetime.now(): 100 | message_remainder['Title'] = "Remainder "+ date.strftime("%I:%M %p")+" for Notice"+ message['Title'] 101 | message_remainder['Delay'] = f'{remainder_date}' 102 | try: 103 | # schedule_ntfy(message_remainder) 104 | human_readable_format = "%A, %d %b %Y at %I:%M %p IST" 105 | message['body'] += f'\nRemainder is set for {date.strftime(human_readable_format)}' 106 | logging.info(f" Remainder is set for the date for notice #{id_} ~ {date.strftime(human_readable_format)}") 107 | except Exception as e: 108 | message['body'] += '\nSetting a Reaminder for {date} is failed' 109 | logging.error(f" Failed to set the remainder ~ {str(e)}") 110 | 111 | except Exception as e: 112 | message['body'] += '\n\nSetting a Remainder for any date is failed' 113 | logging.error(f" Failed to set the remainder ~ {str(e)}") 114 | # continue // not required not necessary element of original message 115 | 116 | mails.append(message) 117 | 118 | return mails 119 | 120 | 121 | def has_idx_mutated(lsnif, notices, i): 122 | lidx_from_file = get_latest_index(lsnif) # Latest Index from File 123 | cidx_from_to_send_mails = int(notices[-i]['UID'].split('_')[0]) # Current Index from to send mails 124 | difference_in_idx = cidx_from_to_send_mails - lidx_from_file 125 | 126 | if difference_in_idx != 1: 127 | logging.error(f" Trying to send mail #{cidx_from_to_send_mails} while latest in database is #{lidx_from_file}") 128 | mail = {} 129 | mail['Subject'] = 'Missing Notice' 130 | mail["Title"] = f"#{lidx_from_file+1} | {mail['Subject']}" 131 | mail['body'] = 'Notice not found or missing' 132 | error_ntfy(mail) 133 | return True 134 | 135 | return False 136 | 137 | 138 | def parseBody(session, year, id_): 139 | content = session.get(NOTICE_CONTENT_URL.format(year, id_)) 140 | content_html = bs(content.text, 'html.parser') 141 | content_html_div = bs.find_all(content_html, 'div', {'id': 'printableArea'})[0] 142 | body = content_html_div.decode_contents(formatter='html') 143 | 144 | soup = bs(body, 'html.parser') 145 | 146 | # Convert the soup to string with appropriate formatting 147 | body = soup.get_text(separator='\n', strip=True) 148 | 149 | return body 150 | 151 | 152 | def parseAttachment(session, year, id_): 153 | stream = session.get(ATTACHMENT_URL.format(year, id_), stream=True) 154 | attachment = b'' 155 | for chunk in stream.iter_content(4096): 156 | attachment += chunk 157 | 158 | return attachment 159 | 160 | 161 | def extract_date_time_formats(text): 162 | # Define a regular expression pattern to match various date and time formats 163 | with open('regex_pattern_date.txt', 'r') as file: 164 | pattern = file.read() 165 | 166 | matches = re.findall(pattern, text) 167 | 168 | extracted_formats = [value for match in matches for value in match if value] 169 | dates = [] 170 | for date in extracted_formats: 171 | try: 172 | dates.append(dateutil.parser.parse(date, dayfirst=True)) 173 | except ValueError: 174 | try: 175 | dates.append(extra_date_parser(date)) 176 | except ValueError: 177 | logging.error(f" This date parser need to be added ~ {date}") 178 | continue 179 | 180 | extracted_formats = set(dates) 181 | unique_dates = list(extracted_formats) 182 | 183 | # print(unique_dates, flush=True) 184 | 185 | return unique_dates 186 | 187 | 188 | def extra_date_parser(date_str): 189 | """ 190 | Parses a date string using a list of possible date formats. 191 | 192 | Args: 193 | date_str (str): The date string to be parsed. 194 | 195 | Returns: 196 | datetime: A datetime object representing the parsed date and time. 197 | 198 | Raises: 199 | ValueError: If the date string cannot be parsed with any of the specified formats. 200 | """ 201 | date_formats = [ 202 | "%d.%m.%Y, %I.%M %p", 203 | # "%m/%d/%Y, %I.%M %p", 204 | # "%Y-%m-%d, %H:%M:%S", 205 | "%dth %B %Y, %I.%M %p" 206 | ] 207 | 208 | parsed_date = None 209 | 210 | for format in date_formats: 211 | try: 212 | parsed_date = datetime.datetime.strptime(date_str, format) 213 | break # If parsing succeeds, exit the loop 214 | except ValueError: 215 | continue # If parsing fails, try the next format 216 | 217 | if parsed_date: 218 | return parsed_date 219 | else: 220 | raise ValueError("Unable to parse the date") 221 | 222 | def raise_error(message="An error occurred"): 223 | raise Exception(message) 224 | --------------------------------------------------------------------------------