예제 #1
0
 def run(self, anon=False):
     react = Reaction(post=self.post,
                      is_like=self.is_like,
                      address=Address.new())
     if not anon:
         react.user = self.user_id
     react.save()
     self.send_message(
         TEXT_PAY.format(self.text_name, react.address.address))
     self.send_message(react.address.address)
예제 #2
0
    def setUp(self):
        """Create test client, add sample data."""

        User.query.delete()
        Message.query.delete()

        self.client = app.test_client()

        self.testuser = User.signup(username="******",
                                    email="*****@*****.**",
                                    password="******",
                                    image_url=None)

        self.testuser2 = User.signup(username="******",
                                     email="*****@*****.**",
                                     password="******",
                                     image_url=None)

        self.testuser4 = User.signup(username="******",
                                     email="*****@*****.**",
                                     password="******",
                                     image_url=None)
        self.testuser.id = 1
        self.testuser2.id = 2
        self.testuser4.id = 4
        db.session.commit()

        self.f = FollowersFollowee(follower_id=1, followee_id=2)
        self.f2 = FollowersFollowee(follower_id=2, followee_id=1)
        self.m = Message(id=1, text="test message", user_id=2)
        self.r = Reaction(user_id=1, message_id=1, reaction_type="sad")

        db.session.add_all([self.f, self.f2, self.m, self.r])
        db.session.commit()
def get_all_reactions():
    with sqlite3.connect("./rare.db") as conn:

        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        db_cursor.execute("""
            SELECT 
                r.id,
                r.label,
                r.image_url
            FROM Reactions r
        """)

        reactions = []

        dataset = db_cursor.fetchall()

        for row in dataset:

            react = Reaction(row['id'], row['label'], row['image_url'])

            reactions.append(react.__dict__)

    return json.dumps(reactions)
예제 #4
0
파일: views.py 프로젝트: ogu2/Ymeal-backend
def reaction_process(request,meal_id,custom_reaction):
    print custom_reaction
    device_id = request.POST.get('device_id')
    if not device_id:
        return HttpResponse('No device_id')
    _serving = Serving.objects.filter(pk=meal_id)
    if not _serving:
        return HttpResponse('Meal not found')
    else:
        _serving= _serving[0]
    if type(device_id) is list:
        device_id = str(device_id[0])
    else:
        device_id = str(device_id)
    yuser = YUser.objects.get_or_create(
             device_id =str(device_id)
            )[0]
    # save reaction
    try:
        Reaction.objects.get(
                user = yuser,
                serving = _serving,
                feedback = int(custom_reaction)
                )
    except:
        Reaction(
                user = yuser,
                serving = _serving,
                feedback = int(custom_reaction)
                ).save()
    return HttpResponse('OK')
예제 #5
0
def get_reactions():
    with sqlite3.connect("./rare.db") as conn:

        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        # Write the SQL query to get the information you want
        db_cursor.execute("""
        SELECT
           r.id,
           r.reaction,
           r.reaction_description
        FROM reaction r
        """)

        # Initialize an empty list to hold all reaction representations
        reactions = []

        # Convert rows of data into a Python list
        dataset = db_cursor.fetchall()

        # Iterate list of data returned from database
        for row in dataset:

            # Create a reaction instance from the current row.
            # Note that the database fields are specified in
            # exact order of the parameters defined in the
            # reaction class above.
            reaction = Reaction(row['id'], row['reaction'],
                                row['reaction_description'])
            reactions.append(reaction.__dict__)

    # Use `json` package to properly serialize list as JSON
    return json.dumps(reactions)
예제 #6
0
def get_reactions_by_post_id(post_id):

    with sqlite3.connect("./rare.db") as conn:
        conn.row_factory = sqlite3.Row
        db_cursor = conn.cursor()

        db_cursor.execute(
            """
        SELECT
            r.id,
            r.reaction,
            r.reaction_description 
        FROM reaction r
        WHERE r.post_id = ?
        """, (post_id, ))

        reactions = []

        dataset = db_cursor.fetchall()

        for row in dataset:

            # Create a reaction instance from the current row
            reaction = Reaction(row['id'], row['reaction'],
                                row['reaction_description'])
            reactions.append(reaction.__dict__)

        # Return the JSON serialized reaction object
        return json.dumps(reactions)
예제 #7
0
 def run(self):
     if self.kwargs.get('like'):
         entity = Reaction
         try:
             entity_id = Reaction.select().join(Address).\
                 where(
                     Address.is_accepted == False,
                     Reaction.is_like == True
                 ).\
                 order_by(Reaction.created_at.desc()).\
                 limit(1)[0].id
         except:
             self.send_message('no likes')
             return
     elif self.kwargs.get('dislike'):
         entity = Reaction
         try:
             entity_id = Reaction.select().join(Address).\
                 where(
                     Address.is_accepted == False,
                     Reaction.is_like == False
                 ).\
                 order_by(Reaction.created_at.desc()).\
                 limit(1)[0].id
         except:
             self.send_message('no likes')
             return
     else:
         entity = Post
         try:
             entity_id = Post.select().join(Address).\
                 where(
                     Address.is_accepted == False,
                     Post.is_deleted == False
                 ).\
                 order_by(Post.created_at.desc()).\
                 limit(1)[0].id
         except:
             self.send_message('not posts')
             return
     self.send_message('how much to send?')
     return (ConfirmStep, {'entity_id': entity_id, 'entity': entity})
예제 #8
0
 def post(self):
     params = self.request
     template_values = initialize(self.request)
     if not template_values['user']:
         self.redirect('/')
         return
     try:
         post = ndb.Key(urlsafe=params.get('id')).get()
         member = template_values['member']
         reply = params.get('reply').strip()
         reaction = Reaction(text=reply,
                             member=member.key,
                             datetime=datetime.now())
         reaction.put()
         post.reactions.insert(0, reaction.key)
         post.put()
         template_values['highlight'] = post
         template_values['profile'] = post.key.parent().get()
     except:
         pass
     template = JINJA_ENVIRONMENT.get_template('profile.html')
     self.response.write(template.render(template_values))
예제 #9
0
def add_reaction():
    """Add reaction to DB"""
    if not g.user:
        flash("Unauthorized to complete action", "danger")
        return redirect("/")

    reaction_type = request.json["type"]
    msg_id = request.json["msgId"]
    reaction = Reaction(user_id=g.user.id,
                        message_id=msg_id,
                        reaction_type=reaction_type)
    db.session.add(reaction)
    db.session.commit()
    return jsonify({'msg': 'Added Reaction!'})
예제 #10
0
    def test_user_model(self):
        """Does basic model work?"""

        u = User.signup(username="******",
                        email="*****@*****.**",
                        password="******",
                        image_url="/static/images/default-pic.png")
        u.id = 1
        u2 = User.signup(username="******",
                         email="*****@*****.**",
                         password="******",
                         image_url="/static/images/default-pic.png")
        u2.id = 2

        db.session.commit()

        m = Message(id=1, text="test message", user_id=1)
        r = Reaction(user_id=1, message_id=1, reaction_type="sad")
        f = FollowersFollowee(follower_id=1, followee_id=2)
        f2 = FollowersFollowee(follower_id=2, followee_id=1)

        db.session.add_all([m, r, f, f2])

        db.session.commit()

        # User should have 1 message and 1 follower and 1 following
        self.assertEqual(u.messages.count(), 1)
        self.assertEqual(u.followers.count(), 1)
        self.assertEqual(u.following.count(), 1)

        db.session.delete(f)
        db.session.commit()

        # User should have 0 follower and 1 following
        self.assertEqual(u.followers.count(), 0)
        self.assertEqual(u.following.count(), 1)

        db.session.delete(f2)
        db.session.commit()

        # User should have 0 follower and 0 following
        self.assertEqual(u.followers.count(), 0)
        self.assertEqual(u.following.count(), 0)

        # testing attributes
        self.assertNotEqual(u.password, "HASHED_PASSWORD")
        self.assertEqual(u.email, "*****@*****.**")
        self.assertEqual(u.image_url, "/static/images/default-pic.png")
        self.assertEqual(u.username, "testuser")
        self.assertEqual(u.bio, None)
        self.assertEqual(u.header_image_url, "/static/images/warbler-hero.jpg")
        self.assertEqual(u.location, None)

        # test get_reactions
        self.assertEqual(len(u.get_reactions("sad")), 1)
        self.assertFalse(u.get_reactions("angry"))
        self.assertFalse(u.get_reactions("smile"))
        self.assertFalse(u.get_reactions("laugh"))

        # test get my messages
        self.assertEqual(len(u.get_my_messages()), 1)

        # test auth
        u = User.authenticate(u.username, "HASHED_PASSWORD")
        self.assertTrue(u)

        u = User.authenticate(u.username, "asdfasdf")
        self.assertFalse(u)
예제 #11
0
def filtro(buffer):
    filtros = {
        "trimmedMessageContent": 0,
        "renderContent": 0,
        "skypeguid": 0
    }
    sender = ""
    time = ""
    indexTexto = 0
    indexTextoFinal = 0
    name = ""
    isRichHtml = False
    isRichHtmlDone = False
    richHtml = ""
    reacaoChunk = ""
    isReacaoChunk = False
    hasFiles = False
    emojiReaction = ""
    orgidReaction = ""
    timeReaction = ""
    cvId = ""
    message = ""
    reactions = []
    reacaoChunkReady = False
    files = []
    ok = 1
    link = ""
    hrefLink = ""
    nAspas = False

    for filter in filtros:
        for line in buffer:
            if filter in line:
                filtros[filter] = 1
    for x in filtros.values():
        if x == 0:
            ok = 0

    if ok:
        isMention = False
        mention = ""
        orgid = ""
        nome = ""

        existe = False
        for line in buffer:
            name = ""
            if "conversationId\"[" in line or "@thread.tacv2" in line:
                indexCvId = line.find("conversationId\"")
                indexCvIdFinal = line.find(".spaces", indexCvId)
                if indexCvIdFinal == -1:
                    indexCvIdFinal = line.find("d.tacv2", indexCvId)
                l = list(line)
                for x in range(indexCvId + 16, indexCvIdFinal + 7):
                    cvId += l[x]
            if "imdisplayname" in line:
                indexTexto = line.find("imdisplayname")
                indexTextoFinal = line.find("skypeguid")
                l = list(line)
                for x in range(indexTexto, indexTextoFinal):
                    if "\"" in l[x]:
                        nAspas = not nAspas
                        continue
                    if nAspas:
                        name = name + l[x + 1]
                name = name.replace("\"", "")
                sender = name
                nAspas = False
                nome = sender
            name = ""

            if "creator" in line:
                indexOrgid = line.find("creator\",8:orgid:")
                indexOrgid += 17
                indexOrgidFinal = line.find("\"", indexOrgid)
                l = list(line)
                org = ""
                for x in range(indexOrgid, indexOrgidFinal):
                    org += l[x]
                orgid = org

            if "composetime" in line:
                indexTempo = line.find("originalarrivaltime")
                indexTempoFinal = line.find("clientArrivalTime", indexTempo)

                l = list(line)
                for x in range(indexTempo + 21, indexTempoFinal - 2):
                    name = name + l[x]
                name = name.replace("\"", "")

                try:
                    dtStart = zulu.parse(name)
                    time = datetime.utcfromtimestamp(dtStart.timestamp())
                    time = time.astimezone(tz=tz.tzlocal())
                    time = name
                except:
                    time = "sem tempo"

                nAspas = False

            if "RichText/Html" in line:
                isRichHtml = True
                richHtml += line

            if "renderContent" in line:
                isRichHtml = False
                isRichHtmlDone = True

            if isRichHtml:
                richHtml += line

            if isRichHtmlDone:
                if "<div>".encode("utf-16le") in line.encode("utf-8"):
                    st = utf16customdecoder(richHtml, "<div>")
                    richHtml = st
                    if "https://statics.teams.cdn.office.net/evergreen-assets/skype/v2/" in st:
                        indexMultiplosEmojis = 0
                        indexSpan = 0
                        while indexSpan != -1:
                            indexSpan = st.find("<span class=\"animated-emoticon", indexMultiplosEmojis)
                            indexMultiplosEmojis = indexSpan
                            indexSpanfinal = st.find("</span>", indexSpan)
                            indexSpanfinal += 7
                            l = list(st)
                            span = ""
                            emoji = ""
                            for x in range(indexSpan, indexSpanfinal):
                                span = span + l[x]

                            indexEmoji = span.find("itemid=\"")
                            indexEmojiFinal = span.find(" itemscope")
                            indexEmoji += 7
                            spanList = list(span)
                            for x in range(indexEmoji + 1, indexEmojiFinal - 1):
                                emoji += spanList[x]
                            st = st.replace(span, " " + linkEmoji.format(emoji) + " ")
                            st = st.replace(r"\n", "")
                            richHtml = st
                if "http://schema.skype.com/Mention" in richHtml:
                    indexMencionado = 0
                    span = ""
                    while indexMencionado != -1:
                        # obter pelo orgid
                        isMention = True
                        indexMencionado = richHtml.find("<span itemscope itemtype=\"http://schema.skype.com/Mention\"",
                                                        indexMencionado)
                        indexMencionadoFinal = richHtml.find("</span>", indexMencionado)
                        l = list(richHtml)
                        for x in range(indexMencionado, indexMencionadoFinal):
                            span += l[x]
                        indexSpanMention = span.find("itemid") + 11
                        s = list(span)
                        for x in range(indexSpanMention, len(s)):
                            name += s[x]
                        richHtml = richHtml.replace(span + "</span>", "Mention: {0}".format(name))
                        span = ""
                        mention = name
                        name = ""
                if "http://schema.skype.com/AMSImage" in richHtml:
                    l = list(richHtml)
                    src = " "
                    img = ""
                    indexSrc = richHtml.find("src=\"")
                    indexSrcFinal = richHtml.find("\" width")
                    indexImg = richHtml.find("<img")
                    indexImgFinal = richHtml.find("/>", indexImg)
                    for x in range(indexSrc + 5, indexSrcFinal):
                        src += l[x]
                    for x in range(indexImg, indexImgFinal + 2):
                        img += l[x]
                    src += " "
                    indexRH = richHtml.find(r"RichText/Html")
                    replaceRH = ""
                    for x in range(0, indexRH):
                        replaceRH += l[x]
                    richHtml = richHtml.replace(replaceRH, "", 1)
                    richHtml = richHtml.replace(img, src)
                    richHtml = richHtml.replace(r"RichText/Html", "")
                    richHtml = richHtml.replace(r"contenttype", "")
                    richHtml = richHtml.replace(r"contentc", "")
                    richHtml = richHtml.replace(r"text", "")
                    richHtml = richHtml.replace("<span>", "")
                    richHtml = richHtml.replace("<div>", "")
                    richHtml = richHtml.replace("</span>", "")
                    richHtml = richHtml.replace("</div>", "")
                    richHtml = richHtml.replace(r"\n", "")
                    richHtml = richHtml.replace("\"", "")
                    richHtml = richHtml[3::]

                    richHtml = "RichText<div>" + richHtml
                    richHtml += "</div>"

                if richHtml.find("RichText") != -1:
                    rHtml = ""
                    richHtml = richHtml.replace("<div style=\"font-size:14px;\"", "")
                    l = list(richHtml)
                    indexTexto = richHtml.find("<div")
                    for x in range(richHtml.find(r"RichText"), indexTexto):
                        rHtml += l[x]
                    indexTexto += 5
                    indexTextoFinal = richHtml.find("</div>")
                    indexHref = 0
                    for x in range(indexTexto, indexTextoFinal):
                        name = name + l[x]
                    name = name.replace("<div>", "")
                    name = name.replace(rHtml, "")
                    name = name.replace("\n", "")
                    name = name.strip()
                    # if name.find(r"\n",0,3)!=-1:
                    #     name = name.replace(r"r\")
                    if name.find("<a href") != -1:
                        n = list(name)
                        while True:
                            if "externalid" in name:
                                break
                            indexHref = name.find("<a href", indexHref)
                            if indexHref == -1:
                                break
                            indexHrefFinal = name.find("</a>", indexHref) + 4
                            indexTitle = name.find("\" title=", indexHref)
                            for x in range(indexHref, indexHrefFinal):
                                hrefLink += n[x]
                            if name.find("\" rel", indexHref, indexTitle) != -1:
                                indexTitle = name.find("\" rel", indexHref, indexTitle)
                            for x in range(indexHref + 9, indexTitle):
                                link += n[x]
                            name = name.replace(hrefLink, link)
                            indexHref += 20
                            hrefLink = ""
                            link = ""
                    if name.find("<div itemprop=\"copy-paste-block\"") != -1:
                        name = name.replace("<div itemprop=\"copy-paste-block\"", "")
                    nAspas = False
                    name = name.replace(r"&quot;", "\"")
                    name = name.replace("<u>", "")
                    if name.find(">", 2):
                        name = name.replace(">", "", 1)
                    message = name
                    name = ""
                    isRichHtmlDone = False
            if "http://schema.skype.com/File" in line:
                indexFileUrl = 0
                indexNomeFile = 0
                while True:
                    localizacao = ""
                    indexFileUrl = line.find("fileUrl", indexFileUrl)
                    if indexFileUrl == -1:
                        break
                    indexFileUrl += 10
                    indexFileUrlFinal = line.find("siteUrl", indexFileUrl) - 3
                    indexNomeFile = line.find("fileName", indexNomeFile) + 11
                    indexNomeFileFinal = line.find("fileType", indexNomeFile) - 3
                    indexCleanTexto = richHtml.find("<div><span><img")
                    indexCleanTextoFinal = richHtml.find("</div>", indexCleanTexto) + 6
                    if indexCleanTexto != -1 and indexCleanTextoFinal != -1 and indexCleanTexto < indexCleanTextoFinal:
                        r = list(richHtml)
                        spanDelete = ""
                        for x in range(indexCleanTexto, indexCleanTextoFinal):
                            spanDelete += r[x]
                        richHtml = richHtml.replace(spanDelete, "")
                        print(richHtml)
                    l = list(line)
                    url = ""
                    nomeFile = ""
                    for x in range(indexFileUrl, indexFileUrlFinal):
                        url += l[x]
                    for x in range(indexNomeFile, indexNomeFileFinal):
                        nomeFile += l[x]

                    indexFileUrl += 50
                    indexNomeFile += 20
                    fich = File(url, nomeFile)
                    files.append(fich)
                    if files.__len__() != 0:
                        hasFiles = True
            if "call-log" in line:
                # print(line)
                start = ""
                end = ""
                state = ""
                originator = ""
                target = ""
                indexStart = line.find("startTime")
                indexStartFinal = line.find("connectTime", indexStart)
                indexEnd = line.find("endTime", indexStartFinal)
                indexEndFinal = line.find("callDirection", indexEnd)
                indexCallState = line.find("callState", indexEndFinal)
                indexOriginator = line.find("originator", indexCallState)
                indexTarget = line.find("target", indexOriginator)
                indexTargetFinal = line.find("originatorParticipant", indexTarget)
                l = list(line)
                for x in range(indexStart + 12, indexStartFinal - 3):
                    start += l[x]
                for x in range(indexEnd + 10, indexEndFinal - 3):
                    end += l[x]
                for x in range(indexCallState + 12, indexOriginator - 3):
                    state += l[x]
                for x in range(indexOriginator + 21, indexTarget - 3):
                    originator += l[x]
                for x in range(indexTarget + 17, indexTargetFinal - 3):
                    target += l[x]

                if originator in arrayContactos:
                    contactoOriginator = arrayContactos.get(originator)
                else:
                    ind = line.find("originatorParticipant")
                    displayOrig = ""
                    for x in range(line.find("displayName", ind) + 14, line.find("\"}", ind)):
                        displayOrig += l[x]
                    contactoOriginator = Contacto(displayOrig, "sem email", originator)
                    arrayContactos[originator] = contactoOriginator
                if target in arrayContactos:
                    contactoTarget = arrayContactos.get(target)
                else:
                    displayTarget = ""
                    indT = line.find("targetParticipant")
                    for x in range(line.find("displayName", indT) + 14, line.find("\"}", indT)):
                        displayTarget += l[x]
                    contactoTarget = Contacto(displayTarget, "sem email", target)
                    arrayContactos[target] = contactoTarget
                dtStart = zulu.parse(start)
                callstart = datetime.utcfromtimestamp(dtStart.timestamp())
                callstart = callstart.astimezone(tz=tz.tzlocal())
                dtEnd = zulu.parse(start)
                callEnd = datetime.utcfromtimestamp(dtEnd.timestamp())
                callEnd = callstart.astimezone(tz=tz.tzlocal())

                chamada = Chamada(contactoOriginator, str(callstart), str(callEnd), contactoTarget, state)
                arrayCallOneToOne.append(chamada)

            if isReacaoChunk and "ams_referencesa" in line:
                isReacaoChunk = False
                reacaoChunkReady = True

            if isReacaoChunk:
                reacaoChunk += line
                reacaoChunk += ";"
            if "deltaEmotions" in line:
                isReacaoChunk = True

            if reacaoChunkReady:
                emojiReaction = ""
                timeReaction = ""
                reacoes = reacaoChunk.split(";")
                reacoes = list(dict.fromkeys(reacoes))
                orgidReact = ""
                for r in reacoes:

                    if r != "":
                        reaction = Reaction()
                        rl = list(r)
                        indexKey = r.find("key")
                        indexKeyFinal = r.find("usersa", indexKey)
                        if indexKey != -1:
                            emojiReaction = ""
                            for x in range(indexKey + 5, indexKeyFinal - 2):
                                emojiReaction += rl[x]
                        indexOrgidReacao = r.find("orgid")
                        indexOrgidReacaoFinal = r.find("timeN", indexOrgidReacao)
                        for x in range(indexOrgidReacao + 6, indexOrgidReacaoFinal - 2):
                            orgidReact += rl[x]
                        try:
                            for x in range(0, 13):
                                timeReaction += rl[x]
                        except:
                            print("")
                        reaction.orgid = orgidReact
                        reaction.emoji = emojiReaction
                        reaction.time = timeReaction
                        arrayReacoes.append(reaction)
                        orgidReact = ""
                        timeReaction = ""
                        reacaoChunkReady = False

        reacaoChunk = ""

        if message != "" or hasFiles:
            if "Call Log for Call" not in message:
                mensagem = MensagemCompleta()
                if isMention:
                    mensagem.isMention = True
                mensagem.mention = mention
                mensagem.message = message
                mensagem.time = time
                mensagem.sender = sender

                mensagem.cvID = cvId
                mensagem.reactions = arrayReacoes
                arrayReacoes.clear()
                mensagem.files = files
                arrayMensagens.append(mensagem)
                hasFiles = False