def get_by_user(self, city_id, user=None, user_id=None, username=None): if username is not None: try: user = User.objects.get(username__iexact=username) except User.DoesNotExist: return None if user is not None: key = 'city_unit_%s_%s' % (city_id, user.id) elif user_id is not None: key = 'city_unit_%s_%s' % (city_id, user_id) item = cache.get(key) if item is not None: return pickle.loads(str(item)) try: if user is not None: item = self.get(user=user, city_id=city_id) elif user_id is not None: item = self.get(user__id=user_id, city_id=city_id) else: logging.warning('CityUnit not found. USER:%s, ID:%s' % (str(user), str(user_id))) return None except CityUnit.DoesNotExist: item = CityUnit() item.user = user or User.objects.get(pk=user_id) item.city_id = city_id item.save() cache.set(key, pickle.dumps(item)) return item
def get_by_city(self, city=None, city_id=None): if city is not None: key = 'city_product_req_%s' % city.id elif city_id is not None: key = 'city_product_req_%s' % city_id item = cache.get(key) if item is not None: return pickle.loads(str(item)) try: if city is not None: item = self.get(city=city) elif city_id is not None: item = self.get(city__id=city_id) else: logging.warning('CityProductReq not found. CITY:%s, ID:%s' % (str(city), str(city_id))) return None except CityProductReq.DoesNotExist: cp = CityProductReq() cp.city = city or CityMap.objects.get_by_id(city_id) cp.save() item = cp cache.set(key, pickle.dumps(item)) return item
def hire_unit(self, unit_id): try: unit = self.all_unit[str(unit_id)] except KeyError: logging.warning("Unit with ID=%s NOT FOUND" % str(unit_id)) if len(self.city_unit_progress.units) >= self.engine.settings.MAX_SECURITY_BUILD_QUEUE: self.engine.log.message(message=_('Maximum length of the queue reached')) return if not self.engine.user.profile.has_enough('cash', unit.price): self.engine.log.message(message=_('Not enough cash')) return if unit.credit > 0 and not self.engine.user.profile.has_enough('credit', unit.credit): self.engine.log.message(message=_('Not enough credits. Add some first.')) return if len(self.city_unit_progress.units) == 0: self.city_unit_progress.unit = "[[%d,%d]]" % (int(unit_id), int(time.time()) + int(unit.time_to_build) * 60) self.city_unit_progress.next_at = datetime.datetime.fromtimestamp( int(time.time()) + int(unit.time_to_build) * 60) else: units = self.city_unit_progress.units last_unit = self.city_unit_progress.units.pop() units.append([int(unit_id), int(last_unit[1]) + int(unit.time_to_build) * 60]) self.city_unit_progress.unit = json.dumps(units) # self.city_unit_progress.next_at = datetime.datetime.fromtimestamp(self.city_unit_progress.units[0][1]) self.engine.user.profile.spend('cash', unit.price) if unit.credit > 0: self.engine.user.profile.spend('credit', unit.credit) self.city_unit_progress.save() self.engine.log.message(message=_("Unit hiring process started"))
def get_by_user(self, user=None, user_id=None): if user is not None: key = 'user_inventory_%s' % user.id elif user_id is not None: key = 'user_inventory_%s' % user_id item = cache.get(key) if item is not None: return pickle.loads(str(item)) try: if user is not None: item = self.get(user=user) elif user_id is not None: item = self.get(user__id=user_id) else: logging.warning('Inventory not found. USER:%s, ID:%s' % (str(user), str(user_id))) return None except Inventory.DoesNotExist: item = Inventory() item.user = user item.item = '' item.active = '' item.save() cache.set(key, pickle.dumps(item)) return item
def get_by_user(self, user=None, user_id=None): if user is not None: key = 'map_move_%s' % (user.id) elif user_id is not None: key = 'map_move_%s' % (user_id) item = cache.get(key) if item is not None: return pickle.loads(str(item)) try: if user is not None: item = self.get(user=user) elif user_id is not None: item = self.get(user__id=user_id) else: logging.warning('MapMove not found. USER:%s, ID:%s.' % (str(user), str(user_id))) return None except MapMove.DoesNotExist: item = MapMove() item.user = user or User.objects.get(pk=user_id) item.save() cache.set(key, pickle.dumps(item)) return item
def get_by_user(self, user=None, user_id=None): if user is not None: key = 'user_garage_%s' % user.id elif user_id is not None: key = 'user_garage_%s' % user_id item = cache.get(key) if item is not None: return pickle.loads(str(item)) try: if user is not None: item = self.get(user=user) elif user_id is not None: item = self.get(user__id=user_id) else: logging.warning('Garage not found. USER:%s, ID:%s' % (str(user), str(user_id))) return None except Garage.DoesNotExist: car = Garage() car.user = user car.item = '' car.save() item = car cache.set(key, pickle.dumps(item)) return item
def get_by_user(self, city_id, user=None, user_id=None): # if user is not None: # key = 'city_unit_progress_%s_%s' % (city_id, user.id) # elif user_id is not None: # key = 'city_unit_progress_%s_%s' % (city_id, user_id) # # item = cache.get(key) # if item is not None: # return pickle.loads(str(item)) try: if user is not None: item = self.get(user=user, city_id=city_id) elif user_id is not None: item = self.get(user__id=user_id, city_id=city_id) else: logging.warning('CityUnitProgress not found. USER:%s, ID:%s' % (str(user), str(user_id))) return None except CityUnitProgress.DoesNotExist: cs = CityUnitProgress() cs.user = user cs.city_id = city_id cs.save() item = cs # cache.set(key, pickle.dumps(item)) return item
def get_by_user(self, sector, user=None, user_id=None): if user is not None: key = 'world_map_%s_sector_%s' % (user.id, sector) elif user_id is not None: key = 'world_map_%s_sector_%s' % (user_id, sector) item = cache.get(key) if item is not None: return pickle.loads(str(item)) try: if user is not None: item = self.get(user=user, sector=sector) elif user_id is not None: item = self.get(user__id=user_id, sector=sector) else: logging.warning('WorldMap not found. USER:%s, ID:%s. Sector: %s' % (str(user), str(user_id), sector)) return None except WorldMap.DoesNotExist: wm = WorldMap() wm.user = user wm.city = json.dumps([0 for x in xrange(100)]) wm.sector = sector wm.save() item = wm cache.set(key, pickle.dumps(item)) return item
def match_req(self, reqs): for name, req in reqs.iteritems(): if name == "skills": u = UserSkill.objects.get_by_user(user=self.user) for skill, lvl in req.iteritems(): if not u.skills.has_key(skill): return False if int(u.skills[skill]) < int(lvl): return False elif name == "car": from crims.item.models import Garage u = Garage.objects.get_by_user(user=self.user) elif name == "member": from crims.family.models import UserFamily u = UserFamily.objects.get_by_user(user=self.user) if len(u.members) < int(req): return False elif name == "lady": from crims.city.models import CityHooker u = CityHooker.objects.get_by_city(user=self.engine.user.profile.default_city_id) if len(u.hookers) < int(req): return False else: logging.warning("Cannot match %s req" % str(name)) return False return True
def get_by_city(self, city=None, city_id=None): if city is not None: key = 'city_hooker_%s' % city.id elif city_id is not None: key = 'city_hooker_%s' % city_id item = cache.get(key) if item is not None: return pickle.loads(str(item)) try: if city is not None: item = self.get(city=city) elif city_id is not None: item = self.get(city__id=city_id) else: logging.warning('CityHooker not found. CITY:%s, ID:%s' % (str(city), str(city_id))) return None except CityHooker.DoesNotExist: item = CityHooker() item.city = city or CityMap.objects.get_by_id(city_id) item.hooker = '' item.save() cache.set(key, pickle.dumps(item)) return item
def get_by_user(self, user=None, user_id=None): if user is not None: key = 'user_product_%s' % user.id elif user_id is not None: key = 'user_product_%s' % user_id item = cache.get(key) if item is not None: return pickle.loads(str(item)) try: if user is not None: item = self.get(user=user) elif user_id is not None: item = self.get(user__id=user_id) else: logging.warning('UserProduct not found. USER:%s, ID:%s' % (str(user), str(user_id))) return None except UserProduct.DoesNotExist: up = UserProduct() up.user = user or User.objects.get(pk=user_id) up.item = json.dumps({}) up.save() item = up cache.set(key, pickle.dumps(item)) return item
def do_skill(self, skill_type): try: skill = self.to_do_skill[skill_type] except KeyError: logging.warning('skill_type:%s does not exist' % skill_type) return if len(self.skills.queues) > 0: # one queue for everyone? self.engine.log.message(message=_('You can\'t learn two things at the same time')) return if not self.profile.has_enough('cash', skill.cost): self.engine.log.message(message=_('Not enough cash')) return self.skills.queue = json.dumps( {skill.name: str(datetime.datetime.now() + datetime.timedelta(minutes=skill.time))[:19]}) self.skills.save() self.profile.cash -= skill.cost self.profile.has_skills = True self.profile.save() logging.debug('%s: learning %s skill at lvl %s' % (self.user, skill.name, skill.level)) self.engine.stream.trigger('skill_learn_start') self.engine.stream.trigger('skill_%d_learn_start' % int(skill.id)) self.engine.log.message(message=_('Learning right now, come back later.')) return True
def stream_delete(request, stream_id): try: stream = UserStream.objects.get(pk=stream_id) if stream.user == request.engine.user.user: stream.delete() else: logging.warning('UserStream ID:%s not belong to %s!' % (str(stream_id), str(request.engine.user.user))) except UserStream.DoesNotExist: logging.warning('UserStream ID:%s not found!' % str(stream_id)) return request.engine.redirect(reverse('home'))
def has_enough(self, type, amt): items = self.items if items.has_key(type): if items[type] >= amt: return True else: return False else: logging.warning('%s not in product types' % str(type)) return False
def wall_stream_delete(request, stream_id): from crims.city.models import CityWall, CityMap try: stream = CityWall.objects.get(pk=stream_id) if stream.city.owner_id == request.engine.user.user.id: stream.delete() else: logging.warning('UserStream ID:%s not belong to %s!' % (str(stream_id), str(request.engine.user.user))) except CityWall.DoesNotExist: logging.warning('UserStream ID:%s not found!' % str(stream_id)) return request.engine.redirect(reverse('home'))
def get_by_id(self, group_id): key = 'map_move_group_%s' % group_id item = cache.get(key) try: item = self.get(pk=group_id) except MapMoveGroup.DoesNotExist: logging.warning('MapMoveGroup not found. ID:%s' % str(group_id)) return None cache.set(key, pickle.dumps(item)) return item
def __init__(self, engine): self.engine = engine if self.engine.source == 'fb': from django.contrib.auth.models import User try: self.profile = UserProfile.objects.get(fb_id=self.engine.request.facebook.uid) except UserProfile.DoesNotExist: profile = UserProfile() profile.user = User.objects.create_user("fb_%s" % self.engine.request.facebook.uid, "*****@*****.**" % self.engine.request.facebook.uid, User.objects.make_random_password(length=10, allowed_chars='abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')) profile.username = "******" % self.engine.request.facebook.uid profile.fb_id = self.engine.request.facebook.uid profile.save() self.profile = profile # extra actions self.profile.add_log(log_type='register', log_type_id=self.profile.user.id, log='from facebook', ip=self.engine.request.META.get('REMOTE_ADDR')) else: self.profile = UserProfile.objects.get_by_id(self.engine.request.user.id) if self.profile is None: from django.contrib.auth import logout logout(self.engine.request) self.user = self.profile.user # username bug workaround if self.profile.username == '': self.profile.username = self.user.username self.profile.save() logging.warning('fixed username of %s' % self.user.username) self.SKILL = { 'driving': _('Driving'), 'shooting': _('Shooting'), 'stealing': _('Stealing'), 'security_breaking': _('Security breaking'), 'negotiating': _('Negotiating'), 'marketing': _('Marketing'), 'business': _('Business running'), 'smuggling': _('Smuggling'), 'hacking': _('Hacking'), 'natural_resources': _('Natural resource management'), }
def block_money(self, amount): if amount <= 0: logging.warning("%s: tried to block <= 0 amount" % (self.engine.user.user)) self.engine.log.message(message=_("You highest offer is higher")) return False if self.engine.user.profile.has_enough('cash', amount): self.engine.user.profile.cash -= amount self.engine.user.profile.save() logging.debug("%s: blocked $%d for auction" % (self.engine.user.user, amount)) return True self.engine.log.message(message=_("Not enough cash")) return False
def remove_per_day(self, source, source_id): """Usuwa wpis z tabeli z dziennymi zarobkami/wydatkami""" try: UserPerDay.objects.filter(user=self.user, source=source, source_id=source_id)[0].delete() except UserPerDay.DoesNotExist: logging.warning( "Nie udalo sie usunac pay-per-day z paremetrami: user_id:%s, source:%s, source_id:%s" % (self.user.id, source, source_id) ) except IndexError: logging.warning( "Nie udalo sie usunac pay-per-day z paremetrami: user_id:%s, source:%s, source_id:%s" % (self.user.id, source, source_id) )
def get_by_id(self, hooker_id): key = 'hooker_%s' % hooker_id hooker = cache.get(key) if hooker is not None: return pickle.loads(str(hooker)) try: hooker = self.get(pk=hooker_id) except Hooker.DoesNotExist: logging.warning('Hooker not found. ID:%s' % str(hooker_id)) return None cache.set(key, pickle.dumps(hooker)) return hooker
def rem_unit(self, id, cnt=1): units = self.units try: if units[str(id)] <= 0 or units[str(id)] < cnt: raise ValueError units[str(id)] -= cnt except (KeyError, ValueError): logging.warning('Failed to remove unit_id:%s (city:%s, user:%s)' % (str(id), self.city_id, self.user)) return False if units[str(id)] == 0: del units[str(id)] self.unit = json.dumps(units) self.save() logging.debug('rem_unit id:%s, city:%s, user:%s' % (id, self.city_id, self.user)) return True
def get_by_id(self, item_id): key = 'item_%s' % item_id item = cache.get(key) if item is not None: return pickle.loads(str(item)) try: item = self.get(pk=item_id) except Item.DoesNotExist: logging.warning('Item not found. ID:%s' % str(item_id)) return None cache.set(key, pickle.dumps(item)) return item
def get_by_type(self, type, source='main'): key = 'product_%s_price_%s' % (type, source) item = cache.get(key) if item is not None: return pickle.loads(str(item)) try: item = self.get(type=type, source=source) except ProductPrice.DoesNotExist: logging.warning('ProductPrice not found. TYPE:%s' % str(type)) return None cache.set(key, pickle.dumps(item)) return item
def give_item(self, profile): auction_details = json.loads(self.auction.details) if auction_details['product_type'] != 'car': logging.warning("give item / product type: %s" % auction_details['product_type']) return False car = Item.objects.get_by_id(auction_details['product_id']) if car is None: logging.warning("give item / unknown car with id: %s" % auction_details['product_id']) return False garage = Garage.objects.get_by_user(user=profile.user) garage.buy_item(car.id) profile.next_total_recalc = True profile.save() return True
def produce_item(self, type, name, amount): try: item = self.all_product[type][name] except KeyError: logging.warning("Product with TYPE=%s and NAME=%s NOT FOUND" % (str(type), str(name))) return try: amount = int(amount) price = int(item.base_price) # * level speed = int(item.base_speed) # * level except ValueError: logging.warning("One of provided values incorrect") return # if len(self.city_unit_progress.units) >= self.engine.settings.MAX_SECURITY_BUILD_QUEUE: # self.engine.log.message(message=_('Maximum length of the queue reached')) # return if not self.engine.user.profile.has_enough('cash', price * amount): self.engine.log.message(message=_('Not enough cash')) return if len(self.city_product_progress.items) == 0: self.city_product_progress.item = "[[\"%s\",\"%s\",%d,%d]]" % ( str(item.type), str(item.name), amount, int(time.time()) + speed * amount) self.city_product_progress.next_at = datetime.datetime.fromtimestamp(int(time.time()) + speed * amount) else: last_item = self.city_product_progress.items.pop() if last_item[2] < int(time.time()): last_item[2] = int(time.time()) self.city_product_progress.item = self.city_product_progress.item[:-2] + "],[\"%s\",\"%s\",%d,%d]]" % ( str(item.type), str(item.name), int(amount), int(last_item[2]) + speed * amount) self.engine.user.profile.spend('cash', price * amount) self.city_product_progress.save() self.engine.log.message(message=_("Production started"))
def get_by_name(self, bonus_name): key = "bonus_name_%s" % str(bonus_name) all_bonuses = cache.get(key) if all_bonuses is not None: all_bonuses = pickle.loads(str(all_bonuses)) try: return all_bonuses[str(bonus_name)] except KeyError: logging.warning("Bonus not found. Name:%s" % str(bonus_name)) return None all_bonuses = {} for bonus in Bonus.objects.all(): all_bonuses[str(bonus.name)] = bonus cache.set(key, pickle.dumps(all_bonuses)) try: return all_bonuses[str(bonus_name)] except KeyError: logging.warning("Bonus not found. Name:%s" % str(bonus_name)) return None
def bid(self, item_id, amount): # Validation try: auction_id = int(item_id) amount = int(amount) except KeyError: return None except ValueError: return None except TypeError: return None if self.get_auction(auction_id) is None: return None # Too old auction? if datetime.datetime.now() > self.auction.end_at: self.engine.log.message(message=_("Auction ended")) return False # Your auction? if self.auction.seller == self.engine.user.user: self.engine.log.message(message=_("Can't bid on your auction of course :)")) return False # Less then curren_price? if amount <= self.auction.current_price: self.engine.log.message( message=_("Offer more than $%(amount)d") % {'amount': int(self.auction.current_price)}) return None # Have space in the garage? if self.engine.user.profile.max_cars == len(Garage.objects.get_by_user(user=self.engine.user.user).items): self.engine.log.message(message=_("No space left in the garage. Other your cars will park on the street.")) # Highest offer? if len(self.bids) == 0: if self.get_bid(self.auction.start_price, amount) is not False: self._outbid(self.auction.start_price) return True return False highest_bid = self.bids[0] # Podnies wlasny udzial if highest_bid.buyer == self.engine.user.user: if self.block_money(amount - highest_bid.max_price) is not False: highest_bid.max_price = amount highest_bid.save() self.engine.log.message( message=_("Your current maximum offer is %(max)d") % {'max': highest_bid.max_price}) return True return False # Automatycznie podbicie if amount > highest_bid.price and amount <= highest_bid.max_price: if self.get_bid(amount, amount) is False: return False if amount == highest_bid.max_price: highest_bid.price = highest_bid.max_price highest_bid.save() else: highest_bid.price = amount + 1 highest_bid.save() self.my_offer.price = amount self.my_offer.max_price = amount self.my_offer.save() self.auction.current_price = highest_bid.price self.auction.save() self.engine.log.message(message=_("You have been outbidded")) return True # Przebijam if amount > highest_bid.max_price: if self.get_bid(amount, amount) is False: return False highest_bid.price = highest_bid.max_price highest_bid.save() self.my_offer.price = highest_bid.max_price + 1 self.my_offer.max_price = amount self.my_offer.save() self.auction.current_price = self.my_offer.price self.auction.save() self.engine.log.message(message=_("Your offer is currently the highest")) if highest_bid.buyer != self.my_offer.buyer: self.engine.stream.post('auction_outbid', title_replace='%s' % self.auction.title, user=highest_bid.buyer) return True logging.warning("Unknown bid option") return False
def move_units(self, post): from crims.city.models import MapMove, MapMoveGroup # Queue limitation check current_queue = MapMove.objects.get_by_user(user=self.engine.user.user) if self.engine.user.profile.is_premium: limit = settings.MAP_MOVE_QUEUE_LIMIT_PREMIUM else: limit = settings.MAP_MOVE_QUEUE_LIMIT if len(current_queue.units) >= limit: self.engine.log.message(message=_('Limit of moving units is %d' % limit)) return # Start city validation try: s_city_id = int(post['city_id']) except (ValueError, KeyError): logging.warning('Start city id:%s is not valid integer' % str(post['city_id'])) self.engine.log.message(message=_('Request is invalid')) return s_city = CityMap.objects.get_by_id(s_city_id) if s_city is None: logging.warning('Start city is not valid with ID:%d' % s_city_id) self.engine.log.message(message=_('Request is invalid')) return e_city = CityMap.objects.get_by_id(self.id) # Units validation try: req_units = {} for k, v in post.items(): if k.find('unit_') != 0 or int(v) <= 0: continue req_units[int(k.replace('unit_', ''))] = int(v) except ValueError: logging.warning('POST is not valid') self.engine.log.message(message=_('Request is invalid')) return if len(req_units) == 0: self.engine.log.message(message=_('No unit selected')) return # Validate if user has units of each kind city_units = self.get_units(city_id=s_city_id) my_units = city_units.units for k, v in req_units.iteritems(): if not my_units.has_key(str(k)) or int(my_units[str(k)]) < int(v): self.engine.log.message(message=_('Has not enough units to select')) return # MOVE... from crims.common.helpers._crims import calc_route transport_type = 'default' # TODO: wprowadzic pozniej inne arrival_date = int(time.time() + int( calc_route(s_city.sector, s_city.position, e_city.sector, e_city.position) * 60.0 * settings.MOVE_TIME_PER_KM[transport_type])) # Take units for unit_id, unit_amount in req_units.iteritems(): my_units[str(unit_id)] -= int(unit_amount) if my_units[str(unit_id)] == 0: del my_units[str(unit_id)] city_units.unit = json.dumps(my_units) city_units.save() # Make a move mvg = MapMoveGroup() mvg.unit = json.dumps(req_units) mvg.save() current_units = current_queue.units if len(current_units) == 0: current_queue.next_at = datetime.datetime.fromtimestamp(arrival_date) else: current_queue.next_at = datetime.datetime.fromtimestamp(min([x[3] for x in current_queue.units])) current_units.append([s_city_id, self.id, mvg.id, arrival_date]) current_queue.unit = json.dumps(current_units) current_queue.save() self.engine.log.message(message=_('Units are moving')) return True