Beispiel #1
0
 def render_POST(self, request):
     #super(SongResource, self).render_POST(request)
     artist = request.args['artist'][0]
     title = request.args['title'][0]
     length = int(float(request.args['length'][0]))
     send_event(event='song', artist=artist, title=title, length=length)
     return 'OK'
Beispiel #2
0
    def update(self):
        # background
        pygame.draw.rect(self.image, (30, 0, 100),
                         pygame.Rect(0, 0, settings.RESOLUTION[0], settings.NOW_PLAYING_HEIGHT))

        # progress bar
        self.progress = (time.time() - self.track_start) / float(self.track_length)
        if self.progress < 1:
            pygame.draw.rect(self.image, (100, 0, 255),
                             pygame.Rect(0, 0, settings.RESOLUTION[0]*self.progress, settings.NOW_PLAYING_HEIGHT))
        else:
            self.kill()
            send_event(event='song_finished')

        # track info
        self.image.blit(self.metadata, (settings.PADDING,
                                        settings.NOW_PLAYING_HEIGHT - self.metadata.get_height() - settings.PADDING))

        # remaining time
        r = self.track_end - time.time()
        m, s = divmod(r, 60)
        remaining = pygame.font.Font(
            settings.PROGRESS_FONT,
            settings.PROGRESS_FONT_SIZE
            ).render('%d:%02d' % (m, s), True, pygame.Color('white'))
        self.image.blit(remaining, (settings.RESOLUTION[0]-remaining.get_width()*1.2,
                                    settings.NOW_PLAYING_HEIGHT - remaining.get_height() - settings.PADDING))
Beispiel #3
0
 def render_POST(self, request):
     event_dict = {'event': 'info'}
     for k, v in request.args.items():
         event_dict.update({k: v[0]})
         # send_event(eventrequest.args['show'][0]
         # event_dict.update({'show': request.args['show'][0]})
         # event_dict.update({'onair': request.args['onair'][0]})
     send_event(**event_dict)
     return 'OK'
Beispiel #4
0
 def __init__(self, value='', color='white', textcolor='black'):
     Sprite.__init__(self)
     self.image = pygame.Surface((settings.RESOLUTION[0], settings.NOW_PLAYING_HEIGHT))
     self.image.fill(pygame.Color(color))
     self.rect = self.image.get_rect()
     self.text = pygame.font.Font(
         settings.PROGRESS_FONT,
         settings.PROGRESS_FONT_SIZE
         ).render('%s' % (value), True, pygame.Color(textcolor))
     self.image.blit(self.text, (settings.RESOLUTION[0]/2 - self.text.get_width()/2,
                                     settings.NOW_PLAYING_HEIGHT - self.text.get_height() - settings.PADDING))
     self.rect.bottom = settings.RESOLUTION[1]
     send_event(event='position', now_playing=True)
Beispiel #5
0
def process_upload(file, roomId, userId, body, txnId, config, ts):
    if "maxUploadSize" in config and file["size"] > config["maxUploadSize"]:
        link = get_link(file)
        print("WARNING: File too large, sending as a link: " + link)
        messageContent = {
            "body": link + '(' + file["name"] + ')',
            "format": "org.matrix.custom.html",
            "formatted_body":
            '<a href="' + link + '">' + file["name"] + '</a>',
            "msgtype": "m.text",
        }
        res = send_event(config, messageContent, roomId, userId,
                         "m.room.message", txnId, ts)
        if res == False:
            print("ERROR while sending file link to room '" + roomId)

    else:
        thumbUri = ""
        thumbnailContentUri = ""

        if "thumb_video" in file:
            thumbUri = file["thumb_video"]
        if "thumb_360" in file:
            thumbUri = file["thumb_360"]

        if thumbUri and "filetype" in file:
            content = {
                "mimetype": file["mimetype"],
                "title": file["name"] + '_thumb' + file["filetype"],
            }

            thumbnailContentUri = uploadContentFromURI(content, thumbUri,
                                                       config, userId)

        fileContentUri = uploadContentFromURI(
            {
                "title": file["title"],
                "mimetype": file["mimetype"]
            }, file["url_private"], config, userId)

        messageContent = slackFileToMatrixMessage(file, fileContentUri,
                                                  thumbnailContentUri)

        res = send_event(config, messageContent, roomId, userId,
                         "m.room.message", txnId, ts)
        if res == False:
            print("ERROR while sending file to room '" + roomId)

    txnId = txnId + 1
    return txnId
    def parse(self, response):
        rows = response.css('table tr')
        entries = 0

        if len(rows) <= 0:
            utils.Report.warning(
                'There are no rows to go through... Perhaps the syntax has changed?'
            )

        for cve in rows:
            fields = cve.css('td')

            try:
                date = serialize_date(
                    utils.get_string(fields[0].css('::text').extract()))
            except ValueError:
                continue

            reference = utils.get_string(fields[2].css('a ::text').extract())
            url = utils.get_string(fields[2].xpath('a//@href').extract())
            description = utils.get_string(fields[4].css('::text').extract())

            if len(reference) > 0 and len(url) > 0:
                entries += 1
            else:
                print('Invalid CVE has been detected.')
                continue

            # Check if the leak has been published in a time window.
            if utils.start_date() <= date:
                leak = {
                    'date': date,
                    'reference': reference,
                    'url': 'https://pivotal.io' + url,
                    'description': description
                }

                if not utils.event_exists(leak['reference']):
                    print('Adding new CVE event. {}'.format(leak['reference']))
                    utils.send_event('pivotal', leak)
                else:
                    print('CVE {} already registered. Skipping.'.format(
                        leak['reference']))

        if entries <= 0:
            print('There has been an issue parsing the page.')
            utils.Report.critical(
                'No entries could be detected! Please have a manual check instead.'
            )
Beispiel #7
0
def send_reaction(config, roomId, eventId, reactionKey, userId, txnId):

    content = {
        "m.relates_to": {
            "event_id": eventId,
            "key": reactionKey,
            "rel_type": "m.annotation",
        },
    }

    res = send_event(config, content, roomId, userId, "m.reaction", txnId)

    return res
Beispiel #8
0
def process_snippet(file, roomId, userId, body, txnId, config, ts):
    htmlString = ""
    res = requests.get(file["url_private"])
    if res.status_code != 200:
        print("ERROR! Received %d %s" % (res.status_code, res.reason))
        if 400 <= res.status_code < 500:
            try:
                print(res.json()["error"])
            except Exception:
                pass
        return txnId

    htmlString = res.content.decode("utf-8")

    htmlCode = ""
    # Because escaping 6 backticks is not good for readability.
    code = "```\n" + htmlString + "\n```"
    if "filetype" in file:
        htmlCode = '<pre><code class="language-' + file["filetype"] + '">'
    else:
        htmlCode = "<pre><code>"

    htmlCode += htmlString
    htmlCode += "</code></pre>"

    messageContent = {
        "body": code,
        "format": "org.matrix.custom.html",
        "formatted_body": htmlCode,
        "msgtype": "m.text",
    }

    # send message to room
    res = send_event(config, messageContent, roomId, userId, "m.room.message",
                     txnId, ts)
    if res == False:
        link = get_link(file)
        print("Could not send snippet: " + link)
        print("Trying to send as file...")
        txnId = process_upload(file, roomId, userId, body, txnId, config, ts)
        return txnId

    return txnId
Beispiel #9
0
 def render_POST(self, request):
     event_dict = {'event': 'announcement'}
     for k, v in request.args.items():
         event_dict.update({k: v[0]})
     send_event(**event_dict)
     return 'OK'
Beispiel #10
0
 def render_GET(self, request):
     send_event(event='stop')
     return 'OK'
Beispiel #11
0
def parse_and_send_message(config, message, matrix_room, txnId, is_later):
    content = {}
    is_thread = False
    is_reply = False

    if message["type"] == "message":
        if "subtype" in message:
            if (message["subtype"] == "bot_message"
                    or message["subtype"] == "bot_remove"
                    or message["subtype"] == "slackbot_response"
                    or message["subtype"] == "channel_name"
                    or message["subtype"] == "channel_join"
                    or message["subtype"] == "channel_purpose"
                    or message["subtype"] == "group_name"
                    or message["subtype"] == "group_join"
                    or message["subtype"] == "group_purpose"):
                return txnId

            if message["subtype"] == "file_comment":
                # TODO migrate file_comments
                return txnId

        # ignore hidden messages
        if "hidden" in message:
            if message["hidden"] == True:
                return txnId
        # ignore hidden files message
        if "is_hidden_by_limit" in message:
            if message["is_hidden_by_limit"] == True:
                return txnId

        if "user" in message:  #TODO what messages have no user?
            if not message["user"] in userLUT:
                # ignore messages from bots
                return txnId
        else:
            print("Message without user")
            print(message)

        # list of subtypes
        '''
        bot_message    A message was posted by an app or integration
        me_message    A /me message was sent
        message_changed    A message was changed
        message_deleted    A message was deleted
        channel_join    A member joined a channel
        channel_leave    A member left a channel
        channel_topic    A channel topic was updated
        channel_purpose    A channel purpose was updated
        channel_name    A channel was renamed
        channel_archive    A channel was archived
        channel_unarchive    A channel was unarchived
        group_join    A member joined a group
        group_leave    A member left a group
        group_topic    A group topic was updated
        group_purpose    A group purpose was updated
        group_name    A group was renamed
        group_archive    A group was archived
        group_unarchive    A group was unarchived
        file_share    A file was shared into a channel
        file_reply    A reply was added to a file
        file_mention    A file was mentioned in a channel
        pinned_item    An item was pinned in a channel
        unpinned_item    An item was unpinned from a channel
        '''

        body = message["text"]

        # TODO do not migrate empty messages?
        #if body == "":
        #
        #    return txnId

        # replace mentions
        body = body.replace("<!channel>", "@room")
        body = body.replace("<!here>", "@room")
        body = body.replace("<!everyone>", "@room")
        body = re.sub('<@[A-Z0-9]+>', replace_mention, body)

        if "files" in message:
            if "subtype" in message:
                print(message["subtype"])
                if message["subtype"] == "file_comment" or message[
                        "subtype"] == "thread_broadcast":
                    #TODO treat as reply
                    print("")
                else:
                    txnId = process_files(message["files"], matrix_room,
                                          userLUT[message["user"]], body,
                                          txnId, config)
            else:
                txnId = process_files(message["files"], matrix_room,
                                      userLUT[message["user"]], body, txnId,
                                      config)

        if "attachments" in message:
            if message["user"] in userLUT:  # ignore attachments from bots
                txnId = process_attachments(message["attachments"],
                                            matrix_room,
                                            userLUT[message["user"]], body,
                                            txnId, config)
                for attachment in message["attachments"]:
                    if "is_share" in attachment and attachment["is_share"]:
                        if body:
                            body += "\n"
                        attachment_footer = "no footer"
                        if "footer" in attachment:
                            attachment_footer = attachment["footer"]
                        attachment_text = "no text"
                        if "text" in attachment:
                            attachment_text = attachment["text"]
                        body += "".join([
                            "&gt; _Shared (", attachment_footer, "):_ ",
                            attachment_text, "\n"
                        ])

        if "replies" in message:  # this is the parent of a thread
            is_thread = True
            previous_message = None
            for reply in message["replies"]:
                if "user" in message and "ts" in message:
                    first_message = message["user"] + message["ts"]
                    current_message = reply["user"] + reply["ts"]
                    if not previous_message:
                        previous_message = first_message
                    replyLUT[current_message] = previous_message
                    if config_yaml["threads-reply-to-previous"]:
                        previous_message = current_message

        # replys / threading
        if "thread_ts" in message and "parent_user_id" in message and not "replies" in message:  # this message is a reply to another message
            is_reply = True
            if not message["user"] + message["ts"] in replyLUT:
                # seems like we don't know the thread yet, save event for later
                if not is_later:
                    later.append(message)
                return txnId
            slack_event_id = replyLUT[message["user"] + message["ts"]]
            matrix_event_id = eventLUT[slack_event_id]

        # TODO pinned / stared items?

        # replace emojis
        body = emojize(body, use_aliases=True)

        # TODO some URLs with special characters (e.g. _ ) are parsed wrong
        formatted_body = slackdown.render(body)

        if not is_reply:
            content = {
                "body": body,
                "msgtype": "m.text",
                "format": "org.matrix.custom.html",
                "formatted_body": formatted_body,
            }
        else:
            replyEvent = threadLUT[message["parent_user_id"] +
                                   message["thread_ts"]]
            fallbackHtml = getFallbackHtml(matrix_room, replyEvent)
            fallbackText = getFallbackText(replyEvent)
            body = fallbackText + "\n\n" + body
            formatted_body = fallbackHtml + formatted_body
            content = {
                "m.relates_to": {
                    "m.in_reply_to": {
                        "event_id": matrix_event_id,
                    },
                },
                "msgtype": "m.text",
                "body": body,
                "format": "org.matrix.custom.html",
                "formatted_body": formatted_body,
            }

        # send message
        ts = message["ts"].replace(".", "")[:-3]
        res = send_event(config, content, matrix_room,
                         userLUT[message["user"]], "m.room.message", txnId, ts)
        # save event id
        if res == False:
            print("ERROR while sending event '" + message["user"] + " " +
                  message["ts"] + "'")
        else:
            _content = json.loads(res.content)
            # use "user" combined with "ts" as id like Slack does as "client_msg_id" is not always set
            if "user" in message and "ts" in message:
                eventLUT[message["user"] +
                         message["ts"]] = _content["event_id"]
            txnId = txnId + 1
            if is_thread:
                threadLUT[message["user"] + message["ts"]] = {
                    "body": body,
                    "formatted_body": formatted_body,
                    "sender": userLUT[message["user"]],
                    "event_id": _content["event_id"]
                }

            # handle reactions
            if "reactions" in message:
                roomId = matrix_room
                eventId = eventLUT[message["user"] + message["ts"]]
                for reaction in message["reactions"]:
                    for user in reaction["users"]:
                        #print("Send reaction in room " + roomId)
                        try:
                            send_reaction(
                                config, roomId, eventId,
                                emojize(":" + reaction["name"] + ":",
                                        use_aliases=True), userLUT[user],
                                txnId)
                            txnId = txnId + 1
                        except KeyError:
                            print("KeyError in reaction at " + message["ts"])

    else:
        print("Ignoring message type " + message["type"])
    return txnId