Skip to content

Commit

Permalink
extracted to "expect_media_fields"
Browse files Browse the repository at this point in the history
  • Loading branch information
frimpongopoku committed Oct 10, 2023
1 parent 793a2b3 commit 4764cc4
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 45 deletions.
21 changes: 4 additions & 17 deletions src/api/handlers/media_library.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from api.decorators import admins_only
from api.services.media_library import MediaLibraryService
from _main_.utils.massenergize_response import MassenergizeResponse
from api.store.common import expect_media_fields


class MediaLibraryHandler(RouteHandler):
Expand Down Expand Up @@ -86,21 +87,8 @@ def addToGallery(self, request):
"is_universal", bool
).expect(
"tags", "str_list"
).expect(
"size", str
).expect(
"size_text", str
).expect(
"description"
).expect(
"underAge", bool
).expect(
"copyright", bool
).expect(
"copyright_att", str
).expect(
"guardian_info", str
)
self = expect_media_fields(self)
args, err = self.validator.verify(args, strict=True)
if err:
return err
Expand Down Expand Up @@ -144,9 +132,7 @@ def edit_details(self, request):
"""Saves changes to updated image details"""
context: Context = request.context
args: dict = context.args
self.validator.expect("description").expect("underAge", bool).expect(
"copyright", bool
).expect("copyright_att", str).expect("guardian_info", str).expect(
self.validator.expect(
"tags", "str_list"
).expect(
"community_ids", list
Expand All @@ -155,6 +141,7 @@ def edit_details(self, request):
).expect(
"user_upload_id", int, is_required=True
).expect("publicity", str)
self = expect_media_fields(self)
args, err = self.validator.verify(args, strict=True)
if err:
return err
Expand Down
71 changes: 46 additions & 25 deletions src/api/store/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,24 @@
import pytz
from _main_.utils.utils import Console
from api.store.utils import getCarbonScoreFromActionRel
from database.models import UserActionRel
from database.models import UserActionRel
from django.db.models import Q
from django.utils import timezone
from django.utils import timezone


LAST_VISIT = "last-visit"
LAST_WEEK = "last-week"
LAST_MONTH = "last-month"
LAST_YEAR = "last-year"

def js_datetime_to_python(datetext):

def js_datetime_to_python(datetext):
_format = "%Y-%m-%dT%H:%M:%SZ"
_date = datetime.datetime.strptime(datetext, _format)
return pytz.utc.localize(_date)

def make_time_range_from_text(time_range):

def make_time_range_from_text(time_range):
today = datetime.datetime.utcnow()
if time_range == LAST_WEEK:
start_time = today - datetime.timedelta(days=7)
Expand All @@ -31,32 +33,36 @@ def make_time_range_from_text(time_range):
end_time = today
elif time_range == LAST_YEAR:
start_time = today - datetime.timedelta(days=365)
end_time = today
end_time = today
return [pytz.utc.localize(start_time), pytz.utc.localize(end_time)]


def count_action_completed_and_todos(**kwargs):
"""
### args: communities(list), actions(list), time_range(str), start_date(str), end_date(str)
This function counts how many times an action has been completed, or added to todolist
Returns an array of dictionaries with the following: (name,id,done_count, todo_count, carbon_score, category)
* Given a list of communities, todo/done will be counted within only those communities.
* When given a list of actions, counts will only be done for only the actions given
* Given a list of communities, todo/done will be counted within only those communities.
* When given a list of actions, counts will only be done for only the actions given
* When given both (actions & communities) an AND query will be built before counting
* And when a time range is specified, all the query combinations listed above will run within the given time range
"""

communities = kwargs.get("communities", [])
actions = kwargs.get("actions", [])
action_count_objects = {}
query = None
time_range = kwargs.get("time_range")
time_range = kwargs.get("time_range")

# ----------------------------------------------------------------------------
if time_range == "custom":
start_date = kwargs.get('start_date',"")
end_date = kwargs.get("end_date","")
time_range = [js_datetime_to_python(start_date), js_datetime_to_python(end_date)]
else:
if time_range == "custom":
start_date = kwargs.get("start_date", "")
end_date = kwargs.get("end_date", "")
time_range = [
js_datetime_to_python(start_date),
js_datetime_to_python(end_date),
]
else:
time_range = make_time_range_from_text(time_range) if time_range else []
# ----------------------------------------------------------------------------

Expand All @@ -70,13 +76,13 @@ def count_action_completed_and_todos(**kwargs):
action__in=actions,
is_deleted=False,
)
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------

if not query:
return []

# add time range specification to the query if available
if time_range:
if time_range:
query &= Q(updated_at__range=time_range)

completed_actions = UserActionRel.objects.filter(query).select_related(
Expand Down Expand Up @@ -112,10 +118,6 @@ def count_action_completed_and_todos(**kwargs):
return list(action_count_objects.values())






def create_pdf_from_rich_text(rich_text, filename):
# Convert rich text to PDF
pdf_buffer = io.BytesIO()
Expand All @@ -125,17 +127,36 @@ def create_pdf_from_rich_text(rich_text, filename):

# Close the buffer and return the response
pdf_buffer.seek(0)
response = FileResponse(pdf_buffer, content_type='application/pdf')
response['Content-Disposition'] = f'attachment; filename={filename}.pdf'
response = FileResponse(pdf_buffer, content_type="application/pdf")
response["Content-Disposition"] = f"attachment; filename={filename}.pdf"
return pdf_buffer.getvalue(), response


def sign_mou(mou_rich_text, user=None, date=None):
return f"""
def sign_mou(mou_rich_text, user=None, date=None):
return (
f"""
{mou_rich_text}
<div>
<h1>Signed By</h2>
<h2>Name: {user.full_name}</h2>
<h2>Date: {date} </h2>
</div>
""" if (user and date) else mou_rich_text
"""
if (user and date)
else mou_rich_text
)


def expect_media_fields(self):
self.validator.expect("size", str).expect("size_text", str).expect(
"description"
).expect("underAge", bool).expect("copyright", bool).expect(
"copyright_att", str
).expect(
"guardian_info", str
).expect(
"permission_key", str
).expect(
"permission_notes", str
)
return self
10 changes: 8 additions & 2 deletions src/api/store/media_library.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from functools import reduce
from django.core.exceptions import ValidationError
from database.utils.settings.model_constants.user_media_uploads import UserMediaConstants
from database.utils.settings.model_constants.user_media_uploads import (
UserMediaConstants,
)
from sentry_sdk import capture_message
from _main_.utils.context import Context
from _main_.utils.footage.FootageConstants import FootageConstants
Expand Down Expand Up @@ -52,6 +54,8 @@ def edit_details(self, args, context: Context):
"has_copyright_permission": copyright_permission,
"guardian_info": guardian_info,
"copyright_att": copyright_att,
"permission_key": args.get("permission_key", None),
"permission_notes": args.get("permission_notes", None),
}
user_media_upload.info = info
# user_media_upload.save()
Expand All @@ -62,7 +66,7 @@ def edit_details(self, args, context: Context):
user_media_upload.communities.clear()
user_media_upload.communities.set(communities)

if publicity:
if publicity:
user_media_upload.publicity = publicity
user_media_upload.save()

Expand Down Expand Up @@ -344,6 +348,8 @@ def addToGallery(self, args, context):
"has_copyright_permission": copyright_permission,
"guardian_info": guardian_info,
"copyright_att": copyright_att,
"permission_key": args.get("permission_key", None),
"permission_notes": args.get("permission_notes", None),
}

try:
Expand Down
2 changes: 1 addition & 1 deletion src/database/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -1209,7 +1209,7 @@ def __str__(self):

def simple_json(self):
res = model_to_dict(
self, ["settings", "media", "created_at", "id", "is_universal", "info"]
self, ["settings", "media", "created_at", "id", "is_universal", "info", "publicity"]
)
res["user"] = get_summary_info(self.user)
res["image"] = get_json_if_not_none(self.media)
Expand Down

0 comments on commit 4764cc4

Please sign in to comment.