-
-
Notifications
You must be signed in to change notification settings - Fork 775
/
views.py
4895 lines (4050 loc) · 179 KB
/
views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
'''
Copyright (C) 2019 Gitcoin Core
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
from __future__ import print_function, unicode_literals
import hashlib
import json
import logging
import os
import time
from copy import deepcopy
from datetime import datetime
from decimal import Decimal
from django.conf import settings
from django.contrib import messages
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.core.serializers.json import DjangoJSONEncoder
from django.db.models import Avg, Count, Prefetch, Q
from django.http import Http404, HttpResponse, JsonResponse
from django.shortcuts import redirect
from django.template import loader
from django.template.response import TemplateResponse
from django.templatetags.static import static
from django.urls import reverse
from django.utils import timezone
from django.utils.html import escape, strip_tags
from django.utils.http import is_safe_url
from django.utils.text import slugify
from django.utils.translation import gettext_lazy as _
from django.views.decorators.clickjacking import xframe_options_exempt
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_GET, require_POST
import magic
from app.utils import clean_str, ellipses, get_default_network
from avatar.utils import get_avatar_context_for_user
from avatar.views_3d import avatar3dids_helper
from bleach import clean
from bounty_requests.models import BountyRequest
from cacheops import invalidate_obj
from chat.tasks import add_to_channel
from chat.utils import create_channel_if_not_exists, create_user_if_not_exists
from dashboard.context import quickstart as qs
from dashboard.utils import (
ProfileHiddenException, ProfileNotFoundException, get_bounty_from_invite_url, get_orgs_perms, profile_helper,
)
from economy.utils import ConversionRateNotFoundError, convert_amount, convert_token_to_usdt
from eth_utils import to_checksum_address, to_normalized_address
from gas.utils import recommend_min_gas_price_to_confirm_in_time
from git.utils import (
get_auth_url, get_gh_issue_details, get_github_user_data, get_url_dict, is_github_token_valid, search_users,
)
from kudos.models import KudosTransfer, Token, Wallet
from kudos.utils import humanize_name
from mailchimp3 import MailChimp
from marketing.mails import admin_contact_funder, bounty_uninterested
from marketing.mails import funder_payout_reminder as funder_payout_reminder_mail
from marketing.mails import (
new_reserved_issue, share_bounty, start_work_approved, start_work_new_applicant, start_work_rejected,
wall_post_email,
)
from marketing.models import EmailSubscriber, Keyword
from oauth2_provider.decorators import protected_resource
from pytz import UTC
from ratelimit.decorators import ratelimit
from retail.helpers import get_ip
from web3 import HTTPProvider, Web3
from .export import (
ActivityExportSerializer, BountyExportSerializer, GrantExportSerializer, ProfileExportSerializer,
filtered_list_data,
)
from .helpers import (
bounty_activity_event_adapter, get_bounty_data_for_activity, handle_bounty_views, load_files_in_directory,
)
from .models import (
Activity, BlockedURLFilter, Bounty, BountyDocuments, BountyEvent, BountyFulfillment, BountyInvites, CoinRedemption,
CoinRedemptionRequest, Coupon, Earning, FeedbackEntry, HackathonEvent, HackathonProject, HackathonRegistration,
HackathonSponsor, Interest, LabsResearch, PortfolioItem, Profile, ProfileSerializer, ProfileView, RefundFeeRequest,
SearchHistory, Sponsor, Subscription, Tool, ToolVote, TribeMember, UserAction, UserVerificationModel,
)
from .notifications import (
maybe_market_tip_to_email, maybe_market_tip_to_github, maybe_market_tip_to_slack, maybe_market_to_email,
maybe_market_to_github, maybe_market_to_slack, maybe_market_to_user_discord, maybe_market_to_user_slack,
)
from .utils import (
apply_new_bounty_deadline, get_bounty, get_bounty_id, get_context, get_etc_txn_status, get_unrated_bounties_count,
get_web3, has_tx_mined, is_valid_eth_address, re_market_bounty, record_user_action_on_interest,
release_bounty_to_the_public, web3_process_bounty,
)
logger = logging.getLogger(__name__)
confirm_time_minutes_target = 4
# web3.py instance
w3 = Web3(HTTPProvider(settings.WEB3_HTTP_PROVIDER))
@protected_resource()
def oauth_connect(request, *args, **kwargs):
active_user_profile = Profile.objects.filter(user_id=request.user.id).select_related()[0]
from marketing.utils import should_suppress_notification_email
user_profile = {
"login": active_user_profile.handle,
"email": active_user_profile.user.email,
"name": active_user_profile.user.get_full_name(),
"handle": active_user_profile.handle,
"id": f'{active_user_profile.user.id}',
"auth_data": f'{active_user_profile.user.id}',
"auth_service": "gitcoin",
"notify_props": {
"email": "false",
"push": "mention",
"desktop": "all",
"desktop_sound": "true",
"mention_keys": f'{active_user_profile.handle}, @{active_user_profile.handle}',
"channel": "true",
"first_name": "false"
}
}
return JsonResponse(user_profile, status=200, safe=False)
def org_perms(request):
if request.user.is_authenticated and getattr(request.user, 'profile', None):
profile = request.user.profile
response_data = get_orgs_perms(profile)
else:
return JsonResponse(
{'error': _('You must be authenticated via github to use this feature!')},
status=401)
return JsonResponse({'orgs': response_data}, safe=False)
def record_user_action(user, event_name, instance):
instance_class = instance.__class__.__name__.lower()
kwargs = {
'action': event_name,
'metadata': {f'{instance_class}_pk': instance.pk},
}
if isinstance(user, User):
kwargs['user'] = user
elif isinstance(user, str):
try:
user = User.objects.get(username=user)
kwargs['user'] = user
except User.DoesNotExist:
return
if hasattr(user, 'profile'):
kwargs['profile'] = user.profile
try:
UserAction.objects.create(**kwargs)
except Exception as e:
# TODO: sync_profile?
logger.error(f"error in record_action: {e} - {event_name} - {instance}")
def record_bounty_activity(bounty, user, event_name, interest=None):
"""Creates Activity object.
Args:
bounty (dashboard.models.Bounty): Bounty
user (string): User name
event_name (string): Event name
interest (dashboard.models.Interest): Interest
Raises:
None
Returns:
None
"""
kwargs = {
'activity_type': event_name,
'bounty': bounty,
'metadata': get_bounty_data_for_activity(bounty)
}
if isinstance(user, str):
try:
user = User.objects.get(username=user)
except User.DoesNotExist:
return
if hasattr(user, 'profile'):
kwargs['profile'] = user.profile
else:
return
if event_name == 'worker_applied':
kwargs['metadata']['approve_worker_url'] = bounty.approve_worker_url(user.profile)
kwargs['metadata']['reject_worker_url'] = bounty.reject_worker_url(user.profile)
elif event_name in ['worker_approved', 'worker_rejected'] and interest:
kwargs['metadata']['worker_handle'] = interest.profile.handle
try:
if event_name in bounty_activity_event_adapter:
event = BountyEvent.objects.create(bounty=bounty,
event_type=bounty_activity_event_adapter[event_name],
created_by=kwargs['profile'])
bounty.handle_event(event)
return Activity.objects.create(**kwargs)
except Exception as e:
logger.error(f"error in record_bounty_activity: {e} - {event_name} - {bounty} - {user}")
def helper_handle_access_token(request, access_token):
# https://gist.github.com/owocki/614a18fbfec7a5ed87c97d37de70b110
# interest API via token
github_user_data = get_github_user_data(access_token)
request.session['handle'] = github_user_data['login']
profile = Profile.objects.filter(handle__iexact=request.session['handle']).first()
request.session['profile_id'] = profile.pk
def create_new_interest_helper(bounty, user, issue_message, signed_nda=None):
approval_required = bounty.permission_type == 'approval'
acceptance_date = timezone.now() if not approval_required else None
profile_id = user.profile.pk
record_bounty_activity(bounty, user, 'start_work' if not approval_required else 'worker_applied')
interest = Interest.objects.create(
profile_id=profile_id,
issue_message=issue_message,
pending=approval_required,
acceptance_date=acceptance_date,
signed_nda=signed_nda,
)
bounty.interested.add(interest)
record_user_action(user, 'start_work', interest)
maybe_market_to_slack(bounty, 'start_work' if not approval_required else 'worker_applied')
maybe_market_to_user_slack(bounty, 'start_work' if not approval_required else 'worker_applied')
maybe_market_to_user_discord(bounty, 'start_work' if not approval_required else 'worker_applied')
return interest
@csrf_exempt
def gh_login(request):
"""Attempt to redirect the user to Github for authentication."""
return redirect('social:begin', backend='github')
@csrf_exempt
def gh_org_login(request):
"""Attempt to redirect the user to Github for authentication."""
return redirect('social:begin', backend='gh-custom')
def get_interest_modal(request):
bounty_id = request.GET.get('pk')
if not bounty_id:
raise Http404
try:
bounty = Bounty.objects.get(pk=bounty_id)
except Bounty.DoesNotExist:
raise Http404
if bounty.event and request.user.is_authenticated:
is_registered = HackathonRegistration.objects.filter(registrant=request.user.profile, hackathon_id=bounty.event.id) or None
else:
is_registered = None
context = {
'bounty': bounty,
'gitcoin_discord_username': request.user.profile.gitcoin_discord_username if request.user.is_authenticated else None,
'active': 'get_interest_modal',
'title': _('Add Interest'),
'user_logged_in': request.user.is_authenticated,
'is_registered': is_registered,
'login_link': '/login/github?next=' + request.GET.get('redirect', '/')
}
return TemplateResponse(request, 'addinterest.html', context)
@csrf_exempt
@require_POST
def new_interest(request, bounty_id):
"""Claim Work for a Bounty.
:request method: POST
Args:
bounty_id (int): ID of the Bounty.
Returns:
dict: The success key with a boolean value and accompanying error.
"""
profile_id = request.user.profile.pk if request.user.is_authenticated and hasattr(request.user, 'profile') else None
access_token = request.GET.get('token')
if access_token:
helper_handle_access_token(request, access_token)
github_user_data = get_github_user_data(access_token)
profile = Profile.objects.prefetch_related('bounty_set') \
.filter(handle=github_user_data['login']).first()
profile_id = profile.pk
else:
profile = request.user.profile if profile_id else None
if not profile_id:
return JsonResponse(
{'error': _('You must be authenticated via github to use this feature!')},
status=401)
try:
bounty = Bounty.objects.get(pk=bounty_id)
except Bounty.DoesNotExist:
raise Http404
if bounty.is_project_type_fulfilled:
return JsonResponse({
'error': _(f'There is already someone working on this bounty.'),
'success': False},
status=401)
max_num_issues = profile.max_num_issues_start_work
currently_working_on = profile.active_bounties.count()
if currently_working_on >= max_num_issues:
return JsonResponse(
{
'error': _(f'You cannot work on more than {max_num_issues} issues at once'),
'success': False
},
status=401
)
if profile.no_times_slashed_by_staff():
return JsonResponse({
'error': _('Because a staff member has had to remove you from a bounty in the past, you are unable to start'
'more work at this time. Please leave a message on slack if you feel this message is in error.'),
'success': False},
status=401)
try:
Interest.objects.get(profile_id=profile_id, bounty=bounty)
return JsonResponse({
'error': _('You have already started work on this bounty!'),
'success': False},
status=401)
except Interest.DoesNotExist:
issue_message = request.POST.get("issue_message")
signed_nda = None
if request.POST.get("signed_nda"):
signed_nda = BountyDocuments.objects.filter(
pk=request.POST.get("signed_nda")
).first()
interest = create_new_interest_helper(bounty, request.user, issue_message, signed_nda)
if interest.pending:
start_work_new_applicant(interest, bounty)
if bounty.event:
try:
if bounty.chat_channel_id is None or bounty.chat_channel_id is '':
try:
bounty_channel_name = slugify(f'{bounty.github_org_name}-{bounty.github_issue_number}')
created, channel_details = create_channel_if_not_exists({
'team_id': settings.GITCOIN_HACK_CHAT_TEAM_ID,
'channel_display_name': f'{bounty_channel_name}-{bounty.title}'[:60],
'channel_name': bounty_channel_name[:60]
})
bounty_channel_id = channel_details['id']
bounty.chat_channel_id = bounty_channel_id
bounty.save()
except Exception as e:
logger.error(str(e))
raise ValueError(e)
else:
bounty_channel_id = bounty.chat_channel_id
funder_profile = Profile.objects.get(handle__iexact=bounty.bounty_owner_github_username)
if funder_profile:
if funder_profile.chat_id is '':
try:
created, funder_details_response = create_user_if_not_exists(funder_profile)
funder_profile.chat_id = funder_details_response['id']
funder_profile.save()
except Exception as e:
logger.error(str(e))
raise ValueError(e)
if profile.chat_id is '':
try:
created, profile_lookup_response = create_user_if_not_exists(profile)
profile.chat_id = profile_lookup_response['id']
profile.save()
except Exception as e:
logger.error(str(e))
raise ValueError(e)
profiles_to_connect = [
funder_profile.chat_id,
profile.chat_id
]
add_to_channel.delay(
{'id': bounty_channel_id}, profiles_to_connect
)
except Exception as e:
print(str(e))
except Interest.MultipleObjectsReturned:
bounty_ids = bounty.interested \
.filter(profile_id=profile_id) \
.values_list('id', flat=True) \
.order_by('-created')[1:]
Interest.objects.filter(pk__in=list(bounty_ids)).delete()
return JsonResponse({
'error': _('You have already started work on this bounty!'),
'success': False},
status=401)
if request.POST.get('discord_username'):
profile = request.user.profile
profile.gitcoin_discord_username = request.POST.get('discord_username')
profile.save()
msg = _("You have started work.")
approval_required = bounty.permission_type == 'approval'
if approval_required:
msg = _("You have applied to start work. If approved, you will be notified via email.")
elif not approval_required and not bounty.bounty_reserved_for_user:
msg = _("You have started work.")
elif not approval_required and bounty.bounty_reserved_for_user != profile:
msg = _("You have applied to start work, but the bounty is reserved for another user.")
JsonResponse({
'error': msg,
'success': False},
status=401)
return JsonResponse({
'success': True,
'profile': ProfileSerializer(interest.profile).data,
'msg': msg,
})
@csrf_exempt
@require_POST
def post_comment(request):
profile_id = request.user.profile if request.user.is_authenticated and hasattr(request.user, 'profile') else None
if profile_id is None:
return JsonResponse({
'success': False,
'msg': '',
})
bounty_id = request.POST.get('bounty_id')
bountyObj = Bounty.objects.get(pk=bounty_id)
fbAmount = FeedbackEntry.objects.filter(
sender_profile=profile_id,
bounty=bountyObj
).count()
if fbAmount > 0:
return JsonResponse({
'success': False,
'msg': 'There is already a approval comment',
})
receiver_profile = Profile.objects.filter(handle=request.POST.get('review[receiver]')).first()
kwargs = {
'bounty': bountyObj,
'sender_profile': profile_id,
'receiver_profile': receiver_profile,
'rating': request.POST.get('review[rating]', '0'),
'satisfaction_rating': request.POST.get('review[satisfaction_rating]', '0'),
'private': not bool(request.POST.get('review[public]', '0') == "1"),
'communication_rating': request.POST.get('review[communication_rating]', '0'),
'speed_rating': request.POST.get('review[speed_rating]', '0'),
'code_quality_rating': request.POST.get('review[code_quality_rating]', '0'),
'recommendation_rating': request.POST.get('review[recommendation_rating]', '0'),
'comment': request.POST.get('review[comment]', 'No comment.'),
'feedbackType': request.POST.get('review[reviewType]','approver')
}
feedback = FeedbackEntry.objects.create(**kwargs)
feedback.save()
return JsonResponse({
'success': True,
'msg': 'Finished.'
})
def rating_modal(request, bounty_id, username):
# TODO: will be changed to the new share
"""Rating modal.
Args:
pk (int): The primary key of the bounty to be rated.
Raises:
Http404: The exception is raised if no associated Bounty is found.
Returns:
TemplateResponse: The rate bounty view.
"""
try:
bounty = Bounty.objects.get(pk=bounty_id)
except Bounty.DoesNotExist:
return JsonResponse({'errors': ['Bounty doesn\'t exist!']},
status=401)
params = get_context(
ref_object=bounty,
)
params['receiver']=username
params['user'] = request.user if request.user.is_authenticated else None
return TemplateResponse(request, 'rating_modal.html', params)
def rating_capture(request):
# TODO: will be changed to the new share
"""Rating capture.
Args:
pk (int): The primary key of the bounty to be rated.
Raises:
Http404: The exception is raised if no associated Bounty is found.
Returns:
TemplateResponse: The rate bounty capture modal.
"""
user = request.user if request.user.is_authenticated else None
if not user:
return JsonResponse(
{'error': _('You must be authenticated via github to use this feature!')},
status=401)
return TemplateResponse(request, 'rating_capture.html')
def unrated_bounties(request):
"""Rating capture.
Args:
pk (int): The primary key of the bounty to be rated.
Raises:
Http404: The exception is raised if no associated Bounty is found.
Returns:
TemplateResponse: The rate bounty capture modal.
"""
# request.user.profile if request.user.is_authenticated and getattr(request.user, 'profile', None) else None
unrated_count = 0
user = request.user.profile if request.user.is_authenticated else None
if not user:
return JsonResponse(
{'error': _('You must be authenticated via github to use this feature!')},
status=401)
if user:
unrated_count = get_unrated_bounties_count(user)
# data = json.dumps(unrated)
return JsonResponse({
'unrated': unrated_count,
}, status=200)
@csrf_exempt
@require_POST
def remove_interest(request, bounty_id):
"""Unclaim work from the Bounty.
Can only be called by someone who has started work
:request method: POST
post_id (int): ID of the Bounty.
Returns:
dict: The success key with a boolean value and accompanying error.
"""
profile_id = request.user.profile.pk if request.user.is_authenticated and getattr(request.user, 'profile', None) else None
access_token = request.GET.get('token')
if access_token:
helper_handle_access_token(request, access_token)
github_user_data = get_github_user_data(access_token)
profile = Profile.objects.filter(handle=github_user_data['login']).first()
profile_id = profile.pk
if not profile_id:
return JsonResponse(
{'error': _('You must be authenticated via github to use this feature!')},
status=401)
try:
bounty = Bounty.objects.get(pk=bounty_id)
except Bounty.DoesNotExist:
return JsonResponse({'errors': ['Bounty doesn\'t exist!']},
status=401)
try:
interest = Interest.objects.get(profile_id=profile_id, bounty=bounty)
record_user_action(request.user, 'stop_work', interest)
record_bounty_activity(bounty, request.user, 'stop_work')
bounty.interested.remove(interest)
interest.delete()
maybe_market_to_slack(bounty, 'stop_work')
maybe_market_to_user_slack(bounty, 'stop_work')
maybe_market_to_user_discord(bounty, 'stop_work')
except Interest.DoesNotExist:
return JsonResponse({
'errors': [_('You haven\'t expressed interest on this bounty.')],
'success': False},
status=401)
except Interest.MultipleObjectsReturned:
interest_ids = bounty.interested \
.filter(
profile_id=profile_id,
bounty=bounty
).values_list('id', flat=True) \
.order_by('-created')
bounty.interested.remove(*interest_ids)
Interest.objects.filter(pk__in=list(interest_ids)).delete()
return JsonResponse({
'success': True,
'msg': _("You've stopped working on this, thanks for letting us know."),
})
@csrf_exempt
@require_POST
def extend_expiration(request, bounty_id):
"""Extend expiration of the Bounty.
Can only be called by funder or staff of the bounty.
:request method: POST
post_id (int): ID of the Bounty.
Returns:
dict: The success key with a boolean value and accompanying error.
"""
user = request.user if request.user.is_authenticated else None
if not user:
return JsonResponse(
{'error': _('You must be authenticated via github to use this feature!')},
status=401)
try:
bounty = Bounty.objects.get(pk=bounty_id)
except Bounty.DoesNotExist:
return JsonResponse({'errors': ['Bounty doesn\'t exist!']},
status=401)
is_funder = bounty.is_funder(user.username.lower()) if user else False
if is_funder:
deadline = round(int(request.POST.get('deadline')))
result = apply_new_bounty_deadline(bounty, deadline)
record_user_action(request.user, 'extend_expiration', bounty)
record_bounty_activity(bounty, request.user, 'extend_expiration')
return JsonResponse({
'success': True,
'msg': _(result['msg']),
})
return JsonResponse({
'error': _("You must be funder to extend expiration"),
}, status=200)
@csrf_exempt
@require_POST
def cancel_reason(request):
"""Add Cancellation Reason for Bounty during Cancellation
request method: POST
Params:
pk (int): ID of the Bounty.
canceled_bounty_reason (string): STRING with cancel reason
"""
user = request.user if request.user.is_authenticated else None
if not user:
return JsonResponse(
{'error': _('You must be authenticated via github to use this feature!')},
status=401
)
try:
bounty = Bounty.objects.get(pk=request.POST.get('pk'))
except Bounty.DoesNotExist:
return JsonResponse(
{'errors': ['Bounty not found']},
status=404
)
is_funder = bounty.is_funder(user.username.lower()) if user else False
if is_funder:
canceled_bounty_reason = request.POST.get('canceled_bounty_reason', '')
bounty.canceled_bounty_reason = canceled_bounty_reason
bounty.save()
return JsonResponse({
'success': True,
'msg': _("cancel reason added."),
})
return JsonResponse(
{
'error': _('bounty cancellation is bounty funder operatio'),
},
status=410
)
@require_POST
@csrf_exempt
def uninterested(request, bounty_id, profile_id):
"""Remove party from given bounty
Can only be called by the bounty funder
:request method: GET
Args:
bounty_id (int): ID of the Bounty
profile_id (int): ID of the interested profile
Params:
slashed (str): if the user will be slashed or not
Returns:
dict: The success key with a boolean value and accompanying error.
"""
try:
bounty = Bounty.objects.get(pk=bounty_id)
except Bounty.DoesNotExist:
return JsonResponse({'errors': ['Bounty doesn\'t exist!']},
status=401)
is_logged_in = request.user.is_authenticated
is_funder = bounty.is_funder(request.user.username.lower())
is_staff = request.user.is_staff
is_moderator = request.user.profile.is_moderator if hasattr(request.user, 'profile') else False
if not is_logged_in or (not is_funder and not is_staff and not is_moderator):
return JsonResponse(
{'error': 'Only bounty funders are allowed to remove users!'},
status=401)
slashed = request.POST.get('slashed')
interest = None
try:
interest = Interest.objects.get(profile_id=profile_id, bounty=bounty)
bounty.interested.remove(interest)
maybe_market_to_slack(bounty, 'stop_work')
maybe_market_to_user_slack(bounty, 'stop_work')
maybe_market_to_user_discord(bounty, 'stop_work')
if is_staff or is_moderator:
event_name = "bounty_removed_slashed_by_staff" if slashed else "bounty_removed_by_staff"
else:
event_name = "bounty_removed_by_funder"
record_user_action_on_interest(interest, event_name, None)
record_bounty_activity(bounty, interest.profile.user, 'stop_work')
interest.delete()
except Interest.DoesNotExist:
return JsonResponse({
'errors': ['Party haven\'t expressed interest on this bounty.'],
'success': False},
status=401)
except Interest.MultipleObjectsReturned:
interest_ids = bounty.interested \
.filter(
profile_id=profile_id,
bounty=bounty
).values_list('id', flat=True) \
.order_by('-created')
bounty.interested.remove(*interest_ids)
Interest.objects.filter(pk__in=list(interest_ids)).delete()
profile = Profile.objects.get(id=profile_id)
if profile.user and profile.user.email and interest:
bounty_uninterested(profile.user.email, bounty, interest)
else:
print("no email sent -- user was not found")
return JsonResponse({
'success': True,
'msg': _("You've stopped working on this, thanks for letting us know."),
})
def onboard_avatar(request):
return redirect('/onboard/contributor?steps=avatar')
def onboard(request, flow=None):
"""Handle displaying the first time user experience flow."""
if flow not in ['funder', 'contributor', 'profile']:
if not request.user.is_authenticated:
raise Http404
target = 'funder' if request.user.profile.persona_is_funder else 'contributor'
new_url = f'/onboard/{target}'
return redirect(new_url)
elif flow == 'funder':
onboard_steps = ['github', 'metamask', 'avatar']
elif flow == 'contributor':
onboard_steps = ['github', 'metamask', 'avatar', 'skills', 'job']
elif flow == 'profile':
onboard_steps = ['avatar']
profile = None
if request.user.is_authenticated and getattr(request.user, 'profile', None):
profile = request.user.profile
steps = []
if request.GET:
steps = request.GET.get('steps', [])
if steps:
steps = steps.split(',')
if (steps and 'github' not in steps) or 'github' not in onboard_steps:
if not request.user.is_authenticated or request.user.is_authenticated and not getattr(
request.user, 'profile', None
):
login_redirect = redirect('/login/github?next=' + request.get_full_path())
return login_redirect
if request.POST.get('eth_address') and request.user.is_authenticated and getattr(request.user, 'profile', None):
profile = request.user.profile
eth_address = request.GET.get('eth_address')
valid_address = is_valid_eth_address(eth_address)
if valid_address:
profile.preferred_payout_address = eth_address
profile.save()
return JsonResponse({'OK': True})
theme = request.GET.get('theme', '3d')
from avatar.views_3d import get_avatar_attrs
skin_tones = get_avatar_attrs(theme, 'skin_tones')
hair_tones = get_avatar_attrs(theme, 'hair_tones')
avatar_options = [
('classic', '/onboard/profile?steps=avatar&theme=classic'),
('3d', '/onboard/profile?steps=avatar&theme=3d'),
('bufficorn', '/onboard/profile?steps=avatar&theme=bufficorn'),
('female', '/onboard/profile?steps=avatar&theme=female'),
]
params = {
'title': _('Onboarding Flow'),
'steps': steps or onboard_steps,
'flow': flow,
'profile': profile,
'theme': theme,
'avatar_options': avatar_options,
'3d_avatar_params': None if 'avatar' not in steps else avatar3dids_helper(theme),
'possible_skin_tones': skin_tones,
'possible_hair_tones': hair_tones,
}
params.update(get_avatar_context_for_user(request.user))
return TemplateResponse(request, 'ftux/onboard.html', params)
@login_required
def users_directory(request):
"""Handle displaying users directory page."""
from retail.utils import programming_languages, programming_languages_full
keywords = programming_languages + programming_languages_full
params = {
'is_staff': request.user.is_staff,
'active': 'users',
'title': 'Users',
'meta_title': "",
'meta_description': "",
'keywords': keywords
}
return TemplateResponse(request, 'dashboard/users.html', params)
def users_fetch_filters(profile_list, skills, bounties_completed, leaderboard_rank, rating, organisation ):
if not settings.DEBUG:
network = 'mainnet'
else:
network = 'rinkeby'
if skills:
profile_list = profile_list.filter(keywords__icontains=skills)
if len(bounties_completed) == 2:
profile_list = profile_list.annotate(
count=Count('fulfilled')
).filter(
count__gte=bounties_completed[0],
count__lte=bounties_completed[1],
)
if len(leaderboard_rank) == 2:
profile_list = profile_list.filter(
leaderboard_ranks__isnull=False,
leaderboard_ranks__leaderboard='quarterly_earners',
leaderboard_ranks__rank__gte=leaderboard_rank[0],
leaderboard_ranks__rank__lte=leaderboard_rank[1],
leaderboard_ranks__active=True,
)
if rating != 0:
profile_list = profile_list.annotate(
average_rating=Avg('feedbacks_got__rating', filter=Q(feedbacks_got__bounty__network=network))
).filter(
average_rating__gte=rating
)
if organisation:
profile_list1 = profile_list.filter(
fulfilled__bounty__network=network,
fulfilled__accepted=True,
fulfilled__bounty__github_url__icontains=organisation
)
profile_list2 = profile_list.filter(
organizations__icontains=organisation
)
profile_list = (profile_list1 | profile_list2).distinct()
return profile_list
@require_GET
def users_fetch(request):
"""Handle displaying users."""
q = request.GET.get('search', '')
skills = request.GET.get('skills', '')
persona = request.GET.get('persona', '')
limit = int(request.GET.get('limit', 10))
page = int(request.GET.get('page', 1))
order_by = request.GET.get('order_by', '-actions_count')
bounties_completed = request.GET.get('bounties_completed', '').strip().split(',')
leaderboard_rank = request.GET.get('leaderboard_rank', '').strip().split(',')
rating = int(request.GET.get('rating', '0'))
organisation = request.GET.get('organisation', '')
user_id = request.GET.get('user', None)
if user_id:
current_user = User.objects.get(id=int(user_id))
else:
current_user = request.user if hasattr(request, 'user') and request.user.is_authenticated else None
context = {}
if not settings.DEBUG:
network = 'mainnet'
else:
network = 'rinkeby'
if current_user:
profile_list = Profile.objects.prefetch_related(
'fulfilled', 'leaderboard_ranks', 'feedbacks_got'
).exclude(hide_profile=True)
else:
profile_list = Profile.objects.prefetch_related(
'fulfilled', 'leaderboard_ranks', 'feedbacks_got'
).exclude(hide_profile=True)
if q:
profile_list = profile_list.filter(Q(handle__icontains=q) | Q(keywords__icontains=q))
if persona:
if persona == 'Funder':
profile_list = profile_list.filter(dominant_persona='funder')
if persona == 'Coder':