Skip to content

Commit

Permalink
fixes the pixelation of the collection images, and also allows genera…
Browse files Browse the repository at this point in the history
…tion of them without creating a collection (esp upon checkout) (#8523)

* img fixes for grants

* make fix

* performance considerations

* removes imgs

* Update grant-thanks-modal.js

Co-authored-by: Aditya Anand M C <aditya.anandmc@gmail.com>
  • Loading branch information
owocki and thelostone-mc authored Mar 10, 2021
1 parent 9b2b3d7 commit d9d28f5
Show file tree
Hide file tree
Showing 10 changed files with 84 additions and 31 deletions.
10 changes: 4 additions & 6 deletions app/app/static_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def save(self, name, content):
# Record the clean file content (pre gzip)
file_content = content.file
# Save remote copy to S3
super(SilentFileStorage, self).save(name, content)
super(SilentFileStorage, self).save(name, content)
# Only save files that are part of the compress blocks locally
if ".scss" in name or ".js" in name or ".css" in name:
# restore the clean file_content
Expand All @@ -52,14 +52,12 @@ def exists(self, name):
# Check file exists on S3
exists = super(SilentFileStorage, self).exists(name)
# This is a hack to get a status report during S3ManifestStaticStorage._postProcess
print("INFO " + datetime.now().strftime("%Y-%m-%d %H:%M:%S") +
" - Checking for matching file hash on S3 - " + name + ": " + (
"Skipping based on matching file hashes" if exists else "Hashes did not match"
)
print(
"INFO " + datetime.now().strftime("%Y-%m-%d %H:%M:%S") + " - Checking for matching file hash on S3 - " +
name + ": " + ("Skipping based on matching file hashes" if exists else "Hashes did not match")
)
return exists


def url(self, name, force=True):
"""Handle catching bad URLs and return the name if route is unavailable."""
try:
Expand Down
10 changes: 5 additions & 5 deletions app/app/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
from avatar.router import router as avatar_router
from dashboard.router import router as dbrouter
from grants.router import router as grant_router
from grants.views import cart_thumbnail
from kudos.router import router as kdrouter

from .sitemaps import sitemaps
Expand Down Expand Up @@ -120,6 +121,9 @@
re_path(r'^dynamic/kudos/(?P<kudos_id>\d+)/(?P<name>\w*)', kudos.views.image, name='kudos_dynamic_img'),
re_path(r'^kudos/new/?', kudos.views.newkudos, name='newkudos'),


path('dynamic/grants_cart_thumb/<str:profile>/<str:grants>', cart_thumbnail, name='cart_thumbnail'),

# mailing list
url('mailing_list/funders/', dashboard.views.funders_mailing_list),
url('mailing_list/hunters/', dashboard.views.hunters_mailing_list),
Expand Down Expand Up @@ -160,11 +164,7 @@
dashboard.views.authenticate_idena,
name='authenticate_idena'
),
url(
r'^api/v0.1/profile/(?P<handle>.*)/logout_idena',
dashboard.views.logout_idena,
name='logout_idena'
),
url(r'^api/v0.1/profile/(?P<handle>.*)/logout_idena', dashboard.views.logout_idena, name='logout_idena'),
url(
r'^api/v0.1/profile/(?P<handle>.*)/recheck_idena_status',
dashboard.views.recheck_idena_status,
Expand Down
8 changes: 8 additions & 0 deletions app/assets/v2/js/grants/grant-thanks-modal.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ Vue.component('contribution-thanks-modal', {
data: function() {
return {
modalId: 'contribution-thanks',
imgURL: '',
numberOfContributions: 0,
donations: [],
tweetUrl: ''
Expand All @@ -12,6 +13,13 @@ Vue.component('contribution-thanks-modal', {
const checkoutData = CartData.loadCheckedOut();
const shouldShow = checkoutData.length > 0;

let grant_ids = '';

for (let i = 0; i < checkoutData.length; i++) {
grant_ids = grant_ids + checkoutData[i]['grant_id'] + ',';
}

this.imgURL = '/dynamic/grants_cart_thumb/' + document.contxt['github_handle'] + '/' + grant_ids;
this.numberOfContributions = checkoutData.length;

this.tweetUrl = `https://twitter.com/intent/tweet?text=I just funded ${this.numberOfContributions} grants on @gitcoin ${CartData.share_url()}`;
Expand Down
15 changes: 15 additions & 0 deletions app/grants/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,21 @@ def response_change(self, request, obj):
class GrantCollectionAdmin(admin.ModelAdmin):
list_display = ['pk', 'title', 'description', 'hidden', 'cache', 'featured']
raw_id_fields = ['profile', 'grants', 'curators']
readonly_fields = ['img']


def response_change(self, request, obj):
if "_generate_cache" in request.POST:
obj.generate_cache()
self.message_user(request, "generated cache")
return redirect(obj.admin_url)

def img(self, instance):
try:
html = f'<img src="{instance.cover.url}">'
return mark_safe(html)
except:
return "N/A"


class GrantBrandingRoutingPolicyAdmin(admin.ModelAdmin):
Expand Down
2 changes: 1 addition & 1 deletion app/grants/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2077,7 +2077,7 @@ def generate_cache(self):
}

try:
cover = generate_collection_thumbnail(self, 348, 175)
cover = generate_collection_thumbnail(self, 348 * 5, 175 * 5)
filename = f'thumbnail_{self.id}.png'
buffer = BytesIO()
cover.save(fp=buffer, format='PNG')
Expand Down
20 changes: 11 additions & 9 deletions app/grants/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,15 @@
from django.urls import path, re_path

from grants.views import (
add_grant_from_collection, bulk_fund, bulk_grants_for_cart, cancel_grant_v1, clr_grants, collection_thumbnail,
contribute_to_grants_v1, contribution_addr_from_all_as_json, contribution_addr_from_grant_as_json,
contribution_addr_from_grant_during_round_as_json, contribution_addr_from_round_as_json,
contribution_info_from_grant_during_round_as_json, create_matching_pledge_v1, flag, get_collection,
get_collections_list, get_ethereum_cart_data, get_grant_payload, get_grants, get_interrupted_contributions,
get_replaced_tx, grant_activity, grant_categories, grant_details, grant_details_api, grant_details_contributions,
grant_details_contributors, grant_edit, grant_fund, grant_new, grant_new_whitelabel, grants, grants_addr_as_json,
grants_bulk_add, grants_by_grant_type, grants_cart_view, grants_info, grants_landing, grants_stats_view,
ingest_contributions, ingest_contributions_view, invoice, leaderboard, manage_ethereum_cart_data,
add_grant_from_collection, bulk_fund, bulk_grants_for_cart, cancel_grant_v1, cart_thumbnail, clr_grants,
collection_thumbnail, contribute_to_grants_v1, contribution_addr_from_all_as_json,
contribution_addr_from_grant_as_json, contribution_addr_from_grant_during_round_as_json,
contribution_addr_from_round_as_json, contribution_info_from_grant_during_round_as_json, create_matching_pledge_v1,
flag, get_collection, get_collections_list, get_ethereum_cart_data, get_grant_payload, get_grants,
get_interrupted_contributions, get_replaced_tx, grant_activity, grant_categories, grant_details, grant_details_api,
grant_details_contributions, grant_details_contributors, grant_edit, grant_fund, grant_new, grant_new_whitelabel,
grants, grants_addr_as_json, grants_bulk_add, grants_by_grant_type, grants_cart_view, grants_info, grants_landing,
grants_stats_view, ingest_contributions, ingest_contributions_view, invoice, leaderboard, manage_ethereum_cart_data,
new_matching_partner, profile, quickstart, remove_grant_from_collection, save_collection, subscription_cancel,
toggle_grant_favorite, verify_grant,
)
Expand Down Expand Up @@ -60,6 +60,8 @@
path('bulk_cart', bulk_grants_for_cart, name='bulk_grants_for_cart'),
path('<int:grant_id>/favorite', toggle_grant_favorite, name='favorite_grant'),
path('activity', grant_activity, name='log_activity'),

path('cart_thumb/<str:profile>/<str:grants>', cart_thumbnail, name='cart_thumbnail'),
path('<int:grant_id>/<slug:grant_slug>', grant_details, name='details'),
path('<int:grant_id>/<slug:grant_slug>/', grant_details, name='details2'),
path('collections/<int:collection_id>/thumbnail', collection_thumbnail, name='get_collection_thumbnail'),
Expand Down
10 changes: 7 additions & 3 deletions app/grants/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,12 @@ def add_grant_to_active_clrs(grant):


def generate_collection_thumbnail(collection, width, heigth):
grants = collection.grants.all()
profile = collection.profile
return generate_img_thumbnail_helper(grants, profile, width, heigth)


def generate_img_thumbnail_helper(grants, profile, width, heigth):
MARGIN = int(width / 30)
MID_MARGIN = int(width / 90)
BG = (111, 63, 245)
Expand All @@ -207,8 +213,6 @@ def generate_collection_thumbnail(collection, width, heigth):
GRANT_BOX = (GRANT_WIDTH, GRANT_HEIGHT)
media_url = '' if 'media' not in MEDIA_URL else BASE_URL[:-1]

grants = collection.grants.all()

logos = []
for grant in grants:
if grant.logo:
Expand All @@ -226,7 +230,7 @@ def generate_collection_thumbnail(collection, width, heigth):
logos.append(None)

thumbail = Image.new('RGBA', IMAGE_BOX, color=BG)
avatar_url = f'{media_url}{collection.profile.avatar_url}'
avatar_url = f'{media_url}{profile.avatar_url}'
fd = urllib.request.urlopen(avatar_url)

# Make rounder profile avatar img
Expand Down
31 changes: 27 additions & 4 deletions app/grants/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,14 @@
from economy.utils import convert_amount, convert_token_to_usdt
from gas.utils import conf_time_spread, eth_usd_conv_rate, gas_advisories, recommend_min_gas_price_to_confirm_in_time
from grants.models import (
CartActivity, Contribution, Flag, Grant, GrantBrandingRoutingPolicy, GrantCategory, GrantCLR, GrantCollection,
GrantType, GrantAPIKey, MatchPledge, PhantomFunding, Subscription,
CartActivity, Contribution, Flag, Grant, GrantAPIKey, GrantBrandingRoutingPolicy, GrantCategory, GrantCLR,
GrantCollection, GrantType, MatchPledge, PhantomFunding, Subscription,
)
from grants.tasks import process_grant_creation_admin_email, process_grant_creation_email, update_grant_metadata
from grants.utils import emoji_codes, generate_collection_thumbnail, get_user_code, is_grant_team_member, sync_payout
from grants.utils import (
emoji_codes, generate_collection_thumbnail, generate_img_thumbnail_helper, get_user_code, is_grant_team_member,
sync_payout,
)
from inbox.utils import send_notification_to_user_from_gitcoinbot
from kudos.models import BulkTransferCoupon, Token
from marketing.mails import (
Expand Down Expand Up @@ -2535,6 +2538,7 @@ def grants_bulk_add(request, grant_str):
views = redis.incr(key)

grants_data = grant_str.split(':')[0].split(',')
grant_ids = []

for ele in grants_data:
# new format will support amount and token in the URL separated by ;
Expand All @@ -2544,14 +2548,17 @@ def grants_bulk_add(request, grant_str):
grants[grant_id] = {
'id': int(grant_id)
}
grant_ids.append(grant_id)

if len(grant_data) == 3: # backward compatibility
grants[grant_id]['amount'] = grant_data[1]
grants[grant_id]['token'] = FTokens.objects.filter(id=int(grant_data[2])).first()

by_whom = ""
prefix = ""
handle = ''
try:
handle = f"{grant_str.split(':')[1]}"
by_whom = f"by {grant_str.split(':')[1]}"
prefix = f"{grant_str.split(':')[2]} : "
except:
Expand All @@ -2568,9 +2575,11 @@ def grants_bulk_add(request, grant_str):
grant_titles = ", ".join([grant['obj'].title for grant in grants])
title = f"{prefix}{len(grants)} Grants in Shared Cart {by_whom} : Viewed {views} times"

grant_ids = ",".join([str(ele) for ele in grant_ids])
avatar_url = f'/dynamic/grants_cart_thumb/{handle}/{grant_ids}'
context = {
'grants': grants,
'avatar_url': request.build_absolute_uri(static('v2/images/twitter_cards/grants9.png')),
'avatar_url': avatar_url,
'title': title,
'card_desc': "Click to Add All to Cart: " + grant_titles

Expand Down Expand Up @@ -3145,6 +3154,20 @@ def add_grant_from_collection(request, collection_id):
'grants': grants,
})

@cache_page(60 * 60)
def cart_thumbnail(request, profile, grants):
width = int(request.GET.get('w', 348 * 5))
height = int(request.GET.get('h', 175 * 5))
grant_ids = grants.split(",")
grant_ids = [ele for ele in grant_ids if ele]
grants = Grant.objects.filter(pk__in=grant_ids)[:4]
profile = Profile.objects.get(handle=profile.lower())
thumbnail = generate_img_thumbnail_helper(grants, profile, width, height)

response = HttpResponse(content_type="image/png")
thumbnail.save(response, "PNG")

return response

@login_required
@staff_member_required
Expand Down
2 changes: 2 additions & 0 deletions app/retail/templates/admin/change_form.html
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@
<input type="submit" value="Recalculate CLR" name="_calc_clr" value="1">
<input type="submit" value="Mark as Fraud" name="_mark_fraud" value="1">
<input type="submit" value="Approve Grant" name="_approve_grant" value="1">
{% elif 'grantcollection/' in request.build_absolute_uri %}
<input type="submit" value="Generate Cache" name="_generate_cache" value="1">
{% elif 'grantclr/' in request.build_absolute_uri %}
<input type="submit" value="Recalculate CLR" name="_recalculate_clr" value="1">
{% elif 'granttype/' in request.build_absolute_uri %}
Expand Down
7 changes: 4 additions & 3 deletions app/retail/templates/shared/grant_thanks_modal.html
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,18 @@
</div>
<div class="mx-3 mx-md-5 pb-4">
<div class="d-inline-flex flex-column-reverse flex-md-column text-left text-md-center">
<h3 class="mb-0 mb-md-5 d-flex-inline">Thank you for your contribution to open source!</h3>
<img class="align-self-center d-flex-inline mb-5 mb-md-0" width="35%" style="max-width: 728px;" src="{% static "v2/images/grants/space-funding-woman.png" %}" />
<h3 class="mb-0 mb-md-5 d-flex-inline center">Thank you for your contribution!</h3>
<img class="align-self-center d-flex-inline mb-5 mb-md-0" width="75%" style="max-width: 728px;" :src="imgURL" />
</div>
<div class="mt-5 my-4">

You've successfully contributed to [[numberOfContributions]] grants:
</div>
<hr />
<div>
<template v-for="donation in donations">
<div class="my-3">
[[donation.grant_title]]<br />
<a :href="donation.grant_url" target="_blank">[[donation.grant_title]]</a><br />
[[donation.grant_donation_amount]] [[donation.grant_donation_currency]]
<span v-if="donation.grant_donation_clr_match > 0" class="text-success"> + [[donation.grant_donation_clr_match]] DAI matching</span>
</div>
Expand Down

0 comments on commit d9d28f5

Please sign in to comment.