def put(self, request, *args, **kwargs):
     try:
         access_token = kwargs['access_token']
         id = kwargs['id']
         notification = NotificationView.get_notification(access_token, id)
         logger.info(notification.message)
         serializer = NotificationSerializer(notification, request.data, partial=True)
         if serializer.is_valid():
             serializer.save()
         return response.Response(serializer.data)
     except Exception as e:
         NotificationView.handle_error(e)
Esempio n. 2
0
 def post(self, request, *args, **kwargs):
     access_token = kwargs['access_token']
     try:
         message = request.data['message']
         url = None
         user = UserProfileView.get_profile(access_token).user
         if request.data.__contains__('url'):
             url = request.data['url']
         notification = Notification.objects.create_notification(
             message, user, url)
         notification.save()
         serializer = NotificationSerializer(notification)
         conn = stomp.Connection([(STOMP_SERVER_URL, STOMP_PORT)])
         conn.start()
         conn.connect('admin', 'password', wait=True)
         conn.send(body=json.dumps(serializer.data),
                   destination='/topic/notifications_' + str(user.id))
         logger.info("Sending a message through apollo")
         time.sleep(2)
         logger.info("Message Sent.........Disconnecting")
         conn.disconnect()
         logger.info("Disconnected !!!")
         return response.Response(serializer.data)
     except Exception as e:
         NotificationView.handle_error(e)
Esempio n. 3
0
 def get(self, request, *args, **kwargs):
     access_token = kwargs['access_token']
     id = kwargs['id']
     try:
         notification = NotificationView.get_notification(access_token, id)
         logger.info(notification.message)
         serializer = NotificationSerializer(notification)
         return response.Response(serializer.data)
     except Exception as e:
         NotificationView.handle_error(e)
    def delete(self, request, *args, **kwargs):
        try:
            logger.info("Starting DELETE method")
            access_token = kwargs['access_token']
            global exitFlag
            exitFlag = 0
            id = kwargs['id']
            logger.info("access token is " + access_token + " event id is" +
                        id)
            user = UserProfileView.get_profile(access_token).user
            event = Event.objects.get(pk=id)
            logger.info("event obtained from id")
            if "user_ids" in request.data:
                if user in event.admin.all():
                    user_ids = eval(request.data['user_ids'])
                    for user_id in user_ids:
                        user_ = BdayAppUser.objects.get(pk=user_id)
                        friends = UserProfileView.get_profile(
                            access_token).app_friends.all()
                        friends_ = UserProfile.objects.get(
                            user=user_).app_friends.all()
                        if user in friends_ and user_ in friends:
                            event.members.remove(user_)
                            event.save()
                            members = event.members.all()
                            admins = event.admin.all()
                            workQueue = Queue.Queue(10)
                            queueLock.acquire()
                            for member in members:
                                chat = EventChat.objects.create_event_chat(
                                    Event.objects.get(pk=id),
                                    user,
                                    wish=None,
                                    message_field=str(user.id) + " deleted " +
                                    str(user_.id) + " from the event",
                                    url_field=None,
                                    file_field=None,
                                    type='CENTER')
                                chat.save()
                                logger.info("added center chat")
                                notification_message = "Admin " + UserProfile.objects.get(
                                    user=user
                                ).first_name + " has deleted " + UserProfile.objects.get(
                                    user=user_
                                ).first_name + " from event " + event.name
                                notification = Notification.objects.create_notification(
                                    notification_message,
                                    member,
                                    None,
                                    type='MEMBER_DELETION_BY_ADMIN',
                                    event=event)
                                notification.save()
                                serializer = NotificationSerializer(
                                    notification)
                                workQueue.put({
                                    "data":
                                    serializer.data,
                                    "destination":
                                    '/topic/notifications_' + str(member.id)
                                })
                            for admin in admins:
                                chat = EventChat.objects.create_event_chat(
                                    Event.objects.get(pk=id),
                                    user,
                                    wish=None,
                                    message_field=str(user.id) + " deleted " +
                                    str(user_.id) + " from the event",
                                    url_field=None,
                                    file_field=None,
                                    type='CENTER')
                                chat.save()
                                logger.info("added center chat")
                                notification_message = "Admin " + UserProfile.objects.get(
                                    user=user
                                ).first_name + " has deleted " + UserProfile.objects.get(
                                    user=user_
                                ).first_name + " from event " + event.name
                                notification = Notification.objects.create_notification(
                                    notification_message,
                                    admin,
                                    None,
                                    type='MEMBER_DELETION_BY_ADMIN',
                                    event=event)
                                notification.save()
                                serializer = NotificationSerializer(
                                    notification)
                                workQueue.put({
                                    "data":
                                    serializer.data,
                                    "destination":
                                    '/topic/notifications_' + str(admin.id)
                                })

                            queueLock.release()
                            threads = []
                            for i in range(0, MAX_THREADS):
                                thread = MultiThreading(
                                    "WORKER " + str(i), workQueue)
                                thread.start()
                                threads.append(thread)
                            while not workQueue.empty():
                                pass

                            # Notify threads it's time to exit
                            exitFlag = 1
                            for t in threads:
                                t.join()
                            logger.info("Sent all Notification")
                        else:
                            raise exceptions.PermissionDenied()

                    #event.members.remove(BdayAppUser.objects.get(pk=request.data['user_id']))
                    #event.save()
                    logger.info("Completing DELETE method")
                    return response.Response(status=status.HTTP_202_ACCEPTED)
                else:
                    raise exceptions.PermissionDenied()
            else:
                if user in event.members.all() and user not in event.admin.all(
                ):
                    event.members.remove(user)
                    members = event.members.all()
                    admins = event.admin.all()
                    workQueue = Queue.Queue(10)
                    queueLock.acquire()
                    for member in members:
                        event.save()
                        chat = EventChat.objects.create_event_chat(
                            Event.objects.get(pk=event.id),
                            user,
                            wish=None,
                            message_field=str(user.id) + "left the event",
                            url_field=None,
                            file_field=None,
                            type='CENTER')
                        chat.save()
                        notification_message = "Your friend " + UserProfile.objects.get(
                            user=user
                        ).first_name + " left the event " + event.name
                        notification = Notification.objects.create_notification(
                            notification_message,
                            member,
                            None,
                            type='MEMBER_LEAVING_EVENT',
                            event=event)
                        notification.save()
                        serializer = NotificationSerializer(notification)
                        workQueue.put({
                            "data":
                            serializer.data,
                            "destination":
                            '/topic/notifications_' + str(member.id)
                        })
                    for admin in admins:
                        event.save()
                        chat = EventChat.objects.create_event_chat(
                            Event.objects.get(pk=event.id),
                            user,
                            wish=None,
                            message_field=str(user.id) + "left the event",
                            url_field=None,
                            file_field=None,
                            type='CENTER')
                        chat.save()
                        notification_message = "Your friend " + UserProfile.objects.get(
                            user=user
                        ).first_name + " left the event " + event.name
                        notification = Notification.objects.create_notification(
                            notification_message,
                            admin,
                            None,
                            type='MEMBER_LEAVING_EVENT',
                            event=event)
                        notification.save()
                        serializer = NotificationSerializer(notification)
                        workQueue.put({
                            "data":
                            serializer.data,
                            "destination":
                            '/topic/notifications_' + str(admin.id)
                        })

                    queueLock.release()
                    threads = []
                    for i in range(0, MAX_THREADS):
                        thread = MultiThreading("WORKER " + str(i), workQueue)
                        thread.start()
                        threads.append(thread)
                    while not workQueue.empty():
                        pass
                    # Notify threads it's time to exit
                    exitFlag = 1
                    for t in threads:
                        t.join()
                    logger.info("Sent all Notification")
                    logger.info("Completing DELETE method")
                else:
                    raise exceptions.PermissionDenied()
        except Event.DoesNotExist:
            raise exceptions.NotFound("event does not exist")
        except Exception as e:
            EventMembersView.handle_error(e)
    def put(self, request, *args, **kwargs):
        try:
            logger.info("Starting PUT method")
            access_token = kwargs['access_token']
            id = kwargs['id']
            global exitFlag
            exitFlag = 0
            logger.info("access token is " + access_token + " event id is" +
                        id)
            user_profile = UserProfileView.get_profile(access_token)
            user = user_profile.user
            event = Event.objects.get(pk=id)
            logger.info("event obtained from id")
            if user in event.admin.all():
                user_ids = eval(request.data['user_ids'])
                for user_id in user_ids:
                    user_ = BdayAppUser.objects.get(pk=user_id)
                    friends = UserProfileView.get_profile(
                        access_token).app_friends.all()
                    friends_ = UserProfile.objects.get(
                        user=user_).app_friends.all()
                    if user in friends_ and user_ in friends:
                        event.members.add(user_)
                        event.save()
                        chat_buffer = UnreadChatBuffer.objects.create(
                            event=event, user=user_, last_read_chat=None)
                        chat_buffer.save()
                        chat = EventChat.objects.create_event_chat(
                            Event.objects.get(pk=event.id),
                            user_,
                            wish=None,
                            message_field=str(user_.id) + " joined the event",
                            url_field=None,
                            file_field=None,
                            type='CENTER')
                        chat.save()
                        logger.info("added center chat")
                        notification_message = "Your friend " + user_profile.first_name + " added you to event " + event.name
                        notification = Notification.objects.create_notification(
                            notification_message,
                            user_,
                            None,
                            type="NEW_MEMBER_ADDITION",
                            event=event)
                        notification.save()
                        logger.info("added notification message " +
                                    notification_message)
                        serializer = NotificationSerializer(notification)
                        conn = stomp.Connection([(STOMP_SERVER_URL, STOMP_PORT)
                                                 ])
                        conn.start()
                        conn.connect(STOMP_ID, STOMP_PASSWORD, wait=True)
                        conn.send(body=json.dumps(serializer.data),
                                  destination='/topic/notifications_' +
                                  str(user_.id))
                        logger.info("Sending a message through apollo")
                        time.sleep(2)
                        logger.info("Message Sent.........Disconnecting")
                        conn.disconnect()
                        logger.info("Disconnected !!!")
                    else:
                        raise exceptions.PermissionDenied()
                    event_members = event.members.all()
                    event_admins = event.admin.all()
                    workQueue = Queue.Queue(10)
                    queueLock.acquire()
                    for member in event_members:
                        if member.id is user_.id:
                            continue
                        notification_message = "Your friend " + UserProfile.objects.get(
                            user=user_
                        ).first_name + " joined the event " + event.name
                        notification = Notification.objects.create_notification(
                            notification_message,
                            member,
                            None,
                            type="NEW_MEMBER_JOINED",
                            event=event)
                        notification.save()
                        serializer = NotificationSerializer(notification)
                        workQueue.put({
                            "data":
                            serializer.data,
                            "destination":
                            '/topic/notifications_' + str(member.id)
                        })
                    for admin in event_admins:
                        notification_message = "Your friend " + UserProfile.objects.get(
                            user=user_
                        ).first_name + " joined the event " + event.name
                        notification = Notification.objects.create_notification(
                            notification_message,
                            admin,
                            None,
                            type="NEW_MEMBER_JOINED",
                            event=event)
                        notification.save()
                        serializer = NotificationSerializer(notification)
                        workQueue.put({
                            "data":
                            serializer.data,
                            "destination":
                            '/topic/notifications_' + str(admin.id)
                        })

                    queueLock.release()
                    threads = []
                    for i in range(0, MAX_THREADS):
                        thread = MultiThreading("WORKER " + str(i), workQueue)
                        thread.start()
                        threads.append(thread)
                    while not workQueue.empty():
                        pass

                    # Notify threads it's time to exit
                    exitFlag = 1
                    for t in threads:
                        t.join()
                    logger.info("Sent all notifications")
                logger.info("Completing PUT method")
                return response.Response(status=status.HTTP_202_ACCEPTED)
            else:
                raise exceptions.PermissionDenied()
        except Event.DoesNotExist:
            raise exceptions.NotFound("event does not exist")
        except Exception as e:
            EventMembersView.handle_error(e)
Esempio n. 6
0
def process_payment(request):
    global exitFlag
    exitFlag = 0
    checksum = None
    message = {}
    if request.method == "POST":
        respons_dict = {}

        for i in request.POST.keys():
            print i
            respons_dict[i] = request.POST[i]
            if i == 'CHECKSUMHASH':
                checksum = request.POST[i]

        if 'GATEWAYNAME' in respons_dict:
            if respons_dict['GATEWAYNAME'] == 'WALLET':
                respons_dict['BANKNAME'] = 'null'

        verify = Checksum.verify_checksum(respons_dict, MERCHANT_KEY, checksum)
        print verify

        if verify:
            if respons_dict['RESPCODE'] == '01':
                print "order successful"
                for element in [
                        "SUBS_ID", "PROMO_CAMP_ID", "PROMO_STATUS",
                        "PROMO_RESPCODE"
                ]:
                    if element not in respons_dict:
                        respons_dict[element] = None
                user_profile = UserProfileView.get_profile(
                    request.session["ACCESS_TOKEN"])
                if request.session["transaction_type"] == "USER":
                    wallet = Wallet.objects.get(
                        associated_user=user_profile.user)
                else:
                    event = Event.objects.get(pk=request.session["event_id"])
                    wallet = Wallet.objects.get(associated_event=event)
                with transaction.atomic():
                    amount = moneyed.Money(float(respons_dict['TXNAMOUNT']),
                                           respons_dict['CURRENCY'])
                    wallet.balance = wallet.balance + amount
                    wallet.save()
                    if request.session["transaction_type"] == "USER":
                        transaction_object = Transaction.objects.create(
                            from_wallet=None,
                            to_wallet=Wallet.objects.get(
                                associated_user=user_profile.user),
                            type='CREDIT',
                            amount=amount,
                            default_currency=respons_dict['CURRENCY'],
                            status=respons_dict["STATUS"],
                            order_id=respons_dict["ORDERID"],
                            external_transaction_flag=True,
                            external_subscription_id=respons_dict["SUBS_ID"],
                            external_transaction_id=respons_dict["TXNID"],
                            bank_transaction_id=respons_dict["BANKTXNID"],
                            transaction_date=respons_dict["TXNDATE"],
                            gateway_name=respons_dict["GATEWAYNAME"],
                            bank_name=respons_dict["BANKNAME"],
                            payment_mode=respons_dict["PAYMENTMODE"],
                            promo_camp_id=respons_dict["PROMO_CAMP_ID"],
                            promo_status=respons_dict["PROMO_STATUS"],
                            promo_response_code=respons_dict["PROMO_RESPCODE"])
                    else:
                        transaction_object = Transaction.objects.create(
                            from_wallet=None,
                            to_wallet=Wallet.objects.get(
                                associated_event=event),
                            type='CREDIT',
                            amount=amount,
                            default_currency=respons_dict['CURRENCY'],
                            status=respons_dict["STATUS"],
                            order_id=respons_dict["ORDERID"],
                            external_transaction_flag=True,
                            external_subscription_id=respons_dict["SUBS_ID"],
                            external_transaction_id=respons_dict["TXNID"],
                            bank_transaction_id=respons_dict["BANKTXNID"],
                            transaction_date=respons_dict["TXNDATE"],
                            gateway_name=respons_dict["GATEWAYNAME"],
                            bank_name=respons_dict["BANKNAME"],
                            payment_mode=respons_dict["PAYMENTMODE"],
                            promo_camp_id=respons_dict["PROMO_CAMP_ID"],
                            promo_status=respons_dict["PROMO_STATUS"],
                            promo_response_code=respons_dict["PROMO_RESPCODE"])
                    transaction_object.save()
                    if request.session["transaction_type"] == "EVENT":
                        members = event.members.all()
                        admins = event.admin.all()
                        workQueue = Queue.Queue(10)
                        queueLock.acquire()
                        for member in members:
                            notification_message = "Your friend " + user_profile.first_name + " contributed " + str(
                                amount.amount) + " to event " + event.name
                            notification = Notification.objects.create_notification(
                                notification_message, member, None)
                            notification.save()
                            serializer = NotificationSerializer(notification)
                            workQueue.put({
                                "data":
                                serializer.data,
                                "destination":
                                '/topic/notifications_' + str(member.id)
                            })
                        for admin in admins:
                            notification_message = "Your friend " + user_profile.first_name + " contributed " + str(
                                amount.amount) + " to event " + event.name
                            notification = Notification.objects.create_notification(
                                notification_message, admin, None)
                            notification.save()
                            serializer = NotificationSerializer(notification)
                            workQueue.put({
                                "data":
                                serializer.data,
                                "destination":
                                '/topic/notifications_' + str(admin.id)
                            })
                        queueLock.release()
                        threads = []
                        for i in range(0, MAX_THREADS):
                            thread = MultiThreading("WORKER " + str(i),
                                                    workQueue)
                            thread.start()
                            threads.append(thread)
                        while not workQueue.empty():
                            pass

                        # Notify threads it's time to exit
                        exitFlag = 1
                        for t in threads:
                            t.join()
                        print "Sent all Notification"
            else:
                print "order unsuccessful because" + respons_dict['RESPMSG']
        else:
            print "order unsuccessful because" + respons_dict['RESPMSG']
        message["details"] = respons_dict['RESPMSG']
        return HttpResponse(status=200,
                            content_type="application/json",
                            content=json.dumps(message))
    def sync_friends(user_profile):
        try:
            global exitFlag
            exitFlag = 0
            user_friends = user_profile.app_friends.all()
            graph = facebook.GraphAPI(access_token=user_profile.access_token,
                                      version='2.8')
            friends_from_facebook = graph.get_connections('me', "friends")
            while True:
                try:
                    for friend in friends_from_facebook['data']:
                        id = friend['id'].encode('utf-8')
                        try:
                            if UserProfile.objects.get(
                                    profile_id=id) is not None:
                                friends_profile = UserProfile.objects.get(
                                    profile_id=id)
                                if user_profile.user not in friends_profile.app_friends.all(
                                ):
                                    friends_profile.app_friends.add(
                                        user_profile.user)
                                    friends_profile.save()

                                    notification_message = "Your friend " + user_profile.first_name + " joined BdayApp !"
                                    notification = Notification.objects.create_notification(
                                        notification_message,
                                        friends_profile.user,
                                        None,
                                        type='NEW_JOINEE')
                                    notification.save()
                                    serializer = NotificationSerializer(
                                        notification)
                                    conn = stomp.Connection([(STOMP_SERVER_URL,
                                                              STOMP_PORT)])
                                    conn.start()
                                    conn.connect(STOMP_ID,
                                                 STOMP_PASSWORD,
                                                 wait=True)
                                    conn.send(
                                        body=json.dumps(serializer.data),
                                        destination='/topic/notifications_' +
                                        str(friends_profile.user.id))
                                    logger.info(
                                        "Sending a message through apollo")
                                    time.sleep(2)
                                    logger.info(
                                        "Message Sent.........Disconnecting")
                                    conn.disconnect()
                                    logger.info("Disconnected !!!")

                                    if friends_profile.birthday is not None:
                                        friends_bday_reminder = Reminder.objects.create_reminder(
                                            friends_profile.user_name +
                                            "'s Bday",
                                            datetime.datetime.strptime(
                                                friends_profile.birthday,
                                                '%m/%d/%Y'),
                                            user_profile.user,
                                            False,
                                            None,
                                            friends_profile.picture,
                                            type='FACEBOOK',
                                            reminder_for=friends_profile.user)
                                        friends_bday_reminder.save()
                                if friends_profile.user not in user_profile.app_friends.all(
                                ):
                                    user_profile.app_friends.add(
                                        friends_profile.user)
                                    user_profile.save()

                                    notification_message = "Your friend " + friends_profile.first_name + " joined BdayApp !"
                                    notification = Notification.objects.create_notification(
                                        notification_message,
                                        user_profile.user,
                                        None,
                                        type='NEW_JOINEE')
                                    notification.save()
                                    serializer = NotificationSerializer(
                                        notification)
                                    conn = stomp.Connection([(STOMP_SERVER_URL,
                                                              STOMP_PORT)])
                                    conn.start()
                                    conn.connect(STOMP_ID,
                                                 STOMP_PASSWORD,
                                                 wait=True)
                                    conn.send(
                                        body=json.dumps(serializer.data),
                                        destination='/topic/notifications_' +
                                        str(user_profile.user.id))
                                    logger.info(
                                        "Sending a message through apollo")
                                    time.sleep(2)
                                    logger.info(
                                        "Message Sent.........Disconnecting")
                                    conn.disconnect()
                                    logger.info("Disconnected !!!")

                                    if user_profile.birthday is not None:
                                        self_bday_reminder_for_friends = Reminder.objects.create_reminder(
                                            user_profile.user_name + "'s Bday",
                                            datetime.datetime.strptime(
                                                user_profile.birthday,
                                                '%m/%d/%Y'),
                                            friends_profile.user,
                                            False,
                                            None,
                                            user_profile.picture,
                                            type='FACEBOOK',
                                            reminder_for=user_profile.user)
                                        self_bday_reminder_for_friends.save()
                        except UserProfile.DoesNotExist:
                            continue
                    # Attempt to make a request to the next page of data, if it exists.
                    friends_from_facebook = graph.get_connections(
                        "me",
                        "friends",
                        after=friends_from_facebook['paging']['cursors']
                        ['after'])
                except KeyError:
                    # When there are no more pages (['paging']['next']), break from the
                    # loop and end the script.
                    logger.debug("Break encountered")
                    break
        except Exception as e:
            UserProfileView.handle_error(e)
    def post(self, request, access_token, *args, **kwargs):
        try:
            global exitFlag
            exitFlag = 0
            user = BdayAppUser.objects.create_user()
            minimum_balance = moneyed.Money(0, 'INR')
            maximum_balance = moneyed.Money(100000, 'INR')
            wallet = Wallet.objects.create_wallet(minimum_balance,
                                                  maximum_balance, 'U', 'INR',
                                                  user, None)
            user_profile = UserProfile.objects.create_user_profile(
                access_token, request.data['profile_type'], user)
            serializer = UserProfileSerializer(user_profile)
            friends = user_profile.app_friends.all()
            total_number_of_friends = 0
            workQueue = Queue.Queue(10)
            queueLock.acquire()

            for friend in friends:
                total_number_of_friends += 1
                notification_message = "Your friend " + user_profile.first_name + " just joined BdayApp ! Gift him !!!"
                notification = Notification.objects.create_notification(
                    notification_message, friend, None)
                notification.save()
                serializer = NotificationSerializer(notification)
                workQueue.put({
                    "data":
                    serializer.data,
                    "destination":
                    '/topic/notifications_' + str(friend.id)
                })
            queueLock.release()
            threads = []
            for i in range(0, MAX_THREADS):
                thread = MultiThreading("WORKER " + str(i), workQueue)
                thread.start()
                threads.append(thread)
            while not workQueue.empty():
                pass

            # Notify threads it's time to exit

            exitFlag = 1
            for t in threads:
                t.join()
            print "Sent all Notification"

            # conn = stomp.Connection([(STOMP_SERVER_URL, STOMP_PORT)])
            # conn.start()
            # conn.connect('admin', 'password', wait=True)
            # conn.send(body=json.dumps(serializer.data), destination='/topic/notifications_' + str(friend.id))
            # logger.info("Sending a message through apollo")
            # time.sleep(2)
            # logger.info("Message Sent.........Disconnecting")
            # conn.disconnect()
            # logger.info("Disconnected !!!")

            logger.info("Total friends" + str(total_number_of_friends))
            if total_number_of_friends > 0:
                notification_message = "Your have" + str(
                    total_number_of_friends) + " friends on Bdayapp. Kudos !!"
                notification = Notification.objects.create_notification(
                    notification_message, user_profile.user, None)
                notification.save()
                serializer = NotificationSerializer(notification)
                conn = stomp.Connection([(STOMP_SERVER_URL, STOMP_PORT)])
                conn.start()
                conn.connect(STOMP_ID, STOMP_PASSWORD, wait=True)
                conn.send(body=json.dumps(serializer.data),
                          destination='/topic/notifications_' +
                          str(user_profile.user.id))
                logger.info("Sending a message through apollo")
                time.sleep(2)
                logger.info("Message Sent.........Disconnecting")
                conn.disconnect()
                logger.info("Disconnected !!!")

            return response.Response(serializer.data)
        except Exception as e:
            UserProfileView.handle_error(e)