Пример #1
0
    def request_friendship(cls, friend_1, friend_2, text=None):
        own_request = cls._get_for(friend_1, friend_2)
        if own_request:
            if text is not None: #
                own_request._model.text = text
                own_request.save()
            return own_request

        his_request = cls._get_for(friend_2, friend_1)
        if his_request:
            his_request._confirm()
            return his_request

        model = cls._model_class.objects.create(friend_1=friend_1._model,
                                                friend_2=friend_2._model,
                                                text=text)
        prototype = cls(model=model)

        message = u'''
игрок %(account_link)s предлагает вам дружить:

%(text)s

----------
принять или отклонить предложение вы можете на этой странице: %(friends_link)s
''' % {'account_link': u'[url="%s"]%s[/url]' % (full_url('http', 'accounts:show', friend_1.id), friend_1.nick_verbose),
       'text': text,
       'friends_link': u'[url="%s"]предложения дружбы[/url]' % full_url('http', 'accounts:friends:candidates')}

        # send message from name of user, who request friendship
        # since many users try to respod to system user
        MessagePrototype.create(friend_1, friend_2, message)

        return prototype
Пример #2
0
    def create_reject_request_message(self, initiator):
        message = '''
Игрок %(clan_leader_link)s отказал вам в принятии в гильдию %(clan_link)s.
''' % {'clan_leader_link': '[url="%s"]%s[/url]' % (full_url('http', 'accounts:show', initiator.id), initiator.nick_verbose),
       'clan_link': '[url="%s"]%s[/url]' % (full_url('http', 'accounts:clans:show', self.clan.id), self.clan.name)}

        MessagePrototype.create(initiator, self.account, message)
Пример #3
0
 def _confirm(self):
     MessagePrototype.create(get_system_user(),
                             self.friend_1,
                             u'игрок %(account_link)s подтвердил, что вы являетесь друзьями' %
                             {'account_link': u'[url=%s]%s[/url]' % (full_url('http', 'accounts:show', self.friend_2.id), self.friend_2.nick_verbose)})
     self._model.is_confirmed = True
     self.save()
Пример #4
0
    def create_remove_member_message(self, initiator, removed_account):
        message = '''
Игрок %(clan_leader_link)s исключил вас из гильдии %(clan_link)s.
''' % {'clan_leader_link': '[url="%s"]%s[/url]' % (full_url('http', 'accounts:show', initiator.id), initiator.nick_verbose),
       'clan_link': '[url="%s"]%s[/url]' % (full_url('http', 'accounts:clans:show', self.id), self.name)}

        MessagePrototype.create(initiator, removed_account, message)
Пример #5
0
    def process(self):
        from the_tale.accounts.personal_messages.prototypes import MessagePrototype as PersonalMessagePrototype
        from the_tale.accounts.logic import get_system_user

        accounts_ids = AccountPrototype.live_query().filter(is_fast=False,
                                                            created_at__lt=datetime.datetime.now() - accounts_settings.RANDOM_PREMIUM_CREATED_AT_BARRIER,
                                                            active_end_at__gt=datetime.datetime.now(),
                                                            premium_end_at__lt=datetime.datetime.now()).exclude(id=self.initiator_id).values_list('id', flat=True)

        if not accounts_ids:
            return False

        account = AccountPrototype.get_by_id(random.choice(accounts_ids))

        with transaction.atomic():
            account.prolong_premium(self.days)
            account.save()

            PersonalMessagePrototype.create(get_system_user(), account, self.MESSAGE % {'days': self.days})

            self.receiver_id = account.id
            self.state = relations.RANDOM_PREMIUM_REQUEST_STATE.PROCESSED
            self.save()

        return True
Пример #6
0
def portal_day_started(sender, **kwargs):  # pylint: disable=W0613
    accounts_query = AccountPrototype.live_query().filter(
        active_end_at__gt=datetime.datetime.now(),
        ban_game_end_at__lt=datetime.datetime.now(),
        ban_forum_end_at__lt=datetime.datetime.now(),
        premium_end_at__lt=datetime.datetime.now())

    accounts_number = accounts_query.count()
    if accounts_number < 1:
        return

    account_model = accounts_query[random.randint(0, accounts_number - 1)]

    account = AccountPrototype(model=account_model)

    settings[portal_settings.SETTINGS_ACCOUNT_OF_THE_DAY_KEY] = str(account.id)

    environment.workers.accounts_manager.cmd_run_account_method(
        account_id=account.id,
        method_name=AccountPrototype.prolong_premium.__name__,
        data={'days': portal_settings.PREMIUM_DAYS_FOR_HERO_OF_THE_DAY})

    message = '''
Поздравляем!

Ваш герой выбран героем дня и Вы получаете %(days)d дней подписки!
''' % {
        'days': portal_settings.PREMIUM_DAYS_FOR_HERO_OF_THE_DAY
    }

    MessagePrototype.create(get_system_user(), account, message)
Пример #7
0
    def remove_friendship(cls, initiator, friend):
        request = cls.get_for_bidirectional(initiator, friend)

        if request is None: return

        if request.is_confirmed:
            MessagePrototype.create(
                get_system_user(), friend,
                'игрок %(account_link)s удалил вас из списка друзей' % {
                    'account_link':
                    '[url="%s"]%s[/url]' %
                    (full_url('http', 'accounts:show',
                              initiator.id), initiator.nick_verbose)
                })
        else:
            MessagePrototype.create(
                get_system_user(), friend,
                'игрок %(account_link)s отказался добавить вас в список друзей'
                % {
                    'account_link':
                    '[url="%s"]%s[/url]' %
                    (full_url('http', 'accounts:show',
                              initiator.id), initiator.nick_verbose)
                })

        request.remove()

        return
Пример #8
0
def portal_day_started(sender, **kwargs): # pylint: disable=W0613
    accounts_query = AccountPrototype.live_query().filter(active_end_at__gt=datetime.datetime.now(),
                                                          ban_game_end_at__lt=datetime.datetime.now(),
                                                          ban_forum_end_at__lt=datetime.datetime.now(),
                                                          premium_end_at__lt=datetime.datetime.now())

    accounts_number = accounts_query.count()
    if accounts_number < 1:
        return

    account_model = accounts_query[random.randint(0, accounts_number-1)]

    account = AccountPrototype(model=account_model)

    settings[portal_settings.SETTINGS_ACCOUNT_OF_THE_DAY_KEY] = str(account.id)

    environment.workers.accounts_manager.cmd_run_account_method(account_id=account.id,
                                                                method_name=AccountPrototype.prolong_premium.__name__,
                                                                data={'days': portal_settings.PREMIUM_DAYS_FOR_HERO_OF_THE_DAY})

    message = u'''
Поздравляем!

Ваш герой выбран героем дня и Вы получаете %(days)d дней подписки!
''' % {'days': portal_settings.PREMIUM_DAYS_FOR_HERO_OF_THE_DAY}

    MessagePrototype.create(get_system_user(), account, message)
Пример #9
0
    def test_day_started_signal(self):
        self.assertFalse(
            portal_settings.SETTINGS_ACCOUNT_OF_THE_DAY_KEY in settings)

        self.assertEqual(MessagePrototype._db_count(), 0)

        with mock.patch(
                'the_tale.accounts.workers.accounts_manager.Worker.cmd_run_account_method'
        ) as cmd_run_account_method:
            portal_signals.day_started.send(self.__class__)

        self.assertEqual(cmd_run_account_method.call_count, 1)
        self.assertEqual(
            cmd_run_account_method.call_args,
            mock.call(account_id=self.account.id,
                      method_name='prolong_premium',
                      data={
                          'days':
                          portal_settings.PREMIUM_DAYS_FOR_HERO_OF_THE_DAY
                      }))

        self.assertEqual(
            int(settings[portal_settings.SETTINGS_ACCOUNT_OF_THE_DAY_KEY]),
            self.account.id)

        self.assertEqual(MessagePrototype._db_count(), 1)
        message = MessagePrototype._db_get_object(0)
        self.assertEqual(message.sender_id, get_system_user().id)
        self.assertEqual(message.recipient_id, self.account.id)
Пример #10
0
    def process(self):
        from the_tale.accounts.personal_messages.prototypes import MessagePrototype as PersonalMessagePrototype
        from the_tale.accounts.logic import get_system_user

        accounts_ids = AccountPrototype.live_query().filter(
            is_fast=False,
            created_at__lt=datetime.datetime.now() -
            accounts_settings.RANDOM_PREMIUM_CREATED_AT_BARRIER,
            active_end_at__gt=datetime.datetime.now(),
            premium_end_at__lt=datetime.datetime.now()).exclude(
                id=self.initiator_id).values_list('id', flat=True)

        if not accounts_ids:
            return False

        account = AccountPrototype.get_by_id(random.choice(accounts_ids))

        with transaction.atomic():
            account.prolong_premium(self.days)
            account.save()

            PersonalMessagePrototype.create(get_system_user(), account,
                                            self.MESSAGE % {'days': self.days})

            self.receiver_id = account.id
            self.state = relations.RANDOM_PREMIUM_REQUEST_STATE.PROCESSED
            self.save()

        return True
Пример #11
0
    def test_send_premium_expired_notifications(self):
        self.assertEqual(PersonalMessagePrototype._db_count(), 0)

        account_1 = self.account
        account_2 = self.accounts_factory.create_account()
        account_3 = self.accounts_factory.create_account()
        account_4 = self.accounts_factory.create_account()

        account_1.prolong_premium(
            accounts_settings.PREMIUM_EXPIRED_NOTIFICATION_IN.days - 1)
        account_1.save()

        account_3.prolong_premium(
            accounts_settings.PREMIUM_EXPIRED_NOTIFICATION_IN.days - 1)
        account_3.save()

        account_4.prolong_premium(
            accounts_settings.PREMIUM_EXPIRED_NOTIFICATION_IN.days + 1)
        account_4.save()

        zero_time = datetime.datetime.fromtimestamp(0)

        self.assertEqual(account_1._model.premium_expired_notification_send_at,
                         zero_time)
        self.assertEqual(account_2._model.premium_expired_notification_send_at,
                         zero_time)
        self.assertEqual(account_3._model.premium_expired_notification_send_at,
                         zero_time)
        self.assertEqual(account_4._model.premium_expired_notification_send_at,
                         zero_time)

        AccountPrototype.send_premium_expired_notifications()

        account_1.reload()
        account_2.reload()
        account_3.reload()
        account_4.reload()

        self.assertNotEqual(
            account_1._model.premium_expired_notification_send_at, zero_time)
        self.assertEqual(account_2._model.premium_expired_notification_send_at,
                         zero_time)
        self.assertNotEqual(
            account_3._model.premium_expired_notification_send_at, zero_time)
        self.assertEqual(account_4._model.premium_expired_notification_send_at,
                         zero_time)

        current_time = datetime.datetime.now()

        self.assertTrue(
            current_time - datetime.timedelta(seconds=60) < account_1._model.
            premium_expired_notification_send_at < current_time)
        self.assertTrue(
            current_time - datetime.timedelta(seconds=60) < account_3._model.
            premium_expired_notification_send_at < current_time)

        self.assertEqual(PersonalMessagePrototype._db_count(), 2)
Пример #12
0
def reset_bans(context):

    context.master_account.reset_ban_forum()
    context.master_account.reset_ban_game()

    MessagePrototype.create(logic.get_system_user(), context.master_account,
                            'С вас сняли все ограничения, наложенные ранее.')

    return dext_views.AjaxOk()
Пример #13
0
def reset_bans(context):

    context.master_account.reset_ban_forum()
    context.master_account.reset_ban_game()

    MessagePrototype.create(logic.get_system_user(),
                            context.master_account,
                            u'С вас сняли все ограничения, наложенные ранее.')

    return dext_views.AjaxOk()
Пример #14
0
    def test_index_second_page(self):
        for i in range(conf.settings.MESSAGES_ON_PAGE):
            MessagePrototype.create(self.account2, self.account1, 'test message_2_1 %d' % i)

        texts = []
        for i in range(conf.settings.MESSAGES_ON_PAGE):
            texts.append(('test message_2_1 %d' % i, 1))

        self.request_login(self.account1.email)
        self.check_html_ok(self.request_html(url('accounts:messages:')), texts=texts)
Пример #15
0
    def setUp(self):
        super(PrototypeTests, self).setUp()
        create_test_map()

        self.account1 = self.accounts_factory.create_account()
        self.account2 = self.accounts_factory.create_account()
        self.account3 = self.accounts_factory.create_account()

        self.message = MessagePrototype.create(self.account1, self.account2, 'message 1')
        self.message_2 = MessagePrototype.create(self.account1, self.account2, 'message 2')
Пример #16
0
 def _confirm(self):
     MessagePrototype.create(
         get_system_user(), self.friend_1,
         'игрок %(account_link)s подтвердил, что вы являетесь друзьями' % {
             'account_link':
             '[url=%s]%s[/url]' %
             (full_url('http', 'accounts:show',
                       self.friend_2.id), self.friend_2.nick_verbose)
         })
     self._model.is_confirmed = True
     self.save()
Пример #17
0
    def test_send_premium_expired_notifications(self):
        self.assertEqual(PersonalMessagePrototype._db_count(), 0)

        register_user("test_user_2", "*****@*****.**", "111111")
        register_user("test_user_3", "*****@*****.**", "111111")
        register_user("test_user_4", "*****@*****.**", "111111")

        account_1 = self.account
        account_2 = AccountPrototype.get_by_nick("test_user_2")
        account_3 = AccountPrototype.get_by_nick("test_user_3")
        account_4 = AccountPrototype.get_by_nick("test_user_4")

        account_1.prolong_premium(accounts_settings.PREMIUM_EXPIRED_NOTIFICATION_IN.days - 1)
        account_1.save()

        account_3.prolong_premium(accounts_settings.PREMIUM_EXPIRED_NOTIFICATION_IN.days - 1)
        account_3.save()

        account_4.prolong_premium(accounts_settings.PREMIUM_EXPIRED_NOTIFICATION_IN.days + 1)
        account_4.save()

        zero_time = datetime.datetime.fromtimestamp(0)

        self.assertEqual(account_1._model.premium_expired_notification_send_at, zero_time)
        self.assertEqual(account_2._model.premium_expired_notification_send_at, zero_time)
        self.assertEqual(account_3._model.premium_expired_notification_send_at, zero_time)
        self.assertEqual(account_4._model.premium_expired_notification_send_at, zero_time)

        AccountPrototype.send_premium_expired_notifications()

        account_1.reload()
        account_2.reload()
        account_3.reload()
        account_4.reload()

        self.assertNotEqual(account_1._model.premium_expired_notification_send_at, zero_time)
        self.assertEqual(account_2._model.premium_expired_notification_send_at, zero_time)
        self.assertNotEqual(account_3._model.premium_expired_notification_send_at, zero_time)
        self.assertEqual(account_4._model.premium_expired_notification_send_at, zero_time)

        current_time = datetime.datetime.now()

        self.assertTrue(
            current_time - datetime.timedelta(seconds=60)
            < account_1._model.premium_expired_notification_send_at
            < current_time
        )
        self.assertTrue(
            current_time - datetime.timedelta(seconds=60)
            < account_3._model.premium_expired_notification_send_at
            < current_time
        )

        self.assertEqual(PersonalMessagePrototype._db_count(), 2)
Пример #18
0
    def test_index_second_page(self):
        for i in xrange(conf.settings.MESSAGES_ON_PAGE):
            MessagePrototype.create(self.account2, self.account1,
                                    'test message_2_1 %d' % i)

        texts = []
        for i in xrange(conf.settings.MESSAGES_ON_PAGE):
            texts.append(('test message_2_1 %d' % i, 1))

        self.request_login(self.account1.email)
        self.check_html_ok(self.request_html(url('accounts:messages:')),
                           texts=texts)
Пример #19
0
    def setUp(self):
        super(PrototypeTests, self).setUp()
        create_test_map()

        self.account1 = self.accounts_factory.create_account()
        self.account2 = self.accounts_factory.create_account()
        self.account3 = self.accounts_factory.create_account()

        self.message = MessagePrototype.create(self.account1, self.account2,
                                               'message 1')
        self.message_2 = MessagePrototype.create(self.account1, self.account2,
                                                 'message 2')
Пример #20
0
    def increment_level(self, send_message=False):
        from the_tale.accounts.prototypes import AccountPrototype
        from the_tale.accounts.personal_messages.prototypes import MessagePrototype
        from the_tale.accounts.logic import get_system_user

        self._model.level += 1
        self.add_message('hero_common_journal_level_up', hero=self, level=self.level)

        self.force_save_required = True

        if send_message:
            account = AccountPrototype.get_by_id(self.account_id)
            MessagePrototype.create(get_system_user(), account, text=u'Поздравляем, Ваш герой получил %d уровень!' % self.level)
Пример #21
0
    def increment_level(self, send_message=False):
        from the_tale.accounts.prototypes import AccountPrototype
        from the_tale.accounts.personal_messages.prototypes import MessagePrototype
        from the_tale.accounts.logic import get_system_user

        self._model.level += 1
        self.add_message('hero_common_journal_level_up', hero=self, level=self.level)

        self.force_save_required = True

        if send_message:
            account = AccountPrototype.get_by_id(self.account_id)
            MessagePrototype.create(get_system_user(), account, text=u'Поздравляем, Ваш герой получил %d уровень!' % self.level)
Пример #22
0
    def test_mail_send__to_system_user(self):
        from the_tale.accounts.logic import get_system_user

        Message.objects.all().delete()

        PersonalMessagePrototype.create(self.account_1, get_system_user(), 'test text')

        message = MessagePrototype.get_priority_message()

        self.assertEqual(len(mail.outbox), 0)
        message.process()
        self.assertTrue(message.state.is_PROCESSED)
        self.assertEqual(len(mail.outbox), 0)
Пример #23
0
    def create_request_message(self, initiator):
        message = '''
Игрок %(account)s просит принять его в вашу гильдию:

%(text)s

----------
принять или отклонить предложение вы можете на этой странице: %(invites_link)s
''' % {'account': '[url="%s"]%s[/url]' % (full_url('http', 'accounts:show', self.account.id), self.account.nick_verbose),
       'text': self.text,
       'invites_link': '[url="%s"]Заявки в гильдию[/url]' % full_url('http', 'accounts:clans:membership:for-clan')}

        MessagePrototype.create(initiator, self.clan.get_leader(), message)
Пример #24
0
    def notify_about_premium_expiration(self):
        from the_tale.accounts.personal_messages.prototypes import MessagePrototype as PersonalMessagePrototype
        from the_tale.accounts.logic import get_system_user

        current_time = datetime.datetime.now()

        message = u'''
До окончания подписки осталось: %(verbose_timedelta)s.

Вы можете продлить подписку на странице нашего %(shop_link)s.
''' % {'verbose_timedelta': verbose_timedelta(self.premium_end_at - current_time),
       'shop_link': u'[url="%s"]магазина[/url]' % full_url('http', 'shop:shop')}

        PersonalMessagePrototype.create(get_system_user(), self, message)
Пример #25
0
    def test_mail_send__to_system_user(self):
        from the_tale.accounts.logic import get_system_user

        Message.objects.all().delete()

        PersonalMessagePrototype.create(self.account_1, get_system_user(),
                                        'test text')

        message = MessagePrototype.get_priority_message()

        self.assertEqual(len(mail.outbox), 0)
        message.process()
        self.assertTrue(message.state.is_PROCESSED)
        self.assertEqual(len(mail.outbox), 0)
Пример #26
0
    def create_invite_message(self, initiator):
        message = '''
Игрок %(clan_leader_link)s предлагает вам вступить в гильдию %(clan_link)s:

%(text)s

----------
принять или отклонить предложение вы можете на этой странице: %(invites_link)s
''' % {'clan_leader_link': '[url="%s"]%s[/url]' % (full_url('http', 'accounts:show', initiator.id), initiator.nick_verbose),
       'text': self.text,
       'clan_link': '[url="%s"]%s[/url]' % (full_url('http', 'accounts:clans:show', self.clan.id), self.clan.name),
       'invites_link': '[url="%s"]Приглашения в гильдию [/url]' % full_url('http', 'accounts:clans:membership:for-account')}

        MessagePrototype.create(initiator, self.account, message)
Пример #27
0
    def setUp(self):
        super(PrototypeTests, self).setUp()
        create_test_map()

        result, account_id, bundle_id = register_user('test_user1', '*****@*****.**', '111111')
        self.account1 = AccountPrototype.get_by_id(account_id)

        result, account_id, bundle_id = register_user('test_user2', '*****@*****.**', '111111')
        self.account2 = AccountPrototype.get_by_id(account_id)

        result, account_id, bundle_id = register_user('test_user3', '*****@*****.**', '111111')
        self.account3 = AccountPrototype.get_by_id(account_id)

        self.message = MessagePrototype.create(self.account1, self.account2, 'message 1')
        self.message_2 = MessagePrototype.create(self.account1, self.account2, 'message 2')
Пример #28
0
    def test_day_started_signal__only_not_premium(self):
        self.assertEqual(AccountPrototype._db_count(), 1)

        self.account.prolong_premium(days=30)
        self.account.save()

        old_premium_end_at = self.account.premium_end_at

        self.assertEqual(MessagePrototype._db_count(), 0)

        portal_signals.day_started.send(self.__class__)

        self.assertEqual(MessagePrototype._db_count(), 0)

        self.account.reload()
        self.assertEqual(old_premium_end_at, self.account.premium_end_at)
Пример #29
0
    def test_success__ban_total(self):
        self.check_ajax_ok(self.client.post(reverse('accounts:ban', args=[self.account_1.id]), self.form_data(BAN_TYPE.TOTAL)))

        self.account_1.reload()
        self.assertTrue(self.account_1.is_ban_forum)
        self.assertTrue(self.account_1.is_ban_game)
        self.assertEqual(MessagePrototype._db_count(), 1)
Пример #30
0
    def process(self):
        from the_tale.accounts.personal_messages.prototypes import MessagePrototype as PersonalMessagePrototype

        message = PersonalMessagePrototype.get_by_id(self.message_id)

        if message is None:
            return True  # message can be removed by admins or with removed thread

        account = message.recipient

        if not account.personal_messages_subscription:
            return True

        if account.id == get_system_user().id or account.is_bot:
            return True

        if not account.email:
            return True

        subject = '«Сказка»: личное сообщение'

        context = {'message': message}

        html_content = jinja2.render(self.EMAIL_HTML_TEMPLATE, context)
        text_content = jinja2.render(self.EMAIL_TEXT_TEMPLATE, context)

        return logic.send_mail([account], subject, text_content, html_content)
Пример #31
0
    def process(self):
        from the_tale.accounts.personal_messages.prototypes import MessagePrototype as PersonalMessagePrototype

        message = PersonalMessagePrototype.get_by_id(self.message_id)

        if message is None:
            return True # message can be removed by admins or with removed thread

        account = message.recipient

        if not account.personal_messages_subscription:
            return True

        if account.id == get_system_user().id or account.is_bot:
            return True

        if not account.email:
            return True

        subject = '«Сказка»: личное сообщение'

        context = {'message': message}

        html_content = jinja2.render(self.EMAIL_HTML_TEMPLATE, context)
        text_content = jinja2.render(self.EMAIL_TEXT_TEMPLATE, context)

        return logic.send_mail([account], subject, text_content, html_content)
    def check_not_processed(self, premiums=0):
        self.assertEqual(MessagePrototype._db_count(), 0)
        self.assertEqual(AccountPrototype._db_filter(premium_end_at__gt=datetime.datetime.now()).count(), premiums)

        self.request.reload()
        self.assertTrue(self.request.state.is_WAITING)
        self.assertEqual(self.request.receiver_id, None)
Пример #33
0
    def test_success__ban_total(self):
        self.check_ajax_ok(self.client.post(reverse('accounts:ban', args=[self.account_1.id]), self.form_data(BAN_TYPE.TOTAL)))

        self.account_1.reload()
        self.assertTrue(self.account_1.is_ban_forum)
        self.assertTrue(self.account_1.is_ban_game)
        self.assertEqual(MessagePrototype._db_count(), 1)
    def test_process__has_active_accounts(self):
        AccountPrototype._db_all().update(active_end_at=datetime.datetime.now() + datetime.timedelta(days=1))

        self.request.process()

        self.assertEqual(MessagePrototype._db_count(), 1)

        message = MessagePrototype._db_get_object(0)
        self.assertEqual(message.recipient_id, self.account_2.id)
        self.assertEqual(message.sender_id, get_system_user().id)

        self.assertEqual(list(AccountPrototype._db_filter(premium_end_at__gt=datetime.datetime.now()).values_list('id', flat=True)), [self.account_2.id])

        self.request.reload()
        self.assertTrue(self.request.state.is_PROCESSED)
        self.assertEqual(self.request.receiver_id, self.account_2.id)
Пример #35
0
    def test_day_started_signal__only_not_premium(self):
        self.assertEqual(AccountPrototype._db_count(), 1)

        self.account.prolong_premium(days=30)
        self.account.save()

        old_premium_end_at = self.account.premium_end_at

        self.assertEqual(MessagePrototype._db_count(), 0)

        portal_signals.day_started.send(self.__class__)

        self.assertEqual(MessagePrototype._db_count(), 0)

        self.account.reload()
        self.assertEqual(old_premium_end_at, self.account.premium_end_at)
Пример #36
0
 def test_answer_to_no_permissions(self):
     message = MessagePrototype.create(self.account2, self.account3,
                                       'message_2_3 1')
     self.check_html_ok(self.post_ajax_html(
         url('accounts:messages:new', answer_to=message.id),
         {'recipients': self.account2.id}),
                        texts=[('pgf-error-no_permissions_to_answer_to', 1)
                               ])
Пример #37
0
    def test_form_errors(self):
        self.check_ajax_error(self.client.post(reverse('accounts:ban', args=[self.account_1.id]), self.form_data(BAN_TYPE.FORUM, description=u'')),
                              'form_errors')

        self.account_1.reload()
        self.assertFalse(self.account_1.is_ban_forum)
        self.assertFalse(self.account_1.is_ban_game)
        self.assertEqual(MessagePrototype._db_count(), 0)
Пример #38
0
 def test_delete_from_recipient(self):
     self.request_login(self.account2.email)
     self.check_ajax_ok(
         self.post_ajax_json(
             url('accounts:messages:delete', self.message.id)))
     message = MessagePrototype.get_by_id(self.message.id)
     self.assertFalse(message.hide_from_sender)
     self.assertTrue(message.hide_from_recipient)
Пример #39
0
    def test_form_errors(self):
        self.check_ajax_error(self.client.post(reverse('accounts:ban', args=[self.account_1.id]), self.form_data(BAN_TYPE.FORUM, description=u'')),
                              'form_errors')

        self.account_1.reload()
        self.assertFalse(self.account_1.is_ban_forum)
        self.assertFalse(self.account_1.is_ban_game)
        self.assertEqual(MessagePrototype._db_count(), 0)
Пример #40
0
 def test_answer_to(self):
     message = MessagePrototype.create(self.account2, self.account1,
                                       'message_2_1 1')
     self.check_html_ok(self.post_ajax_html(
         url('accounts:messages:new', answer_to=message.id),
         {'recipients': self.account2.id}),
                        texts=[('pgf-new-message-form', 1),
                               ('message_2_1 1', 1)])
Пример #41
0
    def setUp(self):
        super(IndexRequestsTests, self).setUp()

        self.messages_1_2 = [
            MessagePrototype.create(self.account1, self.account2,
                                    'message_1_2 1'),
            MessagePrototype.create(self.account1, self.account2,
                                    'message_1_2 2'),
            MessagePrototype.create(self.account1, self.account2,
                                    'message_1_2 3')
        ]

        self.messages_2_1 = [
            MessagePrototype.create(self.account2, self.account1,
                                    'message_2_1 1'),
            MessagePrototype.create(self.account2, self.account1,
                                    'message_2_1 2')
        ]

        self.messages_3_1 = [
            MessagePrototype.create(self.account3, self.account1,
                                    'message_3_1 1')
        ]
        self.messages_3_2 = [
            MessagePrototype.create(self.account3, self.account2,
                                    'message_3_2 1')
        ]
Пример #42
0
    def notify_about_premium_expiration(self):
        from the_tale.accounts.personal_messages.prototypes import MessagePrototype as PersonalMessagePrototype
        from the_tale.accounts.logic import get_system_user

        current_time = datetime.datetime.now()

        message = '''
До окончания подписки осталось: %(verbose_timedelta)s.

Вы можете продлить подписку на странице нашего %(shop_link)s.
''' % {
            'verbose_timedelta':
            verbose_timedelta(self.premium_end_at - current_time),
            'shop_link':
            '[url="%s"]магазина[/url]' % full_url('http', 'shop:shop')
        }

        PersonalMessagePrototype.create(get_system_user(), self, message)
    def check_not_processed(self, premiums=0):
        self.assertEqual(MessagePrototype._db_count(), 0)
        self.assertEqual(
            AccountPrototype._db_filter(
                premium_end_at__gt=datetime.datetime.now()).count(), premiums)

        self.request.reload()
        self.assertTrue(self.request.state.is_WAITING)
        self.assertEqual(self.request.receiver_id, None)
Пример #44
0
    def add_achievement(self, achievement, notify):
        from the_tale.collections.prototypes import GiveItemTaskPrototype
        from the_tale.accounts.personal_messages.prototypes import MessagePrototype
        from the_tale.accounts.logic import get_system_user

        already_had_achievement = self.achievements.has_achievement(
            achievement)

        self.achievements.add_achievement(achievement)
        self._model.points = self.achievements.get_points()

        rewards = achievement.rewards
        approved_rewards = achievement.approved_rewards

        for item in rewards:
            GiveItemTaskPrototype.create(self.account_id, item.id)

        if not notify or already_had_achievement:
            return

        rewards_message = ''

        if approved_rewards:
            reward_texts = []
            for item in approved_rewards:
                reward_texts.append('[url=%s#k%d]%s[/url]' % (full_url(
                    'http', 'collections:collections:show',
                    item.kit.collection.id), item.kit.id, item.caption))
            rewards_message = 'Награды: %s' % ', '.join(reward_texts)

        message = (
            'Вы заработали достижение «%(achievement)s» — %(description)s. %(rewards_message)s'
            % {
                'achievement':
                '[url=%s#a%d]%s[/url]' %
                (full_url('http', 'accounts:achievements:group', achievement.
                          group.slug), achievement.id, achievement.caption),
                'description':
                achievement.description,
                'rewards_message':
                rewards_message
            })

        MessagePrototype.create(get_system_user(), self.account, message)
Пример #45
0
    def test_add_achievement__notify(self):
        with self.check_delta(GiveItemTaskPrototype._db_count, 2):
            with self.check_delta(MessagePrototype._db_count, 1):
                self.account_achievements_1.add_achievement(self.achievement_1, notify=True)

        message = MessagePrototype._db_get_object(0)
        self.assertEqual(message.sender_id, get_system_user().id)
        self.assertEqual(message.recipient_id, self.account_1.id)
        self.assertTrue((url('accounts:achievements:group', self.achievement_1.group.slug) + ('#a%d' % self.achievement_1.id)) in
                        message.text)
Пример #46
0
    def test_day_started_signal(self):
        self.assertFalse(portal_settings.SETTINGS_ACCOUNT_OF_THE_DAY_KEY in settings)

        self.assertEqual(MessagePrototype._db_count(), 0)

        with mock.patch('the_tale.accounts.workers.accounts_manager.Worker.cmd_run_account_method') as cmd_run_account_method:
            portal_signals.day_started.send(self.__class__)

        self.assertEqual(cmd_run_account_method.call_count, 1)
        self.assertEqual(cmd_run_account_method.call_args, mock.call(account_id=self.account.id,
                                                                     method_name='prolong_premium',
                                                                     data={'days': portal_settings.PREMIUM_DAYS_FOR_HERO_OF_THE_DAY}))

        self.assertEqual(int(settings[portal_settings.SETTINGS_ACCOUNT_OF_THE_DAY_KEY]), self.account.id)

        self.assertEqual(MessagePrototype._db_count(), 1)
        message = MessagePrototype._db_get_object(0)
        self.assertEqual(message.sender_id, get_system_user().id)
        self.assertEqual(message.recipient_id, self.account.id)
Пример #47
0
    def remove_friendship(cls, initiator, friend):
        request = cls.get_for_bidirectional(initiator, friend)

        if request is None: return

        if request.is_confirmed:
            MessagePrototype.create(get_system_user(),
                                    friend,
                                    u'игрок %(account_link)s удалил вас из списка друзей' %
                                    {'account_link': u'[url="%s"]%s[/url]' % (full_url('http', 'accounts:show', initiator.id), initiator.nick_verbose)})
        else:
            MessagePrototype.create(get_system_user(),
                                    friend,
                                    u'игрок %(account_link)s отказался добавить вас в список друзей' %
                                    {'account_link': u'[url="%s"]%s[/url]' % (full_url('http', 'accounts:show', initiator.id), initiator.nick_verbose)})

        request.remove()

        return
Пример #48
0
    def test_send_premium_expired_notifications(self):
        self.assertEqual(PersonalMessagePrototype._db_count(), 0)

        account_1 = self.account
        account_2 = self.accounts_factory.create_account()
        account_3 = self.accounts_factory.create_account()
        account_4 = self.accounts_factory.create_account()

        account_1.prolong_premium(accounts_settings.PREMIUM_EXPIRED_NOTIFICATION_IN.days-1)
        account_1.save()

        account_3.prolong_premium(accounts_settings.PREMIUM_EXPIRED_NOTIFICATION_IN.days-1)
        account_3.save()

        account_4.prolong_premium(accounts_settings.PREMIUM_EXPIRED_NOTIFICATION_IN.days+1)
        account_4.save()

        zero_time = datetime.datetime.fromtimestamp(0)

        self.assertEqual(account_1._model.premium_expired_notification_send_at, zero_time)
        self.assertEqual(account_2._model.premium_expired_notification_send_at, zero_time)
        self.assertEqual(account_3._model.premium_expired_notification_send_at, zero_time)
        self.assertEqual(account_4._model.premium_expired_notification_send_at, zero_time)

        AccountPrototype.send_premium_expired_notifications()

        account_1.reload()
        account_2.reload()
        account_3.reload()
        account_4.reload()

        self.assertNotEqual(account_1._model.premium_expired_notification_send_at, zero_time)
        self.assertEqual(account_2._model.premium_expired_notification_send_at, zero_time)
        self.assertNotEqual(account_3._model.premium_expired_notification_send_at, zero_time)
        self.assertEqual(account_4._model.premium_expired_notification_send_at, zero_time)

        current_time = datetime.datetime.now()

        self.assertTrue(current_time-datetime.timedelta(seconds=60) < account_1._model.premium_expired_notification_send_at < current_time)
        self.assertTrue(current_time-datetime.timedelta(seconds=60) < account_3._model.premium_expired_notification_send_at < current_time)

        self.assertEqual(PersonalMessagePrototype._db_count(), 2)
Пример #49
0
    def test_no_rights(self):
        self.request_logout()
        self.request_login('*****@*****.**')

        self.check_ajax_error(self.client.post(reverse('accounts:ban', args=[self.account_1.id]), self.form_data(BAN_TYPE.FORUM)),
                              'accounts.no_moderation_rights')

        self.account_1.reload()
        self.assertFalse(self.account_1.is_ban_forum)
        self.assertFalse(self.account_1.is_ban_game)
        self.assertEqual(MessagePrototype._db_count(), 0)
Пример #50
0
    def setUp(self):
        super(PersonalMessagesTests, self).setUp()

        create_test_map()

        self.account_1 = self.accounts_factory.create_account()
        self.account_2 = self.accounts_factory.create_account()

        self.personal_message = PersonalMessagePrototype.create(self.account_1, self.account_2, 'test text')

        self.message = MessagePrototype.get_priority_message()
Пример #51
0
    def test_no_rights(self):
        self.request_logout()
        self.request_login('*****@*****.**')

        self.check_ajax_error(self.client.post(reverse('accounts:ban', args=[self.account_1.id]), self.form_data(BAN_TYPE.FORUM)),
                              'accounts.no_moderation_rights')

        self.account_1.reload()
        self.assertFalse(self.account_1.is_ban_forum)
        self.assertFalse(self.account_1.is_ban_game)
        self.assertEqual(MessagePrototype._db_count(), 0)
Пример #52
0
def ban(context):

    if context.form.c.ban_type.is_FORUM:
        context.master_account.ban_forum(context.form.c.ban_time.days)
        message = u'Вы лишены права общаться на форуме. Причина: \n\n%(message)s'
    elif context.form.c.ban_type.is_GAME:
        context.master_account.ban_game(context.form.c.ban_time.days)
        message = u'Ваш герой лишён возможности влиять на мир игры. Причина: \n\n%(message)s'
    elif context.form.c.ban_type.is_TOTAL:
        context.master_account.ban_forum(context.form.c.ban_time.days)
        context.master_account.ban_game(context.form.c.ban_time.days)
        message = u'Вы лишены права общаться на форуме, ваш герой лишён возможности влиять на мир игры. Причина: \n\n%(message)s'
    else:
        raise dext_views.ViewError(code='unknown_ban_type', message=u'Неизвестный тип бана')

    MessagePrototype.create(logic.get_system_user(),
                            context.master_account,
                            message % {'message': context.form.c.description})

    return dext_views.AjaxOk()
Пример #53
0
def ban(context):

    if context.form.c.ban_type.is_FORUM:
        context.master_account.ban_forum(context.form.c.ban_time.days)
        message = 'Вы лишены права общаться на форуме. Причина: \n\n%(message)s'
    elif context.form.c.ban_type.is_GAME:
        context.master_account.ban_game(context.form.c.ban_time.days)
        message = 'Ваш герой лишён возможности влиять на мир игры. Причина: \n\n%(message)s'
    elif context.form.c.ban_type.is_TOTAL:
        context.master_account.ban_forum(context.form.c.ban_time.days)
        context.master_account.ban_game(context.form.c.ban_time.days)
        message = 'Вы лишены права общаться на форуме, ваш герой лишён возможности влиять на мир игры. Причина: \n\n%(message)s'
    else:
        raise dext_views.ViewError(code='unknown_ban_type',
                                   message='Неизвестный тип бана')

    MessagePrototype.create(logic.get_system_user(), context.master_account,
                            message % {'message': context.form.c.description})

    return dext_views.AjaxOk()
Пример #54
0
    def request_friendship(cls, friend_1, friend_2, text=None):
        own_request = cls._get_for(friend_1, friend_2)
        if own_request:
            if text is not None:  #
                own_request._model.text = text
                own_request.save()
            return own_request

        his_request = cls._get_for(friend_2, friend_1)
        if his_request:
            his_request._confirm()
            return his_request

        model = cls._model_class.objects.create(friend_1=friend_1._model,
                                                friend_2=friend_2._model,
                                                text=text)
        prototype = cls(model=model)

        message = '''
игрок %(account_link)s предлагает вам дружить:

%(text)s

----------
принять или отклонить предложение вы можете на этой странице: %(friends_link)s
''' % {
            'account_link':
            '[url="%s"]%s[/url]' % (full_url(
                'http', 'accounts:show', friend_1.id), friend_1.nick_verbose),
            'text':
            text,
            'friends_link':
            '[url="%s"]предложения дружбы[/url]' %
            full_url('http', 'accounts:friends:candidates')
        }

        # send message from name of user, who request friendship
        # since many users try to respod to system user
        MessagePrototype.create(friend_1, friend_2, message)

        return prototype
Пример #55
0
    def setUp(self):
        super(PersonalMessagesTests, self).setUp()

        create_test_map()

        self.account_1 = self.accounts_factory.create_account()
        self.account_2 = self.accounts_factory.create_account()

        self.personal_message = PersonalMessagePrototype.create(
            self.account_1, self.account_2, 'test text')

        self.message = MessagePrototype.get_priority_message()
Пример #56
0
    def setUp(self):
        super(PersonalMessagesTests, self).setUp()
        create_test_map()

        register_user('user_1', '*****@*****.**', '111111')
        self.account_1 = AccountPrototype.get_by_nick('user_1')

        register_user('user_2', '*****@*****.**', '111111')
        self.account_2 = AccountPrototype.get_by_nick('user_2')

        self.personal_message = PersonalMessagePrototype.create(self.account_1, self.account_2, 'test text')

        self.message = MessagePrototype.get_priority_message()