Exemple #1
0
 def start_chat(self):
     self.__client_name = self.__name.get().strip('\n').strip(' ')
     client_pass = self.__password.get().strip('\n').strip(' ')
     self.__my_cursor.execute(
         "SELECT * FROM users WHERE name=%s AND Password=%s",
         (self.__client_name, client_pass))
     msg = self.__my_cursor.fetchone()
     if client_pass is not None and self.__client_name is not None:
         if not msg:
             Notification('the user doesn\'t exist').start()
             return
         self.__my_cursor.execute(
             "SELECT connected FROM users WHERE name=%s AND Password=%s",
             (self.__client_name, client_pass))
         msg = self.__my_cursor.fetchone()
         if msg[0] == 'True':
             Notification('the user already connected to the chat').start()
             return
         else:
             sqlf = "UPDATE users SET connected='True' WHERE name=%s AND Password=%s"
             self.__my_cursor.execute(sqlf,
                                      (self.__client_name, client_pass))
             self.__my_database.commit()
             name_len = len(self.__client_name)
             self.__client_name = str(name_len) + self.__client_name
         try:
             Chat(Host, Port, self.__client_name, self.__window,
                  self.__start)
         except:
             Notification('The server is currently unavailable').start()
             sql = "UPDATE users SET connected='False' WHERE name=%s "
             self.__my_cursor.execute(sql, (self.__client_name[1:], ))
             self.__my_database.commit()
Exemple #2
0
    def startNotificationTest(self):
        texte = [
            "Vor langer langer Zeit lebte ein Tux in Österreich und hatte keine Windows daheim",
            "Quod erat demonsdrandum",
            "Einer der nichts weiß und nicht weiß das er nichts weiß, weiß weniger als einer der weiß dass er nichts weiß"
        ]
        """ start showing Notification within a Thread for non blocking """
        # creates the Notification Dialog
        n = Notification_Core()
        notification = Notification(n)
        notification.showInformation(texte[0])

        n = Notification_Core()
        notification = Notification(n)
        notification.setDemo()
        notification.showError(texte[1])

        n = Notification_Core()
        notification = Notification(n)
        notification.setDemo()
        notification.showWarning(texte[2])

        n = Notification_Core()
        notification = Notification(n)
        notification.setDemo()
        notification.showSuccess(texte[0])
Exemple #3
0
 def run(self):
     config = Config('./credentials.properties')
     exchangeName = "test"
     notification = Notification(config, exchangeName)
     interval = 10  #this is the time interval in second where the system load is check (i.e., control Interval)
     loadDetectionInstance = PMLoadDetection(interval, notification)
     loadDetectionInstance.start()
Exemple #4
0
def create_notification(sender, instance, created, **kwargs):
    """This receiver creates notifications whenever a comment is saved
  """
    if created:
        parent = instance.content_object
        # Some Events don't have authors. In such cases, no need to create notifications.
        try:
            user = parent.author
        except:
            user = None

        if user and not user == instance.user:
            parent_comment = instance.parent
            # If this is a comment alert the commenter instead
            if parent_comment:
                notify_type = "comment"
                user = parent_comment.user
            else:
                notify_type = parent.type_name().lower()
            read = NotificationRead.objects.get(user=user)
            notify = Notification(user=user,
                                  author=instance.user,
                                  content_object=parent,
                                  time=datetime.datetime.utcnow(),
                                  notification_type=notify_type)
            notify.save()
            read.unread = read.unread + 1
            read.save()
 def run(self):
     logger.info("Thread of TriggerHandler initialized")
     count = 0
     try:
         while True:
             count += 1
             time.sleep(self.sleepTime)
             logger.debug(f"Checking, Run: {count}")
             for i in self.triggers.values():
                 if not i.activated:
                     continue
                 ticker = yf.Ticker(i.symbol)
                 logging.debug(f"Obtained Ticker, {i.symbol}")
                 information = ticker.info
                 logging.debug(
                     f"Checking ticker.info, {information['previousClose']} for stock {information['longName']}"
                 )
                 price = None
                 if information['ask'] == 0:
                     price = float(information['previousClose'])
                 else:
                     price = float(information['ask'])
                 if i.relation(price, float(i.value)):
                     Notification(i, information['longName'])
                     if i.autoDeactivateOnTrigger:
                         i.activated = False
     except:  # noqa: E722
         exc_type, exc_obj, exc_tb = sys.exc_info()
         fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
         logger.error("ERROR! Type: {}, File: {}, Line: {}".format(
             exc_type, fname, exc_tb.tb_lineno))
Exemple #6
0
async def on_message(message):
    fmt = "%H:%M:%S %m/%d/%Y"
    if message.author == client.user:  #client.user is remindbot.
        return  #avoid infinite loop.
    #$remind time date
    #time 00:00-23:59
    #date MM/DD/YYYY
    if message.content.startswith('$help'):
        await message.channel.send(
            'Syntax: \n $remind Hour:Min Month/Date/Year Meeting_Title')
        await message.channel.send(
            'All times are in PST, and Hours are recorded from 0 to 24. React to RemindBot\'s reply to sign up for the event.'
        )
    if message.content.startswith('$remind'):
        splitStr = []
        splitStr = message.content.split(" ")
        #print(splitStr)
        time = splitStr[1].split(
            ":")  # Get Time divided into a list 0:Hours 1:Min
        date = splitStr[2].split(
            "/")  # Get Date divided into a list 0:Months 1:Day 2:Year
        if int(time[0]) > 23 or int(time[0]) < 0 or int(time[1]) < 0 or int(
                time[1]) > 59 or int(date[0]) > 12 or int(date[0]) < 1:
            await message.channel.send('Bad format')
            return
        time_object_current = datetime.now(timezone('US/Pacific'))
        time_object_current_new = time_object_current  #.replace(second = 0)
        current_time = time_object_current_new.strftime(fmt)
        print("Current time: ", current_time)
        #splitStr[1] += ":00" + splitStr[2]
        #print(splitStr[1])
        print(time)
        print(date)
        time_object_user = datetime(int(date[2]),
                                    int(date[0]),
                                    int(date[1]),
                                    hour=int(time[0]),
                                    minute=int(time[1]),
                                    tzinfo=timezone('US/Pacific'))
        user_time = time_object_user.strftime(fmt)
        print("User Time: ", user_time)
        time = (time_object_user -
                time_object_current_new).total_seconds() + 420
        print(time)
        #t = #Timer(time, #method_name_here)#
        #t.start()
        title = " "
        s = title.join(splitStr[3:])
        bot = await message.channel.send(" ***" + s + "*** " +
                                         ' Meeting scheduled at: ' + user_time)
        await bot.add_reaction("\N{THUMBS UP SIGN}")
        #time_funcs.sleep(5)
        print("TITLE:", s)
        print(bot.id)
        print(message.id)
        noti = Notification(s, time, [], bot)
        notificationDict[bot.id] = noti
        print(notificationDict)
        await noti.mention_ping()
Exemple #7
0
 def change_password(self):
     password = ask_string('Password', 'Enter your new password')
     if password is not None:
         password = password.strip()
         if not password or not password.isalnum():
             Notification('invalid password').start()
             return
         self.__d.get_my_cursor().execute('UPDATE users SET password="******" WHERE name=%s', (self.__me[1:],))
         Info('password has been changed successfully to '+password).start()
 def fset(self, value):
     old_value = self._percent_complete
     self._percent_complete = value
     notification = Notification(message=NOTIFICATIONS[1],
                                 sender=self,
                                 user_info=dict(
                                     old_percentage=old_value,
                                     new_percentage=value))
     self.notification_center.post_notification(notification)
Exemple #9
0
 def testPostNotification_empty_message(self):
     self.connection = db_connect()
     self.user = login(self.connection, '*****@*****.**', 'BlackInk')
     notif = Notification()
     try:
         post_notification(self.user, self.connection, notif)
     except ValueError:
         self.failstate = True
     self.assertTrue(self.failstate)
 def post_notification_with_info(self, message, sender, user_info=None):
     """
     TODO: Docstring for post_notification_with_info
     
     @param message TODO
     @param sender TODO
     @param user_info TODO
     """
     self.post_notification(Notification(message, sender, user_info))
 def fset(self, value):
     old_value = self._percent_complete
     if value == old_value:
         # Do not update or send a notification if nothing has changed
         return
     self._percent_complete = value
     notification = Notification(message=NOTIFICATIONS[1],
                                 sender=self,
                                 user_info=dict(old_percentage=old_value, new_percentage=value))
     self.notification_center.post_notification(notification)
    def __run_daemon(self, TEST_MODE: bool = False):
        # initiaing BatteryMonitor
        try:
            monitor = BatteryMonitor(TEST_MODE)
        except subprocess.CalledProcessError as e:
            # initiaing Notification
            notification = Notification("acpi")
            time.sleep(3)
            del notification
            self.__quit()

        # initiaing Notification
        notification = Notification("success")
        time.sleep(3)
        notification.show_specific_notifications(monitor)
        while True:
            if monitor.is_updated():
                notification.show_specific_notifications(monitor)
            time.sleep(3)
Exemple #13
0
 def testPostNotification(self):
     self.connection = db_connect()
     self.user = login(self.connection, '*****@*****.**', 'BlackInk')
     self.failstate = False
     notif = Notification('', 'GOOGL', 0.00, 'Hello World')
     try:
         key = post_notification(self.user, self.connection, notif)
     except ValueError:
         self.failstate = True
     self.assertFalse(self.failstate)
     del_notification(self.user, self.connection, key['name'])
Exemple #14
0
    def setUp(self):
        self.student = User("user", "password", 1)
        self.lecture = LectureTopic(1, "L1", "author", "Lecture", "info")
        self.comment = Comment(1, "author", "info", 2, self.lecture.getLTid())
        self.subscribe = Subscription(1, self.lecture.getLTid(),
                                      self.student.getUid())
        self.notify = Notification(1, self.subscribe.getSid())

        self.db_fd, app.app.config['DATABASE'] = tempfile.mkstemp()
        app.app.testing = True
        self.app = app.app.test_client()
        with app.app.app_context():
            app.init_db()
Exemple #15
0
    def __init__(self,data,dataManager,monitor):

        self.__dataLogger = data
        self.__databaseManager = dataManager
        self.__monitor = monitor
        self.__notifier = Notification(self.__databaseManager)
        
        self.__temperature = self.__dataLogger.getTemperature()
        self.__humidity = self.__dataLogger.getHumidity()
        self.__minTemperature = self.__monitor.getMinTemperature()
        self.__maxTemperature = self.__monitor.getMaxTemperature()
        self.__minHumidity = self.__monitor.getMinHumidity()
        self.__maxHumidity = self.__monitor.getMaxHumidity()
 def fset(self, value):
     value = value.upper()
     if(value == self._status):
         # Do not update or send a notification if nothing has changed
         return
     if(value in STATUS_STRINGS):
         old_value = self._status
         self._status = value
         notification = Notification(message=NOTIFICATIONS[0],
                                     sender=self,
                                     user_info=dict(old_status=old_value, new_status=value))
         self.notification_center.post_notification(notification)
     else:
         raise KeyError('Status (%s) unknown. Use one of %s.' % (value, STATUS_STRINGS))
Exemple #17
0
    def sql_retrieve(conn, searchfield=None, searchval=None):
        conn.row_factory = sqlite3.Row
        if searchfield:
            cur = conn.execute(
                'SELECT * FROM Notification WHERE "{}"="{}"'.format(
                    searchfield, searchval))
        else:
            cur = conn.execute('SELECT * from Notification')

        # construct the object
        results = []
        for tablerow in cur.fetchall():
            newobj = Notification(tablerow['Nid'], tablerow['subscription'])
            results.append(newobj)
        return results
Exemple #18
0
 def testDeleteNotification(self):
     self.connection =db_connect()
     self.user = login(self.connection, '*****@*****.**', 'BlackInk')
     self.failstate = False
     notif = Notification('', 'GOOGL', 0.00, 'Hello World')
     key= post_notification(self.user, self.connection, notif)
     notifList = pull_notifications(self.user, self.connection)
     self.assertNotEqual(notifList, None)
     for i in notifList:
         if i == key['name']:
             try:
                 del_notification(self.user, self.connection, i)
             except:
                 self.failstate = True
             self.assertFalse(self.failstate)
             break
Exemple #19
0
def main():
    notification = Notification()
    command = input()

    while command.split(' ')[0] != 'EXIT':

        if command.split(' ')[0] == 'SEND':
            notification.set_message(command.split(' ', 2)[2])
            notification.set_state(States[command.split(' ')[1]])
            notifier.send_message(notification, States[command.split(' ')[1]])

        command = input()

    notification.set_message(command)
    notifier.send_message(notification, 0)
    open("legitnetwork.txt", "w").close()
Exemple #20
0
def postComment(type, form, LTid):
    body = form.Body.data
    # When creating a new comment the 0 for the id is just a place holder because when put into the database we will auto increment the id
    newPost = Comment(0, session['user_id'], body, 0, LTid)
    persist(newPost)
    subscriptions = retrieve(Subscription, "LTid", LTid)

    for subscription in subscriptions:
        newNotification = Notification(0, subscription.getSid())
        persist(newNotification)

    flash('Comment Created', 'success')
    if type == 'Topic':
        return redirect(url_for("topic_discussion", id = LTid))
    elif type == 'Lecture':
        return redirect(url_for("lecture_discussion", id = LTid))
Exemple #21
0
    def notification_for_ticket(ticket: Ticket):
        title = "Ticket Updated"
        email_address = ticket.email_address

        message = None
        if ticket.status == "Created":
            message = "Your ticket has been created!"
        elif ticket.status == "Waiting on client input":
            message = "Your project is waiting on client input."
        elif ticket.status == "Ready for pickup":
            message = "Your project is ready for pickup!"
        elif ticket.status == "Closed":
            message = "Your ticket has been closed."
        else:
            message = ticket.status

        return Notification(title, message, email_address)
Exemple #22
0
def main():
    initialize_config()

    # Configure logging. Reset with every restart
    logging.basicConfig(
        format='%(asctime)s [%(levelname)s]:[%(threadName)s] %(message)s',
        filename=log_file_path,
        filemode='w',
        level=logging.INFO)
    logging.info("Starting Safe Eyes")

    if not running():
        validate_config()

        global break_screen
        global core
        global notification
        global tray_icon
        global language
        global context

        context = {}
        language = Utility.load_language(config['language'])

        # Initialize the Safe Eyes Context
        context['version'] = SAFE_EYES_VERSION

        tray_icon = TrayIcon(config, language, show_settings, show_about,
                             enable_safeeyes, disable_safeeyes, on_quit)
        break_screen = BreakScreen(on_skipped, on_postponed,
                                   break_screen_glade, style_sheet_path)
        break_screen.initialize(config, language)
        core = SafeEyesCore(context, show_notification, show_alert,
                            close_alert, on_countdown,
                            tray_icon.next_break_time)
        core.initialize(config, language)
        core.start()
        notification = Notification(language)

        handle_system_suspend()

        Gtk.main()
    else:
        logging.info('SafeEyes is already running')
        sys.exit(0)
    def __init__(self):
        """
            On initialisation the BluetoothManager class retrieves the temperature ranges from the Monitor Class
        """

        #declare variables that handle interactions with other classes
        self.__monitor = Monitor()
        self.__notifier = Notification()

        #declare variables that will store the head and message that will be sent via pushbullet
        self.__head = None
        self.__message = None

        #declare variables the store the ranges from the Monitor class using the classes methods
        self.__minTemperature = self.__monitor.getMinTemperature()
        self.__maxTemperature = self.__monitor.getMaxTemperature()
        self.__minHumidity = self.__monitor.getMinHumidity()
        self.__maxHumidity = self.__monitor.getMaxHumidity()
Exemple #24
0
 def command_1(self, data):
     data = data[1:]
     if 'had been kicked you out from the chat' in data:
         self.kick_from_chat(data)
         return 0
     if 'You have unmuted' in data or 'You have muted' in data or 'You have been muted by' in data \
             or 'You have been unmuted by' in data:
         Info(data).start()
         return 1
     if 'You can\'t kick your self' in data or 'You are not a manager' in data \
             or ' doesn\'t exist in the chat' \
             in data or 'This client does not exist' in data or \
             'You can\'t mute yourself' in data or 'is not in the chat' in data or \
             ' doesn\'t exist in the chat' in data \
             or "You can't send a private message to yourself" in data:
         Notification(data).start()
         return 1
     else:
         self.regular_msg(data)
         return 1
Exemple #25
0
 def get_input(self, event1):
     if self.__handle_data.get_mute() == 'True':
         Notification('You can not speak here').start()
         self.__entry.delete(0, 'end')
         return
     else:
         message = self.__entry.get()
         message = message.strip()
         if message == '' or message is None:
             return ''
         self.__txt.config(state=NORMAL)
         self.__message_tag = 'The message date is ' + DATE + ' ' + str(
             time.strftime("%H:%M"))
         self.__txt.insert(
             END,
             str(time.strftime("%H:%M")) + " " + message + '\n',
             (self.__message_tag, ))
         self.__txt.tag_bind(
             self.__message_tag,
             "<Enter>",
             lambda event, date=self.__message_tag: self.show_info(date))
         self.__txt.tag_bind(
             self.__message_tag,
             "<Leave>",
             lambda event, date=self.__message_tag: self.show_info(""))
         self.__txt.yview(END)
         self.__entry.delete(0, 'end')
         self.__my_chat = self.__my_chat + DATE + ' ' + str(time.strftime("%H:%M")) + " " + self.__client_name[1:]\
                         + ': ' + emoji.demojize(message) + '\n'
         sql = "UPDATE users SET chat = %s "
         self.__my_cursor.execute(sql, (self.__my_chat, ))
         message = '01' + message
         self.__client_socket.write((self.__client_name + message).encode())
         self.__txt.config(state=DISABLED)
         if message == '0101quit':
             self.__root.quit()
             self.exit()
Exemple #26
0
 def start_chat(self):
     self.__client_name = self.__name.get().strip('\n').strip(' ')
     client_pass = self.__password.get().strip('\n').strip(' ')
     sql = 'INSERT INTO users (name, Password) VALUES(%s, %s)'
     sql2 = 'INSERT INTO private_chats (name) VALUES(%s)'
     if client_pass is not None and self.__client_name is not None:
         client_pass = client_pass.strip()
         self.__client_name = self.__client_name.strip('\n')
         self.__client_name = self.__client_name.strip()
         if not self.__client_name or not client_pass:
             Notification('please try again').start()
             return
         self.__client_name = self.__client_name.replace(' ', '_')
         self.__my_cursor.execute('SELECT name FROM users ')
         msg = self.__my_cursor.fetchall()
         if self.__client_name[0] == '@':
             Notification('the username cannot begins with @').start()
             return
         if not client_pass:
             Notification('invalid password').start()
         if len(self.__client_name) > 9:
             Notification('Please Enter a shorter username').start()
             return
         for i in msg:
             if i[0] == self.__client_name:
                 Notification('The username already exist').start()
                 return
         user1 = (self.__client_name, client_pass)
         sql3 = "ALTER TABLE private_chats ADD COLUMN " + self.__client_name + " TEXT(5000) "
         self.__my_cursor.execute(sql, user1)
         self.__my_cursor.execute(sql2, (self.__client_name,))
         self.__my_cursor.execute(sql3)
         self.__my_database.commit()
         self.__client_name = str(len(self.__client_name)) + self.__client_name
         try:
             Chat(Host, Port, self.__client_name, self.__window, self.__start)
         except:
             Notification('The server is currently unavailable').start()
             sql = "UPDATE users SET connected='False' WHERE name=%s "
             self.__my_cursor.execute(sql, (self.__client_name[1:],))
             self.__my_database.commit()
Exemple #27
0
class UnitTests(TestCase):
    def setUp(self):
        # Setting up mock database
        self.supervisor = User.objects.create(username="******",
                                              password="******",
                                              permissions="1000",
                                              address="testAddress",
                                              phonenumber="TestPhoneNum",
                                              email="TestEmail")
        self.admin = User.objects.create(username="******",
                                         password="******",
                                         permissions="0111",
                                         address="testAddress",
                                         phonenumber="TestPhoneNum",
                                         email="TestEmail")
        self.ta = User.objects.create(username="******",
                                      password="******",
                                      permissions="0001",
                                      address="testAddress",
                                      phonenumber="TestPhoneNum",
                                      email="TestEmail")
        self.instructor = User.objects.create(username="******",
                                              password="******",
                                              permissions="0010",
                                              address="testAddress",
                                              phonenumber="TestPhoneNum",
                                              email="TestEmail")
        self.userNoPriv = User.objects.create(username="******",
                                              password="******",
                                              permissions="0000",
                                              address="testAddress",
                                              phonenumber="TestPhoneNum",
                                              email="TestEmail")
        self.testuser = User.objects.create(username="******",
                                            password="******",
                                            permissions="0000",
                                            address="testAddress",
                                            phonenumber="TestPhoneNum",
                                            email="TestEmail")

    u = UserEdits()
    n = Notification()
    c = CourseEdit()
    d = DataRetrieval()

    def test_add_userUnsuccessful(self):
        self.assertEqual(
            self.u.add_user("bad", "bad", "-1", "home", "4141231234",
                            "*****@*****.**", self.admin),
            "Failed to add user. Improper parameters")

    def test_add_user_TA_NoPermission(self):
        self.assertEqual(
            self.u.add_user("UserName", "userpassword", "0001", "home",
                            "4141231234", "*****@*****.**", self.ta),
            "Illegal permissions to do this action")

    def test_add_user_Instructor_NoPermission(self):
        self.assertEqual(
            self.u.add_user("UserName", "password", "0001", "home",
                            "4141231234", "*****@*****.**",
                            self.instructor),
            "Illegal permissions to do this action")

    def test_add_user_Admin_Successful(self):
        self.assertEqual(
            "User successfully added",
            self.u.add_user("UserName", "password", "0001", "home",
                            "4141231234", "*****@*****.**", self.admin))

    def test_add_user_Supervisor_Successful(self):
        self.assertEqual(
            self.u.add_user("UserName", "password", "0001", "home",
                            "4141231234", "*****@*****.**",
                            self.supervisor), "User successfully added")

    def test_add_user_Admin_Failed(self):
        self.assertEqual(
            self.u.add_user(" ", "password", "0001", "home", "4141231234",
                            "studgmailcom", self.admin),
            "Failed to add user. Improper parameters")

    def test_add_user_Supervisor_Failed(self):
        self.assertEqual(
            self.u.add_user("UserName", " ", "0001", "home", "4141231234",
                            "studgmail.com", self.supervisor),
            "Failed to add user. Improper parameters")

    def test_delete_user_TA_NoPermission(self):
        self.assertEqual(self.u.delete_user(1, self.ta),
                         "Illegal permissions to do this action")

    def test_delete_user_Instructor_NoPermission(self):
        self.assertEqual(self.u.delete_user(1, self.instructor),
                         "Illegal permissions to do this action")

    def test_delete_user_Admin_FailedToDelete(self):
        self.assertEqual(self.u.delete_user(-1, self.admin),
                         "User unsuccessfully deleted")

    def test_delete_user_Supervisor_FailedToDelete(self):
        self.assertEqual(self.u.delete_user(-1, self.supervisor),
                         "User unsuccessfully deleted")

    def test_delete_user_Supervisor_FailedToDelete_Cannot_Delete_Self(self):
        self.assertEqual(self.u.delete_user("superu", self.supervisor),
                         "Unable to delete active user")

    def test_delete_user_Admin_SuccessDelete(self):
        self.assertEqual(self.u.delete_user("testuser", self.admin),
                         "User successfully deleted")

    def test_delete_user_Supervisor_SuccessToDelete(self):
        self.assertEqual(self.u.delete_user("testuser", self.supervisor),
                         "User successfully deleted")

    def test_ChangeUser_Admin_IllegalField(self):
        self.assertEqual(self.u.change_contact("User", "NewField", "BadField"),
                         "Illegal changed field")

    def test_ChangeUser_Supervisor_IllegalField(self):
        self.assertEqual(self.u.change_contact("User", "NewField", "BadField"),
                         "Illegal changed field")

    def test_ChangeUser_Admin_IllegalChangedField(self):
        self.assertEqual(self.u.change_contact("User", "***a!`", "Name"),
                         "Illegal changed field")

    def test_ChangeUser_Supervisor_IllegalChangedField(self):
        self.assertEqual(self.u.change_contact("User", "***a!`", "Name"),
                         "Illegal changed field")

    def test_ChangeUser_Admin_Success(self):
        self.assertEqual(self.u.change_contact("admin", "password", "Name"),
                         "Contact information changed")

    def test_ChangeUser_Supervisor_Success(self):
        self.assertEqual(self.u.change_contact("superu", "password", "Name"),
                         "Contact information changed")

    def test_edit_user_TA_NoPermission(self):
        self.assertEqual(
            self.u.edit_user("testuser", "username", "NewName", self.ta),
            "Illegal permissions to do this action")

    def test_edit_user_Instructor_NoPermission(self):
        self.assertEqual(
            self.u.edit_user("testuser", "username", "NewName",
                             self.instructor),
            "Illegal permissions to do this action")

    def test_edit_user_Admin_UserDNE(self):
        self.assertEqual(
            self.u.edit_user("userdne", "username", "NewName", self.admin),
            "Failed to update user")

    def test_edit_user_Supervisor_UserDNE(self):
        self.assertEqual(
            self.u.edit_user("superdne", "username", "NewName",
                             self.supervisor), "Failed to update user")

    def test_edit_user_Admin_IllegalFieldChange(self):
        self.assertEqual(
            self.u.edit_user("testuser", "IllegalField", "NewName",
                             self.admin), "Tried to change illegal field")

    def test_edit_user_Supervisor_IllegalFieldChange(self):
        self.assertEqual(
            self.u.edit_user("testuser", "IllegalField", "NewName",
                             self.supervisor), "Tried to change illegal field")

    def test_edit_user_Admin_IllegalChangedField(self):
        self.assertEqual(
            self.u.edit_user("testuser", "username", "****", self.admin),
            "Failed to updated user")

    def test_edit_user_Supervisor_IllegalChangedField(self):
        self.assertEqual(
            self.u.edit_user("testuser", "username", "****", self.supervisor),
            "Failed to updated user")

    def test_edit_user_Admin_SuccessfulChange(self):
        self.assertEqual(
            self.u.edit_user("testuser", "username", "NewName", self.admin),
            "User successfully updated")

    def test_edit_user_Supervisor_SuccessfulChange(self):
        self.assertEqual(
            self.u.edit_user("testuser", "username", "NewName",
                             self.supervisor), "User successfully updated")

    def test_SendNotification_TA_NoPermission(self):
        self.assertEqual(
            self.n.send_email("*****@*****.**", "*****@*****.**", "subject",
                              "body", self.ta),
            "Illegal permissions to do this action")

    def test_SendNotification_Instructor_NoPermission(self):
        self.assertEqual(
            self.n.send_email("*****@*****.**", "*****@*****.**", "subject",
                              "body", self.instructor),
            "Illegal permissions to do this action")

    def test_SendNotification_Admin_FromAddressDNE(self):
        self.assertEqual(
            self.n.send_email("*****@*****.**", "*****@*****.**",
                              "subject", "body", self.admin),
            "From user does not exist")

    def test_SendNotification_Supervisor_FromAddressDNE(self):
        self.assertEqual(
            self.n.send_email("*****@*****.**", "*****@*****.**",
                              "subject", "body", self.supervisor),
            "From user does not exist")

    def test_SendNotification_Admin_ToAddressDNE(self):
        self.assertEqual(
            self.n.send_email("*****@*****.**", "*****@*****.**",
                              "subject", "body", self.admin),
            "To user does not exist")

    def test_SendNotification_Supervisor_ToAddressDNE(self):
        self.assertEqual(
            self.n.send_email("*****@*****.**", "*****@*****.**",
                              "subject", "body", self.supervisor),
            "To user does not exist")

    def test_SendNotification_Admin_IllegalEmailBody(self):
        self.assertEqual(
            self.n.send_email("*****@*****.**", "*****@*****.**", "subject",
                              "  ", self.admin), "Illegal subject")

    def test_SendNotification_Supervisor_IllegalEmailBody(self):
        self.assertEqual(
            self.n.send_email("*****@*****.**", "*****@*****.**", "subject",
                              "  ", self.supervisor), "Illegal subject")

    def test_SendNotification_Admin_IllegalEmailSubject(self):
        self.assertEqual(
            self.n.send_email("*****@*****.**", "*****@*****.**", " ", "body",
                              self.admin), "Illegal email body")

    def test_SendNotification_Supervisor_IllegalEmailSubject(self):
        self.assertEqual(
            self.n.send_email("*****@*****.**", "*****@*****.**", " ", "body",
                              self.supervisor), "Illegal email body")

    def test_SendNotification_Admin_Success(self):
        self.assertEqual(
            self.n.send_email("*****@*****.**", "*****@*****.**", "subject",
                              "body", self.admin), "Email sent")

    def test_SendNotification_Supervisor_Success(self):
        self.assertEqual(
            self.n.send_email("*****@*****.**", "*****@*****.**", "subject",
                              "body", self.supervisor), "Email sent")

    def test_SendTaEmail_TA_NoPermission(self):
        self.assertEqual(
            self.n.send_email_to_ta("from@gmail", "to@gmail", "subject",
                                    "body", self.ta),
            "You do not have permission")

    def test_SendTAEmail_Instructor_TADoesNotExist(self):
        self.assertEqual(
            self.n.send_email_to_ta("from@gmail", "nonexistantta@gmail",
                                    "subject", "body", self.instructor),
            "TA does not exist")

    def test_SendTAEmail_Instructor_IllegalFrom(self):
        self.assertEqual(
            self.n.send_email_to_ta("*****@*****.**", "*****@*****.**",
                                    "subject", "body", self.instructor),
            "From user does not exist")

    def test_SendTAEmail_Instructor_IllegalEmailBody(self):
        self.assertEqual(
            self.n.send_email_to_ta("*****@*****.**", "*****@*****.**",
                                    "subject", " ", self.instructor),
            "Illegal email body")

    def test_SendTAEmail_Instructor_IllegalEmailSubject(self):
        self.assertEqual(
            self.n.send_email_to_ta("*****@*****.**", "*****@*****.**", " ",
                                    "body", self.instructor),
            "Illegal subject")

    def test_SendTAEmail_Instructor_Success(self):
        self.assertEqual(
            self.n.send_email_to_ta("*****@*****.**", "*****@*****.**",
                                    "subject", "body", self.instructor),
            "Email sent to TAs successfully")

    def test_SendTAEmail_Admin_Success(self):
        self.assertEqual(
            self.n.send_email_to_ta("*****@*****.**", "*****@*****.**",
                                    "subject", "body", self.admin),
            "Email sent to TAs successfully")

    def test_SendTAEmail_Supervisor_Success(self):
        self.assertEqual(
            self.n.send_email_to_ta("*****@*****.**", "*****@*****.**",
                                    "subject", "body", self.supervisor),
            "Email sent to TAs successfully")

    def test_view_all_courses_TA_NoCourses(self):
        self.assertEqual(self.c.view_all_courses(self.ta), "No courses")

    def test_view_all_courses_TA_Courses(self):
        self.assertEqual(self.c.view_all_courses(self.ta), "List of classes: ")

    def test_view_all_courses_Instructor_Courses(self):
        self.assertEqual(self.c.view_all_courses(self.instructor),
                         "List of classes: ")

    def test_view_all_courses_Admin_Courses(self):
        self.assertEqual(self.c.view_all_courses(self.admin),
                         "List of classes: ")

    def test_view_all_courses_Supervisor_Courses(self):
        self.assertEqual(self.c.view_all_courses(self.supervisor),
                         "List of classes: ")

    def test_assign_ta_TA_NoPermission(self):
        self.assertEqual(self.c.assign_ta("ta", 1, 800, self.ta),
                         "Do not have permissions for this action")

    def test_assign_ta_Instructor_TADNE(self):
        self.assertEqual(
            self.c.assign_ta("TADoesNotExist", 1, 800, self.instructor),
            "Ta does not exist")

    def test_assign_ta_Instructor_CourseDNE(self):
        self.assertEqual(
            self.c.assign_ta("taInDatabase", -1, 800, self.instructor),
            "Course section does not exist")

    def test_assign_ta_Instructor_LabSectionDNE(self):
        self.assertEqual(
            self.c.assign_ta("taInDatabase", 1, -1, self.instructor),
            "Lab section does not exist")

    def test_assign_ta_Instructor_Success(self):
        self.assertEqual(
            self.c.assign_ta("taInDatabase", 1, 800, self.instructor),
            "TA assigned to Course/Lab section")

    def test_assign_ta_Admin_Success(self):
        self.assertEqual(self.c.assign_ta("taInDatabase", 1, 800, self.admin),
                         "TA assigned to Course/Lab section")

    def test_assign_ta_Supervisor_Success(self):
        self.assertEqual(
            self.c.assign_ta("taInDatabase", 1, 800, self.supervisor),
            "TA assigned to Course/Lab section")

    def test_create_course_TA_NoPermission(self):
        self.assertEqual(
            self.c.create_course("instructorInDB", "courseInDb",
                                 datetime.now(), datetime.now(), self.ta),
            "Illegal permissions to do this action")

    def testcreate_course_Instructor_NoPermission(self):
        self.assertEqual(
            self.c.create_course("instructorInDB", "courseInDb",
                                 datetime.now(), datetime.now(),
                                 self.instructor),
            "Illegal permissions to do this action")

    def testcreate_course_Admin_InvalidTeacher(self):
        self.assertEqual(
            self.c.create_course("instructorNotInDb", "courseInDb",
                                 datetime.now(), datetime.now(), self.admin),
            "Teacher entered does not exist")

    def test_create_course_Admin_IllegalClassId(self):
        self.assertEqual(
            self.c.create_course("instructorU", "@@@@@", datetime.now(),
                                 datetime.now(), self.admin),
            "Illegal class id")

    def test_create_course_Admin_IllegalClassTime(self):
        self.assertEqual(
            self.c.create_course("instructorU", "courseInDb", datetime.now(),
                                 datetime.now() - timedelta(days=1),
                                 self.admin), "Illegal class time entered")

    def test_create_course_Admin_Success(self):
        self.assertEqual(
            self.c.create_course("instructorU", "courseInDb", datetime.now(),
                                 datetime.now() + timedelta(days=1),
                                 self.admin), "Course successfully added")

    def test_delete_course_TA_NoPermission(self):
        self.assertEqual(self.c.delete_course(1, self.ta),
                         "Do not have permission to complete this action")

    def test_delete_course_Instructor_NoPermission(self):
        self.assertEqual(self.c.delete_course(1, self.instructor),
                         "Do not have permission to complete this action")

    def test_delete_course_Admin_InvalidCourseId(self):
        self.assertEqual(self.c.delete_course(-1, self.admin),
                         "Invalid course ID entered")

    def test_view_course_assignments_TA_NoPermission(self):
        self.assertEqual(self.d.get_all_courses(self.ta),
                         "Illegal permissions to do this action")

    def test_view_course_assignments_Instructor_NoPermission(self):
        self.assertEqual(self.d.get_all_courses(self.instructor),
                         "Illegal permissions to do this action")

    def test_view_course_assignments_Admin_CourseIdDNE(self):
        self.assertEqual(self.c.view_course_assignments(-1, self.admin),
                         "Course does not exist")

    def test_view_course_assignments_Admin_Success(self):
        self.assertEqual(self.c.view_course_assignments(1, self.admin),
                         "Course assignments: ")

    def test_view_course_assignments_Supervisor_Success(self):
        self.assertEqual(self.c.view_course_assignments(1, self.supervisor),
                         "Course assignments: ")

    def test_view_database_get_info(self):
        list = self.d.view_database()
        self.assertEqual(len(list), 6)
Exemple #28
0
def parse_source_code(begin: int, end: int, destination: Collection):
    """This method is for parsing the source codes stored by SourceCodeExtractor.py"""

    print("Parsing source code..")

    companies_to_check = [
        "AKBNK", "GARAN", "BIMAS", "TUPRS", "TCELL", "SAHOL", "ISCTR", "EREGL",
        "KCHOL", "HALKB", "EKGYO", "THYAO", "ARCLK", "VAKBN", "PETKIM",
        "YKBNK", "TOASO", "SISE", "ASELS", "ENKA", "ULKER", "TTKOM", "TAVHL",
        "FROTO", "SODA", "TKFEN", "KRDMD", "MAVI", "KOZAL", "BIST30",
        "BIST100", "BORSAISTANBUL"
    ]

    # connecting to MongoDB
    client = MongoClient()
    db = client.web
    collection = db.tmp

    notifications = []
    for i in range(begin, end + 1):
        # print info
        print(i, (i - begin) * 100 / (end - begin + 1), "%")

        # store notifications to mongoDB after every 200
        if i != begin and i % 200 == 0:
            for item in notifications:
                try:
                    destination.insert_one(item)
                except DuplicateKeyError:
                    print(item["_id"], "----This element already exists----")

                    # optional: comment out to override the data in database
                    # collection.delete_one({"_id": item["_id"]})
                    # collection.insert_one(item)
            notifications.clear()

        try:
            # get source code and parse it
            item = collection.find_one({"_id": i})
            notification = Notification(item["source_code"], item["_id"])

            # add to the list if it is about our companies
            for company in notification.related_companies:
                if company in companies_to_check:
                    notifications.append(notification.dump())
                    break

        except TypeError:  # if it is not found
            print(i, "---not found---")

    # store the remaining notifications
    for item in notifications:
        try:
            destination.insert_one(item)
        except DuplicateKeyError:
            print(item["_id"], "---This element already exists---")

            # optional: comment out to override the data in database
            # collection.delete_one({"_id": item["_id"]})
            # collection.insert_one(item)
    # storing the last parsed notifications index
    try:
        destination.insert_one({'_id': 1, 'max_id': end})
    except DuplicateKeyError:
        destination.delete_one({'_id': 1})
        destination.insert_one({'_id': 1, 'max_id': end})

    collection.drop()
    print("Parsing source code is done!")
Exemple #29
0
 def handle(self):
     notification = Notification()
     notification.send()
Exemple #30
0
            try:
                connection['Database'].child('admins').update({user_id: True},
                                                              user['idToken'])
            except:
                raise HTTPError('Auth refused')
        elif user_id in admins.val():
            try:
                connection['Database'].child('admins').child(user_id).remove()
            except:
                raise HTTPError('Auth refused')
        else:
            raise ValueError('User not found')


def cut_email(user):
    return user['email'].split('@')[0]


from Notification import Notification
if __name__ == "__main__":  #pragma no cover

    quit = False
    connection = db_connect()
    user = login(connection, '*****@*****.**', 'Topgun01')
    #toggle_admin(user, connection, 'btna3jCd7IUsr0gflHAJl4FYg3D2')
    notif = Notification('', 'GOOGL', 0.00, 'Hello World')

    post_notification(user, connection, notif)
    #while quit==False:
    #post_notification_manual(user, connection)