Пример #1
0
    def test_initialization(self):
        from the_tale.common.postponed_tasks.models import PostponedTask
        from the_tale.common.postponed_tasks.prototypes import PostponedTaskPrototype, POSTPONED_TASK_STATE
        from the_tale.common.postponed_tasks.postponed_tasks import FakePostponedInternalTask

        PostponedTaskPrototype.create(FakePostponedInternalTask())

        self.assertEqual(
            PostponedTask.objects.filter(
                state=POSTPONED_TASK_STATE.WAITING).count(), 1)

        self.worker.process_initialize()

        self.assertEqual(
            PostponedTask.objects.filter(
                state=POSTPONED_TASK_STATE.WAITING).count(), 0)
        self.assertEqual(
            PostponedTask.objects.filter(
                state=POSTPONED_TASK_STATE.RESETED).count(), 1)

        self.assertEqual(self.worker.tasks, {})
        self.assertEqual(self.worker.accounts_for_tasks, {})
        self.assertEqual(self.worker.accounts_owners, {
            self.account_1.id: 'game_logic_1',
            self.account_2.id: 'game_logic_2'
        })
        self.assertEqual(self.worker.accounts_queues, {})
        self.assertTrue(self.worker.initialized)
        self.assertFalse(self.worker.wait_next_turn_answer)
        self.assertTrue(GameState.is_working())
Пример #2
0
    def setUp(self):
        super(RefrigeratorTests, self).setUp()

        environment.deinitialize()
        environment.initialize()

        self.worker = environment.workers.refrigerator
        self.worker.initialize()

        self.task_1 = PostponedTaskPrototype.create(FakePostponedInternalTask(result_state=POSTPONED_TASK_LOGIC_RESULT.WAIT))
        self.task_2 = PostponedTaskPrototype.create(FakePostponedInternalTask())
Пример #3
0
    def setUp(self):
        super(RefrigeratorTests, self).setUp()

        environment.deinitialize()
        environment.initialize()

        self.worker = environment.workers.refrigerator
        self.worker.initialize()

        self.task_1 = PostponedTaskPrototype.create(
            FakePostponedInternalTask(
                result_state=POSTPONED_TASK_LOGIC_RESULT.WAIT))
        self.task_2 = PostponedTaskPrototype.create(
            FakePostponedInternalTask())
Пример #4
0
def api_combine(context):
    u'''
Объединить карты из колоды игрока.

- **адрес:** /game/cards/api/combine
- **http-метод:** POST
- **версии:** 1.0
- **параметры:**
    * GET: cards — перечень уникальный идентификаторов карт в колоде игрока через запятую
- **возможные ошибки**:
    * cards.api-combine.wrong_cards — указанные карты нельзя объединить

Метод является «неблокирующей операцией» (см. документацию), формат ответа соответствует ответу для всех «неблокирующих операций».

При завершении операции возвращается дополнительная инфрмация:

    {
      "message": "строка",      // описание результата в формате html
      "card": <card_info>       // описание полученной карты, формат см. в описании формата информации о герое
    }
    '''
    can_combine_status = context.account_hero.cards.can_combine_cards([card.uid for card in context.account_cards])

    if not can_combine_status.is_ALLOWED:
        raise dext_views.ViewError(code=u'wrong_cards', message=can_combine_status.text)

    choose_task = heroes_postponed_tasks.CombineCardsTask(hero_id=context.account_hero.id, cards=[card.uid for card in context.account_cards])

    task = PostponedTaskPrototype.create(choose_task)

    amqp_environment.environment.workers.supervisor.cmd_logic_task(context.account.id, task.id)

    return dext_views.AjaxProcessing(task.status_url)
Пример #5
0
def api_get(context):
    u'''
Взять новую карту в колоду игрока.

- **адрес:** /game/cards/api/get
- **http-метод:** POST
- **версии:** 1.0
- **параметры:** нет
- **возможные ошибки**: нет

Метод является «неблокирующей операцией» (см. документацию), формат ответа соответствует ответу для всех «неблокирующих операций».

При завершении операции возвращается дополнительная инфрмация:

    {
      "message": "строка",      // описание результата в формате html
      "card": <card_info>       // описание полученной карты, формат см. в описании формата информации о герое
    }
    '''
    choose_task = heroes_postponed_tasks.GetCardTask(
        hero_id=context.account_hero.id)

    task = PostponedTaskPrototype.create(choose_task)

    amqp_environment.environment.workers.supervisor.cmd_logic_task(
        context.account.id, task.id)

    return dext_views.AjaxProcessing(task.status_url)
Пример #6
0
    def activate(self, hero, data):
        from the_tale.game.abilities.postponed_tasks import UseAbilityTask

        data['transaction_id'] = None

        if self.TYPE.cost > 0:

            status, transaction_id = game_tt_api.change_energy_balance(
                account_id=hero.account_id,
                type='help-{}'.format(self.TYPE.value),
                energy=-self.TYPE.cost,
                async=False,
                autocommit=False)

            if not status:
                return None

            data['transaction_id'] = transaction_id

        data['hero_id'] = hero.id
        data['account_id'] = hero.account_id

        ability_task = UseAbilityTask(processor_id=self.TYPE.value,
                                      hero_id=hero.id,
                                      data=data)

        task = PostponedTaskPrototype.create(ability_task)

        environment.workers.supervisor.cmd_logic_task(hero.account_id, task.id)

        return task
Пример #7
0
def purchase_lot(buyer_id, lot):
    from the_tale.common.postponed_tasks.prototypes import PostponedTaskPrototype
    from the_tale.finances.market import postponed_tasks

    invoice = bank_prototypes.InvoicePrototype.create(
        recipient_type=bank_relations.ENTITY_TYPE.GAME_ACCOUNT,
        recipient_id=lot.seller_id,
        sender_type=bank_relations.ENTITY_TYPE.GAME_ACCOUNT,
        sender_id=buyer_id,
        currency=bank_relations.CURRENCY_TYPE.PREMIUM,
        amount=lot.price,
        description_for_sender=u'Покупка «%s»' % lot.name,
        description_for_recipient=u'Продажа «%s»' % lot.name,
        operation_uid=u'market-buy-lot-%s' % lot.type)

    transaction = bank_transaction.Transaction(invoice.id)

    logic_task = postponed_tasks.BuyLotTask(seller_id=lot.seller_id,
                                            buyer_id=buyer_id,
                                            lot_id=lot.id,
                                            transaction=transaction)

    task = PostponedTaskPrototype.create(logic_task)

    amqp_environment.environment.workers.refrigerator.cmd_wait_task(task.id)

    return task
Пример #8
0
def purchase_lot(buyer_id, lot):
    from the_tale.common.postponed_tasks.prototypes import PostponedTaskPrototype
    from the_tale.finances.market import postponed_tasks

    invoice = bank_prototypes.InvoicePrototype.create(recipient_type=bank_relations.ENTITY_TYPE.GAME_ACCOUNT,
                                                      recipient_id=lot.seller_id,
                                                      sender_type=bank_relations.ENTITY_TYPE.GAME_ACCOUNT,
                                                      sender_id=buyer_id,
                                                      currency=bank_relations.CURRENCY_TYPE.PREMIUM,
                                                      amount=lot.price,
                                                      description_for_sender=u'Покупка «%s»' % lot.name,
                                                      description_for_recipient=u'Продажа «%s»' % lot.name,
                                                      operation_uid=u'market-buy-lot-%s' % lot.type)

    transaction = bank_transaction.Transaction(invoice.id)

    logic_task = postponed_tasks.BuyLotTask(seller_id=lot.seller_id,
                                            buyer_id=buyer_id,
                                            lot_id=lot.id,
                                            transaction=transaction)

    task = PostponedTaskPrototype.create(logic_task)

    amqp_environment.environment.workers.refrigerator.cmd_wait_task(task.id)

    return task
Пример #9
0
def create_registration_task(session):
    if conf.accounts_settings.SESSION_REGISTRATION_TASK_ID_KEY in session:

        task_id = session[conf.accounts_settings.SESSION_REGISTRATION_TASK_ID_KEY]
        task = PostponedTaskPrototype.get_by_id(task_id)

        if task is not None and (task.state.is_processed or task.state.is_waiting):
            return task

    referer = None
    if conf.accounts_settings.SESSION_REGISTRATION_REFERER_KEY in session:
        referer = session[conf.accounts_settings.SESSION_REGISTRATION_REFERER_KEY]

    referral_of_id = None
    if conf.accounts_settings.SESSION_REGISTRATION_REFERRAL_KEY in session:
        referral_of_id = session[conf.accounts_settings.SESSION_REGISTRATION_REFERRAL_KEY]

    action_id = None
    if conf.accounts_settings.SESSION_REGISTRATION_ACTION_KEY in session:
        action_id = session[conf.accounts_settings.SESSION_REGISTRATION_ACTION_KEY]

    registration_task = postponed_tasks.RegistrationTask(account_id=None,
                                                         referer=referer,
                                                         referral_of_id=referral_of_id,
                                                         action_id=action_id)

    task = PostponedTaskPrototype.create(registration_task,
                                         live_time=conf.accounts_settings.REGISTRATION_TIMEOUT)

    session[conf.accounts_settings.SESSION_REGISTRATION_TASK_ID_KEY] = task.id

    environment.workers.registration.cmd_task(task.id)

    return task
Пример #10
0
def api_get(context):
    u'''
Взять новую карту в колоду игрока.

- **адрес:** /game/cards/api/get
- **http-метод:** POST
- **версии:** 1.0
- **параметры:** нет
- **возможные ошибки**: нет

Метод является «неблокирующей операцией» (см. документацию), формат ответа соответствует ответу для всех «неблокирующих операций».

При завершении операции возвращается дополнительная инфрмация:

    {
      "message": "строка",      // описание результата в формате html
      "card": <card_info>       // описание полученной карты, формат см. в описании формата информации о герое
    }
    '''
    choose_task = heroes_postponed_tasks.GetCardTask(hero_id=context.account_hero.id)

    task = PostponedTaskPrototype.create(choose_task)

    amqp_environment.environment.workers.supervisor.cmd_logic_task(context.account.id, task.id)

    return dext_views.AjaxProcessing(task.status_url)
Пример #11
0
    def test_remove_old_tasks(self):
        task = PostponedTaskPrototype.create(FakePostponedInternalTask())
        task.state = POSTPONED_TASK_STATE.PROCESSED
        task.save()

        removed_task = PostponedTaskPrototype.create(FakePostponedInternalTask())
        removed_task.state = POSTPONED_TASK_STATE.ERROR
        removed_task.save()

        PostponedTaskPrototype.remove_old_tasks()

        self.assertEqual(PostponedTask.objects.all().count(), 3)

        with mock.patch('the_tale.common.postponed_tasks.conf.postponed_tasks_settings.TASK_LIVE_TIME', -1):
            PostponedTaskPrototype.remove_old_tasks()

        self.assertEqual(PostponedTask.objects.all().count(), 1)
Пример #12
0
    def test_check_tasks(self):
        self.worker.process_wait_task(self.task_2.id)
        self.worker.process_wait_task(self.task_1.id)
        self.worker.process_wait_task(PostponedTaskPrototype.create(FakePostponedInternalTask(result_state=POSTPONED_TASK_LOGIC_RESULT.CONTINUE)).id)

        self.worker.check_tasks()

        self.assertEqual(set(self.worker.tasks.keys()), set([self.task_1.id]))
Пример #13
0
    def test_handle_registration__task_not_processed(self):
        registration_task = RegistrationTask(account_id=None, referer=None, referral_of_id=None, action_id=None)
        task = PostponedTaskPrototype.create(registration_task)

        with mock.patch('the_tale.accounts.middleware.login_user') as login_user:
            result = self.middleware.handle_registration(self.make_request_html('/', session={accounts_settings.SESSION_REGISTRATION_TASK_ID_KEY: task.id}))

        self.assertTrue(result.is_TASK_NOT_PROCESSED)
        self.assertEqual(login_user.call_count, 0)
Пример #14
0
    def change_credentials(self):
        from the_tale.accounts.postponed_tasks import ChangeCredentials

        change_credentials_task = ChangeCredentials(task_id=self.id)
        task = PostponedTaskPrototype.create(change_credentials_task)

        environment.workers.accounts_manager.cmd_task(task.id)

        return task
Пример #15
0
    def change_credentials(self):
        from the_tale.accounts.postponed_tasks import ChangeCredentials

        change_credentials_task = ChangeCredentials(task_id=self.id)
        task = PostponedTaskPrototype.create(change_credentials_task)

        environment.workers.accounts_manager.cmd_task(task.id)

        return task
Пример #16
0
    def choose_ability(self, ability_id):

        choose_task = postponed_tasks.ChooseHeroAbilityTask(hero_id=self.hero.id, ability_id=ability_id)

        task = PostponedTaskPrototype.create(choose_task)

        environment.workers.supervisor.cmd_logic_task(self.account.id, task.id)

        return self.json_processing(task.status_url)
Пример #17
0
    def api_choose(self, option_uid, api_version):
        choose_task = MakeChoiceTask(account_id=self.account.id,
                                     option_uid=option_uid)

        task = PostponedTaskPrototype.create(choose_task)

        environment.workers.supervisor.cmd_logic_task(self.account.id, task.id)

        return self.processing(status_url=task.status_url)
Пример #18
0
    def invoke_hero_method(self, account_id, hero_id, method_name, method_kwargs):
        from the_tale.game.heroes import postponed_tasks as heroes_postponed_tasks

        logic_task = heroes_postponed_tasks.InvokeHeroMethodTask(hero_id=hero_id,
                                                                 method_name=method_name,
                                                                 method_kwargs=method_kwargs)

        task = PostponedTaskPrototype.create(logic_task)

        return lambda: environment.workers.supervisor.cmd_logic_task(account_id=account_id, task_id=task.id)
Пример #19
0
    def choose_ability(self, ability_id):

        choose_task = postponed_tasks.ChooseHeroAbilityTask(
            hero_id=self.hero.id, ability_id=ability_id)

        task = PostponedTaskPrototype.create(choose_task)

        environment.workers.supervisor.cmd_logic_task(self.account.id, task.id)

        return self.json_processing(task.status_url)
Пример #20
0
    def reset_name(self):
        change_task = postponed_tasks.ChangeHeroTask(hero_id=self.hero.id,
                                     name=names.generator().get_name(self.hero.race, self.hero.gender),
                                     race=self.hero.race,
                                     gender=self.hero.gender)

        task = PostponedTaskPrototype.create(change_task)

        environment.workers.supervisor.cmd_logic_task(self.hero.account_id, task.id)

        return self.json_processing(task.status_url)
Пример #21
0
    def test_check_tasks(self):
        self.worker.process_wait_task(self.task_2.id)
        self.worker.process_wait_task(self.task_1.id)
        self.worker.process_wait_task(
            PostponedTaskPrototype.create(
                FakePostponedInternalTask(
                    result_state=POSTPONED_TASK_LOGIC_RESULT.CONTINUE)).id)

        self.worker.check_tasks()

        self.assertEqual(set(self.worker.tasks.keys()), set([self.task_1.id]))
Пример #22
0
def create(context):
    check_recipients(context.form)

    logic_task = postponed_tasks.SendMessagesTask(account_id=context.account.id,
                                                  recipients=context.form.c.recipients,
                                                  message=context.form.c.text)

    task = PostponedTaskPrototype.create(logic_task)

    amqp_environment.environment.workers.accounts_manager.cmd_task(task.id)

    return dext_views.AjaxProcessing(status_url=task.status_url)
Пример #23
0
    def test_initialization(self):
        from the_tale.common.postponed_tasks.models import PostponedTask
        from the_tale.common.postponed_tasks.prototypes import PostponedTaskPrototype, POSTPONED_TASK_STATE
        from the_tale.common.postponed_tasks.postponed_tasks import FakePostponedInternalTask

        PostponedTaskPrototype.create(FakePostponedInternalTask())

        self.assertEqual(PostponedTask.objects.filter(state=POSTPONED_TASK_STATE.WAITING).count(), 1)

        self.worker.process_initialize()

        self.assertEqual(PostponedTask.objects.filter(state=POSTPONED_TASK_STATE.WAITING).count(), 0)
        self.assertEqual(PostponedTask.objects.filter(state=POSTPONED_TASK_STATE.RESETED).count(), 1)

        self.assertEqual(self.worker.tasks, {})
        self.assertEqual(self.worker.accounts_for_tasks, {})
        self.assertEqual(self.worker.accounts_owners, {self.account_1.id: 'game_logic_1', self.account_2.id: 'game_logic_2'})
        self.assertEqual(self.worker.accounts_queues, {})
        self.assertTrue(self.worker.initialized)
        self.assertFalse(self.worker.wait_next_turn_answer)
        self.assertTrue(GameState.is_working())
Пример #24
0
    def fast(self):

        if self.account.is_authenticated:
            return self.json_error(
                'accounts.registration.fast.already_registered',
                'Вы уже зарегистрированы')

        if conf.accounts_settings.SESSION_REGISTRATION_TASK_ID_KEY in self.request.session:

            task_id = self.request.session[
                conf.accounts_settings.SESSION_REGISTRATION_TASK_ID_KEY]
            task = PostponedTaskPrototype.get_by_id(task_id)

            if task is not None:
                if task.state.is_processed:
                    return self.json_error(
                        'accounts.registration.fast.already_processed',
                        'Вы уже зарегистрированы, обновите страницу')
                if task.state.is_waiting:
                    return self.json_processing(task.status_url)
                # in other case create new task

        referer = None
        if conf.accounts_settings.SESSION_REGISTRATION_REFERER_KEY in self.request.session:
            referer = self.request.session[
                conf.accounts_settings.SESSION_REGISTRATION_REFERER_KEY]

        referral_of_id = None
        if conf.accounts_settings.SESSION_REGISTRATION_REFERRAL_KEY in self.request.session:
            referral_of_id = self.request.session[
                conf.accounts_settings.SESSION_REGISTRATION_REFERRAL_KEY]

        action_id = None
        if conf.accounts_settings.SESSION_REGISTRATION_ACTION_KEY in self.request.session:
            action_id = self.request.session[
                conf.accounts_settings.SESSION_REGISTRATION_ACTION_KEY]

        registration_task = postponed_tasks.RegistrationTask(
            account_id=None,
            referer=referer,
            referral_of_id=referral_of_id,
            action_id=action_id)

        task = PostponedTaskPrototype.create(
            registration_task,
            live_time=conf.accounts_settings.REGISTRATION_TIMEOUT)

        self.request.session[
            conf.accounts_settings.SESSION_REGISTRATION_TASK_ID_KEY] = task.id

        environment.workers.registration.cmd_task(task.id)

        return self.json_processing(task.status_url)
Пример #25
0
    def reset_abilities(self):

        if not self.hero.abilities.can_reset:
            return self.json_error('heroes.reset_abilities.reset_timeout', 'Сброс способностей пока не доступен')

        reset_task = postponed_tasks.ResetHeroAbilitiesTask(hero_id=self.hero.id)

        task = PostponedTaskPrototype.create(reset_task)

        environment.workers.supervisor.cmd_logic_task(self.account.id, task.id)

        return self.json_processing(task.status_url)
Пример #26
0
    def activate(self, hero, card_uid, data):
        data["hero_id"] = hero.id
        data["account_id"] = hero.account_id
        data["card_uid"] = card_uid

        card_task = UseCardTask(processor_id=self.TYPE.value, hero_id=hero.id, data=data)

        task = PostponedTaskPrototype.create(card_task)

        environment.workers.supervisor.cmd_logic_task(hero.account_id, task.id)

        return task
Пример #27
0
def close_sell_lot(context):

    if context.account.bank_account.amount < context.price:
        raise dext_views.ViewError(code='not_enough_money', message='Не хватает средств для покупки')

    task = logic.close_lot(item_type=context.item_type,
                           price=context.price,
                           buyer_id=context.account.id)
    postponed_task = PostponedTaskPrototype.create(task)
    postponed_task.cmd_wait()

    return dext_views.AjaxProcessing(postponed_task.status_url)
Пример #28
0
def create(context):
    check_recipients(context.form)

    logic_task = postponed_tasks.SendMessagesTask(account_id=context.account.id,
                                                  recipients=context.form.c.recipients,
                                                  message=context.form.c.text)

    task = PostponedTaskPrototype.create(logic_task)

    amqp_environment.environment.workers.accounts_manager.cmd_task(task.id)

    return dext_views.AjaxProcessing(status_url=task.status_url)
Пример #29
0
    def reset_name(self):
        change_task = postponed_tasks.ChangeHeroTask(
            hero_id=self.hero.id,
            name=names.generator.get_name(self.hero.race, self.hero.gender),
            race=self.hero.race,
            gender=self.hero.gender)

        task = PostponedTaskPrototype.create(change_task)

        environment.workers.supervisor.cmd_logic_task(self.hero.account_id,
                                                      task.id)

        return self.json_processing(task.status_url)
Пример #30
0
    def use_ability(self, ability):

        battle = Battle1x1Prototype.get_by_account_id(self.account.id)

        if battle is None or not battle.state.is_PROCESSING:
            return self.json_error('pvp.use_ability.no_battle', 'Бой не идёт, вы не можете использовать способность')

        use_ability_task = UsePvPAbilityTask(battle_id=battle.id, account_id=self.account.id, ability_id=ability.TYPE)

        task = PostponedTaskPrototype.create(use_ability_task)

        environment.workers.supervisor.cmd_logic_task(self.account.id, task.id)

        return self.json_processing(task.status_url)
Пример #31
0
    def reset_abilities(self):

        if not self.hero.abilities.can_reset:
            return self.json_error('heroes.reset_abilities.reset_timeout',
                                   u'Сброс способностей пока не доступен')

        reset_task = postponed_tasks.ResetHeroAbilitiesTask(
            hero_id=self.hero.id)

        task = PostponedTaskPrototype.create(reset_task)

        environment.workers.supervisor.cmd_logic_task(self.account.id, task.id)

        return self.json_processing(task.status_url)
Пример #32
0
    def activate(self, hero, card_uid, data):
        data['hero_id'] = hero.id
        data['account_id'] = hero.account_id
        data['card_uid'] = card_uid

        card_task = UseCardTask(processor_id=self.TYPE.value,
                                hero_id=hero.id,
                                data=data)

        task = PostponedTaskPrototype.create(card_task)

        environment.workers.supervisor.cmd_logic_task(hero.account_id, task.id)

        return task
Пример #33
0
    def activate(self, hero, card, data):
        data['hero_id'] = hero.id
        data['account_id'] = hero.account_id
        data['card'] = {'id': card.uid.hex, 'data': card.serialize()}

        card_task = postponed_tasks.UseCardTask(processor_id=card.type.value,
                                                hero_id=hero.id,
                                                data=data)

        task = PostponedTaskPrototype.create(card_task)

        environment.workers.supervisor.cmd_logic_task(hero.account_id, task.id)

        return task
Пример #34
0
def send_good_to_market(seller_id, good, price):
    from the_tale.common.postponed_tasks.prototypes import PostponedTaskPrototype
    from the_tale.finances.market import postponed_tasks

    logic_task = postponed_tasks.CreateLotTask(account_id=seller_id,
                                               good_type=good.type,
                                               good_uid=good.uid,
                                               price=price)

    task = PostponedTaskPrototype.create(logic_task)

    amqp_environment.environment.workers.market_manager.cmd_logic_task(seller_id, task.id)

    return task
Пример #35
0
    def activate(self, hero, data):
        from the_tale.game.abilities.postponed_tasks import UseAbilityTask

        data['hero_id'] = hero.id
        data['account_id'] = hero.account_id

        ability_task = UseAbilityTask(processor_id=self.TYPE.value,
                                      hero_id=hero.id,
                                      data=data)

        task = PostponedTaskPrototype.create(ability_task)

        environment.workers.supervisor.cmd_logic_task(hero.account_id, task.id)

        return task
Пример #36
0
def send_good_to_market(seller_id, good, price):
    from the_tale.common.postponed_tasks.prototypes import PostponedTaskPrototype
    from the_tale.finances.market import postponed_tasks

    logic_task = postponed_tasks.CreateLotTask(account_id=seller_id,
                                               good_type=good.type,
                                               good_uid=good.uid,
                                               price=price)

    task = PostponedTaskPrototype.create(logic_task)

    amqp_environment.environment.workers.market_manager.cmd_logic_task(
        seller_id, task.id)

    return task
Пример #37
0
    def activate(self, hero, data):
        from the_tale.game.abilities.postponed_tasks import UseAbilityTask

        data['hero_id'] = hero.id
        data['account_id'] = hero.account_id

        ability_task = UseAbilityTask(processor_id=self.TYPE.value,
                                      hero_id=hero.id,
                                      data=data)

        task = PostponedTaskPrototype.create(ability_task)

        environment.workers.supervisor.cmd_logic_task(hero.account_id, task.id)

        return task
Пример #38
0
def api_combine(context):
    card, result = logic.get_combined_card(
        allow_premium_cards=context.account.is_premium,
        combined_cards=context.cards)

    if not result.is_SUCCESS:
        raise dext_views.ViewError(code='wrong_cards', message=result.text)

    try:
        tt_api.change_cards(account_id=context.account.id,
                            operation_type='combine-cards',
                            to_add=[card],
                            to_remove=context.cards)
    except utils_exceptions.TTAPIUnexpectedAPIStatus:
        # return error, in most cases it is duplicate request
        raise dext_views.ViewError(
            code='can_not_combine_cards',
            message=
            'Не удалось объединить карты. Попробуйте обновить страницу и повторить попытку.'
        )

    ##################################
    # change combined cards statistics
    logic_task = heroes_postponed_tasks.InvokeHeroMethodTask(
        hero_id=context.account.id,
        method_name='new_cards_combined',
        method_kwargs={'number': 1})
    task = PostponedTaskPrototype.create(logic_task)
    amqp_environment.environment.workers.supervisor.cmd_logic_task(
        account_id=context.account.id, task_id=task.id)
    ##################################

    MESSAGE = '''
<p>Вы получаете новую карту: <span class="%(rarity)s-card-label">%(name)s</span><br/><br/></p>

<blockquote>%(description)s</blockquote>
'''

    message = MESSAGE % {
        'name': card.name[0].upper() + card.name[1:],
        'description': card.effect.DESCRIPTION,
        'rarity': card.type.rarity.name.lower()
    }

    return dext_views.AjaxOk(content={
        'message': message,
        'card': card.ui_info()
    })
Пример #39
0
def initiate_transfer_money(sender_id, recipient_id, amount, comment):
    from the_tale.common.postponed_tasks.prototypes import PostponedTaskPrototype
    from the_tale.accounts import postponed_tasks

    commission = get_transfer_commission(amount)

    task = postponed_tasks.TransferMoneyTask(sender_id=sender_id,
                                             recipient_id=recipient_id,
                                             amount=amount - commission,
                                             commission=commission,
                                             comment=comment)
    task = PostponedTaskPrototype.create(task)

    amqp_environment.environment.workers.refrigerator.cmd_wait_task(task.id)

    return task
Пример #40
0
def close_lots_by_timeout():
    from the_tale.common.postponed_tasks.prototypes import PostponedTaskPrototype
    from the_tale.finances.market import postponed_tasks

    expired_lots_query = models.Lot.objects.filter(state=relations.LOT_STATE.ACTIVE,
                                                   created_at__lt=datetime.datetime.now()-datetime.timedelta(days=conf.settings.LOT_LIVE_TIME))

    tasks = []

    for lot_id, seller_id in expired_lots_query.values_list('id', 'seller_id'):
        logic_task = postponed_tasks.CloseLotByTimoutTask(lot_id=lot_id)
        task = PostponedTaskPrototype.create(logic_task)
        amqp_environment.environment.workers.market_manager.cmd_logic_task(seller_id, task.id)
        tasks.append(task)

    return tasks
Пример #41
0
def initiate_transfer_money(sender_id, recipient_id, amount, comment):
    from the_tale.common.postponed_tasks.prototypes import PostponedTaskPrototype
    from the_tale.accounts import postponed_tasks

    commission = get_transfer_commission(amount)

    task = postponed_tasks.TransferMoneyTask(sender_id=sender_id,
                                             recipient_id=recipient_id,
                                             amount=amount-commission,
                                             commission=commission,
                                             comment=comment)
    task = PostponedTaskPrototype.create(task)

    amqp_environment.environment.workers.refrigerator.cmd_wait_task(task.id)

    return task
Пример #42
0
    def choose_preferences(self):

        choose_preferences_form = forms.ChoosePreferencesForm(self.request.POST)

        if not choose_preferences_form.is_valid():
            return self.json_error('heroes.choose_preferences.form_errors', choose_preferences_form.errors)

        choose_task = postponed_tasks.ChoosePreferencesTask(hero_id=self.hero.id,
                                            preference_type=choose_preferences_form.c.preference_type,
                                            preference_id=choose_preferences_form.c.preference_id if choose_preferences_form.c.preference_id != '' else None)

        task = PostponedTaskPrototype.create(choose_task)

        environment.workers.supervisor.cmd_logic_task(self.account.id, task.id)

        return self.json_processing(status_url=task.status_url)
Пример #43
0
    def change_hero(self):
        edit_name_form = forms.EditNameForm(self.request.POST)

        if not edit_name_form.is_valid():
            return self.json_error('heroes.change_name.form_errors', edit_name_form.errors)

        change_task = postponed_tasks.ChangeHeroTask(hero_id=self.hero.id,
                                                     name=edit_name_form.c.name,
                                                     race=edit_name_form.c.race,
                                                     gender=edit_name_form.c.gender)

        task = PostponedTaskPrototype.create(change_task)

        environment.workers.supervisor.cmd_logic_task(self.account.id, task.id)

        return self.json_processing(task.status_url)
Пример #44
0
    def test_reset_all(self):
        task = PostponedTaskPrototype.create(FakePostponedInternalTask())
        task.state = POSTPONED_TASK_STATE.PROCESSED
        task.save()

        self.assertEqual(PostponedTask.objects.all().count(), 2)
        self.assertEqual(PostponedTask.objects.filter(state=POSTPONED_TASK_STATE.WAITING).count(), 1)
        self.assertEqual(PostponedTask.objects.filter(state=POSTPONED_TASK_STATE.PROCESSED).count(), 1)
        self.assertEqual(PostponedTask.objects.filter(state=POSTPONED_TASK_STATE.RESETED).count(), 0)

        PostponedTaskPrototype.reset_all()

        self.assertEqual(PostponedTask.objects.all().count(), 2)
        self.assertEqual(PostponedTask.objects.filter(state=POSTPONED_TASK_STATE.WAITING).count(), 0)
        self.assertEqual(PostponedTask.objects.filter(state=POSTPONED_TASK_STATE.PROCESSED).count(), 1)
        self.assertEqual(PostponedTask.objects.filter(state=POSTPONED_TASK_STATE.RESETED).count(), 1)
Пример #45
0
    def buy(self, account):
        if account.is_fast:
            raise exceptions.FastAccountError(purchase_uid=self.uid, account_id=account.id)

        self.additional_checks(account)

        transaction = transaction_logic(account=account,
                                        amount=-self.cost,
                                        description=self.transaction_description,
                                        uid='ingame-purchase-<%s>' % self.uid)

        postponed_logic = self.construct_postponed_task(account, transaction)

        postponed_task = PostponedTaskPrototype.create(postponed_logic)
        postponed_task.cmd_wait()

        return postponed_task
Пример #46
0
    def use_ability(self, ability):

        battle = Battle1x1Prototype.get_by_account_id(self.account.id)

        if battle is None or not battle.state.is_PROCESSING:
            return self.json_error(
                'pvp.use_ability.no_battle',
                'Бой не идёт, вы не можете использовать способность')

        use_ability_task = UsePvPAbilityTask(battle_id=battle.id,
                                             account_id=self.account.id,
                                             ability_id=ability.TYPE)

        task = PostponedTaskPrototype.create(use_ability_task)

        environment.workers.supervisor.cmd_logic_task(self.account.id, task.id)

        return self.json_processing(task.status_url)
Пример #47
0
    def change_hero(self):
        edit_name_form = forms.EditNameForm(self.request.POST)

        if not edit_name_form.is_valid():
            return self.json_error('heroes.change_name.form_errors',
                                   edit_name_form.errors)

        change_task = postponed_tasks.ChangeHeroTask(
            hero_id=self.hero.id,
            name=edit_name_form.c.name,
            race=edit_name_form.c.race,
            gender=edit_name_form.c.gender)

        task = PostponedTaskPrototype.create(change_task)

        environment.workers.supervisor.cmd_logic_task(self.account.id, task.id)

        return self.json_processing(task.status_url)
Пример #48
0
    def say(self):

        battle = Battle1x1Prototype.get_by_account_id(self.account.id)

        if battle is None or not battle.state.is_PROCESSING:
            return self.json_error("pvp.say.no_battle", u"Бой не идёт, вы не можете говорить")

        say_form = SayForm(self.request.POST)

        if not say_form.is_valid():
            return self.json_error("pvp.say.form_errors", say_form.errors)

        say_task = SayInBattleLogTask(battle_id=battle.id, text=say_form.c.text)

        task = PostponedTaskPrototype.create(say_task)

        environment.workers.supervisor.cmd_logic_task(self.account.id, task.id)

        return self.json_processing(task.status_url)
Пример #49
0
def close_lots_by_timeout():
    from the_tale.common.postponed_tasks.prototypes import PostponedTaskPrototype
    from the_tale.finances.market import postponed_tasks

    expired_lots_query = models.Lot.objects.filter(
        state=relations.LOT_STATE.ACTIVE,
        created_at__lt=datetime.datetime.now() -
        datetime.timedelta(days=conf.settings.LOT_LIVE_TIME))

    tasks = []

    for lot_id, seller_id in expired_lots_query.values_list('id', 'seller_id'):
        logic_task = postponed_tasks.CloseLotByTimoutTask(lot_id=lot_id)
        task = PostponedTaskPrototype.create(logic_task)
        amqp_environment.environment.workers.market_manager.cmd_logic_task(
            seller_id, task.id)
        tasks.append(task)

    return tasks
Пример #50
0
    def buy(self, account):
        if account.is_fast:
            raise exceptions.FastAccountError(purchase_uid=self.uid,
                                              account_id=account.id)

        self.additional_checks(account)

        transaction = transaction_logic(
            account=account,
            amount=-self.cost,
            description=self.transaction_description,
            uid='ingame-purchase-<%s>' % self.uid)

        postponed_logic = self.construct_postponed_task(account, transaction)

        postponed_task = PostponedTaskPrototype.create(postponed_logic)
        postponed_task.cmd_wait()

        return postponed_task
Пример #51
0
    def fast(self):

        if self.account.is_authenticated:
            return self.json_error("accounts.registration.fast.already_registered", "Вы уже зарегистрированы")

        if conf.accounts_settings.SESSION_REGISTRATION_TASK_ID_KEY in self.request.session:

            task_id = self.request.session[conf.accounts_settings.SESSION_REGISTRATION_TASK_ID_KEY]
            task = PostponedTaskPrototype.get_by_id(task_id)

            if task is not None:
                if task.state.is_processed:
                    return self.json_error(
                        "accounts.registration.fast.already_processed", "Вы уже зарегистрированы, обновите страницу"
                    )
                if task.state.is_waiting:
                    return self.json_processing(task.status_url)
                # in other case create new task

        referer = None
        if conf.accounts_settings.SESSION_REGISTRATION_REFERER_KEY in self.request.session:
            referer = self.request.session[conf.accounts_settings.SESSION_REGISTRATION_REFERER_KEY]

        referral_of_id = None
        if conf.accounts_settings.SESSION_REGISTRATION_REFERRAL_KEY in self.request.session:
            referral_of_id = self.request.session[conf.accounts_settings.SESSION_REGISTRATION_REFERRAL_KEY]

        action_id = None
        if conf.accounts_settings.SESSION_REGISTRATION_ACTION_KEY in self.request.session:
            action_id = self.request.session[conf.accounts_settings.SESSION_REGISTRATION_ACTION_KEY]

        registration_task = postponed_tasks.RegistrationTask(
            account_id=None, referer=referer, referral_of_id=referral_of_id, action_id=action_id
        )

        task = PostponedTaskPrototype.create(registration_task, live_time=conf.accounts_settings.REGISTRATION_TIMEOUT)

        self.request.session[conf.accounts_settings.SESSION_REGISTRATION_TASK_ID_KEY] = task.id

        environment.workers.registration.cmd_task(task.id)

        return self.json_processing(task.status_url)
Пример #52
0
    def api_choose(self, option_uid, api_version):
        '''
Изменение пути выполнения задания героем

- **адрес:** /game/quests/api/choose/
- **http-метод:** POST
- **версии:** 1.0
- **параметры:**
    * GET: option_uid — уникальный идентификатор выбора в задании (получается с информацией о состоянии игры)
- **возможные ошибки**: нет

Метод является «неблокирующей операцией» (см. документацию), формат ответа соответствует ответу для всех «неблокирующих операций».
        '''
        choose_task = MakeChoiceTask(account_id=self.account.id, option_uid=option_uid)

        task = PostponedTaskPrototype.create(choose_task)

        environment.workers.supervisor.cmd_logic_task(self.account.id, task.id)

        return self.processing(status_url=task.status_url)
Пример #53
0
    def setUp(self):
        super(RequestsTests, self).setUp()
        self.task = PostponedTaskPrototype.create(FakePostponedInternalTask())

        self.client = client.Client()
Пример #54
0
 def setUp(self):
     super(PrototypeTests, self).setUp()
     self.task = PostponedTaskPrototype.create(FakePostponedInternalTask())