def test_past_bookings(self): tested_booking = self.create_booking( self.user_1, start=tznow() - timedelta(minutes=30), end=tznow() - timedelta(minutes=60)) self.assertEqual(Booking.objects.past().first(), tested_booking)
def render(self, context): try: context_time = self.time.resolve(context) except VariableDoesNotExist: context_time = None if not context_time: return '' delta = tznow() - context_time today = tznow().replace(hour=0, minute=0, second=0) yesterday = today - timedelta(days=1) tomorrow = today + timedelta(days=1) if delta.days == 0: if delta.seconds < 60: if context['LANGUAGE_CODE'].startswith('ru') and pytils_enabled: msg = '几秒钟前,几秒钟前,秒前' msg = pytils.numeral.choose_plural(delta.seconds, msg) else: msg = '秒前' return '%d %s' % (delta.seconds, msg) elif delta.seconds < 3600: minutes = int(delta.seconds / 60) if context['LANGUAGE_CODE'].startswith('ru') and pytils_enabled: msg = '分钟前,分钟,分钟前' msg = pytils.numeral.choose_plural(minutes, msg) else: msg = '分钟前' return '%d %s' % (minutes, msg) if today < context_time < tomorrow: return '今天, %s' % context_time.strftime('%H:%M') elif yesterday < context_time < today: return '昨天, %s' % context_time.strftime('%H:%M') else: return dateformat.format(context_time, 'Y-m-d H:i')
def pybb_user_time(context_time, user): delta = tznow() - context_time today = tznow().replace(hour=0, minute=0, second=0) yesterday = today - timedelta(days=1) tomorrow = today + timedelta(days=1) if delta.days == 0: if delta.seconds < 60: msg = ungettext('%d second ago', '%d seconds ago', delta.seconds) return msg % delta.seconds elif delta.seconds < 3600: minutes = int(delta.seconds / 60) msg = ungettext('%d minute ago', '%d minutes ago', minutes) return msg % minutes if is_authenticated(user): if time.daylight: # pragma: no cover tz1 = time.altzone else: # pragma: no cover tz1 = time.timezone tz = tz1 + util.get_pybb_profile(user).time_zone * 60 * 60 context_time = context_time + timedelta(seconds=tz) if today < context_time < tomorrow: return _('today, %s') % context_time.strftime('%H:%M') elif yesterday < context_time < today: return _('yesterday, %s') % context_time.strftime('%H:%M') else: return dateformat.format(context_time, 'd M, Y H:i')
def test_book_twice_the_same_resource_when_it_has_only_one_spot(self): self.room = self.create_room_resource(capacity=1) self.create_booking(self.user_1, tznow(), tznow() + timedelta(hours=1)) with self.assertRaises(OverUsedResource): self.create_booking(self.user_2, tznow(), tznow() + timedelta(hours=1))
def render(self, context): context_time = self.time.resolve(context) delta = tznow() - context_time today = tznow().replace(hour=0, minute=0, second=0) yesterday = today - timedelta(days=1) tomorrow = today + timedelta(days=1) if delta.days == 0: if delta.seconds < 60: msg = _('seconds ago') return u'%d %s' % (delta.seconds, msg) elif delta.seconds < 3600: minutes = int(delta.seconds / 60) msg = _('minutes ago') return u'%d %s' % (minutes, msg) if context['user'].is_authenticated(): if time.daylight: tz1 = time.altzone else: tz1 = time.timezone tz = tz1 + getattr(settings, 'PYBB_DEFAULT_TIME_ZONE', 0) * 60 * 60 context_time = context_time + timedelta(seconds=tz) if today < context_time < tomorrow: return _('today, %s') % context_time.strftime('%H:%M') elif yesterday < context_time < today: return _('yesterday, %s') % context_time.strftime('%H:%M') else: return dateformat.format(context_time, 'd M, Y H:i')
def test_cancel_is_denied_for_past_bookings(self): past_booking = self.create_booking(self.user_1, start=tznow() - timedelta(minutes=55), end=tznow() - timedelta(minutes=25)) with self.assertRaises(BRException): past_booking.actions.cancel()
def test_upcoming_bookings(self): tested_booking = self.create_booking( self.user_1, start=tznow() + timedelta(minutes=30), end=tznow() + timedelta(minutes=60)) self.assertEqual(Booking.objects.upcoming_and_current().first(), tested_booking)
def test_get_overlapping_none_left_bookings(self): tested_booking = self.create_booking( self.user_1, start=tznow() + timedelta(minutes=30), end=tznow() + timedelta(minutes=60)) self.assertEqual( Booking.objects.overlapping_bookings( start=tznow(), end=tznow() + timedelta(minutes=15)).first(), None, tested_booking)
def create_booking(self): User = get_user_model() owner = User.objects.create(username="******") room = Resource.objects.create(label="Room A", type="Conference-room") test_number = BookingCascadeRemovalTestCase.tests_count BookingCascadeRemovalTestCase.tests_count += 1 return Booking.objects.create(owner=owner, resource=room, start_datetime=tznow(), end_datetime=tznow() + timedelta(hours=1), title=f"Booking number {test_number}")
def save(self, commit=True): if self.instance.pk: post = super(PostForm, self).save(commit=False) if self.user: post.user = self.user if post.topic.head == post: post.topic.name = self.cleaned_data['name'] if self.may_create_poll: post.topic.poll_type = self.cleaned_data['poll_type'] post.topic.poll_question = self.cleaned_data[ 'poll_question'] post.topic.updated = tznow() if commit: post.topic.save() post.updated = tznow() if commit: post.save() # Subscribe to topic if self.cleaned_data['subscribe']: post.topic.subscribers.add(self.user) else: post.topic.subscribers.remove(self.user) return post, post.topic allow_post = True if defaults.PYBB_PREMODERATION: allow_post = defaults.PYBB_PREMODERATION(self.user, self.cleaned_data['body']) if self.forum: topic = Topic( forum=self.forum, user=self.user, name=self.cleaned_data['name'], poll_type=self.cleaned_data.get('poll_type', Topic.POLL_TYPE_NONE), poll_question=self.cleaned_data.get('poll_question', None), slug=self.cleaned_data.get('slug', None), ) if not allow_post: topic.on_moderation = True else: topic = self.topic post = Post(user=self.user, user_ip=self.ip, body=self.cleaned_data['body']) if not allow_post: post.on_moderation = True if commit: topic.save() post.topic = topic post.save() return post, topic
def test_end_date_before_Start_date_is_refused(self): booking = self.create_booking(self.user_1) form = BookingForm(instance=booking, data={ 'start_datetime': tznow() + timedelta(minutes=35), 'end_datetime': tznow() + timedelta(minutes=10) }) form.full_clean() with self.assertRaises(ValidationError): form.clean()
def test_booking_status(self): # Assuming we have a booking. it is active as a default tested_booking = self.create_booking( self.user_1, start=tznow() + timedelta(minutes=30), end=tznow() + timedelta(minutes=60)) self.assertEqual(Booking.objects.active().last(), tested_booking) # When I cancel it: tested_booking.actions.cancel() # then it's not active by default but still accessible by admin views. self.assertEqual(Booking.objects.active().last(), None) self.assertEqual(Booking.objects.all().last(), tested_booking)
def test_send_websocket_event(self): self.user_1 = self.create_user("1") self.room = self.create_room_resource(capacity=None) mocked_socket = Mock() with patch( 'apps.booking.hooks.create_connection') as create_connection: create_connection.return_value = mocked_socket booking = self.create_booking(self.user_1, tznow(), tznow() + timedelta(hours=1)) mocked_socket.send.assert_called_once_with( b'%d//%d' % (booking.pk, booking.resource_id)) mocked_socket.close.assert_called_once()
def save(self, *args, **kwargs): created_at = tznow() if self.created is None: self.created = created_at self.render() new = self.pk is None course_changed = False old_post = None if not new: old_post = Post.objects.get(pk=self.pk) if old_post.course != self.course: course_changed = True super(Post, self).save(*args, **kwargs) # If post is course head and moderated, moderate course too if self.course.head == self and not self.on_moderation and self.course.on_moderation: self.course.on_moderation = False self.course.update_counters() self.course.notice.update_counters() if course_changed: old_post.course.update_counters() old_post.course.notice.update_counters()
def pdfTopLlamadas(request): imagen_path = STATICFILES_DIRS[0] + '/logos/logomopsv.png' imagen_bol_path = STATICFILES_DIRS[0] + '/logos/logobolivia.png' top_usuario = full_complex_procedure( ['usuario', 'entrantes', 'salientes', 'operador'], 'bar_complete_usuario', '1999-01-01', str(datetime.date.today())) top_oficina = full_complex_procedure( ['oficina', 'entrantes', 'salientes', 'operador'], 'bar_complete_oficina', '1999-01-01', str(datetime.date.today())) print top_usuario print top_oficina c_llamadas = Llamada.objects.count() c_llamadas_entrantes = Llamada.objects.filter(tipo_llamada_id=1).count() c_llamadas_salientes = Llamada.objects.filter(tipo_llamada_id=2).count() c_llamadas_operador = Llamada.objects.filter(tipo_llamada_id=3).count() with open(imagen_path, 'rb') as img: imagen_path = b64encode(img.read()) with open(imagen_bol_path, 'rb') as img: imagen_bol_path = b64encode(img.read()) return render_to_pdf_response( request, 'reportes/topllamadas.html', { 'today': tznow(), 'imagen': imagen_path, 'imagen_bol': imagen_bol_path, 'c_llamadas': c_llamadas, 'c_llamadas_s': c_llamadas_salientes, 'c_llamadas_e': c_llamadas_entrantes, 'c_llamadas_o': c_llamadas_operador, 'top_usuarios': top_usuario, 'top_oficinas': top_oficina })
def new_or_changed_language(sender, **kwargs): "Signal handler for cals.Language.post_save" new = kwargs['created'] lang = kwargs['instance'] if 'testarossa' in lang.slug: return new_title = 'New language: %s' % lang.name changed_title = 'Changed language: %s' % lang.name # Add relevant badge to conlanger badge = Badge.objects.get(name='Conlanger') add_badge(badge, lang.manager) batchbadge(badge, lang.editors.all()) # Report on new language if new: # New language entry = add_entry_to_blog(lang, new_title, 'feeds/languages_newest_description.html', date_field='created') entry.tags = 'new_language' entry.save() lang.blogentries.add(entry) else: if lang.natlang: return # Changed language, has code to prevent duplicates latest = Entry.objects.latest() one_minute = timedelta(0, 60, 0) if latest.headline != changed_title: if not (latest.headline == new_title and (lang.last_modified - latest.pub_date < one_minute)): entry = add_entry_to_blog(lang, changed_title, 'feeds/languages_description.html', date_field='last_modified') entry.tags = 'changed_language' entry.save() else: latest.pub_date = tznow() latest.save()
def save(self, user=None, **kwargs): if not self.id: self.slug = uslugify(self.name) if user: self.added_by = user self.added = tznow() super(TranslationExercise, self).save(**kwargs)
def create_booking(self, user, start=None, end=None): random_start = tznow() + timedelta(minutes=randint(100, 1000)) random_end = random_start + timedelta(minutes=5) return Booking.objects.create(resource=self.room, owner=user, start_datetime=start or random_start, end_datetime=end or random_end)
def save(self, commit=True): if self.instance.pk: post = super(PostForm, self).save(commit=False) if self.user: post.user = self.user if post.topic.head == post: post.topic.name = self.cleaned_data['name'] post.topic.poll_type = self.cleaned_data['poll_type'] post.topic.poll_question = self.cleaned_data['poll_question'] post.topic.updated = tznow() post.topic.save() post.save() return post allow_post = True if defaults.PYBB_PREMODERATION: allow_post = defaults.PYBB_PREMODERATION(self.user, self.cleaned_data['body']) if self.forum: topic = Topic( forum=self.forum, user=self.user, name=self.cleaned_data['name'], poll_type=self.cleaned_data['poll_type'], poll_question=self.cleaned_data['poll_question'], ) if not allow_post: topic.on_moderation = True topic.save() else: topic = self.topic post = Post(topic=topic, user=self.user, user_ip=self.ip, body=self.cleaned_data['body'], reply_to=self.cleaned_data['reply_to']) if not allow_post: post.on_moderation = True post.save() return post
def save(self, *args, **kwargs): created_at = tznow() if self.created is None: self.created = created_at self.render() new = self.pk is None if self.reply_to is not None: self.level = self.reply_to.level + 1 else: self.level = 0 self.level_code = self.get_level_code() super(Post, self).save(*args, **kwargs) if new: self.topic.updated = created_at self.topic.forum.updated = created_at # If post is topic head and moderated, moderate topic too if self.topic.head == self and self.on_moderation == False and self.topic.on_moderation == True: self.topic.on_moderation = False self.topic.update_counters() self.topic.forum.update_counters()
def upload_to(instance, filename): """ Returns upload path for FileField :type instance: :class:`django.db.models.Model` :param str filename: :rtype: str """ extension = os.path.splitext(filename)[-1].lower() salt, hash_instance = generate_hash(instance.pk) salt, hash_time = generate_hash(tznow().isoformat()) fk_subdir = "" if by_fk_field: fk_field = getattr(instance, by_fk_field) fk_value = get_field_value(fk_field) salt, hash_fk = generate_hash(force_str(fk_value), salt="") fk_subdir = "{hash}/".format(hash=hash_fk[:6]) return "{path}{fk_subdir}{hash}{extension}".format( path=base_path, fk_subdir=fk_subdir, hash=hash_instance[:10] + hash_time[:6], extension=extension )
def lock(self, user, timestamp=None, wait_to_save=False): timestamp = timestamp if timestamp else tznow() self.locked = timestamp self.locked_by = user # save obj now, don't wait for some other method after this if not wait_to_save: self.save()
def test_delete_expired(self): now = tznow() earlier = now - datetime.timedelta(minutes=5) k = Key.objects.create(group=self.kg_sms, expires=earlier) Key.objects.delete_expired() expired_keys = Key.objects.expired() self.assertFalse(expired_keys)
def set_completed(self, stdout, init_file_path, out_file_path, **kwargs): self.job.set_result(init_file_path, out_file_path) self.log_data.update(kwargs) self.log_data['stdout'] = stdout self.log_data['completed'] = True self.date_finished = tznow() self.save()
def get_context_data(self, **kwargs): return super(DemoPDFView, self).get_context_data( pagesize='A4', title='Hi there!', today=tznow(), **kwargs )
def add_event(cls, actor, verb, target=None, action_object=None, description_template='', timestamp=None, extra=None, using=None): """Add event `actor`, `target` and `action_object` are model instances. `actor` is required. `verb` is a short string, preferrably an infinitive. It should not duplicate information about the model instances of `actor`, `target` or `action_object`. `description_template` is used to build a human-readble string from the other arguments. `timestamp` must be a datetime with timezone `extra` must be JSON serializable, preferrably a dict. The info will be added to the `data`-field, and may be looked up from the `description_template`. """ timestamp = timestamp if timestamp else tznow() description = _format_description(locals(), description_template) data = _serialize_event(locals()) new = cls( actor=actor, target=target, action_object=action_object, verb=verb, description=description, timestamp=timestamp, data=data, ) return super().save(new, force_insert=True, force_update=False, using=using, update_fields=None)
def save(self, *args, **kwargs): self.full_clean() # Grab a copy of the outlet pre-save so that we can determine # which hosts need to have their fencing reconfigured. try: old_self = PowerControlDeviceOutlet.objects.get(pk=self.pk) except PowerControlDeviceOutlet.DoesNotExist: old_self = None super(PowerControlDeviceOutlet, self).save(*args, **kwargs) # Need to force a commit here to ensure that the updated outlet # configuration is available to other threads (e.g. fence reconfig). from django.db import transaction transaction.commit() reconfigure = {'reconfigure_fencing': True} previous = old_self.host if old_self else None for host in self._hosts_for_fence_reconfiguration(self.host, previous): if host.pacemaker_configuration: job_scheduler_notify.notify(host.pacemaker_configuration, tznow(), reconfigure) else: job_log.debug("Skipping reconfiguration of non-server %s" % host)
def save(self, *args, **kwargs): created_at = tznow() if self.created is None: self.created = created_at self.render() new = self.pk is None topic_changed = False old_post = None if not new: old_post = Post.objects.get(pk=self.pk) if old_post.topic != self.topic: topic_changed = True super(Post, self).save(*args, **kwargs) # If post is topic head and moderated, moderate topic too if self.topic.head == self and not self.on_moderation and self.topic.on_moderation: self.topic.on_moderation = False self.topic.update_counters() self.topic.forum.update_counters() if topic_changed: old_post.topic.update_counters() old_post.topic.forum.update_counters()
def get_context_data(self, **kwargs): return super(HelloPDFView, self).get_context_data( pagesize="A4", title="Hi there!", today=tznow(), **kwargs )
def save(self, *args, **kwargs): if self.id is None: self.created = tznow() self.updated = tznow() notice_changed = False old_course = None if self.id is not None: old_course = Course.objects.get(id=self.id) if self.notice != old_course.notice: notice_changed = True super(Course, self).save(*args, **kwargs) if notice_changed: old_course.notice.update_counters() self.notice.update_counters()
def test_cancel_is_allowed_on_non_termiated_bookings(self): ongoing_booking = self.create_booking( self.user_1, start=tznow() - timedelta(minutes=55), end=tznow() + timedelta(minutes=25)) future_booking = self.create_booking( self.user_1, start=tznow() + timedelta(minutes=25), end=tznow() + timedelta(minutes=55)) ongoing_booking.actions.cancel() ongoing_booking.refresh_from_db() self.assertEqual(ongoing_booking.status, Booking.CANCELLED) future_booking.actions.cancel() future_booking.refresh_from_db() self.assertEqual(future_booking.status, Booking.CANCELLED)
def check_for_ipv6(request, profile): if ':' in request.META.get('REMOTE_ADDR'): if not profile.seen_ipv6: profile.seen_ipv6 = tznow() messages.success(request, "Welcome, oh fellow user of IPv6! A badge is on the way.") profile.save() else: messages.success(request, 'Welcome!')
def post(self, *args, **kwargs): discussion_ids = self.request.POST.getlist('discussion_ids') redirect_to = self.request.POST.get('next', False) undo = self.kwargs.get('undo', False) if discussion_ids: # Delete all the messages, if they belong to the user. now = tznow() changed_message_list = set() for pk in self.valid_ids(discussion_ids): discussion = get_object_or_404(Discussion, pk=pk) # Check if the user is the owner if discussion.sender_id == self.request.user.pk: if undo: discussion.sender_deleted_at = None else: discussion.sender_deleted_at = now discussion.save() changed_message_list.add(discussion.pk) # Check if the user is a recipient of the message recipients = discussion.recipient_set.filter(user=self.request.user, discussion=discussion) if recipients: for recipient in recipients: if undo: recipient.mark_as_read() else: recipient.mark_as_deleted() changed_message_list.add(discussion.pk) # Send messages if (len(changed_message_list) > 0): if undo: message = ungettext('This discussion has been succesfully restored', 'These discussions have been succesfully restored', len(changed_message_list)) else: message = ungettext('This discussion has been successfully removed', 'These discussions have been successfully removed', len(changed_message_list)) messages.success(self.request, message, fail_silently=True) if redirect_to: return redirect(redirect_to) folder_id = self.kwargs.get('folder_id') if folder_id: return redirect(reverse('discussions_list', kwargs={'folder_id': folder_id})) return redirect(reverse('discussions_list'))
def publish(self, user, timestamp=None): if self.valid: timestamp = timestamp if timestamp else tznow() if not self.locked: self.lock(user, timestamp, True) self.generated_html = self.generate_html() self.published = timestamp self.published_by = user self.save()
def test_get_expired_keys(self): now = tznow() - timedelta(days=1) for key in self.keys[5:]: key.expires = now key.save() self.assertEqual(list(Key.objects.expired().order_by('id')), self.keys[5:]) self.assertEqual(list(Key.objects.available().order_by('id')), self.keys[:5])
def save(self, *args, **kwargs): "Save key and set ttl if the group has it" now = tznow() if not self.pk: self.pub_date = now if self.group.ttl: add_minutes = timedelta(minutes=self.group.ttl) self.expires = self.pub_date + add_minutes super(AbstractKey, self).save(*args, **kwargs)
def test_get_activated_keys(self): now = tznow() for key in self.keys[5:]: key.activated = now key.save() self.assertEqual(list(Key.objects.activated().order_by('id')), self.keys[5:]) self.assertEqual(list(Key.objects.available().order_by('id')), self.keys[:5])
def render(self, context): context_time = self.time.resolve(context) delta = tznow() - context_time today = tznow().replace(hour=0, minute=0, second=0) yesterday = today - timedelta(days=1) tomorrow = today + timedelta(days=1) date_format = get_setting('site', 'global', 'dateformat') if not date_format: date_format = 'd M, Y H:i' if delta.days == 0: if delta.seconds < 60: if pytils_enabled and context.get('LANGUAGE_CODE', '').startswith('ru'): msg = _('seconds ago,seconds ago,seconds ago') msg = pytils.numeral.choose_plural(delta.seconds, msg) else: msg = _('seconds ago') return '%d %s' % (delta.seconds, msg) elif delta.seconds < 3600: minutes = int(delta.seconds / 60) if pytils_enabled and context.get('LANGUAGE_CODE', '').startswith('ru'): msg = _('minutes ago,minutes ago,minutes ago') msg = pytils.numeral.choose_plural(minutes, msg) else: msg = _('minutes ago') return '%d %s' % (minutes, msg) if context['user'].is_authenticated: if time.daylight: tz1 = time.altzone else: tz1 = time.timezone tz = tz1 + util.get_pybb_profile( context['user']).time_zone * 60 * 60 context_time = context_time + timedelta(seconds=tz) if today < context_time < tomorrow: return _('today, %s') % context_time.strftime('%H:%M') elif yesterday < context_time < today: return _('yesterday, %s') % context_time.strftime('%H:%M') else: return dateformat.format(context_time, date_format)
def test_pprint(self): now = tznow() k = Key.objects.create(key='PPRint', group=self.kg_sms, pub_date=now) pub_date = k.pub_date simple = k.pprint() self.assertEqual(simple, 'PPRint (sms) %s (<= None)' % pub_date) k.expires = now k.save() simple = k.pprint() self.assertEqual(simple, 'PPRint (sms) %s (<= %s)' % (pub_date, now))
def check_for_ipv6(request, profile): if ':' in request.META.get('REMOTE_ADDR'): if not profile.seen_ipv6: profile.seen_ipv6 = tznow() messages.success( request, "Welcome, oh fellow user of IPv6! A badge is on the way.") profile.save() else: messages.success(request, 'Welcome!')
def save(self, commit=True): if self.instance.pk: post = super(PostForm, self).save(commit=False) if self.user: post.user = self.user if post.topic.head == post: post.topic.name = self.cleaned_data['name'] if self.may_create_poll: post.topic.poll_type = self.cleaned_data['poll_type'] post.topic.poll_question = self.cleaned_data['poll_question'] post.topic.updated = tznow() if commit: post.topic.save() post.updated = tznow() if commit: post.save() return post, post.topic allow_post = True if defaults.PYBB_PREMODERATION: allow_post = defaults.PYBB_PREMODERATION(self.user, self.cleaned_data['body']) if self.forum: topic = Topic( forum=self.forum, user=self.user, name=self.cleaned_data['name'], poll_type=self.cleaned_data.get('poll_type', Topic.POLL_TYPE_NONE), poll_question=self.cleaned_data.get('poll_question', None), slug=self.cleaned_data.get('slug', None), ) if not allow_post: topic.on_moderation = True else: topic = self.topic post = Post(user=self.user, user_ip=self.ip, body=self.cleaned_data['body']) if not allow_post: post.on_moderation = True if commit: topic.save() post.topic = topic post.save() return post, topic
def add_ban(banner, banned, resource, duration, reason): active_ban = ActiveBan() active_ban.dictation_on = tznow() active_ban.dictated_by = banner active_ban.dictated_to = banned active_ban.duration = duration active_ban.dictation_reason = reason active_ban.start_on = None active_ban.resource = resource active_ban.save() return active_ban
def mark_as_read(self, user=None): from discussions.models import Recipient recipients = self.recipients.all() recipients = Recipient.objects.filter(discussion_id=self.pk) if user: recipients = recipients.filter(user_id=user.pk) recipients.update(read_at=tznow(), status=Recipient.STATUS.read)
def render(self, context): context_time = self.time.resolve(context) delta = tznow() - context_time today = tznow().replace(hour=0, minute=0, second=0) yesterday = today - timedelta(days=1) tomorrow = today + timedelta(days=1) date_format = get_setting('site', 'global', 'dateformat') if not date_format: date_format = 'd M, Y H:i' if delta.days == 0: if delta.seconds < 60: if pytils_enabled and context.get('LANGUAGE_CODE', '').startswith('ru'): msg = _('seconds ago,seconds ago,seconds ago') msg = pytils.numeral.choose_plural(delta.seconds, msg) else: msg = _('seconds ago') return '%d %s' % (delta.seconds, msg) elif delta.seconds < 3600: minutes = int(delta.seconds / 60) if pytils_enabled and context.get('LANGUAGE_CODE', '').startswith('ru'): msg = _('minutes ago,minutes ago,minutes ago') msg = pytils.numeral.choose_plural(minutes, msg) else: msg = _('minutes ago') return '%d %s' % (minutes, msg) if context['user'].is_authenticated: if time.daylight: tz1 = time.altzone else: tz1 = time.timezone tz = tz1 + util.get_pybb_profile(context['user']).time_zone * 60 * 60 context_time = context_time + timedelta(seconds=tz) if today < context_time < tomorrow: return _('today, %s') % context_time.strftime('%H:%M') elif yesterday < context_time < today: return _('yesterday, %s') % context_time.strftime('%H:%M') else: return dateformat.format(context_time, date_format)
def save(self, commit=True): if self.instance.pk: post = super(PostForm, self).save(commit=False) if self.user: post.user = self.user if post.course.head == post: post.course.name = self.cleaned_data['name'] if self.may_create_poll: post.course.poll_type = self.cleaned_data['poll_type'] post.course.poll_question = self.cleaned_data['poll_question'] post.course.updated = tznow() if commit: post.course.save() post.updated = tznow() if commit: post.save() return post allow_post = True if defaults.PYBB_PREMODERATION: allow_post = defaults.PYBB_PREMODERATION(self.user, self.cleaned_data['body']) if self.notice: course = Course( notice=self.notice, user=self.user, name=self.cleaned_data['name'], poll_type=self.cleaned_data.get('poll_type', Course.POLL_TYPE_NONE), poll_question=self.cleaned_data.get('poll_question', None), ) if not allow_post: course.on_moderation = True if commit: course.save() else: course = self.course post = Post(course=course, user=self.user, user_ip=self.ip, body=self.cleaned_data['body']) if not allow_post: post.on_moderation = True if commit: post.save() return post
def test_available(self): now = tznow() earlier = now - datetime.timedelta(minutes=5+random.randint(0, 200)) later = now + datetime.timedelta(minutes=5+random.randint(0, 200)) k1 = Key.objects.create(key='1', group=self.kg_sms, claimed=now) k2 = Key.objects.create(key='2', group=self.kg_sms, claimed=now, expires=earlier) k3 = Key.objects.create(key='3', group=self.kg_sms, claimed=now, expires=later) k4 = Key.objects.create(key='4', group=self.kg_sms) k5 = Key.objects.create(key='5', group=self.kg_sms, expires=earlier) k6 = Key.objects.create(key='6', group=self.kg_sms, expires=later) claimed_keys = Key.objects.claimed() self.assertEqual(set(Key.objects.available()), set((k4, k6)))
def activate(self, user): """Activates a specific key for user, returns activated key on activation, raises an exception otherwise""" now = tznow() if self.expires and self.expires <= now: raise ActivationKeyError('Key expired on %s' % self.expires) if self.activated: raise ActivationKeyError('Key has already been activated') self.activated_by = user self.activated = now self.save() key_activated.send_robust(sender=self, user=user, group=self.group) return self
def test_get_activated_keys(self): now = tznow() for key in self.keys[5:]: key.activated = now key.save() self.assertEqual( list(Key.objects.activated().order_by('id')), self.keys[5:] ) self.assertEqual( list(Key.objects.available().order_by('id')), self.keys[:5] )
def test_get_expired_keys(self): now = tznow() - timedelta(days=1) for key in self.keys[5:]: key.expires = now key.save() self.assertEqual( list(Key.objects.expired().order_by('id')), self.keys[5:] ) self.assertEqual( list(Key.objects.available().order_by('id')), self.keys[:5] )
def render(self, context): context_time = self.time.resolve(context) delta = tznow() - context_time today = tznow().replace(hour=0, minute=0, second=0) yesterday = today - timedelta(days=1) tomorrow = today + timedelta(days=1) if delta.days == 0: if delta.seconds < 60: if context["LANGUAGE_CODE"].startswith("ru") and pytils_enabled: msg = _("seconds ago,seconds ago,seconds ago") msg = pytils.numeral.choose_plural(delta.seconds, msg) else: msg = _("seconds ago") return u"%d %s" % (delta.seconds, msg) elif delta.seconds < 3600: minutes = int(delta.seconds / 60) if context["LANGUAGE_CODE"].startswith("ru") and pytils_enabled: msg = _("minutes ago,minutes ago,minutes ago") msg = pytils.numeral.choose_plural(minutes, msg) else: msg = _("minutes ago") return u"%d %s" % (minutes, msg) if context["user"].is_authenticated(): if time.daylight: tz1 = time.altzone else: tz1 = time.timezone tz = tz1 + context["user"].get_profile().time_zone * 60 * 60 context_time = context_time + timedelta(seconds=tz) if today < context_time < tomorrow: return _("today, %s") % context_time.strftime("%H:%M") elif yesterday < context_time < today: return _("yesterday, %s") % context_time.strftime("%H:%M") else: return dateformat.format(context_time, "d M, Y H:i")
def save(self, user=None, batch=False, using=None, *args, **kwargs): if using: desc_obj = Description.objects.using(using) else: desc_obj = Description.objects if not batch: self.id = next_id(self.__class__) self.last_modified = tznow() if user: self.last_modified_by = user desc_obj.filter(object_id=self.object_id).update(current=False) super(Description, self).save(force_insert=True, using=using, *args, **kwargs) else: super(Description, self).save(using=using, *args, **kwargs)
def forgive(self, ban, reason): """ Forgives an active ban. """ self._check_can_terminate(ban) try: ban = core.forgive_ban(self.__user, ban, tznow(), reason) signals.ban_terminated.send_robust(ban.dictated_to, ban=ban) return ban except Exception as e: raise DetentionServiceError(_(u"An internal error occurred when forgiving a ban " u"- Contact the administrator if this still happens"), "UNKNOWN")