Ejemplo n.º 1
0
    def post(self):
        try:
            data = self.parser.parse_args()['groups']
            body = data['body']
            date = data['date']
            user_id = get_jwt_identity()
            user: UserModel = UserModel.find_by_id(user_id)
            user.groups_date = date
            groups = dict()
            for group in body:
                link = group['link']
                name = group['name']
                number = group['number']
                group_id = re.search(r'https://my.ukma.edu.ua/course/(\d+)',
                                     link).group(1)
                groups[group_id] = number
                subject_model = GroupModel(name, group_id, group['number'],
                                           user_id)
                subject_model.save_to_db()
                signuper = GroupSignuper(groups, user.get_cookies())
                if date is None:
                    signuper.execute()
                else:
                    telegram.start(signuper)

        except Exception as e:
            logger.error(e)
            raise e
            # return {"message": "Some error occurred"}, 500
        return {"message": "Successfully added Groups"}, 201
Ejemplo n.º 2
0
def update(group_id, id):
    if request.method == 'GET':
        message = MessageModel.find_by_id(_id=id, group_id=group_id)
        if message is None:
            flash(
                'The scheduled message is already executed or does not exists.'
            )
            return redirect(url_for('dashboard.index'))
        group = GroupModel.find_by_id(group_id).json()
        return render_template('dashboard/update.html',
                               message=message,
                               group_name=group['channel']['group_name'])
    if request.method == "POST":
        group_id = int(group_id)
        schedule = parse(request.form['schedule'] + '+05:30')
        error = None
        if schedule < datetime.datetime.now(pytz.timezone('Asia/Kolkata')):
            error = 'You can not schedule a message in past'
        if error:
            flash(error)
        job = scheduler.get_job(id)
        message = MessageModel.find_by_id(_id=id, group_id=group_id)
        if job and message:
            schedule_msg(request.form['message'], schedule, group_id, job)
            message.name = request.form['name']
            message.message = request.form['message']
            message.schedule = request.form['schedule'] + '+05:30'
            message.save_to_db()
            return redirect(url_for('dashboard.index'))
    return render_template('dashboard/schedules.html')
Ejemplo n.º 3
0
 def get(self):
     data = GroupUser.parser.parse_args()
     group = GroupModel.find_by_name(data.group_name)
     print(group.members)
     # for u in group.members:
     #     print(u.username)
     return {'users': group.get_users()}
Ejemplo n.º 4
0
    def delete(self, id):
        group = GroupModel.find_by_id(id)

        if group:
            group.delete_from_db()
            return {'message': 'Group deleted!'}, 200
        return {'message': 'Group with that id not found.'}, 404
Ejemplo n.º 5
0
def post_group(parameters):
    if len(parameters['blurb']) > 50:
        return json.dumps(error_obj('Blurb cannot be longer than 50 chars'))
    if GroupModel.get_by_name(parameters['groupName']):
        return json.dumps(error_obj('Group with this name already exists.'))
    user = users.get_current_user()
    user_account = user_info.get_user_account()
    new_group = GroupModel(name=parameters['groupName'],
                           blurb=parameters['blurb'])
    new_group.admin_email = user.email()

    # Making the creator a member
    creator_member = GroupMembers(status=0,
                                  group_key=new_group.key,
                                  email=user.email(),
                                  name=user_account.name)
    creator_member.blurb = 'Let there be a group.'
    creator_member.put()
    new_group.members.append(creator_member.key)
    new_group.put()

    # Putting the group in the member's group list
    user_account.group_keys.append(new_group.key)
    user_account.put()
    return json.dumps(success_obj())
Ejemplo n.º 6
0
 def delete(self, name):
     group = GroupModel.find_by_name(name)
     if group:
         group.delete_from_db()
     else:
         return {'error': 'Group not found'}, 404
     return {'success': 'group deleted'}, 202
Ejemplo n.º 7
0
    def get(self, id):
        group = GroupModel.find_by_id(id)

        if group:
            return group.json(), 200

        return {'message': 'Item with that id not found.'}, 404
Ejemplo n.º 8
0
    def post(self):
        data = request.get_json()
        if self._is_added(data):
            """
            Add new group to DB
            """
            telegram_group = TelegramModel.find_by_group_chat_id(
                data[MESSAGE][CHAT][ID])
            group = GroupModel.find_by_id(telegram_group.group_fk)
            if group:
                logger.info('Group already exists in the database')
                return None
            group = GroupModel(data[MESSAGE][CHAT][TITLE],
                               data[MESSAGE][CHAT][ID])
            telegram = TelegramModel(data[MESSAGE][CHAT][ID],
                                     data[MESSAGE][CHAT][TITLE], group.id)
            try:
                group.save_to_db()
                telegram.save_to_db()
                logger.info('Group added to database')
            except:
                logger.error('unable to add group to database')

        if self._is_removed(data):
            # remove group from db
            telegram_group = TelegramModel.find_by_group_chat_id(
                data[MESSAGE][CHAT][ID])
            group = GroupModel.find_by_id(telegram_group.group_fk)
            if group:
                group.delete_from_db()
                telegram_group.delete_from_db()
                logger.info('Group successfully deleted from database')
            else:
                logger.warning(
                    'Delete executed on a group which does not exist in the database.'
                )

        if self._is_title_changed(data):
            telegram_group = TelegramModel.find_by_group_chat_id(
                data[MESSAGE][CHAT][ID])
            telegram_group.group_name = data[MESSAGE][CHAT][NEW_CHAT_TITLE]
            try:
                group.save_to_db()
                logger.info('Group title updated.')
            except:
                logger.error('Failed to update Group title to {}'.format(
                    data[MESSAGE][CHAT][NEW_CHAT_TITLE]))
Ejemplo n.º 9
0
 def put(self, name):
     data = json.loads(request.data)
     group = GroupModel.find_by_name(name)
     if group:
         group.update(**data)
     else:
         return {'error': 'Group not found'}, 404
     return group.json(), 201
Ejemplo n.º 10
0
 def get(self, name=None):
     queryData = request.args.to_dict()
     if name:
         group = GroupModelModel.find_by_name(name)
         if location:
             return group.json(), 200
         else:
             return {'error': 'group not found'}, 404
     groups = GroupModel.find(**queryData)
     return {'groups': list(map(lambda x: x.json(), groups))}, 200
Ejemplo n.º 11
0
    def put(self, id):
        data = Group.parser.parse_args()

        group = GroupModel.find_by_id(id)

        group.name = data['name']

        if data['description'] is not None:
            group.description = data['description']

        group.save_to_db()

        return group.json(), 200
Ejemplo n.º 12
0
    def post(self, group_id, user_id):
        group = GroupModel.find_by_id(group_id)
        user = UserModel.find_by_id(user_id)

        if group:
            if user:
                group.add_member(user)
                return {
                    'message':
                    "User '{}' added to '{}'".format(user.username, group.name)
                }, 201
            else:
                return {'message': 'User with that ID not found.'}, 404

        return {'message': 'Group with that ID not found.'}, 404
Ejemplo n.º 13
0
    def delete(self, group_id, user_id):
        group = GroupModel.find_by_id(group_id)
        user = UserModel.find_by_id(user_id)

        if group:
            if user:
                group.remove_member(user)
                return {
                    'message':
                    "User '{}' removed from '{}'".format(
                        user.username, group.name)
                }, 200
            else:
                return {'message': 'User with that ID not found.'}, 404

        return {'message': 'Group with that ID not found.'}, 404
Ejemplo n.º 14
0
    def post(self):
        data = Group.parser.parse_args()

        if GroupModel.find_by_name(data['name']):
            return {'message': 'Group with that name already exists.'}, 400

        group = GroupModel(data['name'], data['description'])

        group.save_to_db()

        return group.json(), 201
Ejemplo n.º 15
0
    def post(self, name):
        if GroupModel.find_by_name(name):
            return {'message': "A group with name '{}' already exists.".format(name)}, 400

        group = GroupModel(name)
        try:
            group.save_to_db()
        except Exception as e:
            return {"message": f"An error occurred: {e}"}, 500

        return group.json(), 201
Ejemplo n.º 16
0
    def post(cls):
        group_json = request.get_json()

        if GroupModel.find_by_name(group_json["name"]):
            return {
                "message": NAME_ALREADY_EXISTS.format(group_json["name"])
            }, 400

        group_json["created_at"] = str(datetime.utcnow())
        group_json["updated_at"] = str(datetime.utcnow())
        group = group_schema.load(group_json)

        try:
            group.save_to_db()
        except:
            return {"message": ERROR_INSERTING.format("inserting")}, 500

        return group_schema.dump(group), 201
Ejemplo n.º 17
0
 def post(self, name=None):
     data = json.loads(request.data)
     name = data.get("name", name)
     if GroupModel.find_by_name(name):
         return {
             'error': "A group with name '{}' already exists.".format(name)
         }, 400
     group = GroupModel(**data)
     try:
         group.save_to_db()
     except:
         return {"error": "An error occurred creating the group."}, 500
     return group.json(), 201
Ejemplo n.º 18
0
    def put(cls, id: int):
        group_json = request.get_json()
        group = GroupModel.find_by_id(id)
        process = ""

        if group:
            group.name = group_json["name"]
            group.updated_at = str(datetime.utcnow())
            process = "updating"
        else:
            group_json["created_at"] = str(datetime.utcnow())
            group_json["updated_at"] = str(datetime.utcnow())
            group = group_schema.load(group_json)
            process = "inserting"

        try:
            group.save_to_db()
        except:
            return {"message": ERROR_INSERTING.format(process)}, 500

        return group_schema.dump(group), 200
Ejemplo n.º 19
0
    def post(self):
        user = UserModel.find_by_username(current_identity.username)

        data = GroupUser.parser.parse_args()
        group = GroupModel.find_by_name(data.group_name)

        # check if group exit in user.
        # r=1
        # for u in group.members:
        #     if u.username == user.username:
        #         r=0
        # return {'group': data.group_name, 'status': '1User already a member of this group.'}
        # if r==1:
        group.members.append(user)
        group.save_to_db()

        # checking if a user is already a member of this group.
        # for u in user.groups:
        #     if u.name == data.group_name:
        #         return {'group': data.group_name, 'status': 'User already a member of this group.'}
        user.groups.append(group)
        user.save_to_db()
        return {'group': data.group_name, 'status': 'added'}
Ejemplo n.º 20
0
def schedule_msg(text, schedule, group_id, job=None):
    from resourcess.update import Update
    group = GroupModel.find_by_id(group_id).json()
    func = None
    args = None
    if group['channel']['channel_name'] == 'telegram':
        func = Update.telegram_send_message
        args = [text, int(group['channel']['group_chat_id'])]
    if group['channel']['channel_name'] == 'whatsapp':
        func = Update.whatsapp_send_message
        args = [group['channel']['group_name'], text]
    if job:
        job.modify(func=func, args=args)
        if schedule != job.next_run_time:
            job.reschedule(trigger='date', run_date=schedule)
        return job
    else:
        _id = Job(scheduler).id
        job = scheduler.add_job(id=_id,
                                func=func,
                                run_date=schedule,
                                trigger='date',
                                args=args)
        return job
Ejemplo n.º 21
0
 def get(cls, id: int):
     group = GroupModel.find_by_id(id)
     if group:
         return group_schema.dump(group), 200
     return {"message": GROUP_NOT_FOUND}, 404
Ejemplo n.º 22
0
 def get(self, name):
     group = GroupModel.find_by_name(name)
     if group:
         return group.json()
     return {'message': 'Group not found'}, 404
Ejemplo n.º 23
0
 def get(cls):
     return {"groups": group_list_schema.dump(GroupModel.find_all())}, 200
Ejemplo n.º 24
0
 def delete(cls, id: int):
     group = GroupModel.find_by_id(id)
     if group:
         group.delete_from_db()
         return {"message": GROUP_DELETED}, 200
     return {"message": GROUP_NOT_FOUND}, 404
Ejemplo n.º 25
0
 def get(self, name):
     group = GroupModel.find_by_name(name)
     if group:
         # if we have found the group then return all the posts in this groups.
         return {'post': group.get_posts()}
     return {'message': 'Group not found'}, 404
Ejemplo n.º 26
0
 def delete(self, name):
     group = GroupModel.find_by_name(name)
     if group:
         group.delete_from_db()
         return {'message': 'Group deleted.'}
     return {'message': 'Group not found.'}, 404
Ejemplo n.º 27
0
 def get(self):
     return {'groups': [x.json() for x in GroupModel.find_all()]}, 200
Ejemplo n.º 28
0
 def check_update(self):
     WebDriverWait(self.browser, 50).until(EC.presence_of_element_located(
         (By.XPATH, "//DIV[@id='pane-side']//DIV[@class='_3j7s9']")))
     chats = self.browser.find_elements_by_xpath(
         "//DIV[@id='pane-side']//DIV[@class='_3j7s9']")
     for chat in chats:
         try:
             chat.click()
         except WebDriverException as e:
             continue
         WebDriverWait(self.browser, 50).until(EC.presence_of_element_located(
             (By.CLASS_NAME, '_3AwwN')))
         # collect name of the group
         group_name = self.browser.find_element_by_xpath(
             "//HEADER[@class='_3AwwN']//SPAN[@dir='auto']").text
         whatsapp_group = WhatsAppModel.find_by_name(group_name)
         # check the membership 
         is_removed = None
         try:
             is_removed = self.browser.find_element_by_xpath(
                 "//DIV[@class='_2XiC1']")
         except NoSuchElementException:
             logger.info('')
         if is_removed:
             if whatsapp_group:
                 group = GroupModel.find_by_id(whatsapp_group.group_fk)
                 whatsapp_group.delete_from_db()
                 group.delete_from_db()
             try:
                 self.browser.find_element_by_xpath(
                     "(//SPAN[@data-icon='menu'])[2]"
                 ).click()
                 self.browser.find_element_by_xpath(
                     "//DIV[@class='_3lSL5 _2dGjP'][text()='Delete group']"
                 ).click()
                 self.browser.find_element_by_xpath(
                     "//DIV[@class='_1WZqU PNlAR'][text()='Delete']"
                 ).click()
             
                 self.browser.find_element_by_xpath(
                     "//DIV[@class='_3I_df']"
                 ).click()
                 self.browser.find_element_by_xpath(
                     "//DIV[@class='_1WZqU PNlAR'][text()='Clear']"
                 ).click()
             except:
                 logger.info('')
             continue
         if whatsapp_group:
             continue
         try:
             self.browser.find_element_by_class_name('_3AwwN').click()
         except:
             logger.info('')
         WebDriverWait(self.browser, 50).until(EC.presence_of_element_located(
             (By.CLASS_NAME, '_1xGbt')))
         chat_type = self.browser.find_element_by_class_name('_1xGbt').text
         if chat_type == 'Group info':
             # check if the bot is member of the group or not. if new membership
             # is found add the the membership to the database. if removal of 
             # membership is noticed then reflect the same on the database.
             logger.info('new group found')
             group_model = GroupModel('whatsapp',group_identifier=group_name)
             group_model.save_to_db()
             group_fk = group_model.id
             whatsapp_group = WhatsAppModel(group_name,group_fk)
             whatsapp_group.save_to_db()
Ejemplo n.º 29
0
 def get(self, name):
     group = GroupModel.find_by_name(name)
     if group:
         return group.childingroup()
Ejemplo n.º 30
0
 def get(self, name):
     group = GroupModel.find_by_name(name)
     return {'group_id': group.id}