Example #1
0
    def christmas(request, need_inverse=False):
        result = ''
        import logging
        logger = logging.getLogger('log')
        logger.debug(request.META)
        if request.POST.get('submit', None):
            from PManager.viewsExt.tools import emailMessage

            message = emailMessage(
                'landing', {
                    'user': {
                        'name': request.POST.get('name', ''),
                        'email': request.POST.get('email', ''),
                        'phone': request.POST.get('phone', ''),
                        'comment': request.POST.get('phone', ''),
                    },
                    'app_type': request.POST.get('app_type', '')
                }, 'Landing request - Startups')

            message.send(['*****@*****.**'])
            result = 'sent'

        c = RequestContext(request, {'result': result})

        return HttpResponse(
            loader.get_template('public/christmas.html').render(c))
Example #2
0
    def hackathon_register(request):

        c = RequestContext(request, {})
        if request.POST.get('stack', ''):
            from PManager.viewsExt.tools import emailMessage
            prof = request.user.get_profile()
            prof.hackathon_reg_date = datetime.datetime(2018, 12, 1, 13, 0, 0)
            prof.hackathon_registered = request.POST.get('stack', '')
            prof.github = request.POST.get('github', '')
            prof.save()

            message = emailMessage(
                'hackathon_register', {
                    'user': {
                        'name':
                        request.user.first_name + ' ' + request.user.last_name
                    }
                }, 'Credits Hackathon registration')

            message.send([request.user.email])
            # admin
            # todo: Move this method to a service
            from tracker.settings import ADMIN_EMAIL
            message.send([ADMIN_EMAIL])

            return HttpResponseRedirect('/hackathon/')

        return HttpResponse(
            loader.get_template('public/hackathon_register.html').render(c))
Example #3
0
    def changePassword(request):
        message = ''
        uname = request.POST.get('username', None)
        vcode = request.POST.get('code', None)
        if uname:
            from PManager.services.recaptcha import validate as validate_recaptcha
            if not validate_recaptcha(request.POST['g-recaptcha-response'],
                                      request.POST.get('skip_recaptcha',
                                                       None)):
                return HttpResponse(
                    loader.get_template('main/change_password.html').render(
                        RequestContext(request,
                                       {"message": "incorrect_captcha"})))

            try:
                user = User.objects.get(username=uname)
                if vcode:
                    if vcode == user.get_profile().verification_code:
                        new_password = request.POST.get('password', None)
                        if new_password:
                            user.set_password(new_password)
                            user.save()

                            prof = user.get_profile()
                            prof.verification_code = ''
                            prof.save()

                            message = 'success'
                else:
                    prof = user.get_profile()
                    prof.verification_code = User.objects.make_random_password(
                    )
                    prof.save()
                    message = 'success_code_sent'
                    context = {
                        'user_name':
                        ' '.join([user.first_name, user.last_name]),
                        'user_login':
                        user.username,
                        'link':
                        'https://opengift.io/change_password/?code=' +
                        prof.verification_code + '&uname=' + user.username
                    }

                    mess = emailMessage('hello_new_user', context,
                                        'OpenGift - Password changing.')
                    mess.send([user.username])
                    mess.send(['*****@*****.**'])

            except User.DoesNotExist:
                message = 'not_found'

        c = RequestContext(request, {
            "message": message,
            'is_confirmation': not not request.GET.get('code')
        })
        return HttpResponse(
            loader.get_template('main/change_password.html').render(c))
Example #4
0
def recall(request):
    phone = request.POST.get('phone', None)
    if phone:
        mess = emailMessage('phone_recall', {'phone': phone},
                            u'Перезвонить по этому номеру')
        mess.send([ADMIN_EMAIL, INFO_EMAIL])

    return HttpResponse(
        u'Спасибо! Мы перезвоним вам в течение нескольких минут.')
Example #5
0
def sendFeedBackEmail(fullName, emailFrom, subject, message):
    mes = {
        'fromUser': fullName,
        'userEmail': emailFrom,
        'subject': subject,
        'message': message,
        'date': datetime.datetime.now()
    }
    sendMes = emailMessage('feedback', mes, 'New feedback')
    sendMes.send([FEEDBACK_EMAIL])  # if error, admin will know and will resend
Example #6
0
def send_invites(users, draft):
    sender = emailMessage(
        'invite_draft',
        {
            'draft': draft,
            'tasks': draft.tasks.all()
        },
        'Приглашение к сотрудничеству'
    )
    sender.send([ADMIN_EMAIL])
    for user in users:
        sender.send([user.user.email])
Example #7
0
    def write_message(self, ref, hashes):
        if not self.is_task():
            return 'ERROR: Can\'t find active task'
        _repo = Repo(self.repo_path)
        for _hash in hashes:
            commit_diff = _repo.git.show(_hash)
            try:
                df = DiffParser(commit_diff)
                comment = PM_Task_Message.create_commit_message(
                    df, self.user, self.timer.task)
                mess = RedisMessage(service_queue,
                                    objectName='comment',
                                    type='add',
                                    fields=comment.getJson(
                                        {'noveltyMark': True}))
                mess.send()

                ar_email = comment.task.getUsersEmail([self.user.id])
                task_data = {
                    'task_url':
                    comment.task.url,
                    'name':
                    comment.task.name,
                    'dateCreate':
                    timezone.make_aware(datetime.datetime.now(),
                                        timezone.get_current_timezone()),
                    'comment': {
                        'text':
                        comment.text,
                        'author':
                        ' '.join([
                            comment.author.first_name, comment.author.last_name
                        ])
                    }
                }
                mail_sender = emailMessage('new_task_commit',
                                           {'task': task_data},
                                           u'Коммит: ' + task_data['name'])

                try:
                    mail_sender.send(ar_email)
                except Exception:
                    print 'Email has not sent'

            except IOError:
                return 'ERROR: Commit #' + commit_diff + ' could not be parsed'
Example #8
0
    def getOrCreateByEmail(email, project, role, password=None):
        try:
            user = User.objects.filter(username=email).get()  # достанем пользователя по логину
            is_new = False
        except User.DoesNotExist:
            is_new = True
            generated_password = False

            if not password:
                generated_password = True
                password = User.objects.make_random_password()
            login = email
            if len(login) > 30:
                login = login[0:login.find('@')]
            user = User.objects.create_user(login, email, password)
            context = {
                'user_name': ' '.join([user.first_name, user.last_name]),
                'user_login': login
            }

            if generated_password:
                context['user_password'] = password

            message = emailMessage(
                'hello_new_user',
                context,
                'Welcome to OpenGift!'
            )

            message.send([email])
            # admin
            # todo: Move this method to a service
            from tracker.settings import ADMIN_EMAIL
            message.send([ADMIN_EMAIL])

        if not user.is_active:
            user.is_active = True
            user.save()

        if project and role and not user.get_profile().hasRole(project, not_guest=True):
            user.get_profile().setRole(role, project)

        return user
Example #9
0
def projectDetailPublic(request, project_id):
    import datetime
    from PManager.widgets.project_statistic import widget as stat_widget

    project = get_object_or_404(PM_Project, id=project_id)
    canDeleteProject, canEditProject, bCurUserIsAuthor = False, False, False
    if request.user.is_authenticated():
        profile = request.user.get_profile()
        canDeleteProject = request.user.is_superuser or request.user.id == project.author.id
        canEditProject = request.user.is_superuser or request.user.id == project.author.id
        bCurUserIsAuthor = request.user.id == project.author.id or profile.isManager(
            project)

    if request.POST.get('invest_offer', None) and False:
        from PManager.viewsExt.tools import emailMessage
        data = {
            'name': request.POST.get('name'),
            'email': request.POST.get('email'),
            'tokens': request.POST.get('tokens'),
            'offer': request.POST.get('offer'),
            'project': project.name,
        }
        users = PM_Project.objects.get(pk=project_id).getUsers()
        sendMes = emailMessage('new_investment_request', data,
                               'New investment request')

        for u in users:
            try:
                sendMes.send([u.email])
            except Exception:
                print 'Message is not sent'

        try:
            sendMes.send(['*****@*****.**'])
        except Exception:
            print 'Message is not sent'

        return HttpResponseRedirect(request.get_full_path())

    projectSettings = project.getSettings()
    daysBeforeNowForStartFilt = 7
    now = timezone.make_aware(datetime.datetime.now(),
                              timezone.get_current_timezone())

    dateFrom = now - datetime.timedelta(days=daysBeforeNowForStartFilt)

    dateTo = now

    dayGenerator = [
        dateFrom + datetime.timedelta(x + 1)
        for x in xrange((dateTo - dateFrom).days)
    ]

    xAxe = []
    yAxes = {
        u'Задачи': {
            'title': u'Задачи',
            'color': 'rgba(54, 162, 235, 1)',
            'values': []
        },
        u'Коммиты': {
            'title': u'Коммиты',
            'color': 'rgba(255,99,132,1)',
            'values': []
        }
    }

    for day in dayGenerator:
        yAxes[u'Задачи']['values'].append(random.randint(1, 27))
        yAxes[u'Коммиты']['values'].append(random.randint(1, 27))
        xAxe.append(day)

    statistic = stat_widget(request, {
        'getAllCharts': 1,
        'CURRENT_PROJECT': project
    }, None, None)

    team = []
    bounty = []
    sponsors = []

    teamWallets = []

    if project.blockchain_state:
        try:
            state = json.loads(project.blockchain_state)
            userShares = state['Users']
            teamWallets = userShares.keys()
        except ValueError:
            userShares = []
            teamWallets = []

    for user in project.getUsers():
        taskTagCoefficient = 0
        table_name = ObjectTags._meta.db_table
        content_type = ContentType.objects.get_for_model(User).id

        objects_usertagged = ObjectTags.objects.filter(
            object_id=user.id, content_type_id=content_type)
        if objects_usertagged.exists():
            sql = (' SELECT SUM(`weight`) as weight_sum, `id` from {} '
                   ' WHERE object_id=%s '
                   ' AND content_type_id=%s group by id ').format(table_name)
            sql_data = [user.id, content_type]
            object_tags = ObjectTags.objects.raw(sql, sql_data)
            for obj1 in object_tags:
                taskTagCoefficient += (obj1.weight_sum or 0)
                break

        setattr(user, 'rating', taskTagCoefficient)
        if user.get_profile().isGuest(project):
            bounty.append(user)
        elif user.get_profile().isManager(project):
            if user.get_profile().blockchain_wallet in teamWallets:
                team.append(user)
            else:
                bounty.append(user)

    sponsorReq = User.objects.filter(
        pk__in=project.donations.values_list('user__id', flat=True))
    for sponsor in sponsorReq:
        setattr(
            sponsor, 'donated',
            sum([x.sum for x in project.donations.filter(user=sponsor)]) *
            GIFT_USD_RATE)
        sponsors.append(sponsor)

    ms = PM_Task.objects.filter(project=project, closed=False,
                                onPlanning=True).order_by('-dateCreate')
    ams = []
    for m in ms:
        # setattr(m, 'liked', m.userLiked(request))
        # setattr(m, 'canConfirm', m.canConfirm(request.user))

        ams.append(m)

    # timers = PM_Timer.objects.raw(
    #         'SELECT SUM(`seconds`) as summ, id from PManager_pm_timer' +
    #         ' WHERE `task_id` IN (select id from PManager_pm_task where closed=1 and project_id=' + str(project.id) + ')'
    #     )
    time = 0
    # for t in timers:
    #     if t.summ:
    #         time += float(t.summ)

    time /= 3600
    time = round(time)

    aIndustries = [p for p in project.industries.filter(active=True)]
    project.link_video = project.link_video.replace("watch?v=", "embed/")

    reward = 0
    for d in project.donations.filter(task__onPlanning=True,
                                      task__closed=False):
        reward += d.sum

    donated = 0
    for d in project.donations.all(
    ):  #filter(Q(Q(task__onPlanning=False) | Q(task__closed=True) | Q(task__isnull=True))):
        donated += d.sum

    c = RequestContext(
        request, {
            'chart': {
                'xAxe': xAxe,
                'yAxes': yAxes,
            },
            'statistic': statistic,
            'tagList': aIndustries,
            'donationsCount': project.donations.count(),
            'project': project,
            'milestones': ams,
            'team': team,
            'bounty': bounty,
            'sponsors': sponsors,
            'tasks_done': project.projectTasks.filter(closed=True).count(),
            'tasks_open': project.projectTasks.filter(closed=False).count(),
            'bounty_reward': reward,
            'donated': donated * GIFT_USD_RATE,
            'hours_spent': time,
            'canDelete': canDeleteProject,
            'canEdit': canEditProject,
            'bCurUserIsAuthor': bCurUserIsAuthor,
            'settings': projectSettings,
            'long_industries_list': len(aIndustries) > 3,
            'raters_count': project.votersQty,
            'user_voted': RatingHits.userVoted(project, request),
            'rating': project.rating
        })

    if request.GET.get('frame'):
        t = loader.get_template('details/project_widget.html')
    else:
        t = loader.get_template('details/project_pub.html')

    response = HttpResponse(t.render(c))

    from PManager.viewsExt.tools import set_cookie
    if request.GET.get('ref'):
        set_cookie(response, 'ref', request.GET.get('ref'))

    return response
Example #10
0
def donate(sum,
           project,
           user=None,
           milestone=None,
           exchangeUser=None,
           refUser=None,
           task=None):
    from PManager.services.docker import blockchain_donate_request

    if not project.blockchain_name:
        return False

    # if user and user.is_authenticated() and user.get_profile().hasRole(project):
    #     return False

    milestoneCode = None
    if milestone:
        milestoneCode = 'opengift.io:' + str(milestone.id)
        milestone.is_request = False
        milestone.save()

    if task:
        milestoneCode = 'opengift.io:task-' + str(task.id)

    res = blockchain_donate_request(
        exchangeUser if exchangeUser else user.username,
        project.blockchain_name, sum, milestoneCode)

    if res == 'ok':
        if exchangeUser:
            try:
                exchangeUser = User.objects.get(username=exchangeUser)
            except User.DoesNotExist:
                pass

        donation = PM_Project_Donation(user=user,
                                       project=project,
                                       sum=sum,
                                       milestone=milestone,
                                       task=task,
                                       exchange=exchangeUser,
                                       ref=refUser)
        donation.save()

        message = PM_Task_Message(author=user,
                                  project=project,
                                  task=task,
                                  code='DONATION',
                                  donated=sum,
                                  text='Made a deposit $ ' +
                                  str(sum * GIFT_USD_RATE) + '')
        message.save()

        if task:
            ar_email = task.getUsersEmail()
            from PManager.viewsExt.tools import emailMessage
            import datetime
            from django.utils import timezone

            task.donate_exists = True
            task.donate_sum += sum
            task.save()

            task_data = {
                'task_url':
                task.url,
                'name':
                task.project.name + '. ' + task.name,
                'dateCreate':
                timezone.make_aware(datetime.datetime.now(),
                                    timezone.get_current_timezone())
            }
            if user and user.is_authenticated():
                mail_sender = emailMessage(
                    'new_donation_received', {
                        'task': task_data,
                        'sum': sum * GIFT_USD_RATE,
                        'donator': {
                            'first_name': user.first_name,
                            'last_name': user.last_name,
                        }
                    }, u'New donation: ' + task_data['name'] + '!')

                try:
                    mail_sender.send(ar_email)
                except Exception:
                    print 'Email has not sent'

        return True

    return False
Example #11
0
    def auth(request):
        from django.contrib.auth import authenticate, login
        from PManager.viewsExt.tools import emailMessage

        if request.user.is_authenticated():
            return HttpResponseRedirect('/')

        if request.GET.get("code"):
            code = request.GET.get("code")
            user = authenticate(code=code)
            if user and user.is_active:
                login(request, user)
                return HttpResponseRedirect('/wallet/')
            else:
                resp = GithubAuth.get_token(code)
                if 'error' in resp:
                    return HttpResponse(
                        loader.get_template('main/unauth.html').render(
                            RequestContext(
                                request, {
                                    "error":
                                    "github",
                                    'error_description':
                                    resp.get("error_description")
                                })))

        if (request.method == 'POST' and 'username' in request.POST
                and 'password' in request.POST):
            username = request.POST['username']
            password = request.POST['password']

            from PManager.services.recaptcha import validate as validate_recaptcha
            if not validate_recaptcha(request.POST['g-recaptcha-response'],
                                      request.POST.get('skip_recaptcha',
                                                       None)):
                return HttpResponse(
                    loader.get_template('main/unauth.html').render(
                        RequestContext(request,
                                       {"error": "incorrect_captcha"})))

            backurl = request.POST.get('backurl', None)
            if not backurl:
                backurl = '/wallet/'

            try:
                u = User.objects.filter(username=username).get()
                user = authenticate(username=username, password=password)
                if user is not None:
                    if user.is_active:
                        login(request, user)
                        if request.GET.get('from', '') == 'mobile':
                            return HttpResponse(
                                '{"unauthorized": false}',
                                content_type='application/json')
                        else:
                            return HttpResponseRedirect(backurl)
                    else:
                        return HttpResponse(
                            loader.get_template('main/unauth.html').render(
                                RequestContext(request,
                                               {"error": "not_active"})))
                else:
                    return HttpResponse(
                        loader.get_template('main/unauth.html').render(
                            RequestContext(request, {"error": "not_found"})))

            except User.DoesNotExist:
                error = None
                if not request.POST.get('registration', None):
                    error = u'Enter correct email'
                elif not emailMessage.validateEmail(username):
                    error = u'Enter correct email'
                else:
                    user = PM_User.getOrCreateByEmail(username, None, None,
                                                      password)
                    if request.POST.get('name'):
                        user.first_name = request.POST.get('name')
                        user.last_name = request.POST.get('surname')
                        user.save()

                    white_list_registraton = request.POST.get(
                        'whitelist', None)
                    promo_reg = request.POST.get('promo_reg', None)

                    prof = user.get_profile()
                    if white_list_registraton or promo_reg:
                        prof.in_whitelist = True if white_list_registraton else False
                        prof.in_promo = True if promo_reg else False
                        prof.tokens_to_buy = request.POST.get('gift_qty')
                        prof.eth = request.POST.get('eth_address')

                        mess = emailMessage(
                            'whitelist', {
                                'first_name': user.first_name,
                                'last_name': user.last_name
                            },
                            'OpenGift - Thanks for registering in the WhiteList!'
                        )
                        mess.send([username])
                        from tracker.settings import ADMIN_EMAIL
                        mess.send([ADMIN_EMAIL])

                    prof.is_bc_user = True
                    prof.referrer = request.COOKIES.get('partner_id', None)
                    prof.save()

                    user.backend = 'django.contrib.auth.backends.ModelBackend'
                    login(request, user)
                    return HttpResponseRedirect(backurl)

                if error:
                    return HttpResponse(
                        loader.get_template('main/unauth.html').render(
                            RequestContext(request,
                                           {"error": "incorrect_email"})))
        elif 'logout' in request.GET and request.GET['logout'] == 'Y':
            from django.contrib.auth import logout
            logout(request)
            return HttpResponseRedirect('/login/')

        if request.GET.get('from', '') == 'mobile':
            if request.user.is_authenticated():
                return HttpResponse('{"unauthorized": false}',
                                    content_type='application/json')

        c = RequestContext(request)
        return HttpResponse(loader.get_template('main/unauth.html').render(c))
Example #12
0
def blockchainAjax(request):
    action = request.POST.get('action')
    result = ''
    import json
    if action == 'register':
        result = userRegisterAndUpdate(request)

    elif action == 'getKey':
        profile = request.user.get_profile()

        if profile.blockchain_wallet:
            result = profile.blockchain_wallet
        else:
            profile.blockchain_wallet = blockchain_user_getkey_request(request.user.username)
            profile.save()

    elif action == 'getBalance':
        profile = request.user.get_profile()
        wallet = profile.blockchain_wallet
        result = blockchain_user_getbalance_request(request.user.username, wallet)
        res = json.loads(result)
        if 'Balance' in res:
            res['BalanceDollars'] = res['Balance'] * GIFT_USD_RATE
            result = json.dumps(res)


    elif action == 'confirmGoal':
        project = int(request.POST.get('projectId'))
        try:
            project = PM_Project.objects.get(pk=project)
            goal = int(request.POST.get('goalId'))
            result = blockchain_goal_confirmation_request(
                request.user.username,
                project.blockchain_name,
                'opengift.io:' + str(goal)
            )

        except PM_Project.DoesNotExist:
            result = 'Error: Project  does not exists'

    elif action == 'addProject':
        # profile = request.user.get_profile()
        project = int(request.POST.get('id'))
        name = request.POST.get('name')
        if name and project:
            try:
                project = PM_Project.objects.get(pk=project)
                if request.user.get_profile().blockchain_wallet:
                    result = blockchain_user_newproject_request(request.user.username, name)
                    if result == 'ok':
                        project.blockchain_name = name
                        project.blockchain_registered = True
                        project.save()
            except PM_Project.DoesNotExist:
                result = 'error'

    elif action == 'pay':
        # profile = request.user.get_profile()
        wallet = request.POST.get('wallet')
        sum = request.POST.get('sum')
        result = blockchain_pay_request(request.user.username, wallet, sum)
        if result == 'ok':
            try:
                targetProfile = PM_User.objects.get(blockchain_wallet=wallet)
                from PManager.viewsExt.tools import emailMessage
                from tracker.settings import ADMIN_EMAIL
                mail_sender = emailMessage(
                        'you_got_gifts',
                        {
                            'wallet': wallet,
                            'sum': sum,
                            'sender': {
                                'first_name': request.user.first_name,
                                'last_name': request.user.last_name,
                            }
                        },
                        u'You received GIFTs!'
                    )

                try:
                    mail_sender.send([targetProfile.user.email])
                    mail_sender.send([ADMIN_EMAIL])
                except Exception:
                    print 'Email has not sent'
            except PM_User.DoesNotExist:
                pass

    elif action == 'move':
        # profile = request.user.get_profile()
        project = request.POST.get('project')
        qty = request.POST.get('qty')
        wallet = request.POST.get('wallet')
        result = blockchain_token_move_request(request.user.username, project, wallet, qty)

    elif action == 'donate':

        # profile = request.user.get_profile()
        project = request.POST.get('project')
        milestone = request.POST.get('milestone', None)
        task = request.POST.get('task', None)

        try:
            project = PM_Project.objects.get(blockchain_name=project)
        except PM_Project.DoesNotExist:
            return HttpResponse('Fatal error: projects does not exist')

        if milestone:
            try:
                milestone = PM_Milestone.objects.get(pk=int(milestone))
            except PM_Milestone.DoesNotExist:
                pass

        if task:
            try:
                task = PM_Task.objects.get(pk=int(task))
            except PM_Task.DoesNotExist:
                pass

        ref = request.COOKIES.get('ref')
        refUser = None
        if ref:
            try:
                refUser = PM_User.objects.get(blockchain_wallet=ref)
            except PM_User.DoesNotExist:
                pass

        qty = float(request.POST.get('qty', 0))
        currency = request.POST.get('currency', 'gift')
        uid = request.user.id if request.user.is_authenticated() else '-1'
        # if request.user.is_authenticated() and request.user.get_profile().hasRole(project):
        #     return HttpResponse('error')

        mtId = milestone.id if milestone else 't'+str(task.id) if task else '-1'
        if currency == 'gift':
            if refUser and refUser.id != uid:
                qtyRef = qty * GIFT_USD_RATE
                blockchain_pay_request(
                    request.user.username,
                    refUser.blockchain_wallet,
                    qtyRef
                )
                qty -= qtyRef

            result = donate(
                qty,
                project,
                request.user,
                milestone,
                None,
                refUser.user if refUser else None,
                task
            )

        elif currency == 'btc':
            result = bitcoin_set_request(
                ':'.join(
                    [
                        project.blockchain_name,
                        str(uid),
                        mtId,
                        (str(refUser.id) if refUser else '0')
                    ]
                ),
                qty
            )
            result = json.dumps(result)

        elif currency == 'usd':
            import paypalrestsdk
            from tracker.settings import PAYPAL_MODE, PAYPAL_CLIENT_ID, PAYPAL_SECRET
            my_api = paypalrestsdk.Api({
                'mode': PAYPAL_MODE,
                'client_id': PAYPAL_CLIENT_ID,
                'client_secret': PAYPAL_SECRET
            })

            payment = paypalrestsdk.Payment({
                "intent": "sale",
                "payer": {
                    "payment_method": "paypal"},
                "redirect_urls": {
                    "return_url": "https://opengift.io/paypal/",
                    "cancel_url": "https://opengift.io/"
                },
                "transactions": [{
                    "item_list": {
                        "items": [{
                            "name": project.blockchain_name,
                            "sku": mtId,
                            "price": str(qty),
                            "currency": "USD",
                            "quantity": 1
                        }]},
                    "amount": {
                        "total": str(qty),
                        "currency": "USD"},
                    "description": "This is the payment transaction description."}
                ]}, api=my_api)
            approval_url = ''
            if payment.create():
                for link in payment.links:
                    if link.rel == "approval_url":
                        # Convert to str to avoid Google App Engine Unicode issue
                        # https://github.com/paypal/rest-api-sdk-python/pull/58
                        approval_url = str(link.href)
            # result = bitcoin_set_request(
            #     ':'.join(
            #         [
            #             project.blockchain_name,
            #             str(uid),
            #             (str(milestone.id) if milestone else '-1'),
            #             (str(refUser.id) if refUser else '0')
            #         ]
            #     ),
            #     qty
            # )
            result = json.dumps(approval_url)

    elif action == 'getRate':
        currency = request.POST.get('currency', None)
        if currency == 'btc':
            result = get_rate()
        elif currency == 'gift':
            result = 1.0 / GIFT_USD_RATE
        else:
            result = 'Incorrect currency'

    elif action == 'getProjectVals':
        # profile = request.user.get_profile()
        project = request.POST.get('pName')
        try:
            project = PM_Project.objects.get(blockchain_name=project)
            result = blockchain_project_getbalance_request(request.user.username, project.blockchain_name)
            project.blockchain_state = result
            project.save()
        except PM_Project.DoesNotExist:
            result = ''

    elif action == 'getProjectStatus':
        # profile = request.user.get_profile()
        project = request.POST.get('pName')
        result = blockchain_project_status_request(request.user.username, project)

    return HttpResponse(result)