def admin_user(_id): user = api('/user/%s' % _id) trades = api('/trade?user=%s' % _id) for trade in trades: trade['user'] = user ledger = api('/ledger?user=%s' % _id) return render_template('admin/user.html', u=user, trades=trades, ledger=ledger)
def item(class_id, instance_id): # TODO: app, ctxid? don't know if class/instance are unique or not item = api('/item/%s/%s' % (class_id, instance_id)) if item: has = False name = base64.b64encode(item['name'].encode('utf8')) if g.user: has = api('/user/{}/inventory/{}/{}/has'.format( g.user['_id'], item['app_id'], name)) item['total'] = item.get('available', 0) for var in item.get('variants', []): item['total'] += var.get('available', 0) g.set_context((item['app_id'], item['context_id'])) has_game = False if g.context == 'games': app = g.steam_app = api('/steam/app', name=name) if g.user and app: games = g.user.get('games', []) has_game = any(str(a['appid']) == str(app['app_id']) for a in games) return render_template( 'item.html', item=item, steam_app=g.steam_app, has_item=has, has_game=has_game, ) else: return redirect('/', code=302)
def admin_users(): search = request.args.get('q') if search: users = api('/user', search=search) else: users = api('/user') return render_template('admin/users.html', users=users, search=search)
def __init__(self, addr, ssloptions=None, craftanchor="/p/", staticdir=None, anchors=None, sizelimit=None, noweb=False, nocraft=False, noapi=False, nohang=False, timeout=None, logreq=False, logresp=False, hexdump=False): """ addr: (address, port) tuple. If port is 0, a free port will be automatically chosen. ssloptions: a dictionary containing certfile and keyfile specifications. craftanchor: string specifying the path under which to anchor response generation. staticdir: path to a directory of static resources, or None. anchors: A list of (regex, spec) tuples, or None. sizelimit: Limit size of served data. nocraft: Disable response crafting. noapi: Disable the API. nohang: Disable pauses. """ tcp.TCPServer.__init__(self, addr) self.ssloptions = ssloptions self.staticdir = staticdir self.craftanchor = craftanchor self.sizelimit = sizelimit self.noweb, self.nocraft, self.noapi, self.nohang = noweb, nocraft, noapi, nohang self.timeout, self.logreq, self.logresp, self.hexdump = timeout, logreq, logresp, hexdump if not noapi: app.api() self.app = app.app self.app.config["pathod"] = self self.log = [] self.logid = 0 self.anchors = [] if anchors: for i in anchors: try: arex = re.compile(i[0]) except re.error: raise PathodError("Invalid regex in anchor: %s" % i[0]) try: aresp = rparse.parse_response(self.request_settings, i[1]) except rparse.ParseException, v: raise PathodError("Invalid page spec in anchor: '%s', %s" % (i[1], str(v))) self.anchors.append((arex, i[1]))
def recent_items(): kwargs = {} if g.app: kwargs['app_id'], kwargs['context_id'] = g.app new_items = api('/item', limit=20, instock=1, fields='catalog', **kwargs) recent, _ = unique_items(new_items) recent = list(reversed(sorted(recent, key=lambda i: i['timestamp'])[-6:])) if not g.context or g.context == 'dota': key = api('/item/keys', limit=1, instock=1) if key: recent = key + recent[:-1] return recent
def __init__( self, addr, ssl=False, ssloptions=None, craftanchor="/p/", staticdir=None, anchors=None, sizelimit=None, noweb=False, nocraft=False, noapi=False, nohang=False, timeout=None, logreq=False, logresp=False, explain=False, hexdump=False ): """ addr: (address, port) tuple. If port is 0, a free port will be automatically chosen. ssloptions: a dictionary containing certfile and keyfile specifications. craftanchor: string specifying the path under which to anchor response generation. staticdir: path to a directory of static resources, or None. anchors: A list of (regex, spec) tuples, or None. sizelimit: Limit size of served data. nocraft: Disable response crafting. noapi: Disable the API. nohang: Disable pauses. """ tcp.TCPServer.__init__(self, addr) self.ssl = ssl self.ssloptions = ssloptions or SSLOptions() self.staticdir = staticdir self.craftanchor = craftanchor self.sizelimit = sizelimit self.noweb, self.nocraft, self.noapi, self.nohang = noweb, nocraft, noapi, nohang self.timeout, self.logreq, self.logresp, self.hexdump = timeout, logreq, logresp, hexdump self.explain = explain if not noapi: app.api() self.app = app.app self.app.config["pathod"] = self self.log = [] self.logid = 0 self.anchors = [] if anchors: for i in anchors: try: arex = re.compile(i[0]) except re.error: raise PathodError("Invalid regex in anchor: %s"%i[0]) try: aresp = language.parse_response(self.request_settings, i[1]) except language.ParseException, v: raise PathodError("Invalid page spec in anchor: '%s', %s"%(i[1], str(v))) self.anchors.append((arex, i[1]))
def admin_bots(): bots = api('/bot', short=1) total = 0 traders = [bot for bot in bots if bot.get('trader')] # TODO: some bots might have more or less than 640 slots capacity = len(traders) * 640 for bot in traders: total += bot.get('item_count', 0) return render_template('admin/bots.html', bots=bots, total=total, capacity=capacity)
def enum_admin_items(pricing=False): items = api('/item', need_id=1, overstock=0) worth = 0 total = 0 if items: amounts = defaultdict(int) for item in items: amounts[item['name']] += item['amount'] item_set = {} for item in items: name = item['name'] if pricing and name in item_set: continue amount = amounts[name] price = item.get('price', 0) buy_price = item.get('buy_price', 0) item['hot_price'] = prices.hot_price( item['app_id'], item['context_id'], name, price, amount_matters=False, ) item['hot_buy_price'] = min( prices.hot_price( item['app_id'], item['context_id'], name, buy_price, amount, ), int(math.floor(item['hot_price'] * 0.95)) ) item['hot_buy_percent'] = 100 * round( float(item['hot_buy_price']) / (item['hot_price'] or 1), 3) item['hotness'] = round( item['hot_price'] / (float(item['price']) or 1), 2) if pricing: item['amount'] = amount item_set[name] = item total += amount worth += item['hot_price'] * amount else: total += item['amount'] worth += item['hot_price'] * item['amount'] if pricing: items = sorted(item_set.values(), key=lambda i: (i.get('hotness'), i.get('name'))) else: items.sort(key=lambda i: (i.get('amount'), i.get('name'))) items = list(reversed(items)) return worth, total, items
def fetch_user(): path = request.path if path.startswith(('/static/', '/ajax/pub/', '/favicon.ico')): return g.user = None steamid = session.get('steamid') if 'openid' in session and steamid is None: ip = request.headers.get('X-Forwarded-For', request.remote_addr) g.user = api('/user/login', openid=True, ip=ip) if g.user: session['steamid'] = g.user.get('profile', {}).get('steamid') elif steamid is not None: g.user = api('/user/steam/{0}'.format(steamid)) if g.user: ban = g.user.get('ban') if not ban and g.user.get('steamrep') == 'scammer' and not g.user.get('buy_only'): ban = g.user['ban'] = {'reason': 'SteamRep scammer'} if request.path != '/banned': if ban: return redirect('/banned')
def search(): search = request.args.get('q') if search: # block potential varnish-busting ddos by not letting unauthed search if not g.user: return redirect('/', code=302) elif search.isdigit(): return abort(404) s = base64.b64encode(search.encode('utf8')) items = api('/item/search/%s?instock=1' % s) return render_items(items, search=search) else: return redirect('/', code=302)
def admin_bot_history(_id): bot = api('/bot/%s' % _id) url = bot.get('custom_url', 'http://steamcommunity.com/profiles/{}/'.format(bot['steamid'])) url += 'inventoryhistory' if request.query_string: url += '?' + request.query_string user_agent = ( 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; ' 'Valve Steam Client/2026; )' 'AppleWebKit/535.15 (KHTML, like Gecko) Chrome/18.0.989.0 Safari/535.11' ) headers = {'Accept-Encoding': 'identity', 'User-Agent': user_agent} cookies = bot['cookies'] response = requests.get(url, headers=headers, cookies=cookies) return response.content, response.status_code
def template_context(): if request.path.startswith('/ajax/pub'): return {} elif request.path.startswith('/ajax/user'): return { 'csrf_token': generate_csrf_token, 'user': g.user, } return { 'app': app, 'csrf_token': generate_csrf_token, 'recent': recent_items(), 'request': request, 'stats': api('/trade/stats'), 'user': g.user, }
def items(hero=None, category=None): search = request.args.get('search') if search: # block potential varnish-busting ddos by not letting unauthed search if not g.user: return redirect('/', code=302) elif search.isdigit(): return abort(404) items = api('/item/search/%s?instock=1' % urllib.quote_plus(search)) elif hero: category = hero items = api('/item/hero/%s' % urllib.quote_plus(hero)) elif category: kwargs = {} if g.context == 'dota': if category == 'Courier': kwargs['instock'] = 1 if category == 'Treasure Key': items = api('/item/keys') else: items = api('/item/{}/{}/type/{}'.format(*(g.app + (urllib.quote_plus(category),))), **kwargs) if category == 'Tool': items = [i for i in items if not 'Key' in i['name']] else: if g.context in ('games', 'misc'): kwargs['instock'] = 1 items = api('/item/{}/{}/type/{}'.format(*(g.app + (category,))), **kwargs) elif request.path == '/dota': heroes = api('/item/hero') categories = api('/item/570/2/types') categories = [c for c in categories if c['name']] return render_template('categories.html', heroes=heroes, categories=categories) else: categories = api('/item/{}/{}/types'.format(*g.app)) categories = [c for c in categories if c['name']] if g.context == 'games': categories.append({'name': 'Sellable', 'solo': True}) return render_template('categories.html', categories=categories, title=g.app_name) return render_items(items, category=category)
def admin_trade_fail(_id): api('/trade/%s/update' % _id, data={'success': False}) return redirect('/admin/trade/%s' % _id)
def admin_bot(_id): bot = api('/bot/%s' % _id) return render_template('admin/bot.html', bot=bot)
def register_root_api(api): api = api() for method, value in api.methods.items(): app.add_url_rule('/%s' % method, view_func=getattr(api, method))
def admin_user_credit(_id): amount = request.form.get('amount', 0) if amount > 0: api('/user/%s/credit' % _id, data={'amount': int(amount)}) return redirect('/admin/user/%s' % _id)
def admin_item(_id): item = api('/item/%s' % _id) return render_template('admin/item.html', item=item)
def admin_transaction(_id): transaction = api('/ledger/%s' % _id) return render_template('/admin/transaction.html', transaction=transaction)
def admin_ledger(): ledger = api('/ledger') return render_template('/admin/ledger.html', ledger=ledger)
def create_or_login(resp): session['openid'] = resp.identity_url g.user = api('/user/login') return redirect(oid.get_next_url())
def admin_trade(_id): trade = api('/trade/%s' % _id) return render_template('admin/trade.html', trade=trade)
def admin_trades(): trades = api('/trade?limit=10000') return render_template('admin/trades.html', trades=trades)
def admin_trade_receive(_id, transaction): api('/trade/%s/receive/%s' % (_id, transaction - 1)) return redirect('/admin/trade/%s' % _id)