コード例 #1
0
ファイル: course_view.py プロジェクト: jmajaca/infobot-public
def archive_channel():
    session = Session()
    channel_tag = '#' + request.args.get('tag')
    course = session.query(Course).filter(
        Course.channel_tag == channel_tag).first()
    course.watch = False
    session.add(course)
    pins = session.query(Pin).join(Channel, Pin.channel == Channel.id).filter(
        Pin.done == False).filter(Channel.tag == channel_tag).all()
    for pin in pins:
        client.pins_remove(channel=pin.channel,
                           timestamp='%.6f' % pin.timestamp)
        pin.done = True
        session.add(pin)
    reminders = session.query(Reminder).join(Notification, Reminder.notification == Notification.id)\
        .join(Course, Course.id == Notification.site).filter(Course.channel_tag == channel_tag)\
        .filter(Reminder.posted == False).all()
    for reminder in reminders:
        reminder.posted = True
        session.add(reminder)
    channel = session.query(Channel).filter(Channel.tag == channel_tag).first()
    client.conversations_archive(channel=channel.id)
    channel.archived = True
    session.add(channel)
    session.commit()
    session.flush()
    return redirect(url_for('app_course.course_handler'))
コード例 #2
0
ファイル: course_view.py プロジェクト: jmajaca/infobot-public
def course_handler():
    session = Session()
    default_course_url = 'www.fer.unizg.hr/predmet/'
    form = WatchlistForm()
    courses = session.query(Course).all()
    archived_channel_tags = [
        channel.tag for channel in session.query(Channel).filter(
            Channel.archived == True).all()
    ]
    if form.validate_on_submit():
        watch = False
        if request.form.get('watch_input') == 'on':
            watch = True
        if form.id.data == -1:
            new_course = Course(form.name.data, request.form.get('tag_select'),
                                default_course_url + form.url.data, watch)
            session.add(new_course)
            session.commit()
            session.flush()
        else:
            course = session.query(Course).filter(
                Course.id == form.id.data).first()
            course.name = form.name.data
            course.url = default_course_url + form.url.data
            course.channel_tag = request.form.get('tag_select')
            course.watch = watch
            session.commit()
            session.flush()
        courses = session.query(Course).all()
        form.name.data = ''
        form.url.data = ''
        form.watch.data = True
    watched = [
        course for course in courses
        if course.watch and course.channel_tag not in archived_channel_tags
    ]
    unwatched = [
        course for course in courses
        if not course.watch and course.channel_tag not in archived_channel_tags
    ]
    archived = [
        course for course in courses
        if course.channel_tag in archived_channel_tags
    ]
    users = session.query(SlackUser).filter(SlackUser.name != 'infobot').all()
    # channels = session.query(Channel).all()
    channels = session.query(Channel).outerjoin(
        Course, Channel.tag == Course.channel_tag).filter(
            Course.channel_tag == None).all()
    channel_tags = [channel.tag for channel in channels]
    if not channel_tags.__contains__('#general'):
        channel_tags.append('#general')
    return render_template('course.html',
                           watched_courses=watched,
                           unwatched_courses=unwatched,
                           tags=channel_tags,
                           form=form,
                           users=users,
                           archived_courses=archived), 200
コード例 #3
0
def check_pins(client, logger):
    session = Session()
    pins = session.query(Pin).filter(Pin.done == False).all()
    for pin in pins:
        if datetime.now() >= pin.creation_date + pin.timer:
            response = client.pins_remove(channel=pin.channel,
                                          timestamp='%.6f' % pin.timestamp)
            pin.done = True
            session.commit()
            logger.info_log('Unpinned message with timestamp ' +
                            str(pin.timestamp) + ' in channel ' + pin.channel)
コード例 #4
0
ファイル: course_view.py プロジェクト: jmajaca/infobot-public
def unarchive_channel():
    session = Session()
    channel_tag = '#' + request.args.get('tag')
    channel = session.query(Channel).filter(Channel.tag == channel_tag).first()
    try:
        client.conversations_join(channel=channel.id)
        client.conversations_unarchive(channel=channel.id)
    except Exception as e:
        print(e)
    channel.archived = False
    session.add(channel)
    session.commit()
    session.flush()
    return redirect(url_for('app_course.course_handler'))
コード例 #5
0
ファイル: course_view.py プロジェクト: jmajaca/infobot-public
def add_channel_tag():
    session = Session()
    channel_tag = request.form.get('tag')
    topic = request.form.get('topic')
    users = request.form.getlist('user_select')
    response = client.conversations_create(name=channel_tag, is_private=False)
    channel = response['channel']
    channel_model = Channel(channel['id'], '#' + channel['name'],
                            channel['creator'],
                            datetime.fromtimestamp(channel['created']))
    session.add(channel_model)
    client.conversations_setTopic(channel=channel['id'], topic=topic)
    client.conversations_invite(channel=channel['id'], users=users)
    session.commit()
    session.flush()
    return redirect(url_for('app_course.course_handler'))
コード例 #6
0
def check_reminders(client, logger):
    session = Session()
    reminders = session.query(Reminder).filter(
        Reminder.end_date - Reminder.timer <= datetime.now()).filter(
            Reminder.posted == False).all()
    for reminder in reminders:
        notification = session.query(Notification).filter(
            Notification.id == reminder.notification).first()
        course = session.query(Course).filter(
            notification.site == Course.id).first()
        time_left = reminder.end_date - datetime.now()
        text = '*' + str(time_left) + (
            'h* left until this event\n>' + notification.title + '\n>' +
            reminder.text + '\nSee more at ' + notification.link)
        response = client.chat_postMessage(channel=course.channel_tag,
                                           text=text)
        reminder.posted = True
        logger.info_log('Posted reminder with id ' + str(reminder.id) +
                        ' in channel ' + course.channel_tag + '(' +
                        str(course.channel.id) + ')')
        session.commit()
コード例 #7
0
class ReminderManager:
	"""
	A class that is responsible for handling all actions regarding Slack Workspace reminders

	Attributes
    ----------
    client : WebClient
        a Slack WebClient with which reminders are pulled from Slack Workspace
    database : DataBase
        a objects that is responsible for communicating with database
    logger : Logger
        a object that is saving scanner logs to a predefined file

    Methods
    ---------
    get_reminders()
        returns reminders from database
        kwargs: course, author, from and to dates
        default is return all
    get_filter_options()
        returns all authors and courses
    save()
        saves a changed reminder
        returns result of saving
    delete()
        removes reminder from database
        params: id of the reminder
        return result of removal
	"""

	def __init__(self, client: WebClient, database: DataBase, logger: Logger):
		self.client, self.database, self.logger = client, database, logger
		self.session = Session()

	def get_reminders(self, **kwargs):
		self.logger.info_log('Pulling reminders')
		if not kwargs:
			return self.database.select_many(Reminder)
		else:
			result = self.session.query(Reminder).join(Notification).join(Author).join(Course)
			for filters in kwargs.keys():
				if filters == 'name':
					result = result.filter(getattr(Course, 'name') == kwargs['name'])
				elif filters == 'author':
					result = result.filter(getattr(Author, 'first_name') == kwargs['author'].split(' ')[0])
					result = result.filter(getattr(Author, 'last_name') == kwargs['author'].split(' ')[1])
				elif filters == 'from':
					result = result.filter(getattr(Reminder, 'end_date') >= kwargs['from'])
				elif filters == 'to':
					result = result.filter(getattr(Reminder, 'end_date') < kwargs['to'])
				elif filters == 'posted':
					result = result.filter(getattr(Reminder, 'posted') == kwargs['posted'])
			return result.all()

	def get_filter_options(self):
		self.logger.info_log('Pulling all courses and authors')
		return self.database.select_many(Course), self.database.select_many(Author)

	def save(self, **kwargs):
		self.logger.info_log('Updating reminder with id: ' + kwargs['id'])
		reminder = self.session.query(Reminder).get(kwargs['id'])
		# parse string data
		year, month, day = kwargs['end_date'].split(' ')[0].split('-')
		hour, minute, second = kwargs['end_date'].split(' ')[1].split(':')
		try:
			reminder.end_date = datetime(int(year), int(month), int(day), int(hour), int(minute), int(second))
			reminder.timer = timedelta(seconds=kwargs['timer'])
			reminder.text = kwargs['text']
			reminder.posted = True if kwargs['posted'] is True else False
			self.session.commit()
		except SQLAlchemyError as e:
			self.logger.error_log(e)
			return False
		return True

	def delete(self, reminder_id):
		self.logger.info_log("Removing reminder with id: " + reminder_id)
		try:
			self.session.query(Reminder).filter_by(id=reminder_id).delete()
			self.session.commit()
		except SQLAlchemyError as e:
			self.logger.error_log(e)
			return False
		return True