def process_added_file(message_dict):
    file_link = message_dict['path']
    element_link = '/'.join(file_link.split('/')[:-2])
    board_link = '/'.join(file_link.split('/')[:-4])
    agent = get_agent()
    board = Board.get_board_by_id(board_link,
                                  agent.get_platform_access(),
                                  need_name=False)
    element = Element.get_element_by_id(element_link,
                                        agent.get_platform_access(), board)
    caption = element.get_name()

    added_file = None
    for file in element.get_files():
        platform_url = agent.get_platform_access().get_platform_url()
        if file.get_url()[len(platform_url):] == file_link:
            added_file = file
            break

    logger.debug('helloworld', caption)
    if re.match(pattern='@ta_assignment:.+', string=caption) and len(
            element.get_files()) == 1:
        teacher.send_new_assignment(agent, board, element, added_file)
    if re.match(pattern='@assignment:.+',
                string=caption) and len(element.get_files()) > 1:
        student.send_solution(agent, board, element, added_file)
    if re.match(pattern='@ta_assignment:.+',
                string=caption) and len(element.get_files()) > 1:
        teacher.recieve_solution(agent, board, element, added_file)
    if re.match(pattern='@ta_assignment_graded:.+', string=caption):
        teacher.send_grades(agent, board, element, added_file)
def on_websocket_message(ws, message):
    """Processes websocket messages"""
    message_dict = json.loads(message)
    content_type = message_dict['contentType']
    message_type = content_type.replace('application/vnd.uberblik.', '')

    logger.debug('helloworld', message)
    # if message_type == 'liveUpdateActivityUpdated+json':
    if message_type == 'liveUpdateActivitiesUpdated+json':
        print('I heard live activity {0}'.format(message_dict))
        if message_dict['type'] == 'PostedToBoard':
            print('message detected')
            message_info = message_dict['displayText']
            print(message_info)

    if message_type == 'liveUpdateElementCaptionEdited+json':
        element_caption = message_dict['newCaption']
        # looking for elements that target our agent
        if re.match(pattern='@helloworld:.+', string=element_caption):
            # create instances of Board and Element to work with them
            element_id = message_dict['path']
            news_agent = get_agent()
            board_id = '/'.join(element_id.split('/')[:-2])
            board = Board.get_board_by_id(board_id,
                                          news_agent.get_platform_access(),
                                          need_name=False)
            element = Element.get_element_by_id(
                element_id, news_agent.get_platform_access(), board)
            if element is not None:
                __run_on_element(element)
Example #3
0
 def __create_elements(self, dictionary, regexp):
     """Creates instances of Element from a dictionary"""
     elements = []
     for element in dictionary['elements']:
         href = element['_links'][0]['href']
         name = element['caption']
         if re.match(regexp, name):
             element = Element(self.__platform_access, name, href, self)
             elements.append(element)
     return elements
def on_websocket_message(ws, message):
    """Processes websocket messages"""
    message_dict = json.loads(message)
    content_type = message_dict['contentType']
    message_type = content_type.replace('application/vnd.uberblik.', '')

    logger.debug('helloworld', message)

    if message_type == 'liveUpdateElementCaptionEdited+json':
        element_caption = message_dict['newCaption']
        # looking for elements that target our agent
        if re.match(pattern='@helloworld:.+', string=element_caption):
            # create instances of Board and Element to work with them
            element_id = message_dict['path']
            news_agent = get_agent()
            board_id = '/'.join(element_id.split('/')[:-2])
            board = Board.get_board_by_id(board_id,
                                          news_agent.get_platform_access(),
                                          need_name=False)
            element = Element.get_element_by_id(
                element_id, news_agent.get_platform_access(), board)
            if element is not None:
                name = element_caption.split(":")[1].strip()
                __run_on_element(element, token_name=name)
Example #5
0
    def add_element(self, pos_x, pos_y, size_x=1, size_y=1, caption=''):
        """ Puts a new element on the board.
            Two steps:
            1. Add an element with empty name (no message on the board chat);
            2. Add a caption to new element (message on the board chat)"""
        new_element_link = ''
        try:
            http_method = 'POST'
            detail = 'activities'
            url = self.__url + '/elements'

            payload = """
                {
                  "element": {
                    "posX": \"""" + str(pos_x) + """\",
                    "posY": \"""" + str(pos_y) + """\",
                    "sizeX": \"""" + str(size_x) + """\",
                    "sizeY": \"""" + str(size_y) + """\",
                    "type": "MultiInput",
                    "caption": ""
                  }
                }
              """

            payload = json.dumps(json.loads(payload), separators=(',', ':'))
            values = {}
            headers = self.__platform_access.get_headers(http_method,
                                                         url,
                                                         values,
                                                         detail,
                                                         payload=payload)
            add_element_request = request.Request(url,
                                                  headers=headers,
                                                  data=payload.encode())
            add_element_request.get_method = lambda: http_method
            response = request.urlopen(add_element_request)
            response_dict = json.loads((response.read().decode()))
            new_element_link = response_dict["element"]["_links"][0]["href"]

        except urllib.error.HTTPError as e:
            logger.exception(
                'own_adapter',
                'Error: add element to {} failed. Error type: {}'.format(
                    self.get_name(), str(e)))
            return e.code
        # add element name (creation of the message on the board chat)
        try:
            http_method = 'PUT'
            detail = 'element'
            url = self.__platform_access.get_platform_url() + new_element_link

            payload = """
                        {
                          "element": {
                            "posX": \"""" + str(pos_x) + """\",
                            "posY": \"""" + str(pos_y) + """\",
                            "sizeX": \"""" + str(size_x) + """\",
                            "sizeY": \"""" + str(size_y) + """\",
                            "type": "MultiInput",
                            "caption": \"""" + caption + """\"
                          }
                        }
                      """

            payload = json.dumps(json.loads(payload), separators=(',', ':'))
            values = {}
            headers = self.__platform_access.get_headers(http_method,
                                                         url,
                                                         values,
                                                         detail,
                                                         payload=payload)
            add_name_request = request.Request(url,
                                               headers=headers,
                                               data=payload.encode())
            add_name_request.get_method = lambda: http_method
            response = request.urlopen(add_name_request)
            response_status = response.getcode()
            if response_status == 200:
                raw_data = response.read()
                data = json.loads(raw_data.decode('utf-8'))
                print(data)
                href = data['element']['_links'][0]['href']
                element = Element(self.__platform_access, caption, href, self)
                return element
            return response_status

        except urllib.error.HTTPError as e:
            logger.exception(
                'own_adapter',
                'Error: add element name {} to {} failed. Error type: {}'.
                format(caption, self.get_name(), str(e)))
            return e.code
Example #6
0
def on_ws_message(ws, message):
    global agent, platform_access

    message_dict = json.loads(message)
    content_type = message_dict['contentType']
    message_type = content_type.replace('application/vnd.uberblik.', '')

    logger.info(message)

    if message_type == 'liveUpdateElementCaptionEdited+json':
        # caption of a card has been updated
        element_caption = message_dict['newCaption']

        if element_caption.lower().startswith('hw'):
            element_id = message_dict['path']
            board_id = '/'.join(element_id.split('/')[:-2])
            teacher_board = Board.get_board_by_id(board_id,
                                                  agent.get_platform_access(),
                                                  need_name=False)

            assignment_element = Element.get_element_by_id(
                element_id, agent.get_platform_access(), teacher_board)

            if assignment_element is None:
                return

            assignment_files = assignment_element.get_files()

            if len(assignment_files) < 1:
                return

            assignment_file = assignment_files[-1]
            assignment_download_link = assignment_file.get_download_link()

            command_elements = [e.strip() for e in element_caption.split(',')]

            if len(command_elements) < 2:
                return

            assignment_id, deadline = command_elements[:2]
            assignment_id = int(assignment_id.split(' ')[1])

            # get teams' boards
            teams_boards = [
                b for b in agent.get_boards()
                if 'teacher' not in b.get_name().lower()
            ]

            # create google documents
            docs_descriptors = create_word_documents(
                assignment_id=assignment_id,
                deadline=deadline,
                teams_boards=teams_boards)

            save_teams_docs_links(docs_descriptors, 'HW #%s' % assignment_id)

            stats_pics = create_teams_chart([{
                'team_name': d['team_name'],
                'file_id': d['file_id']
            } for d in docs_descriptors], 'HW #%s' % assignment_id)

            for doc_descriptor in docs_descriptors:
                doc_link = doc_descriptor['doc_link']
                team_board = doc_descriptor['team_board']
                team_name = doc_descriptor['team_name']

                post_assignment_for_team(assignment_id,
                                         assignment_download_link, doc_link,
                                         team_board)

                team_stats_pic = [
                    f for f in stats_pics['teams_pics']
                    if f['team_name'] == team_name
                ]

                if len(team_stats_pic) < 1:
                    print('WARNING! NO PICTURE')
                    continue

                team_stats_pic = team_stats_pic[0]['stats_pic']

                update_team_card(teacher_board, team_board, team_stats_pic)

            update_work_progress_chart(teacher_board,
                                       stats_pics['overall_stats_pic'])
def on_websocket_message(ws, message):
    """Processes websocket messages"""
    message_dict = json.loads(message)
    content_type = message_dict['contentType']
    message_type = content_type.replace('application/vnd.uberblik.', '')

    logger.debug(CURRENT_LOGGER, message)

    if message_type == 'liveUpdateElementCaptionEdited+json':
        element_caption = message_dict['newCaption']
        if re.match(pattern='(@twitter:.+)|(@tw:.+)', string=element_caption):
            tags = element_caption.split(":")[-1].split()

            twitter_api = Twitter()
            twitts = twitter_api.get_msg_by_tags(" ".join(tags))
            links = map(
                lambda x: "https://twitter.com/%s/status/%s" %
                (x.author.name, x.id_str), twitts)

            logger.debug(CURRENT_LOGGER, "twitter keywords: %s" % tags)
            element_id = message_dict['path']
            news_agent = get_agent()
            board_id = '/'.join(element_id.split('/')[:-2])
            board = Board.get_board_by_id(board_id,
                                          news_agent.get_platform_access(),
                                          need_name=False)
            element = Element.get_element_by_id(
                element_id, news_agent.get_platform_access(), board)

            # subscribe_keyword_vk(tags, board_id.split('/')[-1] + '_' + element_id)

    elif message_type == 'liveUpdateActivitiesUpdated+json':
        logger.debug(CURRENT_LOGGER, "liveUpdateActivitiesUpdated")

        element_id = message_dict['path']
        news_agent = get_agent()
        board_id = '/boards/' + element_id.split('/')[-1]
        board = Board.get_board_by_id(board_id,
                                      news_agent.get_platform_access(),
                                      need_name=False)
        # element = Element.get_element_by_id(element_id, news_agent.get_platform_access(), board)
        msg = board.get_last_message()
        logger.debug(CURRENT_LOGGER, msg)

        if re.match(pattern='(/subscribe .+)', string=msg):
            elements = msg.split()
            tag = msg.split()[-1].lstrip("#")
            sn_account = tuple(map(lambda x: x.strip("@"), msg.split()[1:-1]))
            board = board_id.split('/')[-1]

            try:
                if 'tw' in sn_account:
                    if main.twitter_stream:
                        main.twitter_stream.running = False
                    main.subscribe_keyword_twitter(keyword=tag, element=board)
                if 'vk' in sn_account:
                    if vk.api:
                        vk.api.stop()
                    main.subscribe_keyword_vk(keyword=tag, element=board)
            except Exception as e:
                logger.error(CURRENT_LOGGER, e)

        elif re.match(pattern='(/unsubscribe .+)', string=msg):
            pass