Beispiel #1
0
def create_message(message, username, chatroom, time):
    new_message = Message(
        author=username,
        content=message,
        creation_date=time,
        chatroom=chatroom,
    )
    new_message.save()
Beispiel #2
0
def newInboundMessage():
    """ This page will be for all inbound messages, check if customer exists if so, check content of message if == "UNSUBSCRIBE", change user status.
    If customer does not exist add to database.
    """
    try:
        print ('requestform', request.form)
        tel = str(request.form['To'])
        user = db_session.query(User).filter_by(
            phone=tel).one()

        if user:
            customer = db_session.query(
                User_Customer).filter_by(phone=request.form['From']).first()
            if customer:
                if request.form['Text'] == "UNSUBSCRIBE":
                    customer.status = "UNSUBSCRIBED"
            else:
                customer = User_Customer(
                    name='UNKNOWN', phone=request.form['From'], user_id=user.id, status="SUBSCRIBED")
                db_session.add(customer)
                db_session.commit()

            newMessage = Message(
                user_id=user.id, user_customer_id=customer.id, message_uuid=request.form['MessageUUID'], message=request.form['Text'], direction="inbound", status="RECEIVED",
                units=request.form["Units"],
                total_rate=request.form["TotalRate"],
                total_amount=request.form["TotalAmount"], error_code="200", message_time=datetime.datetime.now())

            db_session.add(newMessage)
            db_session.commit()
            return jsonify(newMessage.serialize)
    except:
        print('Something went wrong, rolling back transaction!')
        db_session.rollback()
        db_session.commit()
Beispiel #3
0
def upload_fb():
    body = request.get_json()
    token = body.get('token')
    files = body.get('files')
    i = 0
    try:
        idinfo = id_token.verify_oauth2_token(token, requests.Request(),
                                              environ.get("GOOGLE_CLIENT_ID"))
        if idinfo['iss'] not in [
                'accounts.google.com', 'https://accounts.google.com'
        ]:
            raise ValueError('Wrong issuer')
        userid = idinfo['sub']
        try:
            user = session.query(User).filter(User.id == userid).one()
        except:
            user = User(id=userid)
            session.add(user)
            session.commit()

        for text in files:
            try:
                new_thread = MessageThread(id=i,
                                           user_id=user.id,
                                           person=str(i))
                session.add(new_thread)
                i += 1
                try:
                    session.commit()
                except:
                    session.rollback()
                p, msgs = scrapePage(
                    str(i),
                    text.replace(' EDT', '').replace(' EST', ''))
                for m in msgs:
                    date = datetime.fromtimestamp(m['date'])
                    msg = Message(thread_id=new_thread.id,
                                  type='FB',
                                  body=m['body'],
                                  date=date,
                                  user_speaking=m['user_speaking'])
                    session.add(msg)
            except Exception as e:
                return str(e)
        try:
            session.commit()
        except:
            session.rollback()
            return 'Error', 401
        return json.dumps({'msg': 'Success'}), 200
    except Exception as e:
        session.rollback()
        return str(e)
Beispiel #4
0
def fetch_emails(creds, max_results, fetch_label):
    """
    Fetches a list of emails from the
    authenticated user's mail
    ----------------------------------

    arguments:
        - creds: oauth token object
        - fetch_label: label for filtered fetch 
    """
    service = build('gmail', 'v1', credentials=creds)
    include_spam_trash = False
    if ('SPAM' in fetch_label or 'TRASH' in fetch_label):
        include_spam_trash = True

    result = service.users().messages().list(
        userId='me',
        labelIds=fetch_label,
        maxResults=max_results,
        includeSpamTrash=include_spam_trash).execute()

    message_ids = result.get('messages', [])
    if not message_ids:
        print(f'No new {fetch_label} messages!')
    else:
        print(f'{len(message_ids)} {fetch_label} messages were fetched!')
        s = Session()
        count = 0
        for message_id in message_ids:
            result = service.users().messages().get(
                userId='me', id=message_id['id'], format='metadata').execute()
            headers = result['payload']['headers']
            record = {'message_id': result['id'], 'labels': result['labelIds']}
            for header in headers:
                if header['name'] == 'From':
                    record['sender'] = header['value']
                elif header['name'] == 'To':
                    record['recipient'] = header['value']
                elif header['name'] == 'Subject':
                    record['subject'] = header['value']
                elif header['name'] == 'Date':
                    record['date'] = parser.parse(header['value']).date()

            message = Message(**record)
            q = s.query(Message).filter_by(message_id=message.message_id)
            if not s.query(q.exists()).scalar():
                s.add(message)
                count += 1
        s.commit()
        s.close()
        print(f'{count} new {fetch_label} messages were added to the db!')
Beispiel #5
0
def teacher_station():
    from db.models import CustomUser
    certifications = Certification.objects.filter(
        status=Certification.STATUS_CHOICES[1][0], push_time=None)
    for c in certifications:
        msg = '%s老师入驻啦' % (c.user.full_name or c.user.phone, )
        res = push_message(jpush.all_, msg)
        if res:
            c.push_time = datetime.now()
            c.save()
            querysetlist = []
            for user in CustomUser.objects.filter(is_active=True):
                querysetlist.append(
                    Message(user_id=user.id,
                            message=msg,
                            class_name=Message.CLASS_NAME_CHOICES[2][0],
                            class_id=c.user_id))
            Message.objects.bulk_create(querysetlist)
Beispiel #6
0
def newMessage():
    try:
        # This page will be for creating a new Customer
        customers = db_session.query(
            User_Customer).filter_by(user_id=current_user.id).all()

        if request.method == 'POST':
            apiClient = db_session.query(User_Api_Client).filter_by(
                user_id=current_user.id).all()[0]
            destinationNumbers = list(map(lambda x: db_session.query(User_Customer).filter_by(
                id=int(x)).one().phone, request.form.getlist('customerSelect')))

            # Commented out to not make unnecessary api calls
            client = plivo.RestClient(
                auth_id=aes_decrypt(apiClient.api_id), auth_token=aes_decrypt(apiClient.auth_id))
            response = client.messages.create(
                src=current_user.phone,
                dst="<".join(destinationNumbers),
                text=request.form['message'],
                url="https://sms-messages.herokuapp.com/message/status")

            # message_uuid = []
            # for i in destinationNumbers:
            #     message_uuid.append(datetime.datetime.now())
            # response = {'message_uuid': message_uuid}
            # uncomment below when using api
            for i, uuid in enumerate(response.message_uuid, 0):

                # uncomment below when not using api
                # for i, uuid in enumerate(response['message_uuid'], 0):
                newMessage = Message(
                    user_id=current_user.id, user_customer_id=int(request.form.getlist('customerSelect')[i]), message_uuid=uuid, message=request.form['message'], direction="outbound")
                db_session.add(newMessage)
                db_session.commit()
            flash('The message was sucessfully created!')
            return redirect(url_for('newMessage', customers=customers))
        else:
            return render_template('/messages/newMessage.html', customers=customers)
    except:
        print('some error could not save transaction, rolling back')
        db_session.rollback()
        db_session.commit()
        flash('There was some errors and some of your messages my have Failed!')
        return render_template('/messages/newMessage.html', customers=customers)
Beispiel #7
0
def message_controller(request):
    errors = get_validation_errors(request, 'text', 'to_client')
    if errors:
        return make_response(request, 400, {'errors': errors})

    request_data = request.get('data')
    to_client = request_data.get('to_client')
    text = request_data.get('text')

    with session_scope() as session:
        try:
            to_client = session.query(Client).filter_by(name=to_client).first()

        except AttributeError:
            data = f'Client "{to_client}" not found.'
            return make_response(request, 404, data)

        else:
            from_client = session.query(ClientSession).filter_by(token=request.get('token')).first().client
            from_client_id = from_client.id

            to_client_id = to_client.id

            message = Message(
                text=text, from_client_id=from_client_id,
                to_client_id=to_client_id, created=datetime.fromtimestamp(request.get('time'))
            )
            session.add(message)

            data = {
                'text': text, 'to_client': to_client.name,
                'from_client': from_client.name, 'time': request.get('time')
            }

            to_client_session = to_client.sessions.filter_by(closed=None).first()

            if to_client_session:
                addr, port = to_client_session.remote_addr, to_client_session.remote_port
                r_addr = get_socket_info(addr, port)

                return make_response(request, 200, data, r_addr)

            return make_response(request, 200, data)
Beispiel #8
0
def upload_sms():
    body = request.get_json()
    token = body.get('token')
    sms_thread_id = body.get('thread_id')
    person = body.get('person')
    sms_list = body.get('sms_list')
    try:
        idinfo = id_token.verify_oauth2_token(token, requests.Request(),
                                              environ.get("GOOGLE_CLIENT_ID"))
        if idinfo['iss'] not in [
                'accounts.google.com', 'https://accounts.google.com'
        ]:
            raise ValueError('Wrong issuer')
        userid = idinfo['sub']
        user = session.query(User).filter(User.id == userid).one()
        new_thread = MessageThread(id=sms_thread_id,
                                   user_id=user.id,
                                   person=person)
        session.add(new_thread)
        try:
            session.commit()
        except:
            session.rollback()
        for sms in sms_list:
            date = datetime.fromtimestamp(sms['date'] / 1000.0)
            msg = Message(thread_id=new_thread.id,
                          type='SMS',
                          body=sms['body'],
                          date=date,
                          user_speaking=sms['user_speaking'])
            session.add(msg)
        session.commit()
        return 'Succesful'
    except Exception as e:
        session.rollback()
        return str(e) + 'threadid:' + str(sms_thread_id)