def clear_old_bouncy_objects(): Delivery.objects.filter(created_at__lte=DateTimeService.now() - timedelta(7)).delete() Bounce.objects.filter(created_at__lte=DateTimeService.now() - timedelta(30)).delete() Complaint.objects.filter(created_at__lte=DateTimeService.now() - timedelta(90)).delete()
def purge_expired_incomplete_uploads(): deleted = Image.uploads_in_progress.filter( uploader_expires__lt=DateTimeService.now()).delete() if deleted is not None: logger.info("Purged %d expired incomplete image uploads." % deleted[0]) deleted = ImageRevision.uploads_in_progress.filter( uploader_expires__lt=DateTimeService.now()).delete() if deleted is not None: logger.info("Purged %d expired incomplete image revision uploads." % deleted[0])
def may_submit_to_iotd_tp_process(user: User, image: Image): if not user.is_authenticated: return False, 'UNAUTHENTICATED' if user != image.user: return False, 'NOT_OWNER' if is_free(user): return False, 'IS_FREE' if image.is_wip: return False, 'NOT_PUBLISHED' if image.designated_iotd_submitters.exists() or image.designated_iotd_reviewers.exists(): return False, 'ALREADY_SUBMITTED' if image.subject_type in (SubjectType.GEAR, SubjectType.OTHER, '', None): return False, 'BAD_SUBJECT_TYPE' if image.user.userprofile.exclude_from_competitions: return False, 'EXCLUDED_FROM_COMPETITIONS' if image.user.userprofile.banned_from_competitions: return False, 'BANNED_FROM_COMPETITIONS' if image.published < DateTimeService.now() - timedelta(days=settings.IOTD_SUBMISSION_WINDOW_DAYS): return False, 'TOO_LATE' return True, None
def get_next_available_selection_time_for_judge(self, judge): # type: (User) -> datetime today = DateTimeService.today() # date now = DateTimeService.now() # datetime next_time_due_to_max_per_day = \ DateTimeService.next_midnight() if \ Iotd.objects.filter( judge=judge, date=today).count() >= settings.IOTD_JUDGEMENT_MAX_PER_DAY \ else now # datetime latest_scheduled = Iotd.objects.filter( judge=judge).order_by('-date').first() # Iotd next_time_due_to_max_scheduled_per_judge = \ DateTimeService.next_midnight(latest_scheduled.date) if \ Iotd.objects.filter( judge=judge, date__gt=today).count() >= settings.IOTD_JUDGEMENT_MAX_FUTURE_PER_JUDGE \ else now next_time_due_to_max_scheduled = \ DateTimeService.next_midnight() if \ Iotd.objects.filter(date__gte=today).count() >= settings.IOTD_JUDGEMENT_MAX_FUTURE_DAYS \ else now return max(next_time_due_to_max_per_day, next_time_due_to_max_scheduled_per_judge, next_time_due_to_max_scheduled)
def subscription_signed_up(sender, **kwargs): subscription = kwargs.get('subscription') user_subscription = kwargs.get('usersubscription') user = kwargs.get('user') if 'premium' in subscription.category: if user_subscription.expires is None: user_subscription.expires = DateTimeService.today() user_subscription.extend(datetime.timedelta(days=365.2425)) user_subscription.save() # Invalidate other premium subscriptions UserSubscription.active_objects \ .filter(user=user_subscription.user, subscription__category__startswith='premium') \ .exclude(pk=user_subscription.pk) \ .update(active=False) if Transaction.objects.filter(user=user, event='new usersubscription', timestamp__gte=DateTimeService.now() - datetime.timedelta(minutes=5)): push_notification([user], 'new_subscription', {'BASE_URL': settings.BASE_URL}) else: push_notification([user], 'new_payment', {'BASE_URL': settings.BASE_URL})
def assign_upload_length(): """ Run this tasks every hour to assign `uploader_upload_length` to images that lack it. """ def process(items): for item in items.iterator(): try: url = item.image_file.url response = requests.head(url) # type: Response except ValueError as e: logger.error("assign_upload_length: error %s", str(e)) continue if response.status_code == 200: size = response.headers.get("Content-Length") item.uploader_upload_length = size try: item.save(keep_deleted=True) except IntegrityError: continue logger.info( "assign_upload_length: proccessed %d (%s) = %s" % (item.pk, item.image_file.url, filesizeformat(size))) time_cut = DateTimeService.now() - timedelta(hours=2) images = Image.all_objects.filter(uploader_upload_length__isnull=True, uploaded__gte=time_cut) revisions = ImageRevision.all_objects.filter( uploader_upload_length__isnull=True, uploaded__gte=time_cut) process(images) process(revisions)
def subscription_paid(sender, **kwargs): subscription = kwargs.get('subscription') user = kwargs.get('user') profile = user.userprofile UserProfile.all_objects.filter(user=user).update(updated=timezone.now()) PremiumService.clear_subscription_status_cache_keys(user.pk) if subscription.group.name == 'astrobin_lite': profile.premium_counter = 0 profile.save(keep_deleted=True) elif subscription.group.name == 'astrobin_lite_2020': profile.premium_counter = Image.objects_including_wip.filter( user=user).count() profile.save(keep_deleted=True) if 'premium' in subscription.category and Transaction.objects.filter( user=user, event='new usersubscription', timestamp__gte=DateTimeService.now() - datetime.timedelta(minutes=5)): push_notification([user], None, 'new_subscription', {'BASE_URL': settings.BASE_URL}) else: push_notification([user], None, 'new_payment', {'BASE_URL': settings.BASE_URL})
def test_judge_cannot_select_now_reason_none_no_iotds(self, now): now.return_value = datetime.now() judge = Generators.user(groups=['iotd_judges']) self.assertIsNone(IotdService().judge_cannot_select_now_reason(judge)) self.assertEquals( IotdService().get_next_available_selection_time_for_judge(judge), DateTimeService.now())
def get_last_notification_time(request, pk=None): if pk: try: return Message.objects.get(pk=pk).modified except (Message.DoesNotExist, AttributeError): pass else: if request.user.is_authenticated: try: return Message.objects.filter( user=request.user).latest('modified').modified except (Message.DoesNotExist, AttributeError): pass if 'HTTP_AUTHORIZATION' in request.META: token_in_header = request.META['HTTP_AUTHORIZATION'].replace( 'Token ', '') try: token = Token.objects.get(key=token_in_header) return Message.objects.filter( user=token.user).latest('modified').modified except (Token.DoesNotExist, Message.DoesNotExist, AttributeError): pass return DateTimeService.now()
def test_judge_cannot_select_now_reason_none_no_scheduled_iotds(self, now): now.return_value = datetime.now() iotd = self._create_iotd(date=date.today() - timedelta(1)) self.assertIsNone(IotdService().judge_cannot_select_now_reason( iotd.judge)) self.assertEquals( IotdService().get_next_available_selection_time_for_judge( iotd.judge), DateTimeService.now())
def get_current_user_profile_last_modified(request): if request.user.is_authenticated: return request.user.userprofile.updated if 'HTTP_AUTHORIZATION' in request.META: token_in_header = request.META['HTTP_AUTHORIZATION'].replace( 'Token ', '') try: token = Token.objects.get(key=token_in_header) return token.user.userprofile.updated except (Token.DoesNotExist, AttributeError): pass return DateTimeService.now()
def subscription_paid(sender, **kwargs): subscription = kwargs.get('subscription') user = kwargs.get('user') if subscription.group.name == 'astrobin_lite': profile = user.userprofile profile.premium_counter = 0 profile.save(keep_deleted=True) if 'premium' in subscription.category and Transaction.objects.filter( user=user, event='new usersubscription', timestamp__gte=DateTimeService.now() - datetime.timedelta(minutes=5)): push_notification([user], 'new_subscription', {'BASE_URL': settings.BASE_URL}) else: push_notification([user], 'new_payment', {'BASE_URL': settings.BASE_URL})
def get_latest_top_pick_datetime(request): try: return TopPickArchive.objects.latest( 'image__published').image.published except (TopPickArchive.DoesNotExist, AttributeError): return DateTimeService.now()
def get_images_pending_moderation(self): return Image.objects_including_wip.filter( moderator_decision=0, uploaded__lt=DateTimeService.now() - timedelta(minutes=10))
def is_future(dt): return dt > DateTimeService.now()
def get_latest_iotd_datetime(request): try: return datetime.combine( Iotd.objects.latest('date').date, datetime.min.time()) except (Iotd.DoesNotExist, AttributeError): return DateTimeService.now()
def get_user_detail_last_modified(request, pk): try: userprofile = UserProfile.objects.get(user__pk=pk) return userprofile.updated except UserProfile.DoesNotExist: return DateTimeService.now()
def get_image_last_modified(request, id, r): try: image = ImageService.get_object(id, Image.objects_including_wip) return image.updated except (Image.DoesNotExist, AttributeError): return DateTimeService.now()
def get_user_page_last_modified(request, username): try: userprofile = UserProfile.objects.get(user__username=username) return userprofile.updated except (UserProfile.DoesNotExist, AttributeError): return DateTimeService.now()