示例#1
0
def remove_car(request, car_id):
    car = Car.objects.get_by_id(car_id)
    if car is None: return HttpResponseRedirect(reverse('home'))

    wishlist = WishList.objects.get_by_user(user=request.engine.user.user)
    wishlist.engine = request.engine
    wishlist.remove_item(car.id)

    return HttpResponseRedirect(reverse('home'))
示例#2
0
def stick(request, album_id, car_id):
    request.engine.register("album")
    request.engine.album.set_item(album_id)
    request.engine.album.stick_item(car_id)

    logging.info("car (%d) sticked to %d by %s" % (int(car_id), int(album_id), request.engine.user.user))
    return request.engine.redirect(reverse("album", args=[album_id]))
示例#3
0
def edit(request, partner_id):
    try:
        partner = Partner.objects.get(pk=partner_id)
    except Partner.DoesNotExist:
        return Http404

    if partner.user != request.engine.user.user:
        return Http404

    form = PartnerForm(instance=partner)

    if request.method == 'POST':
        form = PartnerForm(request.POST, instance=partner)

        if form.is_valid():
            form.save()
            return request.engine.redirect(reverse('partners'))

        return {
            'form': form,
            'partner': partner,
        }

    return {
        'form': form,
        'partner': partner,
    }
示例#4
0
def buy(request, album_id):
    request.engine.register('album')
    request.engine.album.buy(album_id)

    logging.info('album (%s) bought by %s' %
                 (album_id, request.engine.user.user))
    return request.engine.redirect(reverse('albums'))
示例#5
0
文件: job.py 项目: yezooz/car-battle
    def __init__(self, engine):
        self.engine = engine
        if not hasattr(engine, 'user'): return engine.redirect(reverse('home'))

        profile = engine.user.profile
        if profile.job_next_day_at is None or profile.job_next_day_at <= datetime.datetime.now():
            UserJob.objects.filter(is_active=True).update(is_active=False)

            profile.job_round = 1
            profile.job_tier = 1
            profile.job_max_round_today = profile.job_max_round
            profile.job_next_day_at = datetime.datetime.now() + datetime.timedelta(days=1)
            profile.job_id = 0
            profile.save()

        self.user_job = UserJob.objects.get_by_user(user=engine.user.user, profile=engine.user.profile)

        # time left
        self.time_left = str(profile.job_next_day_at - datetime.datetime.now()).split('.')[0].split(':')

        if len(self.time_left) > 3:
            self.time_left = ''
        elif len(self.time_left) == 3:
            if int(self.time_left[0]) == 0 and int(self.time_left[1]) == 0:
                self.time_left = 'almost finished'
            elif int(self.time_left[0]) == 0:
                self.time_left = '%smin left' % (self.time_left[1].lstrip('0'))
            else:
                self.time_left = '%sh %smin left' % (self.time_left[0].lstrip('0'), self.time_left[1].lstrip('0'))
        else:
            self.time_left = 'almost finished'
示例#6
0
def edit(request, partner_id):
    try:
        partner = Partner.objects.get(pk=partner_id)
    except Partner.DoesNotExist:
        return Http404

    if partner.user != request.engine.user.user:
        return Http404

    form = PartnerForm(instance=partner)

    if request.method == 'POST':
        form = PartnerForm(request.POST, instance=partner)

        if form.is_valid():
            form.save()
            return request.engine.redirect(reverse('partners'))

        return {
            'form': form,
            'partner': partner,
        }

    return {
        'form': form,
        'partner': partner,
    }
示例#7
0
文件: link.py 项目: yezooz/car-battle
def _save(request, name, back='home'):
    response = request.engine.redirect(reverse(back))

    if not request.GET.has_key('link') or (request.GET.has_key('link') and len(request.GET['link'].strip()) != 16):
        return response

    set_cookie(response, name, request.GET['link'].strip())
    return response
示例#8
0
def stick(request, album_id, car_id):
    request.engine.register('album')
    request.engine.album.set_item(album_id)
    request.engine.album.stick_item(car_id)

    logging.info('car (%d) sticked to %d by %s' %
                 (int(car_id), int(album_id), request.engine.user.user))
    return request.engine.redirect(reverse('album', args=[album_id]))
示例#9
0
def remove(request, uid):
    f = Friend.objects.get_by_user(user=request.engine.user.user)
    f.engine = request.engine
    f.remove_friend(uid)

    request.engine.user.profile.friends = len(f.friends)
    request.engine.user.profile.save()

    return request.engine.redirect(reverse('home'))
示例#10
0
def buy_now(request):
    request.engine.register('auction')
    request.engine.auction.buy_now(request.POST.get('item_id'))

    return request.engine.redirect(
        reverse(
            'auction_details',
            args=[request.POST.get('item_slug'),
                  request.POST.get('item_id')]))
示例#11
0
文件: link.py 项目: Vic121/Car-Battle
def _save(request, name, back='home'):
    response = request.engine.redirect(reverse(back))

    if not request.GET.has_key('link') or (request.GET.has_key('link') and len(
            request.GET['link'].strip()) != 16):
        return response

    set_cookie(response, name, request.GET['link'].strip())
    return response
示例#12
0
def tier_battle(request, param=None):
    request.engine.module = 'battle'

    request.engine.user.get_garage()
    if not request.engine.user.garage.count() >= settings.REQ_CARDS_IN_BATTLE:
        request.engine.log.message(
            message="You need at least %d cars to fight against other players."
            % settings.REQ_CARDS_IN_BATTLE)
        return request.engine.redirect(reverse('jobs'))

    request.engine.register('battle')
    summary = None

    if not param:
        defender = request.engine.user.get_by_id(
            user_id=settings.TIER_BATTLE_PLAYERS[str(
                request.engine.user.profile.job_tier + 1)]).user
        battle = request.engine.battle.start_or_resume(defender, 1)

        if isinstance(battle, basestring):  # validation
            request.engine.log.message(message=battle)
            return request.engine.redirect(reverse('jobs'))

        if battle.step == 4:
            summary = request.engine.battle.get_summary(True)

    else:
        battle = request.engine.battle.resume_current(1)
        battle.next_step(param)
        return request.engine.redirect(reverse('tier_battle'))

    attacker, defender, shown = request.engine.battle.get_current_cards()

    return {
        'attacker': attacker,
        'defender': defender,
        'shown': shown,
        'battle': battle,
        'last_step': battle.step > 3,
        'last_card': battle.card == 1 and battle.step == 4,
        'defender_profile': 'random player',
        'tier_battle': True,
        'summary': summary,
    }
示例#13
0
def sell(request, item_type, item_id):
    from auction.models import Auction
    from common.models import Car
    from job.models import Garage

    item = Car.objects.get_by_id(item_id)
    garage = Garage.objects.get_by_user(user=request.engine.user.user)

    if item is None or not garage.has_car(item.id):
        return request.engine.redirect(reverse('garage'))

    form = SellForm()
    if request.method == 'POST' and request.POST.has_key('duration'):
        form = SellForm(request.POST)

        if form.is_valid():
            a = Auction()
            a.title = "%s %s" % (item.manuf, item.name)
            a.seller = request.engine.user.user
            a.car = item
            a.tier = item.tier
            a.start_price = form.cleaned_data.get('start_price') or 0
            a.buy_it_now_price = form.cleaned_data.get('buy_it_now_price') or 0
            a.current_price = form.cleaned_data['start_price']
            a.is_for_credits = False
            a.is_refunded = False
            a.start_at = datetime.datetime.now()
            a.end_at = datetime.datetime.now() + datetime.timedelta(
                days=int(form.cleaned_data['duration']))
            a.save()

            garage.engine = request.engine
            garage.remove_car(item.id)
            request.engine.user.profile.cars = len(garage)
            request.engine.user.profile.save()

            return request.engine.redirect(reverse('auction'))

    return {
        'item_type': item_type,
        'item_id': item_id,
        'item': item,
        'form': form,
    }
示例#14
0
文件: link.py 项目: yezooz/car-battle
def post_help(request, car_id, help_link):
    car = Car.objects.get_by_id(car_id)

    if hasattr(request.engine, 'facebook'):
        request.engine.facebook.post_help(car, help_link=help_link)
    else:
        print 'posted help for %s on profile' % car.name

    request.engine.log.message(message="Request for help posted to profile")
    return request.engine.redirect(reverse('jobs'))
示例#15
0
文件: link.py 项目: yezooz/car-battle
def post_car(request, car_id):
    car = Car.objects.get_by_id(car_id)

    if hasattr(request.engine, 'facebook'):
        request.engine.facebook.post_car(car)
    else:
        print 'posted %s to profile' % car.name

    request.engine.log.message(message="%s posted to profile" % car.name)
    return request.engine.redirect(reverse('garage'))
示例#16
0
文件: link.py 项目: Vic121/Car-Battle
def post_car(request, car_id):
    car = Car.objects.get_by_id(car_id)

    if hasattr(request.engine, 'facebook'):
        request.engine.facebook.post_car(car)
    else:
        print 'posted %s to profile' % car.name

    request.engine.log.message(message="%s posted to profile" % car.name)
    return request.engine.redirect(reverse('garage'))
示例#17
0
文件: link.py 项目: Vic121/Car-Battle
def post_help(request, car_id, help_link):
    car = Car.objects.get_by_id(car_id)

    if hasattr(request.engine, 'facebook'):
        request.engine.facebook.post_help(car, help_link=help_link)
    else:
        print 'posted help for %s on profile' % car.name

    request.engine.log.message(message="Request for help posted to profile")
    return request.engine.redirect(reverse('jobs'))
示例#18
0
def sell(request, item_type, item_id):
    from auction.models import Auction
    from common.models import Car
    from job.models import Garage

    item = Car.objects.get_by_id(item_id)
    garage = Garage.objects.get_by_user(user=request.engine.user.user)

    if item is None or not garage.has_car(item.id):
        return request.engine.redirect(reverse('garage'))

    form = SellForm()
    if request.method == 'POST' and request.POST.has_key('duration'):
        form = SellForm(request.POST)

        if form.is_valid():
            a = Auction()
            a.title = "%s %s" % (item.manuf, item.name)
            a.seller = request.engine.user.user
            a.car = item
            a.tier = item.tier
            a.start_price = form.cleaned_data.get('start_price') or 0
            a.buy_it_now_price = form.cleaned_data.get('buy_it_now_price') or 0
            a.current_price = form.cleaned_data['start_price']
            a.is_for_credits = False
            a.is_refunded = False
            a.start_at = datetime.datetime.now()
            a.end_at = datetime.datetime.now() + datetime.timedelta(days=int(form.cleaned_data['duration']))
            a.save()

            garage.engine = request.engine
            garage.remove_car(item.id)
            request.engine.user.profile.cars = len(garage)
            request.engine.user.profile.save()

            return request.engine.redirect(reverse('auction'))

    return {
        'item_type': item_type,
        'item_id': item_id,
        'item': item,
        'form': form,
    }
示例#19
0
def tier_battle(request, param=None):
    request.engine.module = 'battle'

    request.engine.user.get_garage()
    if not request.engine.user.garage.count() >= settings.REQ_CARDS_IN_BATTLE:
        request.engine.log.message(
            message="You need at least %d cars to fight against other players." % settings.REQ_CARDS_IN_BATTLE)
        return request.engine.redirect(reverse('jobs'))

    request.engine.register('battle')
    summary = None

    if not param:
        defender = request.engine.user.get_by_id(
            user_id=settings.TIER_BATTLE_PLAYERS[str(request.engine.user.profile.job_tier + 1)]).user
        battle = request.engine.battle.start_or_resume(defender, 1)

        if isinstance(battle, basestring):  # validation
            request.engine.log.message(message=battle)
            return request.engine.redirect(reverse('jobs'))

        if battle.step == 4:
            summary = request.engine.battle.get_summary(True)

    else:
        battle = request.engine.battle.resume_current(1)
        battle.next_step(param)
        return request.engine.redirect(reverse('tier_battle'))

    attacker, defender, shown = request.engine.battle.get_current_cards()

    return {
        'attacker': attacker,
        'defender': defender,
        'shown': shown,
        'battle': battle,
        'last_step': battle.step > 3,
        'last_card': battle.card == 1 and battle.step == 4,
        'defender_profile': 'random player',
        'tier_battle': True,
        'summary': summary,
    }
示例#20
0
def index(request, tab, page_no):
    if not hasattr(request.engine, 'user'):
        return index_anon(request, page_no)

    request.engine.register('auction', tab)
    request.engine.module = 'auction'
    template_tab = 'auction'

    if request.GET.get('tier') and request.GET['tier'] in settings.TIERS:
        filter = request.GET['tier']
    else:
        filter = None

    if tab == 'auction':
        paginator = Paginator(request.engine.auction.items,
                              settings.DEFAULT_AUCTIONS_PER_PAGE,
                              body=8,
                              padding=2)
        selected = request.engine.auction.items[
            (int(page_no) - 1) *
            settings.DEFAULT_AUCTIONS_PER_PAGE:int(page_no) *
            settings.DEFAULT_AUCTIONS_PER_PAGE]

    elif tab == 'watch':
        pass

    elif tab in ('bidding', 'bidded'):
        paginator = Paginator(request.engine.auction.items,
                              settings.DEFAULT_AUCTIONS_PER_PAGE,
                              body=8,
                              padding=2)
        selected = request.engine.auction.items[
            (int(page_no) - 1) *
            settings.DEFAULT_AUCTIONS_PER_PAGE:int(page_no) *
            settings.DEFAULT_AUCTIONS_PER_PAGE]
        template_tab = 'status'

    else:
        return request.engine.redirect(reverse('auction'))

    try:
        current_page = paginator.page(page_no)
    except:
        raise Http404

    return {
        'TEMPLATE': 'auction/index_%s.fbml' % template_tab,
        'tab': tab,
        'page_no': int(page_no),
        'page': current_page,
        'selected': selected,
        'filter': filter,
        'items_count': len(request.engine.auction.items),
    }
示例#21
0
def robbery_tabs(page, tab, lang="en"):
    ret = ""

    if page > 0:
        ret += '<li><a href="%s"">&laquo;</a></li>' % reverse("robbery", args=[page - 1])

    i = 0
    for tabs in settings.ROBBERY_TABS[page]:
        ret += '<li><a href="%s">' % reverse("robbery", args=[page, i])

        if int(tab) == i:
            ret += "<b>%s</b>" % tabs
        else:
            ret += "%s" % tabs
        ret += "</a></li>"
        i += 1

    if len(settings.ROBBERY_TABS) > page + 1:
        ret += '<li><a href="%s"">&raquo;</a></li>' % reverse("robbery", args=[page + 1])

    return ret
示例#22
0
def robbery_tabs(page, tab, lang='en'):
    ret = ''

    if page > 0:
        ret += '<li><a href="%s"">&laquo;</a></li>' % reverse('robbery',
                                                              args=[page - 1])

    i = 0
    for tabs in settings.ROBBERY_TABS[page]:
        ret += '<li><a href="%s">' % reverse('robbery', args=[page, i])

        if int(tab) == i:
            ret += '<b>%s</b>' % tabs
        else:
            ret += '%s' % tabs
        ret += '</a></li>'
        i += 1

    if len(settings.ROBBERY_TABS) > page + 1:
        ret += '<li><a href="%s"">&raquo;</a></li>' % reverse('robbery',
                                                              args=[page + 1])

    return ret
示例#23
0
def buy(request, item):
    if item == 'premium':
        request.engine.user.buy_premium()
    elif item == '3_cars':
        request.engine.user.buy_cars(3, '3')
    elif item == '3_plus_cars':
        request.engine.user.buy_cars(3, '3+')
    elif item == '5_cars':
        request.engine.user.buy_cars(5, '5')
    elif item == '5_plus_cars':
        request.engine.user.buy_cars(5, '5+')
    else:
        request.engine.log.message(message="Unknown option")

    return request.engine.redirect(reverse('store'))
示例#24
0
def index(request, tab, page_no):
    if not hasattr(request.engine, 'user'):
        return index_anon(request, page_no)

    request.engine.register('auction', tab)
    request.engine.module = 'auction'
    template_tab = 'auction'

    if request.GET.get('tier') and request.GET['tier'] in settings.TIERS:
        filter = request.GET['tier']
    else:
        filter = None

    if tab == 'auction':
        paginator = Paginator(request.engine.auction.items, settings.DEFAULT_AUCTIONS_PER_PAGE, body=8, padding=2)
        selected = request.engine.auction.items[
                   (int(page_no) - 1) * settings.DEFAULT_AUCTIONS_PER_PAGE:int(
                       page_no) * settings.DEFAULT_AUCTIONS_PER_PAGE
                   ]

    elif tab == 'watch':
        pass

    elif tab in ('bidding', 'bidded'):
        paginator = Paginator(request.engine.auction.items, settings.DEFAULT_AUCTIONS_PER_PAGE, body=8, padding=2)
        selected = request.engine.auction.items[
                   (int(page_no) - 1) * settings.DEFAULT_AUCTIONS_PER_PAGE:int(
                       page_no) * settings.DEFAULT_AUCTIONS_PER_PAGE
                   ]
        template_tab = 'status'

    else:
        return request.engine.redirect(reverse('auction'))

    try:
        current_page = paginator.page(page_no)
    except:
        raise Http404

    return {
        'TEMPLATE': 'auction/index_%s.fbml' % template_tab,
        'tab': tab,
        'page_no': int(page_no),
        'page': current_page,
        'selected': selected,
        'filter': filter,
        'items_count': len(request.engine.auction.items),
    }
示例#25
0
def details_anon(request, auction_id):
    request.engine.register('auction')
    request.engine.module = 'auction_details'

    if not request.engine.auction.set_auction(auction_id):
        return request.engine.redirect(reverse('auction'))

    if datetime.datetime.now() > request.engine.auction.auction.end_at:
        return {
            'TEMPLATE': 'auction/details_fin_anon.html',
            'item': request.engine.auction,
        }
    return {
        'TEMPLATE': 'auction/details_anon.html',
        'item': request.engine.auction,
    }
示例#26
0
def index(request):
    if request.method == 'POST':
        item = Album()
        item.name = request.POST['name']
        item.short_name = request.POST['short_name']
        item.save()
        request.engine.redirect(reverse('intranet_albums'))

    items = Album.objects.all().order_by('-is_locked', '-is_active', 'min_lvl', 'price', 'name')

    return render_to_response(
        'intranet/album_index.html', {
            'get': request.GET,
            'items': items,
        }, context_instance=RequestContext(request)
    )
示例#27
0
def details_anon(request, auction_id):
    request.engine.register('auction')
    request.engine.module = 'auction_details'

    if not request.engine.auction.set_auction(auction_id):
        return request.engine.redirect(reverse('auction'))

    if datetime.datetime.now() > request.engine.auction.auction.end_at:
        return {
            'TEMPLATE': 'auction/details_fin_anon.html',
            'item': request.engine.auction,
        }
    return {
        'TEMPLATE': 'auction/details_anon.html',
        'item': request.engine.auction,
    }
示例#28
0
def sell(request, car_id):
    request.engine.module = 'garage'
    garage = request.engine.user.get_garage()

    if garage.remove_car(car_id) is True:
        request.engine.log.message(message="Car sold")
    else:
        request.engine.log.message(message="Faced problem with selling car")

    car = Car.objects.get_by_id(car_id)
    if car.tier in ('1', '2', '3', '4', '5'):
        request.engine.user.profile.earn('cash', 2500 * int(car.tier))
    else:
        request.engine.user.profile.earn('cash', 35000)

    return request.engine.redirect(reverse('garage'))
示例#29
0
def details(request, slug, auction_id):
    if not hasattr(request.engine, 'user'):
        return details_anon(request, auction_id)

    request.engine.register('auction')
    request.engine.module = 'auction_details'

    if not request.engine.auction.set_auction(auction_id):
        return request.engine.redirect(reverse('auction'))

    if datetime.datetime.now() > request.engine.auction.auction.end_at:
        return {
            'TEMPLATE': 'auction/details_fin.fbml',
            'item': request.engine.auction,
        }
    return {
        'TEMPLATE': 'auction/details.fbml',
        'item': request.engine.auction,
    }
示例#30
0
def details(request, slug, auction_id):
    if not hasattr(request.engine, 'user'):
        return details_anon(request, auction_id)

    request.engine.register('auction')
    request.engine.module = 'auction_details'

    if not request.engine.auction.set_auction(auction_id):
        return request.engine.redirect(reverse('auction'))

    if datetime.datetime.now() > request.engine.auction.auction.end_at:
        return {
            'TEMPLATE': 'auction/details_fin.fbml',
            'item': request.engine.auction,
        }
    return {
        'TEMPLATE': 'auction/details.fbml',
        'item': request.engine.auction,
    }
示例#31
0
def edit(request, item_id):
    item = Album.objects.get(pk=item_id)

    if request.method == 'POST':
        if request.POST.has_key('remove'):
            item.delete()
        else:
            for k, v in request.POST.iteritems():
                item.__dict__[k] = v.strip()
            if not request.POST.has_key('is_active'): item.__dict__['is_active'] = False
            if not request.POST.has_key('is_locked'): item.__dict__['is_locked'] = False
            item.save()
        return request.engine.redirect(reverse('intranet_albums'))

    return render_to_response(
        'intranet/album_edit.html', {
            'item': item,
        }, context_instance=RequestContext(request)
    )
示例#32
0
def add(request):
    form = PartnerAddForm(instance=Partner())
    if request.method == 'POST':
        form = PartnerAddForm(request.POST, instance=Partner())

        if form.is_valid():
            partner = form.save(commit=False)
            partner.user = request.engine.user.user
            partner.pay_share = settings.PARTNER_SHARE
            partner.save()

            return request.engine.redirect(reverse('partner_edit', args=[partner.id]))

        return {
            'form': form,
        }

    return {
        'form': form,
    }
示例#33
0
def add(request):
    form = PartnerAddForm(instance=Partner())
    if request.method == 'POST':
        form = PartnerAddForm(request.POST, instance=Partner())

        if form.is_valid():
            partner = form.save(commit=False)
            partner.user = request.engine.user.user
            partner.pay_share = settings.PARTNER_SHARE
            partner.save()

            return request.engine.redirect(
                reverse('partner_edit', args=[partner.id]))

        return {
            'form': form,
        }

    return {
        'form': form,
    }
示例#34
0
文件: tips.py 项目: Vic121/Car-Battle
def show_how_to_play(request):
    page = request.engine.module
    profile = request.engine.user.profile

    if page not in settings.HOW_TO_PLAY: return ''
    if profile.how_to_play_status(settings.HOW_TO_PLAY.index(page)) == '0':
        ret = """
			<script type="text/javascript">
			function confirm_close() {
				$.post('%s', {'page': '%s'}, function(data) {
					$('#how_to_play').slideUp();
				});
			}
			</script>
		""" % (reverse('confirm_close'), page)
        ret += '<div id="how_to_play">'
        ret += '<div class="menu">'
        ret += '<div class="close"><a href="#" onclick="confirm_close(); return false;">close</a></div>'
        ret += '<h3>How to Play?</h3>'
        ret += render_to_string('userprofile/how_to_play/' + page + '.html', {})
        ret += '</div></div>'
        return ret
    return ''
示例#35
0
文件: job.py 项目: Vic121/Car-Battle
    def __init__(self, engine):
        self.engine = engine
        if not hasattr(engine, 'user'): return engine.redirect(reverse('home'))

        profile = engine.user.profile
        if profile.job_next_day_at is None or profile.job_next_day_at <= datetime.datetime.now(
        ):
            UserJob.objects.filter(is_active=True).update(is_active=False)

            profile.job_round = 1
            profile.job_tier = 1
            profile.job_max_round_today = profile.job_max_round
            profile.job_next_day_at = datetime.datetime.now(
            ) + datetime.timedelta(days=1)
            profile.job_id = 0
            profile.save()

        self.user_job = UserJob.objects.get_by_user(
            user=engine.user.user, profile=engine.user.profile)

        # time left
        self.time_left = str(profile.job_next_day_at -
                             datetime.datetime.now()).split('.')[0].split(':')

        if len(self.time_left) > 3:
            self.time_left = ''
        elif len(self.time_left) == 3:
            if int(self.time_left[0]) == 0 and int(self.time_left[1]) == 0:
                self.time_left = 'almost finished'
            elif int(self.time_left[0]) == 0:
                self.time_left = '%smin left' % (self.time_left[1].lstrip('0'))
            else:
                self.time_left = '%sh %smin left' % (self.time_left[0].lstrip(
                    '0'), self.time_left[1].lstrip('0'))
        else:
            self.time_left = 'almost finished'
示例#36
0
def decline(request, car_id, user_id):
    g = UserGift.objects.get_by_user(user=request.engine.user.user)
    g.engine = request.engine
    g.decline(car_id, user_id)
    return request.engine.redirect(reverse("home"))
示例#37
0
def buy_now(request):
    request.engine.register('auction')
    request.engine.auction.buy_now(request.POST.get('item_id'))

    return request.engine.redirect(
        reverse('auction_details', args=[request.POST.get('item_slug'), request.POST.get('item_id')]))
示例#38
0
def battle(request, user_id=None, param=None):
    request.engine.module = 'battle'

    if user_id == str(request.engine.user.user.id):
        return request.engine.redirect(reverse('battle'))

    request.engine.user.get_garage()
    if request.engine.user.garage.count() < settings.REQ_CARDS_IN_BATTLE:
        request.engine.log.message(
            message="You need at least %d cars to fight against other players."
            % settings.REQ_CARDS_IN_BATTLE)
        return request.engine.redirect(reverse('battle'))

    request.engine.register('battle')
    summary = None

    if user_id is not None:
        profile = request.engine.user.get_by_id(user_id=user_id)
        battle = request.engine.battle.start_or_resume(profile.user)

        if isinstance(battle, basestring):  # validation
            request.engine.log.message(message=battle)
            return request.engine.redirect(reverse('battle'))

        if battle.step == 4 and battle.card < 3 and request.GET.has_key(
                'next'):
            battle.next_card()
        # elif battle.step == 4 and battle.card == 3 and request.GET.has_key('next'):
        # 	return request.engine.redirect(reverse('battle'))

        if battle.step == 4 and battle.card == 3:
            summary = request.engine.battle.get_summary(True)
        elif battle.step == 4 and battle.card < 3:
            summary = request.engine.battle.get_summary()

    else:
        battle = request.engine.battle.resume_current(3)
        if battle is None:
            request.engine.log.message(
                message=
                "Error occured during battle, our staff were informed. Really sorry, we'll fix it soon."
            )
            return request.engine.redirect(reverse('battle'))

        battle.next_step(param)
        return request.engine.redirect(
            reverse('battle_user', args=[battle.defender.id]))

    try:
        attacker, defender, shown = request.engine.battle.get_current_cards()
    except TypeError:
        request.engine.log.message(
            message=
            "Error occured during battle, our staff were informed. Really sorry, we'll fix it soon."
        )
        return request.engine.redirect(reverse('battle'))

    return {
        'attacker': attacker,
        'defender': defender,
        'shown': shown,
        'battle': battle,
        'last_step': battle.step > 3,
        'last_card': battle.card == 3 and battle.step == 4,
        'user_id': user_id,
        'defender_profile': profile,
        'tier_battle': False,
        'summary': summary,
    }
示例#39
0
def accept(request, car_id, user_id):
    g = UserGift.objects.get_by_user(user=request.engine.user.user)
    g.engine = request.engine
    g.confirm(car_id, user_id)

    return request.engine.redirect(reverse('home'))
示例#40
0
文件: job.py 项目: yezooz/car-battle
    def collect_job(self, car_id):
        car = None

        if not self.user_job or not self.user_job.is_active: return

        try:
            for i in xrange(0, self.user_job.last_tier):
                if self.user_job.jobs[i].id == int(car_id):
                    car = self.user_job.jobs[i]
                    break
            if not car: raise KeyError  # ten sam blad, gdy zly car_id
        except KeyError:
            logging.warning("%s tried to link-collect-hack" % self.engine.user.user)
            # statystyki
            self.engine.log.message(message="You're not yet allowed to collect this car.")
            return

        if car.tier == '6' and not self.engine.user.profile.is_premium:
            self.engine.log.message(
                message="Tier 6 cars are for Supporters only. <a href='%s'>Become a supporter</a>." % reverse('store'))
            return

        # garaz
        self.engine.user.get_garage()
        self.engine.user.garage.add_car(car.id)
        self.engine.user.profile.cars = len(self.engine.user.garage)

        # kasa
        self.engine.user.profile.earn('cash', settings.TIER_INCOME[str(self.user_job.last_tier)], False)
        self.engine.user.profile.earn('exp', settings.EXP['collect_car_tier_%s' % car.tier], engine=self.engine)

        self.engine.user.refresh_profile()

        self.engine.add_summary('job', 'done', {'cash': settings.TIER_INCOME[str(self.user_job.last_tier)],
                                                'exp': settings.EXP['collect_car_tier_%s' % car.tier], 'car': car})

        self.engine.notify.add(user=self.engine.user.user, type='job', key='done', date='today')
        self.engine.notify.add(user=self.engine.user.user, type='job', key='done', date=None)
        if self.user_job.help_has > 0:
            self.engine.notify.add(user=self.engine.user.user, type='job', key='help', date='today')
            self.engine.notify.add(user=self.engine.user.user, type='job', key='help', date=None)

        # finish round
        job_stat = JobStat.objects.get_by_job(job=car)
        job_stat.done += 1
        job_stat.last_did = self.engine.user.user
        job_stat.last_did_at = datetime.datetime.now()
        job_stat.save()

        self.new_round()
示例#41
0
def accept(request, car_id, user_id):
    g = UserGift.objects.get_by_user(user=request.engine.user.user)
    g.engine = request.engine
    g.confirm(car_id, user_id)

    return request.engine.redirect(reverse("home"))
示例#42
0
def decline(request, car_id, user_id):
    g = UserGift.objects.get_by_user(user=request.engine.user.user)
    g.engine = request.engine
    g.decline(car_id, user_id)
    return request.engine.redirect(reverse('home'))
示例#43
0
def collect(request, car_id):
    request.engine.register('job')
    request.engine.job.collect_job(car_id)
    return request.engine.redirect(reverse('jobs'))
示例#44
0
def edit(request, invite_code, secret_code):
    import Image
    import os

    if invite_code is not None and secret_code is not None:
        profile = UserProfile.objects.get_by_invite_key(invite_code)
        if profile is None: return request.engine.redirect('/')
        if request.engine.md5(invite_code + settings.SECRET_KEY)[:16] != secret_code:  return request.engine.redirect(
            reverse('/'))

        from django.contrib.auth import login, get_backends

        backend = get_backends()[0]
        profile.user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__)
        login(request, profile.user)
        return request.engine.redirect(reverse('profile_edit'))

    if not hasattr(request.engine, 'user'):
        return request.engine.redirect('/')

    # TODO: naprawić to
    def check_passwords(old_pass, new_pass1, new_pass2, user):
        if old_pass and user.check_password(old_pass):

            if new_pass1 == new_pass2:
                user.set_password(new_pass1)
                return True
            else:
                return False
        else:
            return False

    def check_avatar(value):
        if 'content-type' in value:
            main, sub = value.content - type.split('/')
            if not (main == 'image' and sub in ['jpeg', 'gif', 'png']):
                request.engine.log.message(message='JPEG, PNG, GIF only.', is_error=True)
                return None

        if value.size > (2 * 1024 * 1024):
            request.engine.log.message(message='Upload only files smaller than 2MB.', is_error=True)
            return None

        # try:
        path = '%savatars/%s/' % (settings.MEDIA_ROOT, str(request.engine.user.profile.user_id / 1000))
        if not os.path.isdir(path):
            os.makedirs(path, 0777)
        path = path + "%s.jpg" % request.engine.user.user.id
        destination = open(path, 'wb+')
        for chunk in value.chunks():
            destination.write(chunk)
        destination.close()

        try:
            img = Image.open(path)
            x, y = img.size
        except Exception, e:
            request.engine.log.message(
                message='Upload a valid image. The file you uploaded was either not an image or a corrupted image.',
                is_error=True)
            return None

        if x > 800 or y > 800:
            request.engine.log.message(message='Upload a valid image. This one is too big in size.', is_error=True)
            return {}
        if x > 50 and y > 50:
            if img.mode not in ('L', 'RGB'):
                img = img.convert('RGB')
            img = img.resize((50, 50), Image.ANTIALIAS)
            img.save(path, "JPEG")

        return path
示例#45
0
def friend_send(request, car_id):
    car = Car.objects.get_by_id(car_id)

    if request.method == "POST":
        if not request.POST.has_key("friend"):
            request.engine.log.message(message="You forgot to select a friend")
            return HttpResponseRedirect(reverse("friend_send", args=[car.id]))

        try:
            receiver = UserProfile.objects.get_by_id(request.POST["friend"])
        except UserProfile.DoesNotExist:
            request.engine.log.message(message="Incorrect friend selected")
            return HttpResponseRedirect(reverse("friend_send", args=[car.id]))

        garage = Garage.objects.get_by_user(user=request.engine.user.user)
        if not garage.has_car(car.id):
            request.engine.log.message(message="Incorrect car selected")
            return HttpResponseRedirect(reverse("friend_send", args=[car.id]))

        # dodajemy gift do pending
        g = UserGift.objects.get_by_user(user=receiver.user)
        g.engine = request.engine
        g.add_pending(car.id, request.engine.user.user.id)

        # usuwamy z garazu
        garage.engine = request.engine
        garage.remove_car(car.id)

        # wysylamy powiadomienie mailem
        Task(
            user=request.engine.user.user,
            task="mail",
            source="gift_received",
            comment=json.dumps(
                {"sender": request.engine.user.profile.user_id, "recipient": receiver.user_id, "car": car_id}
            ),
        ).save()

        request.engine.log.message(message="Car sent to %s" % receiver)
        return HttpResponseRedirect(reverse("garage"))

    friend = Friend.objects.get_by_user(user=request.engine.user.user)
    page_no = request.GET.get("page_no") or 1

    selected = friend.friends[
        (int(page_no) - 1)
        * settings.DEFAULT_FRIENDS_PER_GIFT_PAGE : int(page_no)
        * settings.DEFAULT_FRIENDS_PER_GIFT_PAGE
    ]
    paginator = Paginator(friend.friends, settings.DEFAULT_FRIENDS_PER_GIFT_PAGE, body=8, padding=2)

    try:
        current_page = paginator.page(page_no)
    except:
        return HttpResponseRedirect(reverse("friend_send", args=[car_id]))

    return {
        "car": car,
        "friends": UserProfile.objects.get_many_by_user_ids(selected),
        "page_no": int(page_no),
        "page": current_page,
        "total": len(friend.friends),
    }
示例#46
0
def battle(request, user_id=None, param=None):
    request.engine.module = 'battle'

    if user_id == str(request.engine.user.user.id): return request.engine.redirect(reverse('battle'))

    request.engine.user.get_garage()
    if request.engine.user.garage.count() < settings.REQ_CARDS_IN_BATTLE:
        request.engine.log.message(
            message="You need at least %d cars to fight against other players." % settings.REQ_CARDS_IN_BATTLE)
        return request.engine.redirect(reverse('battle'))

    request.engine.register('battle')
    summary = None

    if user_id is not None:
        profile = request.engine.user.get_by_id(user_id=user_id)
        battle = request.engine.battle.start_or_resume(profile.user)

        if isinstance(battle, basestring):  # validation
            request.engine.log.message(message=battle)
            return request.engine.redirect(reverse('battle'))

        if battle.step == 4 and battle.card < 3 and request.GET.has_key('next'):
            battle.next_card()
        # elif battle.step == 4 and battle.card == 3 and request.GET.has_key('next'):
        # 	return request.engine.redirect(reverse('battle'))

        if battle.step == 4 and battle.card == 3:
            summary = request.engine.battle.get_summary(True)
        elif battle.step == 4 and battle.card < 3:
            summary = request.engine.battle.get_summary()

    else:
        battle = request.engine.battle.resume_current(3)
        if battle is None:
            request.engine.log.message(
                message="Error occured during battle, our staff were informed. Really sorry, we'll fix it soon.")
            return request.engine.redirect(reverse('battle'))

        battle.next_step(param)
        return request.engine.redirect(reverse('battle_user', args=[battle.defender.id]))

    try:
        attacker, defender, shown = request.engine.battle.get_current_cards()
    except TypeError:
        request.engine.log.message(
            message="Error occured during battle, our staff were informed. Really sorry, we'll fix it soon.")
        return request.engine.redirect(reverse('battle'))

    return {
        'attacker': attacker,
        'defender': defender,
        'shown': shown,
        'battle': battle,
        'last_step': battle.step > 3,
        'last_card': battle.card == 3 and battle.step == 4,
        'user_id': user_id,
        'defender_profile': profile,
        'tier_battle': False,
        'summary': summary,
    }
示例#47
0
文件: job.py 项目: Vic121/Car-Battle
    def collect_job(self, car_id):
        car = None

        if not self.user_job or not self.user_job.is_active: return

        try:
            for i in xrange(0, self.user_job.last_tier):
                if self.user_job.jobs[i].id == int(car_id):
                    car = self.user_job.jobs[i]
                    break
            if not car: raise KeyError  # ten sam blad, gdy zly car_id
        except KeyError:
            logging.warning("%s tried to link-collect-hack" %
                            self.engine.user.user)
            # statystyki
            self.engine.log.message(
                message="You're not yet allowed to collect this car.")
            return

        if car.tier == '6' and not self.engine.user.profile.is_premium:
            self.engine.log.message(
                message=
                "Tier 6 cars are for Supporters only. <a href='%s'>Become a supporter</a>."
                % reverse('store'))
            return

        # garaz
        self.engine.user.get_garage()
        self.engine.user.garage.add_car(car.id)
        self.engine.user.profile.cars = len(self.engine.user.garage)

        # kasa
        self.engine.user.profile.earn(
            'cash', settings.TIER_INCOME[str(self.user_job.last_tier)], False)
        self.engine.user.profile.earn('exp',
                                      settings.EXP['collect_car_tier_%s' %
                                                   car.tier],
                                      engine=self.engine)

        self.engine.user.refresh_profile()

        self.engine.add_summary(
            'job', 'done', {
                'cash': settings.TIER_INCOME[str(self.user_job.last_tier)],
                'exp': settings.EXP['collect_car_tier_%s' % car.tier],
                'car': car
            })

        self.engine.notify.add(user=self.engine.user.user,
                               type='job',
                               key='done',
                               date='today')
        self.engine.notify.add(user=self.engine.user.user,
                               type='job',
                               key='done',
                               date=None)
        if self.user_job.help_has > 0:
            self.engine.notify.add(user=self.engine.user.user,
                                   type='job',
                                   key='help',
                                   date='today')
            self.engine.notify.add(user=self.engine.user.user,
                                   type='job',
                                   key='help',
                                   date=None)

        # finish round
        job_stat = JobStat.objects.get_by_job(job=car)
        job_stat.done += 1
        job_stat.last_did = self.engine.user.user
        job_stat.last_did_at = datetime.datetime.now()
        job_stat.save()

        self.new_round()
示例#48
0
def friend_send(request, car_id):
    car = Car.objects.get_by_id(car_id)

    if request.method == 'POST':
        if not request.POST.has_key('friend'):
            request.engine.log.message(message="You forgot to select a friend")
            return HttpResponseRedirect(reverse('friend_send', args=[car.id]))

        try:
            receiver = UserProfile.objects.get_by_id(request.POST['friend'])
        except UserProfile.DoesNotExist:
            request.engine.log.message(message="Incorrect friend selected")
            return HttpResponseRedirect(reverse('friend_send', args=[car.id]))

        garage = Garage.objects.get_by_user(user=request.engine.user.user)
        if not garage.has_car(car.id):
            request.engine.log.message(message="Incorrect car selected")
            return HttpResponseRedirect(reverse('friend_send', args=[car.id]))

        # dodajemy gift do pending
        g = UserGift.objects.get_by_user(user=receiver.user)
        g.engine = request.engine
        g.add_pending(car.id, request.engine.user.user.id)

        # usuwamy z garazu
        garage.engine = request.engine
        garage.remove_car(car.id)

        # wysylamy powiadomienie mailem
        Task(user=request.engine.user.user,
             task='mail',
             source='gift_received',
             comment=json.dumps({
                 'sender': request.engine.user.profile.user_id,
                 'recipient': receiver.user_id,
                 'car': car_id
             })).save()

        request.engine.log.message(message="Car sent to %s" % receiver)
        return HttpResponseRedirect(reverse('garage'))

    friend = Friend.objects.get_by_user(user=request.engine.user.user)
    page_no = request.GET.get('page_no') or 1

    selected = friend.friends[
        (int(page_no) - 1) *
        settings.DEFAULT_FRIENDS_PER_GIFT_PAGE:int(page_no) *
        settings.DEFAULT_FRIENDS_PER_GIFT_PAGE]
    paginator = Paginator(friend.friends,
                          settings.DEFAULT_FRIENDS_PER_GIFT_PAGE,
                          body=8,
                          padding=2)

    try:
        current_page = paginator.page(page_no)
    except:
        return HttpResponseRedirect(reverse('friend_send', args=[car_id]))

    return {
        'car': car,
        'friends': UserProfile.objects.get_many_by_user_ids(selected),
        'page_no': int(page_no),
        'page': current_page,
        'total': len(friend.friends),
    }
示例#49
0
def buy(request, album_id):
    request.engine.register("album")
    request.engine.album.buy(album_id)

    logging.info("album (%s) bought by %s" % (album_id, request.engine.user.user))
    return request.engine.redirect(reverse("albums"))
示例#50
0
def gift(request, user_id, car_id):
    return HttpResponseRedirect(reverse('wishlist', args=[user_id]))
示例#51
0
def index(request):
    def query(query):
        cursor = connection.cursor()
        c = cursor.execute(query)
        return cursor.fetchall()

    def __replace_id(f_id, t_id, s):
        arr = s.split(',')
        f_id, t_id = str(f_id), str(t_id)

        if f_id not in arr: return s

        arr[arr.index(f_id)] = t_id
        return ','.join(arr)

    if request.method == 'POST':
        if not request.POST.has_key('left'): return HttpResponseRedirect(reverse('auction_merge'))

        to_car_id = str(request.POST['left'])
        to_car = Car.objects.get(pk=int(request.POST['left']))
        for k, car_id in request.POST.iteritems():
            if not k.startswith('right_'): continue

            from_car_id = str(car_id)
            from_car = Car.objects.get(pk=int(car_id))

            # replace all car_ids
            for album in Album.objects.all():
                album.car = __replace_id(from_car_id, to_car_id, album.car)
                album.save()

            for album in UserAlbum.objects.all():
                album.car = __replace_id(from_car_id, to_car_id, album.car)
                album.save()

            for auction in Auction.objects.filter(car=from_car):
                auction.car = to_car
                auction.name = to_car.name
                auction.tier = to_car.tier
                auction.save()

            for battle in Battle.objects.all():
                battle.left_card = __replace_id(from_car_id, to_car_id, battle.left_card)
                battle.right_card = __replace_id(from_car_id, to_car_id, battle.right_card)
                if len(battle.state) > 0:
                    state = json.loads(battle.state)
                    if from_car_id not in state.keys(): continue
                    state[to_car_id] = state[from_car_id]
                    del state[from_car_id]
                    battle.state = json.dumps(state)
                battle.save()

            for garage in Garage.objects.all():
                if len(garage.car) == 0: continue

                items = json.loads(garage.car)
                if from_car_id not in items.keys(): continue
                items[to_car_id] = items[from_car_id]
                del items[from_car_id]
                garage.car = json.dumps(items)
                garage.save()

            for wishlist in WishList.objects.all():
                wishlist.item = __replace_id(from_car_id, to_car_id, wishlist.item)
                wishlist.save()

            from_car.in_battle = False
            from_car.is_active_in_battle = False
            from_car.save()
            query("UPDATE common.car SET in_battle=0, is_active_in_battle=0 WHERE id=%d" % int(from_car.id))

            query("INSERT INTO stat.merge_log(from_car_id, to_car_id, created_at) VALUES('%s', '%s', '%s')" % (
                car_id, request.POST['left'], str(datetime.datetime.now())[:19]))

        if request.META.has_key('HTTP_REFERER'):
            return HttpResponseRedirect(request.META['HTTP_REFERER'])
        else:
            return HttpResponseRedirect(reverse('intranet_merge'))

    gta = None
    manufs = None
    if request.GET.has_key('search'):
        gta = Car.objects.filter_with_params(request.GET).filter(is_active=True, is_active_in_battle=True,
                                                                 in_battle=True)
        manufs = gta.values_list('manuf', flat=True).order_by('manuf').distinct()
    else:
        gta = Car.objects.filter(is_active=True, is_active_in_battle=True, in_battle=True)

    if request.GET.has_key('manuf') and len(request.GET['manuf']) > 0:
        gta = gta.order_by('manuf', 'name', 'year')
    else:
        gta = gta.order_by('manuf', '-year', 'name')[:100]

    return render_to_response(
        'intranet/merge.html', {
            'get': request.GET,
            # 'item': item,
            'manufs': manufs or Car.objects.filter(is_active=True, is_active_in_battle=True,
                                                   in_battle=True).values_list('manuf', flat=True).order_by(
                'manuf').distinct(),
            'groups': settings.CAR_GROUPS,
            'results': gta,
        }, context_instance=RequestContext(request)
    )