index int64 | repo_name string | branch_name string | path string | content string | import_graph string |
|---|---|---|---|---|---|
71,936 | usrlocalben/justified | refs/heads/master | /justified/__init__.py | from __future__ import absolute_import
from .justified import *
__version__ = '0.1.0'
| {"/justified/__init__.py": ["/justified/justified.py"]} |
71,976 | topdevman/flask-betg | refs/heads/master | /v1/signals_definitions.py | from flask import signals
# TODO: clean up mess with namings and app definition
from v1.main import db
from v1.badges import BADGES
badges_namespace = signals.Namespace()
general_one_time_badge_signal = badges_namespace.signal("general_one_time_badge_signal")
game_badge_signal = badges_namespace.signal("game_badge_signal") # count and one_time
@general_one_time_badge_signal.connect
def update_general_one_time_badge(player, badge_id, **extra):
"""Use this for single non game actions
if you now exactly badge name for some event"""
player_badges = player.get_badges(badge_id)
badge = getattr(player_badges, badge_id)
if badge["received"]:
return True
badge["received"] = True
player_badges.update_for_notifications(badge_id)
db.session.flush()
return True
@game_badge_signal.connect
def update_games_badges(game, **extra):
"""Signal handler for games badges"""
# FIXME: replace "-" on "_" in gametypes in pollers, required for column naming
gametype = game.gametype.replace("-", "_")
creator_badges, badges_ids_with_groups = game.creator.get_badges_from_groups(
gametype, "games_general_count", "games_general_one_time",
return_ids=True
)
opponent_badges = game.opponent.get_badges_from_groups(
gametype, "games_general_count", "games_general_one_time"
)
def update_badge(user_badge: dict, badge_id: str, group: str, creator: bool):
if user_badge["received"]:
return False
badge_desc = BADGES[group][badge_id]
if badge_desc["type"] == "one_time":
one_time_type = badge_desc["one_time_type"]
if game.winner == "creator":
if one_time_type == "win" and creator:
user_badge["received"] = True
elif one_time_type == "loss" and not creator:
user_badge["received"] = True
elif game.winner == "opponent":
if one_time_type == "win" and not creator:
user_badge["received"] = True
elif one_time_type == "loss" and creator:
user_badge["received"] = True
elif game.winner == "draw" and one_time_type == "draw":
user_badge["received"] = True
return user_badge["received"]
elif badge_desc["type"] == "count":
init_value = user_badge["value"]
count_type = badge_desc["count_type"]
if count_type == "all":
user_badge["value"] += 1
else:
if game.winner == "creator":
if count_type == "win" and creator:
user_badge["value"] += 1
elif count_type == "loss" and not creator:
user_badge["value"] += 1
elif game.winner == "opponent":
if count_type == "win" and not creator:
user_badge["value"] += 1
elif count_type == "loss" and creator:
user_badge["value"] += 1
elif game.winner == "draw" and count_type == "draw":
user_badge["value"] += 1
if badge_desc["max_value"] == user_badge["value"]:
user_badge["received"] = True
return user_badge["received"] or init_value != user_badge["value"]
creator_updated_badges = []
opponent_updated_badges = []
for badge_id, group in badges_ids_with_groups:
if update_badge(getattr(creator_badges, badge_id), badge_id, group, True):
creator_updated_badges.append(badge_id)
if update_badge(getattr(opponent_badges, badge_id), badge_id, group, False):
opponent_updated_badges.append(badge_id)
if creator_updated_badges:
creator_badges.update_for_notifications(*creator_updated_badges)
if opponent_updated_badges:
opponent_badges.update_for_notifications(*opponent_updated_badges)
db.session.flush()
return True
| {"/v1/signals_definitions.py": ["/v1/main.py", "/v1/badges/__init__.py"], "/v1/polling.py": ["/config.py", "/v1/helpers.py", "/v1/models.py", "/v1/apis.py", "/v1/common.py"], "/v1/badges/__init__.py": ["/v1/badges/badges_description.py", "/v1/badges/fifa15.py"], "/v1/apis.py": ["/config.py", "/v1/helpers.py", "/v1/mock.py"], "/v1/__init__.py": ["/v1/main.py"], "/mobsite.py": ["/config.py"], "/v1/badges/fifa15.py": ["/v1/main.py", "/v1/badges/badges_description.py"], "/v1/helpers.py": ["/config.py", "/v1/models.py", "/v1/main.py", "/v1/common.py", "/v1/apis.py", "/v1/__init__.py"], "/v1/models.py": ["/v1/main.py", "/v1/common.py", "/v1/badges/__init__.py", "/config.py", "/v1/helpers.py", "/v1/routes.py", "/v1/polling.py"], "/poll.py": ["/main.py", "/v1/__init__.py"], "/v1/cas.py": ["/config.py", "/v1/main.py", "/v1/apis.py", "/v1/models.py", "/v1/common.py"], "/debug_console.py": ["/main.py", "/v1/models.py", "/v1/helpers.py", "/v1/routes.py"], "/v1/routes.py": ["/config.py", "/v1/signals_definitions.py", "/v1/models.py", "/v1/helpers.py", "/v1/apis.py", "/v1/polling.py", "/v1/main.py"], "/main.py": ["/config.py", "/v1/__init__.py", "/v1/main.py", "/v1/models.py"], "/v1/main.py": ["/config.py", "/v1/__init__.py", "/v1/admin.py"], "/v1/admin.py": ["/v1/models.py", "/v1/polling.py", "/v1/helpers.py"], "/observer.py": ["/config.py", "/v1/polling.py", "/v1/models.py", "/v1/apis.py"]} |
71,977 | topdevman/flask-betg | refs/heads/master | /v1/polling.py | #!/usr/bin/env python3
import sys, os
from datetime import datetime, timedelta
from types import SimpleNamespace
import math
from collections import namedtuple
from functools import lru_cache
from html.parser import HTMLParser
from urllib.parse import quote
import requests
from dateutil.parser import parse as date_parse
if __name__ == '__main__':
# debugging environment; other changes are in the bottom
from apis import *
from mock import log, config, dummyfunc, db
from common import *
ROOT = '.'
try:
sys.path.append('..')
import config as config_module
for p in dir(config_module):
setattr(config, p, getattr(config_module, p))
except ImportError:
pass
else:
# live environment
import config
from .helpers import notify_users, notify_event
from .models import *
from .apis import *
from .common import *
ROOT = os.path.dirname(__file__)+'/../'
class Identity(namedtuple('Identity', 'id name checker choices formatter')):
# Formatter is needed for identities which use non-readable format
# like Steam ID.
# In pair with corresponding checker, it allows to store
# both machine-readable and human-readable values.
_all = {}
def __new__(cls, id, name, checker, choices=None, formatter=None):
if not checker:
checker = lambda val: val
ret = super().__new__(cls, id, name, checker, choices,
formatter or (lambda val: (val, str(val))))
cls._all[id] = ret
return ret
@classmethod
def get(cls, id):
return cls._all.get(id)
@classproperty
def all(cls):
return cls._all.values()
Identity('riot_summonerName', 'Riot Summoner Name ("name" or "region/name")',
Riot.summoner_check)
Identity('steam_id','STEAM ID (numeric, URL or nickname)', Steam.pretty_id,
formatter = lambda x: Steam.split_identity(x)[1])
Identity('starcraft_uid','StarCraft profile URL from battle.net or sc2ranks.com',
StarCraft.check_uid)
# ea_gamertag, fifa_team, tibia_character - will be added in classes
### Polling ###
class Poller:
gametypes = {} # list of supported types for this class
gamemodes_primary = {}
gamemodes_ingame = {}
usemodes = False # do we need to init again for each mode?
sameregion = False # do we need to ensure region is the same for both gamertags
# region is stored as slash delimited prefix of gamertag.
twitch = 0 # do we support twitch for this gametype?
# 0 - not supported, 1 - optional, 2 - mandatory
twitch_gametypes = {}
identity_id = None
twitch_identity_id = None
honesty = False # special for honesty-based poller
# human-readable description of how to play this game.
# Might be dictionary if description should vary
# for different gametypes in same poller.
description = None
subtitle = None
category = None
minutes = 0 # by default, poll as often as possible
# List of tuples (creator, opponent, gamemode, startdate, winner).
# For each of these tuples there should exist finished game
# with specified result.
tests = []
@classproperty
def identity(cls):
return Identity.get(cls.identity_id)
@classproperty
def identity_name(cls):
return cls.identity.name if cls.identity else None
@classproperty
def identity_check(cls):
return cls.identity.checker if cls.identity else lambda val: val
@classproperty
def twitch_identity(cls):
return Identity.get(cls.twitch_identity_id)
@classmethod
@lru_cache()
def findPoller(cls, gametype):
"""
Tries to find poller class for given gametype.
Returns None on failure.
"""
if gametype in cls.gametypes:
return cls
for sub in cls.__subclasses__():
ret = sub.findPoller(gametype)
if ret:
return ret
@classmethod
def allPollers(cls):
yield cls
for sub in cls.__subclasses__():
yield from sub.allPollers()
@classproperty
def gamemodes(cls):
ret = {}
ret.update(cls.gamemodes_ingame)
ret.update(cls.gamemodes_primary)
return ret
@classproperty
def all_gametypes(cls):
types = set(cls.gametypes)
for sub in cls.__subclasses__():
types.update(sub.all_gametypes)
return types
@classproperty
def all_gamemodes(cls):
modes = set(cls.gamemodes)
for sub in cls.__subclasses__():
modes.update(sub.all_gamemodes)
return modes
@classmethod
def gameStarted(cls, game):
"""
This will be called once game invitation is accepted for this gametype.
Default implementation does nothing,
but subclass may want to save some information about current game state
in the passed game object.
This method may be called more than once for single game,
but game will be actually started only after the last call.
Please don't save current time in this method,
instead you can use game.date_accepted field
which shall hold the most relevant value.
"""
pass
def games(self, gametype, gamemode=None):
ret = Game.query.filter_by(
gametype = gametype,
state = 'accepted',
)
if gamemode:
ret = ret.filter_by(
gamemode = gamemode,
)
return ret
def poll(self, now, gametype=None, gamemode=None):
if not gametype:
for gametype in self.gametypes:
if not self.usemodes:
self.prepare()
self.poll(now, gametype)
return
if self.usemodes and not gamemode:
for gamemode in self.gamemodes:
self.prepare()
self.poll(now, gametype, gamemode)
return
query = self.games(gametype, gamemode)
count_games = query.count()
count_ended = 0
log.debug('{}: polling {} games of type {} {}'.format(
self.__class__.__name__,
count_games,
gametype, gamemode
))
hourly = now.minute % 60 == 0
for game in query:
if not hourly and now - game.accept_date > timedelta(hours=12):
log.info('Skipping game {} because it is long-lasting'
.format(game))
continue
try:
if self.pollGame(game):
count_ended += 1
except Exception:
log.exception('Failed to poll game {}'.format(game))
db.session.commit()
log.debug('Polling done, finished {} of {} games'.format(
count_ended, count_games,
))
@classmethod
def gameDone(cls, game, winner, timestamp=None, details=None):
"""
Mark the game as done, setting all needed fields.
Winner is a string.
Timestamp is in seconds, or it can be datetime object, or None for now.
Returns True for convenience (`return self.gameDone(...)`).
"""
log.debug('Marking game {} as done'.format(game))
if winner == 'aborted':
game.winner = 'draw'
game.state = 'aborted'
else:
game.winner = winner
game.state = 'finished'
game.details = details
if not timestamp:
game.finish_date = datetime.utcnow()
elif isinstance(timestamp, datetime):
game.finish_date = timestamp
else:
game.finish_date = datetime.utcfromtimestamp(timestamp)
db.session.commit() # to avoid observer overwriting it before us..
# move funds (only if somebody won)
if winner in ['creator', 'opponent']:
if winner == 'creator':
winner = game.creator
looser = game.opponent
elif winner == 'opponent':
winner = game.opponent
looser = game.creator
winner.balance += game.bet
looser.balance -= game.bet
db.session.add(Transaction(
player = winner,
type = 'won',
sum = game.bet,
balance = winner.balance,
game = game,
))
db.session.add(Transaction(
player = looser,
type = 'lost',
sum = -game.bet,
balance = looser.balance,
game = game,
))
# and unlock bets (always)
# withdrawing them finally from accounts
game.creator.locked -= game.bet
game.opponent.locked -= game.bet
db.session.commit()
notify_users(game)
# cancel stream watcher (if any)
if game.twitch_handle:
try:
ret = requests.delete(
'{}/streams/{}/{}'.format(
config.OBSERVER_URL,
game.twitch_handle,
game.gametype,
),
)
log.info('Deleting watcher: %d' % ret.status_code)
except Exception:
log.exception('Failed to delete watcher')
return True # for convenience
@classmethod
def gameEvent(cls, game, text):
"""
Broadcast notification about game event to game session
"""
return notify_event(
game.root, 'system',
game = game,
text = text,
)
def prepare(self):
"""
Prepare self for new polling, clear all caches.
"""
pass
def pollGame(self, game):
"""
Shall be overriden by subclasses.
Returns True if given game was successfully processed.
"""
raise NotImplementedError
class FifaPoller(Poller, LimitedApi):
gametypes = {
'fifa14-xboxone': 'FIFA14',
'fifa15-xboxone': 'FIFA15',
}
gamemodes = {
'fifaSeasons': 'FIFA Seasons',
'futSeasons': 'FUT Online Seasons',
'fut': 'FUT',
'friendlies': 'Friendlies',
'coop': 'Co-op',
}
subtitle = {
'fifa14-xboxone': '14',
'fifa15-xboxone': '15',
'fifa16-xboxone': '16',
}
category = 'Sport'
identity_id = 'ea_gamertag'
twitch_identity_id = 'fifa_team'
usemodes = True
twitch = 2
twitch_gametypes = {
'fifa14-xboxone': 'FIFA 14',
'fifa15-xboxone': 'FIFA 15',
'fifa16-xboxone': 'FIFA 16',
}
minutes = 30 # poll at most each 30 minutes
gamertag_cache = {}
def gamertag_checker(nick):
# don't use @classmethod
# because they will not work until class is fully defined
cls = FifaPoller
if nick.lower() in cls.gamertag_cache:
if cls.gamertag_cache[nick.lower()]:
return cls.gamertag_cache[nick.lower()]
raise ValueError('Unknown gamertag: '+nick)
url = 'https://www.easports.com/fifa/api/'\
'fifa15-xboxone/match-history/friendlies/{}'.format(quote(nick))
try:
# FIXME
# EA Sports is now almost down, so don't validate gamertag
return nick
# FIXME
ret = requests.get(url)
if ret.status_code == 404:
# don't cache not-registered nicks as they can appear in future
#cls.gamertag_cache[nick.lower()] = None
raise ValueError(
'Gamertag {} seems to be unknown '
'for FIFA game servers'.format(nick))
data = ret.json()['data']
# normalized gamertag (with correct capitalizing)
# if no data then cannot know correct capitalizing; return as is
goodnick = data[0]['self']['user_info'][0] if data else nick
cls.gamertag_cache[nick.lower()] = goodnick
return goodnick
except ValueError:
log.warning('json error: '+str(ret))
if getattr(g, 'gamertag_force', False):
return nick
raise
except Exception as e: # json failure or missing key
log.error('Failed to validate gamertag '+nick, exc_info=True)
if 'ret' in locals():
log.error(ret)
log.error('Allowing it...')
#raise ValueError('Couldn\'t validate this gamertag: {}'.format(nick))
return nick
with open(ROOT+'/fifa_teams.csv') as teamsfile:
fifa_teams = {
name: abbr for name,abbr in
map(lambda x: x.strip().split(','), teamsfile)
}
def fifa_team_checker(val):
cls = FifaPoller
if len(val) in (2,3):
if val not in cls.fifa_teams:
log.warning('Unknown team id: '+val)
return val
# not 3-char, do reverse lookup
rev = {k.casefold(): v for k, v in cls.fifa_teams.items()}
out = rev.get(val.casefold())
if not out:
raise ValueError('Expected 3-letter team id or known team name, got {}'.format(val))
return out
Identity('ea_gamertag', 'XBox GamerTag', gamertag_checker)
Identity('fifa_team', 'FIFA Team Name', fifa_team_checker,
fifa_teams)
del gamertag_checker
del fifa_team_checker
def prepare(self):
self.gamertags = {}
@classmethod
def fetch(cls, gametype, gamemode, nick):
url = 'https://www.easports.com/fifa/api/'\
'{}/match-history/{}/{}'.format(
gametype, gamemode, quote(nick))
try:
return cls.request_json('GET', url)['data']
except Exception as e:
log.error('Failed to fetch match info '
'for player {}, gt {} gm {}'.format(
nick, gametype, gamemode),
exc_info=False) # XXX disabled
return []
def pollGame(self, game, who=None, matches=None):
if not who:
for who in ['creator', 'opponent']:
tag = getattr(game, 'gamertag_'+who)
if tag in self.gamertags:
return self.pollGame(game, who, self.gamertags[tag])
who = 'creator'
matches = self.fetch(game.gametype, game.gamemode,
game.gamertag_creator)
# and cache it
self.gamertags[game.gamertag_creator] = matches
crea = SimpleNamespace(who='creator')
oppo = SimpleNamespace(who='opponent')
for user in [crea, oppo]:
user.tag = getattr(game, 'gamertag_'+user.who)
# `me` is the `who` player object
me, other = (crea, oppo) if who == 'creator' else (oppo, crea)
me.role = 'self'
other.role = 'opponent'
# now that we have who and matches, try to find corresponding match
for match in reversed(matches): # from oldest to newest
log.debug('match: {} cr {}, op {}'.format(
match['timestamp'], *[
[match[u]['user_info'], match[u]['stats']['score']]
for u in ('self', 'opponent')
]
))
# skip this match if it ended before game's start
if math.floor(game.accept_date.timestamp()) \
> match['timestamp'] + 4*3600: # delta of 4 hours
log.debug('Skipping match because of time')
continue
if other.tag.lower() not in map(
lambda t: t.lower(),
match['opponent']['user_info']
):
log.debug('Skipping match because of participants')
continue
# Now we found the match we want! Handle it and return True
log.debug('Found match! '+str(match))
for user in (crea, oppo):
user.score = match[user.role]['stats']['score']
if crea.score > oppo.score:
winner = 'creator'
elif crea.score < oppo.score:
winner = 'opponent'
else:
winner = 'draw'
self.gameDone(game, winner, match['timestamp'],
'Score: {} - {}'.format(crea.score, oppo.score))
return True
class RiotPoller(Poller):
gametypes = {
'league-of-legends': 'League of Legends',
}
gamemodes = {
'RANKED_SOLO_5x5': 'Solo 5x5',
'RANKED_TEAM_3x3': 'Team 3x3',
'RANKED_TEAM_5x5': 'Team 5x5',
}
subtitle = 'The Game'
category = 'Action'
identity_id = 'riot_summonerName'
sameregion = True
description = """
For this game betting is based on match outcome.
"""
def prepare(self):
self.matches = {}
def pollGame(self, game):
def parseSummoner(val):
region, val = val.split('/', 1)
name, id = val.rsplit('/', 1)
return region, name, int(id)
crea = SimpleNamespace()
oppo = SimpleNamespace()
region, crea.name, crea.sid = parseSummoner(game.gamertag_creator)
region2, oppo.name, oppo.sid = parseSummoner(game.gamertag_opponent)
if region2 != region:
log.error('Invalid game, different regions! id {}'.format(game.id))
# TODO: mark game as invalid?..
return False
def checkMatch(match_ref):
# fetch match details
mid = match_ref['matchId']
if mid in self.matches:
ret = self.matches[mid]
else:
ret = Riot.call(
region,
'v2.2',
'match/'+mid,
)
self.matches[mid] = ret
crea.pid = oppo.pid = None # participant id
for participant in ret['participantIdentities']:
for user in [crea, oppo]:
if participant['player']['summonerId'] == user.sid:
user.pid = participant['participantId']
if not oppo.pid:
# Desired opponent didn't participate this match; skip it
return False
crea.tid = oppo.tid = None
crea.won = oppo.won = None
for participant in ret['participants']:
for user in [crea, oppo]:
if participant['participantId'] == user.pid:
user.tid = participant['teamId']
user.won = participant['stats']['winner']
if crea.tid == oppo.tid:
log.warning('Creator and opponent are in the same team!')
# skip this match
return False
self.gameDone(
game,
'creator' if crea.won else
'opponent' if oppo.won else
'draw',
# creation is in ms, duration is in seconds; convert to seconds
round(ret['matchCreation']/1000) + ret['matchDuration']
)
return True
shift = 0
while True:
ret = Riot.call(
region,
'v2.2',
'matchlist/by-summoner/'+str(crea.sid),
data=dict(
beginTime = game.accept_date.timestamp()*1000, # in ms
beginIndex = shift,
rankedQueues = game.gamemode,
),
)
for match in ret['matches']:
if checkMatch(match):
return True
shift += 20
if shift > ret['totalGames']:
break
class Dota2Poller(Poller):
gametypes = {
'dota2': 'DOTA 2',
}
subtitle = '2'
# no gamemodes for this game
identity_id = 'steam_id'
description = """
For this game betting is based on match outcome.
If both players played for the same fraction (radiant/dire),
game is considered draw.
Else winner is the player whose team won.
"""
def prepare(self):
self.matchlists = {}
def pollGame(self, game):
from_oppo = False
matchlist = self.matchlists.get(game.gamertag_creator_val)
if not matchlist:
matchlist = self.matchlists.get(game.gamertag_opponent_val)
from_oppo = True
if not match:
# TODO: handle pagination
# Match list is sorted by start time descending,
# and 100 matches are returned by default,
# so maybe no need (as we check every 30 minutes)
matchlist = Steam.dota2(
method = 'GetMatchHistory',
account_id = game.gamertag_creator_val, # it is in str, but doesn't matter here
date_min = round(game.accept_date.timestamp()),
).get('matches')
# TODO: merge all matches in cache, index by match id,
# and search players in all matches available -
# this may reduce requests count
if not matchlist:
raise ValueError('Couldn\'t fetch match list for account id {}'
.format(game.gamertag_creator_val))
self.matchlists[game.gamertag_creator_val] = match['matches']
for match in matchlist:
if match['start_time'] < game.accept_date.timestamp:
# this match is too old, subsequent are older -> not found
break
player_ids = (Steam.id_to_64(p['account_id'])
for p in match['players']
if 'account_id' in p)
if int(game.gamertag_creator_val
if from_oppo else
game.gamertag_opponent_val) in player_ids:
# found the right match
# now load its details to determine winner and duration
match = Steam.dota2(
method = 'GetMatchDetails',
match_id = match['match_id'],
)
# TODO: update it in cache?
# determine winner
crea = SimpleNamespace()
oppo = SimpleNamespace()
crea.id, oppo.id = map(int,
[game.gamertag_creator_val,
game.gamertag_opponent_val])
for player in match['players']:
for user in (crea, oppo):
if Steam.id_to_64(player.get('account_id')) == user.id:
user.info = player
for user in (crea, oppo):
if not hasattr(user, 'info'):
raise Exception(
'Unexpected condition: crea or oppo not found.'
'{} {}'.format(
match,
game,
)
)
# according to
# https://wiki.teamfortress.com/wiki/WebAPI/GetMatchDetails#Player_Slot
user.dire = bool(user.info['player_slot'] & 0x80)
user.won = user.dire == (not match['radiant_won'])
if crea.dire == oppo.dire:
# TODO: consider it failure?
winner = 'draw'
else:
winner = 'creator' if crea.won else 'opponent'
return self.gameDone(
game,
winner,
match['start_time'] + match['duration']
)
class CSGOPoller(Poller):
gametypes = {
'counter-strike-global-offensive': 'CounterStrike: Global Offensive',
}
identity_id = 'steam_id'
subtitle = 'Global Offensive'
category = 'Action'
description = """
For this game betting is based on match outcome.
If both players played in the same team, game is considered draw.
Else winner is the player whose team won.
"""
# We cannot determine time of last match,
# so we have to poll current state of both players on game creation.
# Then we wait for state to change for both of them
# and to match (number of rounds, etc).
# FIXME: poll more often!
# Because else last match info may be already overwritten when we poll it.
class Match(namedtuple('Match', [
'wins', 't_wins', 'ct_wins',
'max_players', 'kills', 'deaths',
'mvps', 'damage', 'rounds',
'total_matches_played',
])): # there are some other attributes but they are of no use for us
__slots__ = () # to avoid memory wasting
def __eq__(self, other):
# all of the following properties should match
# to consider two matches equal
return all(map(
lambda attr: getattr(self, attr) == getattr(other, attr),
[ 'rounds', 'max_players', ]
))
@classmethod
def fetch_match(cls, userid):
log.debug('Fetching matches for user id %s'%userid)
ret = Steam.call(
'ISteamUserStats', 'GetUserStatsForGame', 'v0002',
appid=730, # CS:GO
steamid=userid, # not worry whether it string or int
).get('playerstats', {})
stats = {s['name']: s['value'] for s in ret.get('stats', [])}
if not stats:
raise ValueError('No stats available for player %s'%userid)
return cls.Match(*[
stats[stat if stat.startswith('total') else 'last_match_'+stat]
for stat in cls.Match._fields
])
@classmethod
def gameStarted(cls, game):
# store "<crea_total>:<oppo_total>" to know when match was played
game.meta = ':'.join(map(
lambda p: str(cls.fetch_match(p).total_matches_played),
(game.gamertag_creator_val, game.gamertag_opponent_val)
))
def prepare(self):
self.matches = {}
def pollGame(self, game):
crea = SimpleNamespace(tag=game.gamertag_creator_val)
oppo = SimpleNamespace(tag=game.gamertag_opponent_val)
crea.total, oppo.total = map(int, game.meta.split(':'))
for user in crea, oppo:
if user.tag not in self.matches:
self.matches[user.tag] = self.fetch_match(user.tag)
user.match = self.matches[user.tag]
if user.match.total_matches_played == user.total:
# total_matches_played didn't change since game was started,
# so it is not finished yet
log.info('total for {} is still {}, skipping this game'.format(
user.total, user.tag,
))
return False
user.won = user.match.wins > user.match.rounds/2
if crea.match != oppo.match: # this compares only common properties
return False # they participated different matches for now
if crea.won == oppo.won:
winner = 'draw'
else:
user = 'creator' if crea.won else 'opponent'
return self.gameDone(
game,
winner,
None, # now - as we don't know exact match ending time
)
class StarCraftPoller(Poller):
gametypes = {
'starcraft': 'Starcraft II',
}
subtitle = 'II'
# no gamemodes for this game
identity_id = 'starcraft_uid'
sameregion = True
description = """
For this game betting is based on match outcome.
"""
def prepare(self):
self.lists = {}
def pollGame(self, game):
"""
For SC2, we cannot determine user's opponent in match.
So we just fetch histories for both players
and look for identical match.
"""
crea = SimpleNamespace(uid=game.gamertag_creator)
oppo = SimpleNamespace(uid=game.gamertag_opponent)
if crea.uid.split('/')[0] != oppo.uid.split('/')[0]:
# should be filtered in endpoint...
raise ValueError('Region mismatch')
game_ts = game.accept_date.timestamp()
for user in crea, oppo:
if user.uid not in self.lists:
ret = StarCraft.profile(user.uid, 'matches')
if 'matches' not in ret:
raise ValueError('Couldn\'t fetch matches for user '+user.uid)
self.lists[user.uid] = ret['matches']
user.hist = [m for m in self.lists[user.uid]
if m['date'] >= game_ts]
for mc in crea.hist:
for mo in oppo.hist:
if all(map(lambda field: mc[field] == mo[field],
['map', 'type', 'speed', 'date'])):
# found the match
if mc['decision'] == mo['decision']:
winner = 'draw'
else:
winner = ('creator'
if mc['decision'] == 'WIN' else
'opponent')
return self.gameDone(game, winner, mc['date'])
class TibiaPoller(Poller, LimitedApi):
gametypes = {
'tibia': 'Tibia',
}
identity_id = 'tibia_character'
description = """
For Tibia, you bet on PvP battle outcome.
After you and your friend make & accept bet on your Tibia character names,
system will monitor if one of these characters dies.
The one who died first from the hand of another character
is considered looser,
even if the killer was not the only cause of death
(e.g. cooperated with monster or other player).
If both characters killed each other in the same second (e.g. with poison),
game result will be considered draw.
Important: both characters should reside in the same world.
"""
class Parser(HTMLParser):
def __call__(self, page):
self.tags = []
self.name = None
self.char_404 = False
self.deaths_found = False
self.deaths = []
try:
self.feed(page)
self.close()
except StopIteration:
pass
if self.char_404:
return None, None
return self.name, self.deaths
@property
def tag(self):
return self.tags[-1] if self.tags else None
def handle_starttag(self, tag, attrs):
self.tags.append(tag)
self.attrs = dict(attrs)
def handle_data(self, data):
if self.name is None and self.tag == 'td' and data == 'Name:':
self.name = ''
return
if self.name == '' and self.tag == 'td':
self.name = data
return
if self.tag == 'b':
if data == 'Could not find character':
self.char_404 = True
raise StopIteration
if data == 'Character Deaths':
self.deaths_found = True
self.date = None
self.msg = None
self.players = None
return
if not self.deaths_found:
return
# here deaths_found == True
if(self.tag == 'td'
and self.attrs.get('width') == '25%'
and self.attrs.get('valign') == 'top'):
# date
if self.msg:
self.deaths.append(
(self.date, self.msg, self.players)
)
self.date = date_parse(data.replace('\xA0', ' '))
self.msg = ''
self.players = []
elif self.date:
self.msg += data
if self.tag == 'a':
self.players.append(data)
def handle_endtag(self, tag):
self.tags.pop()
if self.deaths_found and tag == 'table':
self.deaths.append(
(self.date, self.msg, self.players)
)
raise StopIteration
@classmethod
def fetch(cls, playername):
"""
If player found, returns tuple of normalized name and list of deaths.
If player not found, returns (None, None).
"""
page = cls.request(
'GET',
'http://www.tibia.com/community/',
params=dict(
subtopic = 'characters',
name = playername,
),
).text
parser = cls.Parser(convert_charrefs=True)
ret = parser(page)
log.debug('TibiaPoller: fetching character {}: {}'.format(
playername, ret))
return ret
def identity_check(val):
name, deaths = TibiaPoller.fetch(val.strip())
if not name:
raise ValueError('Unknown character '+val)
# TODO: also save world somewhere
return name
Identity(identity_id, 'Tibia Character name', identity_check)
del identity_check
def prepare(self):
self.players = {}
def getDeaths(self, name):
if name not in self.players:
_, deaths = self.fetch(name)
self.players[name] = deaths
return self.players[name]
def pollGame(self, game):
crea = SimpleNamespace(uid=game.gamertag_creator, role='creator')
oppo = SimpleNamespace(uid=game.gamertag_opponent, role='opponent')
crea.other, oppo.other = oppo, crea
for user in crea, oppo:
user.deaths = self.getDeaths(user.uid)
user.lost = False
user.losedate = None
for date, msg, killers in user.deaths:
if date < game.accept_date:
continue
if user.other.uid in killers:
user.lost = True
if not user.losedate:
user.losedate = date
for user in crea, oppo:
if user.lost:
winner = user.other.role
date = user.losedate
if user.other.lost: # killed each other?
# winner is the one who did it first
if user.losedate == user.other.losedate:
winner = 'draw'
elif user.losedate > user.other.losedate:
# this one won!
date = user.other.losedate
winner = user.role
# else - killed each other but this was killed first
return self.gameDone(game, user.other.role, user.losedate)
return False
class HonestyPoller(Poller):
gametypes = {
'halo-5': 'Halo 5',
'inba2015': 'Inba2k16',
}
honesty = True # we don't need any identities to be active
description = 'This game is supported in Honesty mode only.'
twitch = 0
def poll(self, *args, **kwargs):
# just do nothing
pass
class DummyPoller(Poller):
"""
This poller covers all game types not supported yet.
"""
gametypes = {
'battlefield-4': 'Battlefield 4',
'call-of-duty-advanced-warfare': 'Call Of Duty - Advanced Warfare',
'call-of-duty-black-ops-3': 'Call Of Duty - Black Ops III',
'destiny': 'Destiny',
'grand-theft-auto-5': 'Grand Theft Auto V',
'minecraft': 'Minecraft',
'rocket-league': 'Rocket League',
#'diablo': 'Diablo III', # -- we have no image..
}
identity_id = ''
category = {
'minecraft': 'Action',
'rocket-league': 'Action',
}
subtitle = {
'grand-theft-auto': 'V',
'call-of-duty-advanced-warfare': 'Advanced Warfare',
'call-of-duty-black-ops-3': 'Black Ops III',
}
def pollGame(self, game):
pass
class TestPoller(Poller):
gametypes = {
'test': 'Test',
}
identity_id = ''
twitch = 2
twitch_gametypes = {
'test': 'None', # to allow missing streams
}
def pollGame(self, game):
pass
# validation
for poller in Poller.allPollers():
if poller.identity_id and not poller.identity:
raise ValueError('Bad identity id: '+poller.identity_id)
if poller.twitch_identity_id and not poller.twitch_identity:
raise ValueError('Bad twitch identity id: '+poller.identity_id)
def poll_all():
log.info('Polling started')
# we run each 5 minutes, so round value to avoid delays interfering matching
now = datetime.utcfromtimestamp(
datetime.utcnow().timestamp() // (5*60) * (5*60)
)
# TODO: run them all simultaneously in background, to use 2sec api delays
for poller in Poller.allPollers():
if not poller.identity: # root or dummy
continue
if poller.minutes and now.minute % poller.minutes != 0:
log.info('Skipping poller {} because of timeframes'.format(poller))
continue
pin = poller()
pin.poll(now)
log.info('Polling done')
if __name__ == '__main__':
notify_users = dummyfunc(
'** Notifying users about state change in game {}')
notify_event = dummyfunc(
'** Notifying users about event happened '
'in game {game}, event {text}')
# This is a mock class which simulates database model functionality
class Game:
# actually it should be a reference to this or another Game object
class Query(SimpleNamespace):
_game = None
def __init__(self, **kwargs):
super().__init__(**kwargs)
def filter_by(self, **kwargs):
# copy self
dup = self.__class__(**self.__dict__)
dup.__dict__.update(kwargs)
return dup
def count(self):
return 1
def __iter__(self):
key = tuple((k,v) for k,v in self.__dict__.items()
if not k.startswith('_'))
print('** Querying games with %s'%dict(key))
if not self.__class__._game:
self.__class__._game = Game()
game = self.__class__._game
for attr in ('gametype', 'gamemode', 'start',
'gamertag_creator', 'gamertag_opponent'):
setattr(game, attr, getattr(
self, attr, getattr(
args,
attr[9:] if 'tag_' in attr else attr
)
))
yield game
def first(self):
return next(iter(self))
def clear(self):
self.__class__._game = None
query = Query()
root = 'Gaming session'
_isDone = False
_silent = True
def __init__(self):
self.gamertag_creator = None
self.gamertag_opponent = None
self.gametype = None
self.gamemode = None
self.start = datetime.now()
self.meta = None
self._silent = False
@property
def accept_date(self):
return getattr(self, 'start')
def __setattr__(self, k, v):
if not self._silent and v != getattr(self, k):
print('** Setting property on game obj: {}={}'.format(k,v))
super().__setattr__(k, v)
def gameDone(game, winner, timestamp=None, details=None):
print('** Marking game {} as done - '
'winner {}, timestamp {}, details {}'.format(
game, winner, timestamp, details))
game._isDone = True
Poller.gameDone = gameDone
from argparse import ArgumentParser
parser = ArgumentParser(description='You can run either all-tests mode with -t '
'or custom-test mode with positional arguments.')
parser.add_argument('-t', '--tests', action='store_true', default=False,
help='Testing mode. '
'In this mode other options should not be specified; '
'their values will be taken from Poller.tests field '
'for each poller class.')
parser.add_argument('creator', nargs='?',
help='First opponent\'s identity')
parser.add_argument('opponent', nargs='?',
help='Second opponent\'s identity')
parser.add_argument('gametype', nargs='?',
help='This determines which poller will be used')
parser.add_argument('gamemode', nargs='?',
help='Can be omitted '
'if you want to test all gamemodes of given poller '
'or if it doesn\'t use gamemodes at all.')
parser.add_argument('-s', '--start', type=date_parse, default=None,
help='Time when the virtual game invitation was accepted; '
'defaults to now.')
now = datetime.utcfromtimestamp(
datetime.utcnow().timestamp() // (5*60) * (5*60)
)
parser.add_argument('-n', '--now', nargs=1, default=now,
help='Time when the test is performed (for "minutes" field), '
'defaults to current time rounded by 5 minutes.')
args = parser.parse_args()
if not args.tests and not args.gametype:
parser.error(
'Please specify either --tests or creator, opponent and gametype')
if args.tests:
for poller in Poller.allPollers():
print('Testing poller %s'%poller.__name__)
for gametype in ([args.gametype]
if args.gametype else
poller.gametypes):
tests = poller.tests
if isinstance(tests, dict):
tests = tests.get(gametype, [])
for creator, opponent, gamemode, start, winner in tests:
args.creator = creator
args.opponent = opponent
args.gamemode = gamemode
args.start = date_parse(start)
for role in 'creator', 'opponent':
print('Checking gamertag '+getattr(args, role))
setattr(args, role,
poller.identity_check(
getattr(args, role)))
print()
print('Notifying poller that game was started')
poller.gameStarted(Game.query.first()) # FIXME
pin = poller()
if args.gamemode or not poller.usemodes:
print()
print('Preparing poller')
pin.prepare()
print()
print('Polling')
pin.poll(args.now, gametype, args.gamemode)
game = Game.query.first()
if not game._isDone:
print('This poller didn\'t end this game!')
sys.exit(1)
print('Game was ended.')
if game.winner != winner:
print('This game\'s winner doesn\'t match expected!')
print('Expected {}, got {}'.format(
winner, game.winner,
))
sys.exit(1)
Game.query.clear()
sys.exit()
poller = Poller.findPoller(args.gametype)
if not poller:
parser.error('Unknown gametype '+args.gametype)
if args.gamemode and not poller.usemodes:
parser.error('This poller doesn\'t support game modes')
for role in 'creator', 'opponent':
print('Checking gamertag '+getattr(args, role))
setattr(args, role,
poller.identity_check(
getattr(args, role)))
print()
print('Notifying poller that game was started')
poller.gameStarted(Game.query.first()) # FIXME
pin = poller()
if args.gamemode or not poller.usemodes:
print()
print('Preparing poller')
pin.prepare()
print()
print('Polling')
pin.poll(args.now, args.gametype, args.gamemode)
if(Game.query.first()._isDone):
print('Game was ended!')
else:
print('Didn\'t end the game.')
print('Done.')
| {"/v1/signals_definitions.py": ["/v1/main.py", "/v1/badges/__init__.py"], "/v1/polling.py": ["/config.py", "/v1/helpers.py", "/v1/models.py", "/v1/apis.py", "/v1/common.py"], "/v1/badges/__init__.py": ["/v1/badges/badges_description.py", "/v1/badges/fifa15.py"], "/v1/apis.py": ["/config.py", "/v1/helpers.py", "/v1/mock.py"], "/v1/__init__.py": ["/v1/main.py"], "/mobsite.py": ["/config.py"], "/v1/badges/fifa15.py": ["/v1/main.py", "/v1/badges/badges_description.py"], "/v1/helpers.py": ["/config.py", "/v1/models.py", "/v1/main.py", "/v1/common.py", "/v1/apis.py", "/v1/__init__.py"], "/v1/models.py": ["/v1/main.py", "/v1/common.py", "/v1/badges/__init__.py", "/config.py", "/v1/helpers.py", "/v1/routes.py", "/v1/polling.py"], "/poll.py": ["/main.py", "/v1/__init__.py"], "/v1/cas.py": ["/config.py", "/v1/main.py", "/v1/apis.py", "/v1/models.py", "/v1/common.py"], "/debug_console.py": ["/main.py", "/v1/models.py", "/v1/helpers.py", "/v1/routes.py"], "/v1/routes.py": ["/config.py", "/v1/signals_definitions.py", "/v1/models.py", "/v1/helpers.py", "/v1/apis.py", "/v1/polling.py", "/v1/main.py"], "/main.py": ["/config.py", "/v1/__init__.py", "/v1/main.py", "/v1/models.py"], "/v1/main.py": ["/config.py", "/v1/__init__.py", "/v1/admin.py"], "/v1/admin.py": ["/v1/models.py", "/v1/polling.py", "/v1/helpers.py"], "/observer.py": ["/config.py", "/v1/polling.py", "/v1/models.py", "/v1/apis.py"]} |
71,978 | topdevman/flask-betg | refs/heads/master | /v1/badges/__init__.py | from .badges_description import BADGES
from .fifa15 import Fifa15Badges
| {"/v1/signals_definitions.py": ["/v1/main.py", "/v1/badges/__init__.py"], "/v1/polling.py": ["/config.py", "/v1/helpers.py", "/v1/models.py", "/v1/apis.py", "/v1/common.py"], "/v1/badges/__init__.py": ["/v1/badges/badges_description.py", "/v1/badges/fifa15.py"], "/v1/apis.py": ["/config.py", "/v1/helpers.py", "/v1/mock.py"], "/v1/__init__.py": ["/v1/main.py"], "/mobsite.py": ["/config.py"], "/v1/badges/fifa15.py": ["/v1/main.py", "/v1/badges/badges_description.py"], "/v1/helpers.py": ["/config.py", "/v1/models.py", "/v1/main.py", "/v1/common.py", "/v1/apis.py", "/v1/__init__.py"], "/v1/models.py": ["/v1/main.py", "/v1/common.py", "/v1/badges/__init__.py", "/config.py", "/v1/helpers.py", "/v1/routes.py", "/v1/polling.py"], "/poll.py": ["/main.py", "/v1/__init__.py"], "/v1/cas.py": ["/config.py", "/v1/main.py", "/v1/apis.py", "/v1/models.py", "/v1/common.py"], "/debug_console.py": ["/main.py", "/v1/models.py", "/v1/helpers.py", "/v1/routes.py"], "/v1/routes.py": ["/config.py", "/v1/signals_definitions.py", "/v1/models.py", "/v1/helpers.py", "/v1/apis.py", "/v1/polling.py", "/v1/main.py"], "/main.py": ["/config.py", "/v1/__init__.py", "/v1/main.py", "/v1/models.py"], "/v1/main.py": ["/config.py", "/v1/__init__.py", "/v1/admin.py"], "/v1/admin.py": ["/v1/models.py", "/v1/polling.py", "/v1/helpers.py"], "/observer.py": ["/config.py", "/v1/polling.py", "/v1/models.py", "/v1/apis.py"]} |
71,979 | topdevman/flask-betg | refs/heads/master | /v1/common.py | from flask import current_app
### Logging ###
class log_cls:
"""
Just a handy wrapper for current_app.logger
"""
def __getattr__(self, name):
return getattr(current_app.logger, name)
log = log_cls()
class classproperty:
"""
Cached class property; evaluated only once
"""
def __init__(self, fget):
self.fget = fget
self.obj = {}
def __get__(self, owner, cls):
if cls not in self.obj:
self.obj[cls] = self.fget(cls)
return self.obj[cls]
| {"/v1/signals_definitions.py": ["/v1/main.py", "/v1/badges/__init__.py"], "/v1/polling.py": ["/config.py", "/v1/helpers.py", "/v1/models.py", "/v1/apis.py", "/v1/common.py"], "/v1/badges/__init__.py": ["/v1/badges/badges_description.py", "/v1/badges/fifa15.py"], "/v1/apis.py": ["/config.py", "/v1/helpers.py", "/v1/mock.py"], "/v1/__init__.py": ["/v1/main.py"], "/mobsite.py": ["/config.py"], "/v1/badges/fifa15.py": ["/v1/main.py", "/v1/badges/badges_description.py"], "/v1/helpers.py": ["/config.py", "/v1/models.py", "/v1/main.py", "/v1/common.py", "/v1/apis.py", "/v1/__init__.py"], "/v1/models.py": ["/v1/main.py", "/v1/common.py", "/v1/badges/__init__.py", "/config.py", "/v1/helpers.py", "/v1/routes.py", "/v1/polling.py"], "/poll.py": ["/main.py", "/v1/__init__.py"], "/v1/cas.py": ["/config.py", "/v1/main.py", "/v1/apis.py", "/v1/models.py", "/v1/common.py"], "/debug_console.py": ["/main.py", "/v1/models.py", "/v1/helpers.py", "/v1/routes.py"], "/v1/routes.py": ["/config.py", "/v1/signals_definitions.py", "/v1/models.py", "/v1/helpers.py", "/v1/apis.py", "/v1/polling.py", "/v1/main.py"], "/main.py": ["/config.py", "/v1/__init__.py", "/v1/main.py", "/v1/models.py"], "/v1/main.py": ["/config.py", "/v1/__init__.py", "/v1/admin.py"], "/v1/admin.py": ["/v1/models.py", "/v1/polling.py", "/v1/helpers.py"], "/observer.py": ["/config.py", "/v1/polling.py", "/v1/models.py", "/v1/apis.py"]} |
71,980 | topdevman/flask-betg | refs/heads/master | /v1/apis.py | from flask import request
import os
import time
from datetime import datetime, timedelta
from collections import OrderedDict, namedtuple
import email
import requests
from requests_oauthlib import OAuth1Session
try:
import config
from .helpers import log
except ImportError:
# test environment
from .mock import config, log
### External APIs ###
def nexmo(endpoint, **kwargs):
"""
Shorthand for nexmo api calls
"""
kwargs['api_key'] = config.NEXMO_API_KEY
kwargs['api_secret'] = config.NEXMO_API_SECRET
result = requests.post('https://api.nexmo.com/%s/json' % endpoint, data=kwargs)
return result.json()
def geocode(address):
# TODO: caching
# FIXME: error handling
ret = requests.get('https://maps.googleapis.com/maps/api/geocode/json', params={
'address': address,
'sensor': False,
}).json()
loc = ret['results'][0]['geometry']['location']
return loc['lat'], loc['lng']
class IPInfo:
"""
This is a wrapper for ipinfo.io api with caching.
"""
iso3 = None # will be filled on first use
cache = OrderedDict()
cache_max = 100
@classmethod
def country(cls, ip=None, default=None):
"""
Returns ISO3 country code using country.io for conversion.
IP defaults to `request.remote_addr`.
Will return `default` value if no country found (e.g. for localhost ip)
"""
if not ip:
ip = request.remote_addr
if ip in cls.cache:
# move to end to make it less likely to pop
cls.cache.move_to_end(ip)
return cls.cache[ip] or default
ret = requests.get('http://ipinfo.io/{}/geo'
.format(ip))
try:
ret = ret.json()
except ValueError:
log.warn('No JSON returned by ipinfo.io: '+ret.text)
ret = {}
result = None
if 'country' in ret:
if not cls.iso3:
cls.iso3 = requests.get('http://country.io/iso3.json').json()
result = cls.iso3.get(ret['country'])
if not result:
log.warn('couldn\'t convert country code {} to ISO3'.format(
ret['country']))
cls.cache[ip] = result
if len(cls.cache) > cls.cache_max:
# remove oldest item
cls.cache.popitem(last=False)
return result or default
class PayPal:
token = None
token_ttl = None
base_url = 'https://{}.paypal.com/v1/'.format('api.sandbox'
if config.PAYPAL_SANDBOX else
'api')
@classmethod
def get_token(cls):
if cls.token_ttl and cls.token_ttl <= datetime.utcnow():
cls.token = None # expired
if not cls.token:
ret = requests.post(
cls.base_url+'oauth2/token',
data={'grant_type': 'client_credentials'},
auth=(config.PAYPAL_CLIENT, config.PAYPAL_SECRET),
)
if ret.status_code != 200:
log.error('Couldn\'t get token: {}'.format(ret.status_code))
return
ret = ret.json()
cls.token = ret['access_token']
cls.token_lifetime = (datetime.utcnow() +
timedelta(seconds =
# -10sec to be sure
ret['expires_in'] - 10))
return cls.token
@classmethod
def call(cls, method, url, params=None, json=None):
if not json:
json = params
params = None
url = cls.base_url + url
headers = {
'Authorization': 'Bearer '+cls.get_token(),
#TODO: 'PayPal-Request-Id': None, # use generated nonce
}
ret = requests.request(method, url,
params=params,
json=json,
headers = headers,
)
log.debug('Paypal result: {} {}'.format(ret.status_code, ret.text))
try:
jret = ret.json()
except ValueError:
log.error('Paypal failure - code %s' % ret.status_code,
exc_info=True);
jret = {}
jret['_code'] = ret.status_code
return jret
class Fixer:
# fixer rates are updated daily, but it should be enough for us
item = namedtuple('item', ['ttl','rate'])
cache = OrderedDict()
cache_max = 100
cache_ttl = timedelta(minutes=15)
@classmethod
def latest(cls, src, dst):
if src == dst:
return 1
now = datetime.now()
if (src,dst) in cls.cache:
cls.cache.move_to_end((src,dst))
if cls.cache[(src,dst)].ttl > now:
return cls.cache[(src,dst)].rate
result = requests.get('http://api.fixer.io/latest', params={
'base': src, 'symbols': dst}).json()
if 'rates' not in result:
log.warning('Failure with Fixer api: '+str(result))
return None
rate = result.get('rates').get(dst)
if rate is None:
raise ValueError('Unknown currency '+dst)
cls.cache[(src,dst)] = cls.item(now+cls.cache_ttl, rate)
if len(cls.cache) > cls.cache_max:
cls.cache.popitem(last=False)
return rate
def mailsend(user, mtype, sender=None, delayed=None, usebase=True, **kwargs):
subjects = dict(
greeting = 'Welcome to BetGame',
greet_personal = 'Hey {}'.format(user.nickname or 'BetGame user'),
recover = 'BetGame password recovery',
win = 'BetGame win notification',
)
if mtype not in subjects:
raise ValueError('Unknown message type {}'.format(mtype))
kwargs['name'] = user.nickname
kwargs['email'] = user.email
def load(name, ext, values, base=False):
f = open('{}/templates/mail/{}.{}'.format(
os.path.dirname(__file__)+'/..', # load from path relative to self
name, ext
), 'r')
txt = f.read()
for key,val in values.items():
txt = txt.replace('{%s}' % key, str(val))
if not base:
txt = load('base', ext, dict(
content = txt,
), base=True)
return txt
params = {
'from': sender or config.MAIL_SENDER,
'to': '{} <{}>'.format(user.nickname, user.email),
'subject': subjects[mtype],
'text': load(mtype, 'txt', kwargs, not usebase),
'html': load(mtype, 'html', kwargs, not usebase),
}
if delayed:
params['o:deliverytime'] = email.utils.format_datetime(
datetime.utcnow() + delayed
)
ret = requests.post(
'https://api.mailgun.net/v3/{}/messages'.format(config.MAIL_DOMAIN),
auth=('api',config.MAILGUN_KEY),
data=params,
)
try:
jret = ret.json()
if 'id' in jret:
log.info('mail sent: '+jret['message'])
return True
else:
log.error('mail sending failed: '+jret['message'])
return False
except Exception:
log.exception('Failed to send {} mail to {}'.format(mtype, user))
log.error('{} {}'.format(ret.status_code, ret.text))
return False
class Twitter:
@classmethod
def session(cls, identity):
if ':' not in identity:
raise ValueError('Incorrect identity, should be <token>:<secret>')
key, secret = identity.split(':',1)
return OAuth1Session(
config.TWITTER_API_KEY,
client_secret = config.TWITTER_API_SECRET,
resource_owner_key = key,
resource_owner_secret = secret,
)
@classmethod
def identity(cls, token):
url = 'https://api.twitter.com/1.1/account/verify_credentials.json'
ret = cls.session(token).get(url, params=dict(
include_email='true', # plain True doesn't work here
skip_status='true', # here True would work as well
))
try:
jret = ret.json()
except:
jret = {}
jret['_ret'] = ret
jret['_code'] = ret.status_code
return jret
class JsonApi:
@classmethod
def session(cls):
" If overriden, should return a requests.session object "
return requests
@classmethod
def request(cls, *args, **kwargs):
" Can be overriden "
return cls.session().request(*args, **kwargs)
@classmethod
def request_json(cls, *args, **kwargs):
ret = cls.request(*args, **kwargs)
try:
resp = ret.json()
except ValueError: # json decode error
# error decoding json
log.exception('{} API: not a json in reply, code {}, text {}'.format(
cls.__name__,
ret.status_code,
ret.text,
))
resp = {}
resp['_code'] = ret.status_code
return resp
class LimitedApi(JsonApi):
# this is default delay between subsequent requests to the same api,
# can be overriden in subclasses
DELAY = timedelta(seconds=2)
@classmethod
def request(cls, *args, **kwargs):
"""
This overrides JsonApi's method adding delay.
"""
# TODO: maybe use session for delaying?
now = datetime.utcnow()
last = getattr(cls, '_last', None)
if last:
diff = now - last
delay = cls.DELAY - diff
seconds = delay.total_seconds()
if seconds > 0:
time.sleep(seconds)
# and before we actually call the method, save current time
# (so that api's internal delay will count as a part of our delay)
cls._last = datetime.utcnow()
# now that we slept if needed, call Requests
# and handle any json-related problems
return super().request(*args, **kwargs)
class Riot(LimitedApi):
URL = 'https://{region}.api.pvp.net/api/lol/{region}/{version}/{method}'
REGIONS = [
'br', 'eune', 'euw', 'kr',
'lan', 'las', 'na', 'oce',
'ru', 'tr',
]
@classmethod
def summoner_check(cls, val, region = None):
"""
Summoner name can be either full (with region) or short.
If it is full, it should be in format 'region/name'.
If it is short, this method will try to find matching name
in the first region where it exists.
Returns summoner data in form 'region/name/id'.
"""
if not region and '/' in val:
region, nval = val.split('/',1)
if region in cls.REGIONS:
val = nval
else:
region = None
if not region:
for region in cls.REGIONS:
try:
return cls.summoner_check(val, region)
except ValueError:
pass
raise ValueError('Summoner {} not exists in any region'.format(val))
ret = cls.call(region, 'v1.4', 'summoner/by-name/'+val)
if val.lower() in ret:
return '/'.join([
region,
ret[val.lower()]['name'],
str(ret[val.lower()]['id']),
])
raise ValueError('Unknown summoner name')
@classmethod
def call(cls, region, version, method, params=None, data=None):
if region not in cls.REGIONS:
raise ValueError('Unknown region %s' % region)
params = params or {}
data = data or {}
params['api_key'] = config.RIOT_KEY
return cls.request_json(
'GET',
cls.URL.format(
region=region,
version=version,
method=method,
),
params = params,
data = data,
)
class Steam(LimitedApi):
# as recommended in http://dev.dota2.com/showthread.php?t=47115
DELAY = timedelta(seconds=1)
STEAM_ID_64_BASE = 76561197960265728
@classmethod
def id_to_32(cls, val):
if val > cls.STEAM_ID_64_BASE:
val -= cls.STEAM_ID_64_BASE
return val
@classmethod
def id_to_64(cls, val):
if val < cls.STEAM_ID_64_BASE:
val += cls.STEAM_ID_64_BASE
return val
@classmethod
def parse_id(cls, val):
# convert it to int if applicable
try:
val = int(val)
return cls.id_to_64(val)
except ValueError: pass
if val.startswith('STEAM_'):
val = val.split('STEAM_',1)[1]
ver, a, b = map(int, val.split(':'))
if ver == 0:
return cls.id_to_64(b << 1 + (a & 1))
raise ValueError('unknown ver: '+val)
elif 'steamcommunity.com/' in val: # url
if '/id/' in val:
vanity_name = val.split('/id/',1)[1]
# and fall down
elif '/profiles/' in val:
val = val.split('/profiles/',1)[1]
val = val.split('/')[0]
return int(val)
else:
raise ValueError(val)
else:
# val is probably nickname for vanity URL, so -
vanity_name = val
# at this point val is probably a nickname (or vanity URL part)
# so try to parse it
ret = cls.call(
'ISteamUser', 'ResolveVanityURL', 'v0001',
vanityurl=vanity_name,
)
if 'steamid' not in ret:
raise ValueError('Bad vanity URL '+val)
return int(ret['steamid']) # it was returned as string
@classmethod
def player_nick(cls, val):
"""
Gets *numeric steam ID*, retrieves properly-spelled nickname.
"""
ret = cls.call(
'ISteamUser', 'GetPlayerSummaries', 'v0002',
steamids = val,
)
ps = ret.get('players')
if not ps:
log.error('Couldn\'t load player nickname from Steam')
return None
return ps[0].get('personaname')
@classmethod
def pretty_id(cls, val):
steam_id = cls.parse_id(val)
name = cls.player_nick(steam_id)
if not name:
return steam_id # store w/o dot
return '{}.{}'.format(steam_id, name)
@classmethod
def split_identity(cls, val):
"""
This is reverse for `pretty_id`
"""
id, sep, name = val.partition('.')
return id, name or str(id)
@classmethod
def call(cls, path, method, version, **params):
# TODO: on 503 error, retry in 30 seconds
params['key'] = config.STEAM_KEY
ret = cls.request_json(
'GET',
'https://api.steampowered.com/{}/{}/{}/'.format(
path,
method,
version,
),
params = params,
)
for wrapper in ['result', 'response']:
if ret.keys() == set([wrapper, '_code']): # nothing more
ret[wrapper]['_code'] = ret.get('_code')
return ret[wrapper]
return ret
@classmethod
def dota2(cls, method, match=True, **params):
# docs available at https://wiki.teamfortress.com/wiki/WebAPI#Dota_2
return cls.call('IDOTA2{}_570'.format('Match' if match else ''),
method, 'V001', **params)
class BattleNet(LimitedApi):
# FIXME: there are 2 partitions - CN and Worldwide. We only use worldwide.
# https://dev.battle.net/docs/concepts/Regionality
# https://dev.battle.net/docs/concepts/AccountIds
HOSTS = dict(
us = 'https://us.api.battle.net/',
eu = 'https://eu.api.battle.net/',
kr = 'https://kr.api.battle.net/',
tw = 'https://tw.api.battle.net/',
cn = 'https://api.battlenet.com.cn/',
sea = 'https://sea.api.battle.net/',
)
@classmethod
def call(cls, region, game, endpoint, *params):
host = cls.HOSTS[region]
url = 'https://{host}/{game}/{endpoint}'.format(**locals())
params['apikey'] = config.BATTLENET_KEY
return cls.request_json('GET', url, params=params)
class StarCraft(BattleNet):
@classmethod
def find_uid(cls, val):
"""
Search given user ID on sc2ranks site.
"""
# TODO: api seems not functional
ret = cls.request_json(
'POST',
'http://api.sc2ranks.com/v2/characters/search',
)
# TODO
ret
@classmethod
def check_uid(cls, val):
if val.startswith('http'):
val = val.split('://',1)[1]
parts = val.split('/')
if 'sc2ranks.com/character' in val:
# sc2ranks url example:
# http://www.sc2ranks.com/character/us/5751755/Violet/hots/1v1
region, uid, uname = parts[2:5]
ureg = '1' # seems that it is always 1
elif 'battle.net/sc2' in val and '/profile/' in val:
# battle.net url example:
# http://us.battle.net/sc2/en/profile/7098504/1/Neeblet/matches
if parts[0] == 'www.battlenet.com.cn':
region = 'cn'
else:
# region = subdomain
region = parts[0].split('.',1)[0]
uid, ureg, uname = parts[4:7]
else:
if len(parts) != 4:
return cls.find_uid(val)
region, uid, ureg, uname = parts
if region not in cls.HOSTS:
raise ValueError('Unknown region '+region)
int(uid) # to check for valueerror
int(ureg)
return '/'.join([region, uid, ureg, uname])
@classmethod
def profile(cls, user, part=''):
region, uid, ureg, uname = user.split('/')
return cls.call(
region,
'sc2',
'{}/{}/{}/{}'.format(uid, ureg, uname, part),
)
class Twitch:
@classmethod
def call(cls, endpoint, version=None):
ret = requests.get(
'https://api.twitch.tv/kraken/{}'.format(endpoint),
headers = {
'Accept': 'application/vnd.twitchtv{}+json'.format(
'.'+version if version else ''),
#'Client-ID': ...,
},
)
try:
jret = ret.json()
except ValueError:
jret = {}
jret['_code'] = ret.status_code
return jret
@classmethod
def channel(cls, handle):
return cls.call('channels/{}'.format(handle), 'v3')
@classmethod
def check_handle(cls, val):
pos = val.find('twitch.tv/')
if pos >= 0:
val = val[pos+10:]
# now validate id over twitch
ret = cls.channel(val)
if ret['_code'] == 404:
raise ValueError('No such channel "{}"'.format(val))
log.info('Twitch channel: current game is {}'.format(ret.get('game')))
return val
class WilliamHill:
"""
Unlike other APIs in this module,
this one should be instantiated for usage.
This is because it requires user credentials.
"""
class WilliamHillError(Exception):
pass
BASE = 'https://sandbox.whapi.com/v1/' # XXX is it correct? doc mentions sandbox.*
CAS_HOST = ('https://auth.williamhill%s.com' %
('-test' if config.WH_SANDBOX else ''))
def __init__(self, ticket=None):
self.session = requests.Session()
self.session.headers.update({
'Accept': 'application/vnd.who.Sportsbook+json;v=1;charset=utf-8',
'who-apiKey': config.WH_KEY,
'who-secret': config.WH_SECRET,
})
if ticket:
self.session.headers.update({
'who-ticket': ticket,
})
def request(self, method, url, accept_simple=False, *args, **kwargs):
if accept_simple:
if 'headers' not in kwargs:
kwargs['headers'] = {}
kwargs['headers']['Accept'] = 'application/json'
try:
ret = self.session.request(method, self.BASE+url, *args, **kwargs)
jret = ret.json()
except ValueError: # not a json?
return dict(
error = 'No JSON available',
)
if 'whoFaults' in jret:
fault = jret['whoFaults']
fault = fault[0] if len(fault) > 0 else {}
return dict(
error = fault.get('faultString') or '(no fault description)',
error_code = fault.get('faultCode'),
error_name = fault.get('faultName'),
)
return jret
| {"/v1/signals_definitions.py": ["/v1/main.py", "/v1/badges/__init__.py"], "/v1/polling.py": ["/config.py", "/v1/helpers.py", "/v1/models.py", "/v1/apis.py", "/v1/common.py"], "/v1/badges/__init__.py": ["/v1/badges/badges_description.py", "/v1/badges/fifa15.py"], "/v1/apis.py": ["/config.py", "/v1/helpers.py", "/v1/mock.py"], "/v1/__init__.py": ["/v1/main.py"], "/mobsite.py": ["/config.py"], "/v1/badges/fifa15.py": ["/v1/main.py", "/v1/badges/badges_description.py"], "/v1/helpers.py": ["/config.py", "/v1/models.py", "/v1/main.py", "/v1/common.py", "/v1/apis.py", "/v1/__init__.py"], "/v1/models.py": ["/v1/main.py", "/v1/common.py", "/v1/badges/__init__.py", "/config.py", "/v1/helpers.py", "/v1/routes.py", "/v1/polling.py"], "/poll.py": ["/main.py", "/v1/__init__.py"], "/v1/cas.py": ["/config.py", "/v1/main.py", "/v1/apis.py", "/v1/models.py", "/v1/common.py"], "/debug_console.py": ["/main.py", "/v1/models.py", "/v1/helpers.py", "/v1/routes.py"], "/v1/routes.py": ["/config.py", "/v1/signals_definitions.py", "/v1/models.py", "/v1/helpers.py", "/v1/apis.py", "/v1/polling.py", "/v1/main.py"], "/main.py": ["/config.py", "/v1/__init__.py", "/v1/main.py", "/v1/models.py"], "/v1/main.py": ["/config.py", "/v1/__init__.py", "/v1/admin.py"], "/v1/admin.py": ["/v1/models.py", "/v1/polling.py", "/v1/helpers.py"], "/observer.py": ["/config.py", "/v1/polling.py", "/v1/models.py", "/v1/apis.py"]} |
71,981 | topdevman/flask-betg | refs/heads/master | /v1/__init__.py | from .main import init_app
| {"/v1/signals_definitions.py": ["/v1/main.py", "/v1/badges/__init__.py"], "/v1/polling.py": ["/config.py", "/v1/helpers.py", "/v1/models.py", "/v1/apis.py", "/v1/common.py"], "/v1/badges/__init__.py": ["/v1/badges/badges_description.py", "/v1/badges/fifa15.py"], "/v1/apis.py": ["/config.py", "/v1/helpers.py", "/v1/mock.py"], "/v1/__init__.py": ["/v1/main.py"], "/mobsite.py": ["/config.py"], "/v1/badges/fifa15.py": ["/v1/main.py", "/v1/badges/badges_description.py"], "/v1/helpers.py": ["/config.py", "/v1/models.py", "/v1/main.py", "/v1/common.py", "/v1/apis.py", "/v1/__init__.py"], "/v1/models.py": ["/v1/main.py", "/v1/common.py", "/v1/badges/__init__.py", "/config.py", "/v1/helpers.py", "/v1/routes.py", "/v1/polling.py"], "/poll.py": ["/main.py", "/v1/__init__.py"], "/v1/cas.py": ["/config.py", "/v1/main.py", "/v1/apis.py", "/v1/models.py", "/v1/common.py"], "/debug_console.py": ["/main.py", "/v1/models.py", "/v1/helpers.py", "/v1/routes.py"], "/v1/routes.py": ["/config.py", "/v1/signals_definitions.py", "/v1/models.py", "/v1/helpers.py", "/v1/apis.py", "/v1/polling.py", "/v1/main.py"], "/main.py": ["/config.py", "/v1/__init__.py", "/v1/main.py", "/v1/models.py"], "/v1/main.py": ["/config.py", "/v1/__init__.py", "/v1/admin.py"], "/v1/admin.py": ["/v1/models.py", "/v1/polling.py", "/v1/helpers.py"], "/observer.py": ["/config.py", "/v1/polling.py", "/v1/models.py", "/v1/apis.py"]} |
71,982 | topdevman/flask-betg | refs/heads/master | /mobsite.py | #!/usr/bin/env python3
from flask import Flask, request, Response, session, render_template
from flask import abort, redirect, url_for
import requests
import config
app = Flask(__name__, static_folder = 'static-m')
app.config['APPLICATION_ROOT'] = '/m'
# for session...
app.config['SECRET_KEY'] = config.JWT_SECRET
app.config['API'] = 'http://betgame.co.uk/v1'
app.config['API_ROOT'] = 'http://betgame.co.uk/v1'
# Fix app root...
class ReverseProxied:
def __init__(self, app):
self.app = app
def __call__(self, env, start_resp):
script_name = env.get('HTTP_X_SCRIPT_NAME', '')
if script_name:
env['SCRIPT_NAME'] = script_name
path_info = env['PATH_INFO']
print('pi: %s, sn: %s' % (path_info, script_name))
if path_info.startswith(script_name):
env['PATH_INFO'] = path_info[len(script_name):]
scheme = env.get('HTTP_X_SCHEME', '')
if scheme:
env['wsgi.url_scheme'] = scheme
return self.app(env, start_resp)
app.wsgi_app = ReverseProxied(app.wsgi_app)
# API access
class GameTypes:
"""
Caching access to /gametypes endpoint
"""
cache = None
@classmethod
def _load(cls):
# TODO: expiration timeouts
if not cls.cache:
cls.cache = requests.get(app.config['API_ROOT']+'/gametypes').json()
cls.dcache = {x['id']: x for x in cls.cache['gametypes']}
return cls.dcache
@classmethod
def get(cls, name=None):
if not name:
return cls._load().values()
return cls._load().get(name)
@app.before_request
def beta_auth():
auth = request.authorization
if auth:
login, password = auth.username, auth.password
if login == 'tester' and password == 'bet123':
# passed
return
# require auth
return Response(
'This is a testing site, please authenticate!',
401, {'WWW-Authenticate': 'Basic realm="Login Required"'})
@app.route('/')
def bets():
modes = None
if session.get('gametype'):
modes = GameTypes.get(session['gametype'])['gamemodes']
print('m: '+str(modes))
return render_template('newbet.html')
@app.route('/gametype', methods=['GET','POST'])
def gametype():
if request.method == 'POST':
session['gametype'] = request.form.get('gametype')
return redirect(url_for('bets'))
return render_template('gametype.html', games=GameTypes.get())
@app.route('/leaders')
def leaderboard():
return render_template('leaderboard.html')
@app.route('/challenges')
def challenges():
return render_template('challenges.html')
@app.route('/profile')
def profile():
return render_template('profile.html')
if __name__ == '__main__':
app.run(debug=True)
@app.route('/m')
def mob():
return 'Hello World'
| {"/v1/signals_definitions.py": ["/v1/main.py", "/v1/badges/__init__.py"], "/v1/polling.py": ["/config.py", "/v1/helpers.py", "/v1/models.py", "/v1/apis.py", "/v1/common.py"], "/v1/badges/__init__.py": ["/v1/badges/badges_description.py", "/v1/badges/fifa15.py"], "/v1/apis.py": ["/config.py", "/v1/helpers.py", "/v1/mock.py"], "/v1/__init__.py": ["/v1/main.py"], "/mobsite.py": ["/config.py"], "/v1/badges/fifa15.py": ["/v1/main.py", "/v1/badges/badges_description.py"], "/v1/helpers.py": ["/config.py", "/v1/models.py", "/v1/main.py", "/v1/common.py", "/v1/apis.py", "/v1/__init__.py"], "/v1/models.py": ["/v1/main.py", "/v1/common.py", "/v1/badges/__init__.py", "/config.py", "/v1/helpers.py", "/v1/routes.py", "/v1/polling.py"], "/poll.py": ["/main.py", "/v1/__init__.py"], "/v1/cas.py": ["/config.py", "/v1/main.py", "/v1/apis.py", "/v1/models.py", "/v1/common.py"], "/debug_console.py": ["/main.py", "/v1/models.py", "/v1/helpers.py", "/v1/routes.py"], "/v1/routes.py": ["/config.py", "/v1/signals_definitions.py", "/v1/models.py", "/v1/helpers.py", "/v1/apis.py", "/v1/polling.py", "/v1/main.py"], "/main.py": ["/config.py", "/v1/__init__.py", "/v1/main.py", "/v1/models.py"], "/v1/main.py": ["/config.py", "/v1/__init__.py", "/v1/admin.py"], "/v1/admin.py": ["/v1/models.py", "/v1/polling.py", "/v1/helpers.py"], "/observer.py": ["/config.py", "/v1/polling.py", "/v1/models.py", "/v1/apis.py"]} |
71,983 | topdevman/flask-betg | refs/heads/master | /v1/badges/fifa15.py | from sqlalchemy.orm import deferred
from sqlalchemy.ext.declarative import declared_attr
from v1.main import db
from v1.badges.badges_description import FIFA15_BADGES
class Fifa15Badges(object):
# example
@declared_attr
def fifa15_xboxone_first_win(self):
return deferred(
db.Column(db.MutaleDictPickleType,
default=FIFA15_BADGES["badges"]["fifa15_xboxone_first_win"]["user_bounded"]),
group=FIFA15_BADGES["group_name"] # group of badges, can be grouped by games ids etc.
)
@declared_attr
def fifa15_xboxone_10_wins(self):
return deferred(
db.Column(db.MutaleDictPickleType,
default=FIFA15_BADGES["badges"]["fifa15_xboxone_10_wins"]["user_bounded"]),
group=FIFA15_BADGES["group_name"]
)
@declared_attr
def fifa15_xboxone_first_loss(self):
return deferred(
db.Column(db.MutaleDictPickleType,
default=FIFA15_BADGES["badges"]["fifa15_xboxone_first_loss"]["user_bounded"]),
group=FIFA15_BADGES["group_name"]
)
| {"/v1/signals_definitions.py": ["/v1/main.py", "/v1/badges/__init__.py"], "/v1/polling.py": ["/config.py", "/v1/helpers.py", "/v1/models.py", "/v1/apis.py", "/v1/common.py"], "/v1/badges/__init__.py": ["/v1/badges/badges_description.py", "/v1/badges/fifa15.py"], "/v1/apis.py": ["/config.py", "/v1/helpers.py", "/v1/mock.py"], "/v1/__init__.py": ["/v1/main.py"], "/mobsite.py": ["/config.py"], "/v1/badges/fifa15.py": ["/v1/main.py", "/v1/badges/badges_description.py"], "/v1/helpers.py": ["/config.py", "/v1/models.py", "/v1/main.py", "/v1/common.py", "/v1/apis.py", "/v1/__init__.py"], "/v1/models.py": ["/v1/main.py", "/v1/common.py", "/v1/badges/__init__.py", "/config.py", "/v1/helpers.py", "/v1/routes.py", "/v1/polling.py"], "/poll.py": ["/main.py", "/v1/__init__.py"], "/v1/cas.py": ["/config.py", "/v1/main.py", "/v1/apis.py", "/v1/models.py", "/v1/common.py"], "/debug_console.py": ["/main.py", "/v1/models.py", "/v1/helpers.py", "/v1/routes.py"], "/v1/routes.py": ["/config.py", "/v1/signals_definitions.py", "/v1/models.py", "/v1/helpers.py", "/v1/apis.py", "/v1/polling.py", "/v1/main.py"], "/main.py": ["/config.py", "/v1/__init__.py", "/v1/main.py", "/v1/models.py"], "/v1/main.py": ["/config.py", "/v1/__init__.py", "/v1/admin.py"], "/v1/admin.py": ["/v1/models.py", "/v1/polling.py", "/v1/helpers.py"], "/observer.py": ["/config.py", "/v1/polling.py", "/v1/models.py", "/v1/apis.py"]} |
71,984 | topdevman/flask-betg | refs/heads/master | /v1/helpers.py | from flask import request, abort as flask_abort
from flask import g, current_app
from flask.ext.restful.reqparse import RequestParser, Argument
from flask.ext import restful
from flask.ext.restful.utils import http_status_message
from werkzeug.exceptions import HTTPException
import os
import urllib.parse
import jwt
import hashlib, uuid
from urllib.parse import quote
import json
import requests
from functools import wraps
import binascii
import apns_clerk
import datadog as datadog_api
from eventlet.timeout import Timeout
import config
from .models import *
from .main import db, redis
from .common import *
def datadog(title, text=None, _log=True, **tags):
"""
Call log.info and send event to datadog
"""
if not current_app.debug:
try:
if _log:
log.info('{}: {}'.format(title, text) if text else title)
tags.setdefault('version', 1)
tags.setdefault('application', 'betgame')
if getattr(g, 'user', None):
tags.setdefault('user.id', g.user.id)
tags.setdefault('user.nickname', g.user.nickname)
tags.setdefault('user.email', g.user.email)
datadog_api.api.Event.create(
title=title,
text=text,
tags=[':'.join(map(str, item)) for item in tags.items()],
)
except:
log.exception('Datadog failure')
dd_stat = datadog_api.statsd
### Data returning ###
def abort(message, code=400, **kwargs):
data = {'error_code': code, 'error': message}
if kwargs:
data.update(kwargs)
log.warning('Aborting request {} /{}: {}'.format(
# GET /v1/smth
request.method,
request.base_url.split('//',1)[-1].split('/',1)[-1],
', '.join(['{}: {}'.format(*i) for i in data.items()])))
datadog('Request aborted',
request.base_url.split('//',1)[-1].split('/',1)[-1] + ' ' +
', '.join(['{}: {}'.format(*i) for i in data.items()]),
_log=False,
)
try:
flask_abort(code)
except HTTPException as e:
e.data = data
raise
restful.abort = lambda code,message: abort(message,code) # monkey-patch to use our approach to aborting
restful.utils.error_data = lambda code: {
'error_code': code,
'error': http_status_message(code)
}
### Tokens ###
def validateFederatedToken(service, refresh_token):
if service == 'google':
params = dict(
refresh_token = refresh_token,
grant_type = 'refresh_token',
client_id = config.GOOGLE_AUTH_CLIENT_ID,
client_secret = config.GOOGLE_AUTH_CLIENT_SECRET,
)
ret = requests.post('https://www.googleapis.com/oauth2/v3/token',
data = params).json()
success = 'access_token' in ret
elif service == 'facebook':
ret = requests.get('https://graph.facebook.com/me/permissions',
params = dict(
access_token = refresh_token,
)).json()
success = 'data' in ret
else:
raise ValueError('Bad service '+service)
if not success:
raise ValueError('Invalid or revoked federated token')
def federatedExchangeGoogle(code):
post_data = dict(
code = code,
client_id = config.GOOGLE_AUTH_CLIENT_ID,
client_secret = config.GOOGLE_AUTH_CLIENT_SECRET,
redirect_uri = 'postmessage',
grant_type = 'authorization_code',
scope = '',
)
ret = requests.post('https://accounts.google.com/o/oauth2/token',
data=post_data)
jret = ret.json()
if 'access_token' in jret:
if 'refresh_token' in jret:
return jret['access_token'], jret['refresh_token']
else:
abort('Have access token but no refresh token; '
'please include approval_prompt=force '
'or revoke access and retry.')
else:
err = jret.get('error')
log.error(ret.text)
abort('Failed to exchange code for tokens: %d %s: %s' %
(ret.status_code, jret.get('error', ret.reason),
jret.get('error_description', 'no details')))
def federatedRenewFacebook(refresh_token):
ret = requests.get('https://graph.facebook.com/oauth/access_token',
params=dict(
grant_type='fb_exchange_token',
client_id=config.FACEBOOK_AUTH_CLIENT_ID,
client_secret=config.FACEBOOK_AUTH_CLIENT_SECRET,
fb_exchange_token=refresh_token,
))
# result is in urlencoded form, so convert it to dict
jret = dict(urllib.parse.parse_qsl(ret.text))
if 'access_token' in jret:
return jret['access_token']
else:
try:
err = ret.json().get('error', {})
except Exception:
err = {}
abort('Failed to renew Facebook token: {} {} ({})'.format(
err.get('code', ret.status_code),
err.get('type', ret.reason),
err.get('message', 'no info')))
def federatedRenewTwitter(token):
ret = Twitter.identity(refresh_token)
if ret['_code'] != 200:
log.error(str(ret))
abort('Twitter token seems revoked')
return refresh_token
def makeToken(user, service=None, refresh_token=None,
from_token=None, longterm=False, device=None):
"""
Generate JWT token for given user.
That token will allow the user to login.
:param service: if specified, will generate google- or facebook-based token
:param refresh_token: refresh token for that service
:param from_token: if specified, should be longterm token;
if that token is federated, newly generated will be also federated
from the same service
:param longterm: if True, will generate longterm token
"""
if from_token:
# should be already checked
header, payload = jwt.verify_jwt(from_token, config.JWT_SECRET, ['HS256'],
checks_optional=True) # allow longterm
service = payload.get('svc', service)
if longterm:
if service == 'facebook': # for FB will generate new LT token
refresh_token = federatedRenewFacebook(payload['refresh'])
else:
# for plain and Google longterm tokens don't expire
# so just return an old one
return from_token
payload = {
'sub': user.id,
}
if device:
payload['device'] = device.id
if service: # federated token
if not isinstance(user, Client):
raise ValueError("Cannot generate federated token for "
+ user.__class__.__name__)
if longterm and not refresh_token:
# we don't need it for regular tokens
raise ValueError('No refresh token provided for service '+service)
payload['svc'] = service
if longterm: # store service's refresh token for longterms only
payload['refresh'] = refresh_token
slt = binascii.hexlify(user.password[-4:]).decode() # last 4 bytes of salt as hex
payload['pass'] = slt
if longterm:
payload['longterm'] = True
token = jwt.generate_jwt(payload, config.JWT_SECRET, 'HS256',
lifetime=None if longterm else config.JWT_LIFETIME)
return token
class BadUserId(Exception): pass
class TokenExpired(Exception): pass
def parseToken(token, userid=None, allow_longterm=False):
"""
Returns a Player object if the token is valid,
raises an exception otherwise.
"""
try:
header, payload = jwt.verify_jwt(token, config.JWT_SECRET, ['HS256'],
checks_optional=allow_longterm)
except ValueError:
log.info('error in token parsing', exc_info=1)
raise ValueError("Invalid token provided")
except Exception as e:
if str(e) == 'expired':
raise TokenExpired
raise ValueError("Bad token: "+str(e))
if 'sub' not in payload:
raise ValueError('Invalid token provided')
if not allow_longterm and 'longterm' in payload:
raise ValueError('Longterm token not allowed, use short-living one')
if not payload['sub']:
raise ValueError('Invalid userid in token: '+str(payload['sub']))
if userid and payload['sub'] != userid:
raise BadUserId
user = Player.query.get(payload['sub'])
if not user:
raise ValueError("No such player")
slt = binascii.hexlify(user.password[-4:]).decode() # last 4 bytes of salt
if payload.get('pass') != slt:
raise ValueError('Your password was changed, please login again')
if 'svc' in payload and cls == Client and 'longterm' in payload:
if 'longterm' in payload:
validateFederatedToken(payload.get('svc'), payload.get('refresh'))
g.device_id = payload.get('device', None)
# note that this dev id might be obsolete
# if login was performed without token and then token was specified
return user
def check_auth(userid=None,
allow_nonverified=False,
allow_nonfilled=False,
allow_banned=False,
allow_expired=True,
allow_longterm=False,
optional=False):
"""
Check if auth token is passed,
validate that token
and return user object.
:param allow_expired: if we allow access for vendors with expired subscription.
This defaults to True, so methods should be manually restricted.
:param optional: for missing tokens return None without aborting request
"""
# obtain token
if ('Authorization' in request.headers
and request.headers['Authorization'].startswith('Bearer ')):
token = request.headers['Authorization'][7:]
elif request.json and 'token' in request.json:
token = request.json['token']
elif 'token' in request.values:
token = request.values['token']
else:
if optional:
return None
abort('Authorization required', 401)
# check token
try:
user = parseToken(token, userid, allow_longterm)
except ValueError as e:
abort(str(e), 401)
except BadUserId:
abort('You are not authorized to access this method', 403)
except TokenExpired:
abort('Token expired, please obtain new one', 403, expired=True)
if not allow_nonfilled and not user.complete:
abort('Profile is incomplete, please fill!', 403)
return user
def require_auth(_func=None, **params):
"""
Decorator version of check_auth.
This decorator checks if auth token is passed,
validates that token
and passes user object to the decorated function as a `user` argument.
"""
def decorator(func):
@wraps(func)
def caller(*args, **kwargs):
user = check_auth(**params)
g.user = user
# call function
return func(*args, user=user, **kwargs)
return caller
if hasattr(_func, '__call__'): # used as non-function decorator
return decorator(_func)
return decorator
def secure_only(func):
"""
This decorator prohibits access to method by insecure connection,
excluding development state.
"""
@wraps(func)
def wrapper(*args, **kwargs):
if not request.is_secure and not current_app.debug:
abort('Please use secure connection', 406)
return func(*args, **kwargs)
return wrapper
def sendVerificationCode(user):
'Creates email verification code for user and mails it'
if not hasattr(user, 'isEmailVerified'):
raise ValueError('Invalid user type')
code = uuid.uuid4().hex[:8] # 8 hex digits
user.email_verification_code = code
from .apis import mailsend
mailsend(user, 'verification', code=code)
# db session will be committed after this method called
def checkVerificationCode(user, code):
"""
Checks previously generated JWT token and marks user as verified on success.
Will raise ValueError on failure.
"""
if not hasattr(user, 'isEmailVerified'):
raise ValueError('Invalid user type')
if user.isEmailVerified:
raise ValueError('User already verified')
if user.email_verification_code.strip().lower() != code.strip().lower():
raise ValueError('Incorrect code')
user.email_verification_code = None
db.session.commit()
return True
### Field checkers ###
currency_cache = {}
# FIXME: cache currency queries
def currency(val):
"""
Checks whether the value provided is a valid currency.
Raises ValueError if not.
"""
if not val:
return None
val = val.upper()
if val in currency_cache:
return currency_cache[val]
currency = Currency.query.filter_by(name=val).first()
if not currency:
raise ValueError('Unknown currency %s' % val)
#currency_cache[val] = {'name':currency.name, 'iso':currency.iso}
return currency
def country(val):
if not isinstance(val, str):
raise ValueError(val)
if len(val) != 3:
raise ValueError("Incorrect country code: %s" % val)
# TODO: check if country is valid
return val.upper()
def email_validator(val):
"""
Should be 3 parts separated by @ and .,
none of these parts can be empty.
"""
val = val.strip()
if not '@' in val:
raise ValueError('Not a valid e-mail')
user, domain = val.split('@',1)
if (not user
or not '.' in domain):
raise ValueError('Not a valid e-mail')
a,b = domain.rsplit('.',1)
if not a or not b:
raise ValueError('Not a valid e-mail')
return val
def phone_field(val):
if not isinstance(val, str):
raise ValueError('Bad type '+repr(val))
pnum = ''.join([c for c in val if c in '+0123456789'])
if not pnum:
raise ValueError('No digits in phone number '+repr(val))
return pnum
def boolean_field(val):
if hasattr(val,'lower'):
val = val.lower()
if val in [0,False,'0','off','false','no']:
return False
if val in [1,True,'1','on','true','yes']:
return True
raise ValueError(str(val)+' is not boolean')
def gamertag_force_field(val):
val = boolean_field(val)
if val:
g.gamertag_force = True
return val
def encrypt_password(val):
"""
Check password for weakness, and convert it to its hash.
If password provided is None, will generate a random salt w/o password
"""
if val is None:
# just random salt, 16 bytes
return uuid.uuid4().bytes # 16 bytes
if not isinstance(val, str):
raise ValueError(val)
if len(val) < 4:
raise ValueError("Too weak password, minimum is 4 characters")
if len(val) > 1024:
# prohibit extremely long passwords
# because they cause resource eating
raise ValueError("Too long password")
salt = uuid.uuid4().bytes # 16 bytes
crypted = hashlib.pbkdf2_hmac('SHA1', val.encode(), salt, 10000)
return crypted+salt
def check_password(password, reference):
salt = reference[-16:] # last 16 bytes = uuid length
crypted = hashlib.pbkdf2_hmac('SHA1', password.encode(), salt, 10000)
return crypted+salt == reference
def string_field(field, ftype=None, check_unique=True, allow_empty=False):
"""
This decorator-like function returns a function
which will assert that given string is not longer than maxsize.
Also checks for uniqueness if needed.
"""
maxsize = field.type.length
def check(val):
if not isinstance(val, str):
raise TypeError
if maxsize and len(val) > maxsize:
raise ValueError('Too long string')
if not val:
if allow_empty:
return None
raise ValueError('Empty value not allowed')
# check&convert field type (like email) if provided
if ftype:
val = ftype(val)
# now check for uniqueness, if necessary
if field.unique and check_unique:
userid = getattr(g, 'userid', None)
q = field.class_.query.filter(field==val)
if userid:
q = q.filter(field.class_.id != userid)
exists = db.session.query(q.exists()).scalar()
if exists:
raise ValueError('Already used by someone')
return val
return check
def bitmask_field(options):
'''
Converts comma-separated list of options to bitmask.
'''
def check(val):
if not isinstance(val, str):
raise ValueError
mask = 0
parts = val.split(',')
for part in parts:
if part in options:
mask &= options[part]
elif part == '': # ignore empty parts
continue
else:
raise ValueError('Unknown option: '+part)
return mask
return check
def multival_field(options, allow_empty=False):
"""
Converts comma-separated list to set of strings,
checking each item for validity.
"""
def check(val):
if not isinstance(val, str):
raise ValueError
if not val:
if allow_empty:
return []
raise ValueError('Please choose at least one option')
parts = set(val.split(','))
for part in parts:
if part not in options:
raise ValueError('Unknown option: '+part)
return parts
return check
def hex_field(length):
def check(val):
if len(val) != length:
raise ValueError('Should be %d characters' % length)
for c in val:
if c not in 'abcdefABCDEF' and not c.isdigit():
raise ValueError('Bad character %s' % c)
return val
return check
### Extension of RequestParser ###
class MyArgument(Argument):
def handle_validation_error(self, error, bundle_errors=None):
help_str = '({}) '.format(self.help) if self.help else ''
msg = '[{}]: {}{}'.format(self.name, help_str, error)
abort(msg, problem=self.name)
class MyRequestParser(RequestParser):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.argument_class = MyArgument
# FIXME: cache currency queries
class CurrencyField(restful.fields.Raw):
def format(self, curr):
return {'name': curr.name,
'description': curr.iso,
}
class InverseBooleanField(restful.fields.Boolean):
def format(self, val):
return not bool(val)
class AlternatingNested(restful.fields.Raw):
"""
Similar to Nested, but allows to pass 2 different structures.
They are chosen based on result of `condition` proc evaluation
on surrounding object and value.
"""
def __init__(self, condition, nested, alternate, **kwargs):
super().__init__(nested, **kwargs)
self.condition = condition
self.alternate = alternate
self.nested = nested
def output(self, key, obj):
value = restful.fields.get_value(
key if self.attribute is None else self.attribute, obj)
if value is None:
return super().output(key, obj)
return restful.marshal(value, self.nested
if self.condition(obj, value) else
self.alternate)
class CommaListField(restful.fields.Raw):
def format(self, val):
if not isinstance(val, str):
raise ValueError
if not val: # empty string?
return []
return val.split(',')
class JsonField(restful.fields.Raw):
def format(self, val):
try:
return json.loads(val)
except ValueError:
log.warning('Bad json field data')
return val
# Notification
apns_session = None
def send_push(players, alert, **kwargs):
"""
Sends PUSH message with given alert to given player(s).
Kwargs holds message payload.
This method will also send an event via Redis.
Returns True if sent successfully, False if sending failed
or None if no receivers were found (no push tokens).
"""
if not isinstance(players, list):
players = [players]
# first send via redis
# (it shall just ignore message if nobody listens for it)
redis_msg = json.dumps(kwargs)
redis_base = '{}.event.%s'.format('test' if config.TEST else 'prod')
for p in players:
redis.publish(
redis_base % p.id,
redis_msg,
)
# now let's see if we need to send anything with push
receivers = []
#receivers.append('0'*64) # mock
for p in players:
for d in p.devices.filter_by(failed=False):
if d.push_token:
if len(d.push_token) == 64:
# 64 hex digits = 32 bytes, valid token length
receivers.append(d.push_token)
else:
log.warning('Incorrect push token '+d.push_token)
if not receivers:
log.info('Not sending push to {} because no tokens available'.format(
', '.join([
player.nickname for player in players
]) or '(nobody)',
))
return None
log.debug('Have {} receivers'.format(len(receivers)))
msg = apns_clerk.Message(
receivers,
alert=alert,
badge='increment',
content_available=1,
**kwargs
)
global apns_session
try:
if not apns_session:
apns_session = apns_clerk.Session()
except Exception: # import error, OpenSSL error
log.exception('APNS failure!')
return False
# calculate path relative to this script location,
# because working directory may vary (for observer)
cert_file = os.path.dirname(__file__)+'/../apns_{}.pem'.format(config.APNS_CERT)
conn = apns_session.get_connection(
'push_{}'.format(config.APNS_CERT),
cert_file=cert_file)
class PushTimeout(Exception):
pass
def send_push_do(msg, tries=0):
log.debug('send_push: try {}'.format(tries))
log.debug('{} receivers remaining: {}'.format(
len(msg._tokens),
', '.join(r[:2]+'-'+r[-2:] for r in msg._tokens),
))
srv = apns_clerk.APNs(conn)
try:
log.debug('sending..')
with Timeout(10, PushTimeout):
ret = srv.send(msg)
log.info('push sending done for {}, {}'.format(msg, msg.alert))
except PushTimeout:
log.error('Push sending timeout', exc_info=True)
return False
except Exception:
log.error('APNS connection failure', exc_info=True)
return False
else:
for token, reason in ret.failed.items():
log.warning('Device {} failed by {}, shall remove'.format(token,reason))
dev = Device.query.filter_by(push_token=token).first()
if dev:
log.warning('Marking as failed')
dev.failed = True
db.session.commit()
else:
log.warning('No device found with this token!')
for code, error in ret.errors:
log.warning('Error {}: {}'.format(code, error))
if ret.needs_retry():
if tries < 10:
log.info('needs retry.. so will retry')
return send_push_do(ret.retry(), tries+1)
else:
log.warning('needs retry.. but max retries exceed')
return False
log.info('Push sending finished successfully')
return True
return send_push_do(msg)
def notify_event(root, etype, debug=False, **kwargs):
"""
This method creates & saves Event with given parameters.
Also it sends push notification for all interested parties.
Will not send notification to e.g. sender of chat message.
"""
# create event
evt = Event()
evt.root = root.root # ensure root
evt.type = etype
for k, v in kwargs.items():
setattr(evt, k, v)
# will save only after checking
if not kwargs.get('text'):
types = dict(
message = 'New message received',
betstate = dict(
new = 'New challenge available',
cancelled = 'Challenge invitation was cancelled',
accepted = 'Challenge accepted',
declined = 'Challenge declined',
finished = 'Challenge finished ({result})',
aborted = 'Challenge aborted',
),
abort = 'Challenge abort requested',
)
text = types[etype]
if isinstance(text, dict):
game = evt.game
text = text[game.state]
if '{' in text:
text = text.format(
result =
'draw' if game.winner == 'draw'
else 'winner: {}'.format(
getattr(game, game.winner).nickname,
)
)
if game.state == 'finished' and game.details:
text += ' - ' + game.details
evt.text = text
def notify_event_push(event, players, alert):
from . import routes # for fields list
# for id
db.session.add(event)
db.session.commit()
return send_push(
players,
alert,
event=restful.marshal(
evt, routes.EventResource.fields
),
)
if etype == 'message':
# notify msg receiver
if not evt.message:
raise ValueError('No message provided')
return notify_event_push(
evt, evt.message.receiver,
'Message from {sender}: {text}'.format(
sender = evt.message.sender.nickname,
text = evt.message.text,
),
)
elif etype == 'system':
return notify_event_push(
evt, [evt.root.creator, evt.root.opponent],
'Game event detected: {text}'.format(text=evt.text),
)
elif etype == 'betstate':
game = evt.game
if not game:
raise ValueError('No game specified')
if game.state == 'finished' and game.winner in ['creator','opponent']:
# special handling-
for ticket in game.tickets:
ticket.open = False
winner = (evt.game.creator
if evt.game.winner == 'creator' else
evt.game.opponent)
looser = evt.game.other(winner)
if game.tournament:
game.tournament.handle_game_result(
winner=winner,
looser=looser,
)
ret = bool(notify_event_push(
evt, winner,
'Congratulations, you won the game!',
))
ret &= bool(notify_event_push(
evt, looser,
'Sorry, you lost the game...',
))
return ret
if game.state == 'declined':
if game.tournament:
game.tournament.handle_game_result(
winner=game.creator,
looser=game.opponent,
)
if game.state == 'cancelled':
if game.tournament:
game.tournament.handle_game_result(
winner=game.opponent,
looser=game.creator,
)
if game.state == 'aborted':
if game.tournament:
looser = (evt.game.creator
if evt.game.aborter == 'creator' else
evt.game.opponent)
winner = evt.game.other(looser)
game.tournament.handle_game_result(
winner=winner,
looser=looser,
)
msg = {
'new': '{creator} invites you to compete',
'cancelled': '{creator} cancelled their invitation',
'accepted': '{opponent} accepted your invitation, start playing now!',
'declined': '{opponent} declined your invitation',
'finished': 'Your drew. Better luck next time! {text}',
'aborted': 'Challenge was aborted by request of {aborter}',
}[game.state].format(
creator = evt.game.creator.nickname,
opponent = evt.game.opponent.nickname,
text = evt.text,
aborter = evt.game.aborter.nickname if game.aborter else 'UNKNOWN',
)
players = []
if game.state in ['new', 'cancelled', 'finished']:
players.append(game.opponent)
if game.state in ['accepted', 'declined', 'finished']:
players.append(game.creator)
return notify_event_push(evt, players, msg)
elif etype == 'abort':
if not evt.game:
raise ValueError('No game id specified')
if not evt.game.aborter:
raise ValueError('No aborter user id specified')
receiver = evt.game.other(evt.game.aborter)
return notify_event_push(
evt, receiver,
'Game abort requested by {aborter}'.format(
aborter = evt.game.aborter.nickname,
),
)
else:
raise ValueError('invalid etype '+etype)
def notify_chat(msg):
# create event (for now only if this message is within game)
if msg.game:
# don't send regular message push
return notify_event(
msg.game.root, 'message',
message = msg,
)
# now handle pushes
from . import routes # for fields list
return send_push(
msg.receiver,
'Message from {}: {}'.format(
msg.sender.nickname,
msg.text,
),
message=restful.marshal(
msg, routes.ChatMessageResource.fields
),
)
def notify_users(game, justpush=False, players=None, msg=None):
"""
This method creates record in game session,
sends PUSH notifications about game state change
to all interested users
and also sends congratulations email to game winner.
:param game: game object which state was changed
:param justpush: for debugging; push but no mail nor event.
:param players: don't use it externally
:param msg: don't use it externally
"""
if not players:
# create event, if required
if not justpush:
# FIXME increase badge only for interested users
notify_event(
game.root, 'betstate',
game = game,
newstate = game.state,
)
# determine push&mail receivers
if game.state == 'finished' and game.winner in ['creator','opponent']:
# special handling
winner = game.creator if game.winner == 'creator' else game.opponent
looser = game.other(winner)
notify_users(game, justpush, [winner],
'Congratulations, you won the game!')
notify_users(game, justpush, [looser],
'Sorry, you lost the game...')
return
msg = {
'new': '{creator} invites you to compete',
'cancelled': '{creator} cancelled their invitation',
'accepted': '{opponent} accepted your invitation, start playing now!',
'declined': '{opponent} declined your invitation',
'finished': 'Your drew. Better luck next time!',
'aborted': 'Challenge was aborted by request of {aborter}',
}[game.state].format(
creator = game.creator.nickname,
opponent = game.opponent.nickname,
aborter = game.aborter.nickname if game.aborter else 'UNKNOWN',
)
players = []
if game.state in ['new', 'cancelled', 'finished']:
players.append(game.opponent)
if game.state in ['accepted', 'declined', 'finished']:
players.append(game.creator)
from .apis import mailsend
def send_mail(game):
if game.state == 'finished':
if game.winner == 'creator':
winner = game.creator
elif game.winner == 'opponent':
winner = game.opponent
elif game.winner == 'draw':
return # will not notify anybody
else:
log.error('Internal error: incorrect game winner '+game.winner
+' for state '+game.state)
return
return mailsend(
winner, 'win',
date = game.finish_date.strftime('%d.%m.%Y %H:%M:%S UTC'),
bet = game.bet,
balance = winner.available,
)
from . import routes # for fields list
result = send_push(
players, msg,
game=restful.marshal(
game, routes.GameResource.fields
)
)
if result is None:
result = True # had no tokens - it's okay
# and send email if applicable
if not justpush:
result = result and send_mail(game)
return result | {"/v1/signals_definitions.py": ["/v1/main.py", "/v1/badges/__init__.py"], "/v1/polling.py": ["/config.py", "/v1/helpers.py", "/v1/models.py", "/v1/apis.py", "/v1/common.py"], "/v1/badges/__init__.py": ["/v1/badges/badges_description.py", "/v1/badges/fifa15.py"], "/v1/apis.py": ["/config.py", "/v1/helpers.py", "/v1/mock.py"], "/v1/__init__.py": ["/v1/main.py"], "/mobsite.py": ["/config.py"], "/v1/badges/fifa15.py": ["/v1/main.py", "/v1/badges/badges_description.py"], "/v1/helpers.py": ["/config.py", "/v1/models.py", "/v1/main.py", "/v1/common.py", "/v1/apis.py", "/v1/__init__.py"], "/v1/models.py": ["/v1/main.py", "/v1/common.py", "/v1/badges/__init__.py", "/config.py", "/v1/helpers.py", "/v1/routes.py", "/v1/polling.py"], "/poll.py": ["/main.py", "/v1/__init__.py"], "/v1/cas.py": ["/config.py", "/v1/main.py", "/v1/apis.py", "/v1/models.py", "/v1/common.py"], "/debug_console.py": ["/main.py", "/v1/models.py", "/v1/helpers.py", "/v1/routes.py"], "/v1/routes.py": ["/config.py", "/v1/signals_definitions.py", "/v1/models.py", "/v1/helpers.py", "/v1/apis.py", "/v1/polling.py", "/v1/main.py"], "/main.py": ["/config.py", "/v1/__init__.py", "/v1/main.py", "/v1/models.py"], "/v1/main.py": ["/config.py", "/v1/__init__.py", "/v1/admin.py"], "/v1/admin.py": ["/v1/models.py", "/v1/polling.py", "/v1/helpers.py"], "/observer.py": ["/config.py", "/v1/polling.py", "/v1/models.py", "/v1/apis.py"]} |
71,985 | topdevman/flask-betg | refs/heads/master | /migrations/versions/0cc69c6eee67_tournaments.py | """tournaments
Revision ID: 0cc69c6eee67
Revises: None
Create Date: 2016-01-05 05:49:24.926070
"""
# revision identifiers, used by Alembic.
revision = '0cc69c6eee67'
down_revision = None
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('tournament',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('payin', sa.Float(), nullable=False),
sa.Column('payout', sa.Float(), nullable=False),
sa.Column('aborted', sa.Boolean(), server_default='0', nullable=False),
sa.Column('winner_id', sa.Integer(), nullable=True),
sa.Column('rounds_count', sa.Integer(), nullable=True),
sa.Column('open_date', sa.DateTime(), nullable=False),
sa.Column('start_date', sa.DateTime(), nullable=False),
sa.Column('finish_date', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['winner_id'], ['player.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('participant',
sa.Column('player_id', sa.Integer(), nullable=False),
sa.Column('tournament_id', sa.Integer(), nullable=False),
sa.Column('defeated', sa.Boolean(), server_default='0', nullable=False),
sa.Column('round', sa.Integer(), server_default='1', nullable=False),
sa.Column('order', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['player_id'], ['player.id'], ),
sa.ForeignKeyConstraint(['tournament_id'], ['tournament.id'], ),
sa.PrimaryKeyConstraint('player_id', 'tournament_id'),
sa.UniqueConstraint('tournament_id', 'order')
)
op.create_index(op.f('ix_chat_message_game_id'), 'chat_message', ['game_id'], unique=False)
op.alter_column('event', 'type',
existing_type=mysql.ENUM('message', 'system', 'betstate', 'abort', 'report'),
nullable=False)
op.add_column('game', sa.Column('tournament_id', sa.Integer(), nullable=True))
op.alter_column('game', 'gamemode',
existing_type=mysql.VARCHAR(length=64),
nullable=False)
op.alter_column('game', 'gamertag_creator',
existing_type=mysql.VARCHAR(length=128),
nullable=True)
op.alter_column('game', 'gametype',
existing_type=mysql.VARCHAR(length=64),
nullable=False)
op.create_index(op.f('ix_game_tournament_id'), 'game', ['tournament_id'], unique=False)
op.create_foreign_key(None, 'game', 'tournament', ['tournament_id'], ['id'])
op.create_unique_constraint(None, 'player', ['riot_summonerName'])
op.create_unique_constraint(None, 'player', ['tibia_character'])
op.create_unique_constraint(None, 'player', ['ea_gamertag'])
op.create_unique_constraint(None, 'player', ['nickname'])
op.create_unique_constraint(None, 'player', ['email'])
op.create_unique_constraint(None, 'player', ['steam_id'])
op.create_unique_constraint(None, 'player', ['starcraft_uid'])
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(None, 'player', type_='unique')
op.drop_constraint(None, 'player', type_='unique')
op.drop_constraint(None, 'player', type_='unique')
op.drop_constraint(None, 'player', type_='unique')
op.drop_constraint(None, 'player', type_='unique')
op.drop_constraint(None, 'player', type_='unique')
op.drop_constraint(None, 'player', type_='unique')
op.drop_constraint(None, 'game', type_='foreignkey')
op.drop_index(op.f('ix_game_tournament_id'), table_name='game')
op.alter_column('game', 'gametype',
existing_type=mysql.VARCHAR(length=64),
nullable=True)
op.alter_column('game', 'gamertag_creator',
existing_type=mysql.VARCHAR(length=128),
nullable=False)
op.alter_column('game', 'gamemode',
existing_type=mysql.VARCHAR(length=64),
nullable=True)
op.drop_column('game', 'tournament_id')
op.alter_column('event', 'type',
existing_type=mysql.ENUM('message', 'system', 'betstate', 'abort', 'report'),
nullable=True)
op.drop_index(op.f('ix_chat_message_game_id'), table_name='chat_message')
op.drop_table('participant')
op.drop_table('tournament')
### end Alembic commands ###
| {"/v1/signals_definitions.py": ["/v1/main.py", "/v1/badges/__init__.py"], "/v1/polling.py": ["/config.py", "/v1/helpers.py", "/v1/models.py", "/v1/apis.py", "/v1/common.py"], "/v1/badges/__init__.py": ["/v1/badges/badges_description.py", "/v1/badges/fifa15.py"], "/v1/apis.py": ["/config.py", "/v1/helpers.py", "/v1/mock.py"], "/v1/__init__.py": ["/v1/main.py"], "/mobsite.py": ["/config.py"], "/v1/badges/fifa15.py": ["/v1/main.py", "/v1/badges/badges_description.py"], "/v1/helpers.py": ["/config.py", "/v1/models.py", "/v1/main.py", "/v1/common.py", "/v1/apis.py", "/v1/__init__.py"], "/v1/models.py": ["/v1/main.py", "/v1/common.py", "/v1/badges/__init__.py", "/config.py", "/v1/helpers.py", "/v1/routes.py", "/v1/polling.py"], "/poll.py": ["/main.py", "/v1/__init__.py"], "/v1/cas.py": ["/config.py", "/v1/main.py", "/v1/apis.py", "/v1/models.py", "/v1/common.py"], "/debug_console.py": ["/main.py", "/v1/models.py", "/v1/helpers.py", "/v1/routes.py"], "/v1/routes.py": ["/config.py", "/v1/signals_definitions.py", "/v1/models.py", "/v1/helpers.py", "/v1/apis.py", "/v1/polling.py", "/v1/main.py"], "/main.py": ["/config.py", "/v1/__init__.py", "/v1/main.py", "/v1/models.py"], "/v1/main.py": ["/config.py", "/v1/__init__.py", "/v1/admin.py"], "/v1/admin.py": ["/v1/models.py", "/v1/polling.py", "/v1/helpers.py"], "/observer.py": ["/config.py", "/v1/polling.py", "/v1/models.py", "/v1/apis.py"]} |
71,986 | topdevman/flask-betg | refs/heads/master | /v1/models.py | from datetime import datetime, timedelta
from sqlalchemy import or_, case, and_
from sqlalchemy.orm import deferred, undefer_group, undefer, attributes
from sqlalchemy.sql.expression import func
from sqlalchemy.ext.hybrid import hybrid_property, hybrid_method
from flask import g
from .main import db
from .common import *
from v1.badges import BADGES, Fifa15Badges
import config
class Player(db.Model):
id = db.Column(db.Integer, primary_key=True)
nickname = db.Column(db.String(64), unique=True)
email = db.Column(db.String(128), nullable=True, unique=True)
password = db.Column(db.LargeBinary(36))
facebook_id = db.Column(db.String(64))
facebook_token = db.Column(db.String(128))
twitter_id = db.Column(db.Integer)
twitter_token = db.Column(db.String(256))
williamhill_id = db.Column(db.String(128))
williamhill_token = db.Column(db.String(128))
# williamhill_currency = db.Column(db.String(3)) # TODO handle&save it?
create_date = db.Column(db.DateTime, default=datetime.utcnow)
bio = db.Column(db.Text)
ea_gamertag = db.Column(db.String(64), unique=True)
fifa_team = db.Column(db.String(64), unique=False)
riot_summonerName = db.Column(db.String(64), unique=True)
# in fact, it is integer, but saved as string for compatibility
steam_id = db.Column(db.String(64), unique=True)
starcraft_uid = db.Column(db.String(64), unique=True)
tibia_character = db.Column(db.String(64), unique=True)
balance = db.Column(db.Float, default=0)
locked = db.Column(db.Float, default=0)
def __init__(self):
self.badges = Badges()
db.session.add(self.badges)
def report_for_game(self, game_id):
return Report.query.filter(Report.game_id == game_id, Report.player_id == self.id).first()
@property
def available(self):
return self.balance - self.locked
@property
def balance_obj(self):
return {
'full': self.balance,
'locked': self.locked,
'available': self.available,
}
@property
def complete(self):
return (self.email != None) & (self.nickname != None)
@hybrid_property
def games(self):
return Game.query.filter(
(Game.creator_id == self.id) | # OR
(Game.opponent_id == self.id))
@hybrid_method
def gamecount_impl(self, *filters):
return fast_count(self.games.filter(*filters))
@gamecount_impl.expression
def gamecount_impl(cls, *filters):
return (
cls.games
.filter(*filters)
.with_entities(func.count('*'))
.as_scalar()
)
@hybrid_property
def gamecount(self):
return self.gamecount_impl()
@hybrid_method
def winrate_impl(self, *filters):
count = 0
wins = 0
for game in self.games.filter(Game.state == 'finished', *filters):
count += 1
whoami = 'creator' if game.creator_id == self.id else 'opponent'
if game.winner == 'draw':
wins += 0.5
elif game.winner == whoami:
wins += 1
if count == 0:
# no finished games, no data
return None
return wins / count
@hybrid_property
def mygames(cls):
return (
db.select([func.count(Game.id)])
.where(db.and_(
Game.state == 'finished',
))
)
@hybrid_property
def mygamescount(cls):
return (
cls.mygames
.where(cls.id.in_([
Game.creator_id,
Game.opponent_id,
]))
.label('cnt')
)
@hybrid_property
def mygameswon(cls):
return (
cls.mygames
.where(
(
(Game.creator_id == cls.id) &
(Game.winner == 'creator')
) | (
(Game.opponent_id == cls.id) &
(Game.winner == 'opponent')
)
)
.label('won')
)
@hybrid_property
def mygamesdraw(cls):
return (
cls.mygames.with_only_columns([func.count(Game.id) / 2])
.where(
(
(Game.creator_id == cls.id) |
(Game.opponent_id == cls.id)
) &
Game.winner == 'draw',
)
.label('draw')
)
@winrate_impl.expression
def winrate_impl(cls, *filters):
mygames = (
db.select([func.count(Game.id)])
.where(db.and_(
Game.state == 'finished',
*filters
))
)
count = (
mygames
.where(cls.id.in_([
Game.creator_id,
Game.opponent_id,
]))
.label('cnt')
)
won = (
mygames
.where(
(
(Game.creator_id == cls.id) &
(Game.winner == 'creator')
) | (
(Game.opponent_id == cls.id) &
(Game.winner == 'opponent')
)
)
.label('won')
)
draw = (
mygames.with_only_columns([func.count(Game.id) / 2])
.where(
(
(Game.creator_id == cls.id) |
(Game.opponent_id == cls.id)
) &
Game.winner == 'draw',
)
.label('draw')
)
return case([
(count == 0, None), # if count == 0 then NULL else (calc)
], else_=
(won + draw) / count
)
@hybrid_property
def winrate(self):
if 'winrate_filt' in g and g.winrate_filt:
log.debug('winrate: using filt ' + ','.join(
str(f) for f in g.winrate_filt
))
return self.winrate_impl(*g.winrate_filt)
return self.winrate_impl()
# @hybrid_method
def winratehist(self, days=None, weeks=None, months=None):
count = days or weeks or months
if not count:
raise ValueError('Please provide something!')
# 30.5 is approximate number of days in month
delta = timedelta(days=1 if days else 7 if weeks else 30.5)
now = datetime.utcnow()
ret = []
for i in range(count):
prev = now - delta
count, wins = 0, 0
for game in self.games.filter(
Game.state == 'finished',
Game.finish_date > prev,
Game.finish_date <= now,
):
count += 1
whoami = 'creator' if game.creator_id == self.id else 'opponent'
if game.winner == 'draw':
wins += 0.5
elif game.winner == whoami:
wins += 1
rate = (wins / count) if count else 0
ret.append((prev, count, wins, rate))
now = prev
return ret
@hybrid_property
def lastbet(self):
return self.games.order_by(Game.create_date.desc()).first().create_date
@lastbet.expression
def lastbet(cls):
return (
db.select([Game.create_date])
.where(cls.id.in_([
Game.creator_id,
Game.opponent_id,
]))
.order_by(Game.create_date.desc())
.limit(1)
.label('lastbet')
)
@hybrid_method
def popularity_impl(self, *filters):
return fast_count(
self.games.filter(
Game.state == 'accepted',
*filters
)
)
@popularity_impl.expression
def popularity_impl(cls, *filters):
return (
db.select([func.count(Game.id)])
.where(
db.and_(
cls.id.in_([
Game.creator_id,
Game.opponent_id,
]),
Game.state == 'accepted',
*filters
)
)
.label('popularity')
)
@hybrid_property
def popularity(self):
return self.popularity_impl() # without filters
_leadercache = {} # is a class field
_leadercachetime = None
@property
def leaderposition(self):
if not self._leadercache or self._leadercachetime < datetime.utcnow():
self._leadercachetime = datetime.utcnow() + \
timedelta(minutes=5)
self._leadercache = {}
# This is dirty way, but "db-related" one did not work..
# http://stackoverflow.com/questions/7057772/get-row-position-in-mysql-query
# MySQL kept ordering line numbers according to ID,
# regardless of ORDER BY clause.
# Maybe because of joins or so.
# TODO: maybe cache result in memory for e.g. 5min
q = Player.query.with_entities(
Player.id,
).order_by(
# FIXME: hardcoded algorithm is not a good thing?
Player.winrate.desc(),
Player.gamecount.desc(),
Player.id.desc(),
)
self._leadercache = {
row[0]: n + 1
for n, row in enumerate(q)
}
return self._leadercache[self.id]
@hybrid_property
def recent_opponents(self):
# last 5 sent and 5 received
sent, recv = [
Game.query.filter(field == self.id)
.order_by(Game.create_date.desc())
.limit(5).with_entities(other).subquery()
for field, other in [
(Game.creator_id, Game.opponent_id),
(Game.opponent_id, Game.creator_id),
]
]
return Player.query.filter(or_(
Player.id.in_(db.session.query(sent.c.opponent_id)),
Player.id.in_(db.session.query(recv.c.creator_id)),
))
@property
def has_userpic(self):
from .routes import UserpicResource
return bool(UserpicResource.findfile(self))
_identities = [
'nickname',
'ea_gamertag', 'riot_summonerName', 'steam_id',
]
@classmethod
def find(cls, key):
"""
Retrieves user by player id or integer id.
If id is 'me', will return currently logged in user or None.
"""
if key == '_':
from .helpers import MyRequestParser as RequestParser
parser = RequestParser()
parser.add_argument('id')
args = parser.parse_args()
key = args.id
if key.lower() == 'me':
return getattr(g, 'user', None)
if '@' in key and '.' in key:
return cls.query.filter_by(email=key).first()
p = None
try:
p = cls.query.get(int(key))
except ValueError:
pass
for identity in cls._identities:
if p:
return p
p = cls.query.filter_by(**{identity: key}).first()
return p
@classmethod
def find_or_fail(cls, key):
player = cls.find(key)
if not player:
raise ValueError('Player {} is not registered on BetGame'.format(key))
return player
@classmethod
def search(cls, filt, operation='like'):
"""
Filt should be suitable for SQL LIKE statement.
E.g. "word%" will search anything starting with word.
"""
if len(filt) < 1:
return []
return cls.query.filter(
or_(*[
getattr(
getattr(cls, identity),
operation,
)(filt)
for identity in cls._identities
])
)
def __repr__(self):
return '<Player id={} nickname={} balance={}>'.format(
self.id, self.nickname, self.balance)
@property
def is_authenticated(self): # flask login integration
return True
@property
def is_anonymous(self): # flask login integration
return False
@property
def is_active(self): # flask login integration
return self.id in config.ADMIN_IDS # active means admin
def get_id(self): # flask login integration
return str(self.id)
def get_badges_from_groups(self, *groups, return_ids=False):
"""Loads player's Badges with given badges groups,
if self.badges was accessed it will be updated inplace.
Use this if action may be included inseveral badges of this group
"""
query = db.session.query(Badges).filter(Badges.id == self.badges.id)
# TODO: use when sqlalchemy 1.0.12 will be released
# preferable way to work with "undefer_group", but
# in query undefers only last group
# e.g. query.options(undefer_group("g_1"), undefer_group("g_2"))
# in this column only group "g_2" will be undeferred
# no need to load again from db inside one session
# undeferred_groups = [ # making groups loadable by this query
# undefer_group(g_name)
# for g_name in groups
# if g_name not in self.badges.__dict__
# ]
# if undeferred_groups:
# query.options(
# # another not deferred columns will be loaded automatically
# *undeferred_groups
# ).all()
column_names = columns_from_groups(self.badges, *(g_name for g_name in groups))
undeffered_columns = (
undefer(c_name)
for c_name, c_group in column_names
)
if undeffered_columns:
query.options(
*undeffered_columns
).first()
if return_ids:
return self.badges, column_names
return self.badges
def get_badges(self, *badges):
"""Loads player's Badges with given badges"""
db.session.query(Badges).filter(
Badges.id == self.badges.id
).options(
*(undefer(b_name) for b_name in badges)
).first()
return self.badges
class Transaction(db.Model):
id = db.Column(db.Integer, primary_key=True)
player_id = db.Column(db.Integer, db.ForeignKey('player.id'), index=True)
player = db.relationship(Player,
backref=db.backref('transactions',
lazy='dynamic') # return query, not list
)
date = db.Column(db.DateTime, default=datetime.utcnow)
type = db.Column(db.Enum('deposit', 'withdraw', 'won', 'lost', 'other'), nullable=False)
sum = db.Column(db.Float, nullable=False)
balance = db.Column(db.Float, nullable=False) # new balance
game_id = db.Column(db.Integer, db.ForeignKey('game.id'), nullable=True)
game = db.relationship('Game', backref=db.backref('transaction', uselist=False))
comment = db.Column(db.Text)
def __repr__(self):
return '<Transaction id={} sum={}>'.format(self.id, self.sum)
class Device(db.Model):
id = db.Column(db.Integer, primary_key=True)
player_id = db.Column(db.Integer, db.ForeignKey('player.id'), index=True)
player = db.relationship(Player, backref=db.backref('devices',
lazy='dynamic'))
push_token = db.Column(db.String(128), nullable=True)
last_login = db.Column(db.DateTime, default=datetime.utcnow)
failed = db.Column(db.Boolean, default=False)
def __repr__(self):
return '<Device id={}, failed={}>'.format(self.id, self.failed)
class Tournament(db.Model):
id = db.Column(db.Integer, primary_key=True)
payin = db.Column(db.Float, nullable=False)
payout = db.Column(db.Float, nullable=False)
aborted = db.Column(db.Boolean, nullable=False, default=False, server_default='0')
winner_id = db.Column(db.Integer(), db.ForeignKey(Player.id), nullable=True)
winner = db.relationship(Player, backref='won_tournaments')
gametype = db.Column(db.String(64), nullable=False)
gamemode = db.Column(db.String(64), nullable=False)
players = db.relationship(
Player,
secondary='participant',
backref='tournaments',
lazy='dynamic',
collection_class=list,
)
rounds_count = db.Column(db.Integer)
@hybrid_property
def participants_cap(self):
return 2 ** self.rounds_count
@participants_cap.expression
def participants_cap(cls):
return func.pow(2, cls.rounds_count)
@hybrid_property
def full(self):
return self.participants_count >= self.participants_cap
@hybrid_property
def participants_count(self):
return Participant.query.filter(Participant.tournament_id == self.id).count()
open_date = db.Column(db.DateTime, nullable=False)
start_date = db.Column(db.DateTime, nullable=False)
finish_date = db.Column(db.DateTime, nullable=False)
@hybrid_property
def tournament_length(self) -> timedelta:
return self.finish_date - self.start_date
@hybrid_property
def round_length(self) -> timedelta:
return self.tournament_length / self.rounds_count
@property
def _rounds_dates(self):
for i in range(self.rounds_count):
round_start = self.start_date + self.round_length * i
round_end = self.start_date + self.round_length * (i+1)
yield {
'start': round_start,
'end': round_end,
}
@property
def rounds_dates(self):
return list(self._rounds_dates)
@property
def current_round(self):
round_index = (datetime.utcnow() - self.start_date) // self.round_length
round_index = self.rounds_count if round_index > self.rounds_count else round_index
round_index = 0 if self.round_index < 0 else round_index
return round_index
@hybrid_property
def available(self):
return all((
self.open_date < datetime.utcnow(),
datetime.utcnow() < self.start_date,
self.participants_count < self.participants_cap,
))
@available.expression
def available(cls):
return and_(
cls.open_date < datetime.utcnow(),
datetime.utcnow() < cls.start_date,
cls.participants_count < cls.participants_cap,
)
@hybrid_property
def started(self):
return self.start_date < datetime.utcnow()
def __init__(self, gametype, gamemode, rounds_count, open_date, start_date, finish_date, payin):
assert rounds_count >= 0
assert open_date < start_date < finish_date
self.gametype = gametype
self.gamemode = gamemode
self.rounds_count = rounds_count
self.open_date, self.start_date, self.finish_date = open_date, start_date, finish_date
self.payin = payin
self.payout = payin * self.participants_cap
def create_participant(self, player: Player):
if self.participants_count >= self.participants_cap:
return None
participant = Participant(player.id, self.id)
if not self.participants:
participant.order = 0
else:
participant.order = self.participants[-1].order + 1
return participant
def add_player(self, player: Player):
if self.aborted:
return False, 'This tournament was aborted', 'aborted'
if self.open_date > datetime.utcnow():
return False, 'This tournament is not open yet', 'not_open'
if self.started:
return False, 'This tournament has already started', 'started'
if player.available < self.payin:
return False, 'You don\'t have enough coins', 'coins'
participant = self.create_participant(player)
if participant:
player.locked += self.payin
db.session.add(participant)
db.session.commit()
return True, 'Success', None
else:
return False, 'Tournament is full', 'participants_cap'
def abort(self):
self.aborted = True
for participant in self.participants:
participant.player.locked -= self.payin
db.session.delete(participant)
db.session.commit()
def set_winner(self, participant):
self.winner = participant.player
for participant in self.participants:
participant.player.locked -= self.payin
participant.player.balance -= self.payin
db.session.add(Transaction(
player=participant.player,
type='other',
sum=self.payin,
balance=participant.player.balance,
comment='Tournament buy in'
))
self.winner.balance += self.payout
db.session.add(Transaction(
player=self.winner,
type='win',
sum=self.payout,
balance=self.winner.balance,
comment='Tournament payout'
))
db.session.commit()
def check_winner(self):
maybe_winner = None
for participant in self.participants:
if not maybe_winner or maybe_winner.round < participant.round:
maybe_winner = participant
if maybe_winner and maybe_winner.round > self.rounds_count:
self.set_winner(maybe_winner)
return True
@property
def participants_by_round(self):
participants = list(self.participants)
while len(participants) < self.participants_cap:
participants.append(None)
result = [[
(p1, p2)
for p1, p2 in zip(participants[::2], participants[1::2])
]]
for round_index in range(2, self.rounds_count + 1):
participants = []
for p1, p2 in result[-1]:
if p1 and p1.round >= round_index > p2.round:
participants.append(p1)
continue
if p2 and p2.round >= round_index > p1.round:
participants.append(p2)
continue
participants.append(None)
result.append([
(p1, p2)
for p1, p2 in zip(participants[::2], participants[1::2])
])
return result
@property
def current_opponents_by_id(self) -> dict:
opponents_by_id = {}
participants = self.participants_by_round[self.current_round - 1]
for p1, p2 in participants:
if p1:
opponents_by_id[p1.player_id] = p2
if p2:
opponents_by_id[p2.player_id] = p1
return opponents_by_id
def get_opponent(self, player: Player):
self.check_state()
current_participant = Participant.query.get((player.id, self.id))
if current_participant.defeated or current_participant.round < self.current_round:
return None, 'You were defeated'
if current_participant.round > self.current_round:
return None, 'Next round haven\'t begun yet'
opponent = self.current_opponents_by_id.get(player.id, None)
if opponent:
return opponent.player, None
current_participant.round += 1
db.session.commit()
if self.winner and self.winner.id == player.id:
return None, 'You won tournament!'
return None, None
def check_state(self):
if self.started and not self.full:
self.abort()
# check if previous round games resolved
previous_participants = self.participants_by_round[self.current_round - 2]
for p1, p2 in previous_participants:
if not p1.defeated and not p2.defeated and p1.round < self.current_round and p2.round < self.current_round:
for _p1, _p2 in [(p1, p2), (p2, p1)]:
game = Game.query.filter(
Game.tournament_id == self.id,
Game.creator_id == _p1.player_id,
Game.opponent_id == _p2.player_id
).first()
if game.state == 'new':
game.state = 'declined'
notify_event(game.id, 'betstate', game=game)
db.session.commit()
if not self.aborted and not self.winner:
self.check_winner()
def handle_game_result(self, winner: Player, looser: Player):
winner_participant = Participant.query.get((winner.id, self.id))
looser_participant = Participant.query.get((looser.id, self.id))
if winner_participant.round == looser_participant.round and not winner_participant.defeated and not looser_participant.defeated:
looser_participant.defeated = True
winner_participant.round += 1
db.session.commit()
class Participant(db.Model):
__tablename__ = 'participant'
def __init__(self, player_id, tournament_id):
self.player_id, self.tournament_id = player_id, tournament_id
player_id = db.Column(db.Integer(), db.ForeignKey(Player.id), primary_key=True)
tournament_id = db.Column(db.Integer(), db.ForeignKey(Tournament.id), primary_key=True)
tournament = db.relationship(
Tournament, backref=db.backref(
'participants', order_by='Participant.order'
)
)
player = db.relationship(Player, backref='participations')
defeated = db.Column(db.Boolean, default=False, server_default='0', nullable=False)
round = db.Column(db.Integer, default=1, server_default='1', nullable=False)
order = db.Column(db.Integer, nullable=True)
db.UniqueConstraint(tournament_id, order)
class Ticket(db.Model):
id = db.Column(db.Integer(), primary_key=True)
open = db.Column(db.Boolean(), nullable=False, default=1, server_default='1')
created = db.Column(db.DateTime(), nullable=False, default=datetime.utcnow())
game_id = db.Column(db.Integer(), db.ForeignKey('game.id'))
game = db.relationship('Game', backref='tickets')
type = db.Column(db.Enum('reports_mismatch'), nullable=False)
def __init__(self, game, type):
self.game = game
self.type = type
def chat_with(self, user_id):
for message in self.messages:
assert isinstance(message, ChatMessage)
if message.sender_id == user_id or message.receiver_id == user_id:
yield message
@property
def game_winner_nickname(self):
if self.open:
return None
if self.game.winner == 'draw':
return 'draw'
if self.game.winner == 'creator':
return self.game.creator.nickname
if self.game.winner == 'opponent':
return self.game.opponent.nickname
class Report(db.Model):
game_id = db.Column(db.Integer(), db.ForeignKey('game.id'), primary_key=True, index=True)
player_id = db.Column(db.Integer(), db.ForeignKey(Player.id), primary_key=True, index=True)
ticket_id = db.Column(db.Integer(), db.ForeignKey(Ticket.id), nullable=True, index=True)
game = db.relationship('Game', backref='reports')
player = db.relationship(Player, backref='reports')
ticket = db.relationship(Ticket, backref='reports')
created = db.Column(db.DateTime(), nullable=False, default=datetime.utcnow())
modified = db.Column(db.DateTime(), nullable=True, default=None)
result = db.Column(db.Enum(
'won', 'lost', 'draw',
), nullable=False)
def __init__(self, game, player, result):
self.game = game
self.player = player
self.result = result
self.match = True
self.other_report = None
def modify(self, result):
self.result = result
self.modified = datetime.utcnow()
def check_reports(self):
self.other_report = Report.query.filter(Report.game_id == self.game_id, Report.player_id != self.player_id).first()
if self.other_report:
if self.result == 'won' and self.other_report.result == 'won':
return False
if self.result == 'lost' and self.other_report.result == 'lost':
return False
if self.result == 'draw' and self.other_report.result != 'draw':
return False
return True
class Game(db.Model):
id = db.Column(db.Integer, primary_key=True)
creator_id = db.Column(db.Integer, db.ForeignKey('player.id'), index=True)
creator = db.relationship(Player, foreign_keys='Game.creator_id')
opponent_id = db.Column(db.Integer, db.ForeignKey('player.id'), index=True)
opponent = db.relationship(Player, foreign_keys='Game.opponent_id')
parent_id = db.Column(db.Integer, db.ForeignKey('game.id'),
index=True)
parent = db.relationship('Game', foreign_keys='Game.parent_id',
backref='children', remote_side='Game.id')
gamertag_creator = db.Column(db.String(128))
gamertag_opponent = db.Column(db.String(128))
twitch_handle = db.Column(db.String(128))
twitch_identity_creator = db.Column(db.String(128))
twitch_identity_opponent = db.Column(db.String(128))
gametype = db.Column(db.String(64), nullable=False)
gamemode = db.Column(db.String(64), nullable=False)
meta = db.Column(db.Text) # for poller to use
bet = db.Column(db.Float, nullable=False)
create_date = db.Column(db.DateTime, default=datetime.utcnow)
state = db.Column(db.Enum(
'new', 'cancelled', 'accepted', 'declined', 'finished', 'aborted',
), default='new')
accept_date = db.Column(db.DateTime, nullable=True)
aborter_id = db.Column(db.Integer, db.ForeignKey('player.id'))
aborter = db.relationship(Player, foreign_keys='Game.aborter_id')
winner = db.Column(db.Enum('creator', 'opponent', 'draw'), nullable=True)
details = db.Column(db.Text, nullable=True)
finish_date = db.Column(db.DateTime, nullable=True)
tournament_id = db.Column(db.Integer(), db.ForeignKey(Tournament.id), index=True, nullable=True)
tournament = db.relationship(Tournament, backref='games')
def _make_identity_getter(kind, prop):
def _getter(self):
if not self.gametype:
return None
from .polling import Poller
poller = Poller.findPoller(self.gametype)
identity = getattr(poller, kind)
if not identity:
return None
return getattr(identity, prop)
_getter.__name__ = '_'.join((kind, prop))
return _getter
for kind in 'identity', 'twitch_identity':
for prop in 'id', 'name':
# I know it is not good to modify locals(),
# but it works here (as we are not in function).
# At least it works in python 3.4/3.5
locals()['_'.join((kind, prop))] = property(
_make_identity_getter(kind, prop)
)
del _make_identity_getter
def _make_identity_splitter(role, prop):
attr = 'gamertag_' + role
seq = {'val': 0, 'text': 1}[prop]
def _getter(self):
# formatter returns tuple (internal, human_readable)
return self.identity.formatter(getattr(self, attr))[seq]
return _getter
for role in 'creator', 'opponent':
for prop in 'val', 'text':
locals()['gamertag_{}_{}'.format(role, prop)] = property(
_make_identity_splitter(role, prop)
)
del _make_identity_splitter
@property
def is_root(self):
"""
Returns true if this game is session starter
"""
return not bool(self.parent)
@property
def root(self):
"""
Returns root game for this game
"""
if not self.parent:
return self
return self.parent.root
@property
def has_message(self):
from .routes import GameMessageResource
return bool(GameMessageResource.findfile(self))
@property
def is_ingame(self):
from .polling import Poller
return (self.gamemode in
Poller.findPoller(self.gametype).gamemodes_ingame)
@hybrid_method
def is_game_player(self, player):
return (player.id == self.creator_id) | (player.id == self.opponent_id)
@hybrid_method
def other(self, player):
if player.id == self.creator_id:
return self.opponent
if player.id == self.opponent_id:
return self.creator
return None
@other.expression
def other(cls, player):
return case([
(player.id == cls.creator_id, cls.opponent),
(player.id == cls.opponent_id, cls.creator),
], else_=None)
def __repr__(self):
return '<Game id={} state={}>'.format(self.id, self.state)
class ChatMessage(db.Model):
id = db.Column(db.Integer, primary_key=True)
sender_id = db.Column(db.Integer, db.ForeignKey('player.id'), index=True)
sender = db.relationship(Player, foreign_keys='ChatMessage.sender_id')
receiver_id = db.Column(db.Integer, db.ForeignKey('player.id'), index=True)
receiver = db.relationship(Player, foreign_keys='ChatMessage.receiver_id')
game_id = db.Column(db.Integer, db.ForeignKey('game.id'), index=True)
game = db.relationship(Game)
admin_message = db.Column(db.Boolean, nullable=False, default=False, server_default='0')
text = db.Column(db.Text)
time = db.Column(db.DateTime, default=datetime.utcnow)
has_attachment = db.Column(db.Boolean, default=False)
viewed = db.Column(db.Boolean, default=False)
ticket_id = db.Column(db.Integer, db.ForeignKey('ticket.id'), index=True)
ticket = db.relationship(Ticket, backref=db.backref(
'messages', order_by=time.asc()
))
@hybrid_method
def is_for(self, user):
return (user.id == self.sender_id) | (user.id == self.receiver_id)
def other(self, user):
if user == self.sender:
return self.receiver
if user == self.receiver:
return self.sender
raise ValueError('Message is unrelated to user %d' % user.id)
@classmethod
def for_user(cls, user):
return cls.query.filter(or_(
cls.sender_id == user.id,
cls.receiver_id == user.id,
))
@classmethod
def for_users(cls, a, b):
return cls.query.filter(
cls.sender_id.in_([a.id, b.id]),
cls.receiver_id.in_([a.id, b.id]),
)
def __repr__(self):
return '<ChatMessage id={} text={}>'.format(self.id, self.text)
class Event(db.Model):
id = db.Column(db.Integer, primary_key=True)
# game should be the root game of inner challenges hierarchy
# as it denotes gaming session
# TODO: maybe make it optional?
root_id = db.Column(db.Integer, db.ForeignKey('game.id'),
index=True, nullable=False)
root = db.relationship(Game, backref='events', foreign_keys='Event.root_id')
@db.validates('root')
def validate_root(self, key, game):
# ensure it is the root of game session
return game.root
time = db.Column(db.DateTime, default=datetime.utcnow, index=True)
type = db.Column(db.Enum(
'message', # one user sent message to another
'system', # system notification about game state, bet state unchanged
'betstate', # some bet changed its state, or was created
'abort', # request to abort one of bets in this session
'report', # user reported about game result
), nullable=False)
# for 'message' type
message_id = db.Column(db.Integer, db.ForeignKey('chat_message.id'))
message = db.relationship(ChatMessage)
# for 'system', 'betstate' and 'abort' types
game_id = db.Column(db.Integer, db.ForeignKey('game.id'))
game = db.relationship(Game, foreign_keys='Event.game_id')
# for 'system' and probably 'betstate' types
text = db.Column(db.Text)
# for 'betstate' type
newstate = db.Column(db.String(128))
class Beta(db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(128))
name = db.Column(db.String(128))
gametypes = db.Column(db.Text)
platforms = db.Column(db.String(128))
PLATFORMS = [
'Android',
'iOS',
'Windows Mobile',
'Web',
'other',
]
console = db.Column(db.String(128))
create_date = db.Column(db.DateTime, default=datetime.utcnow)
flags = db.Column(db.Text, default='') # probably json
backup = db.Column(db.Text)
def __repr__(self):
return '<Beta id={}>'.format(self.id)
class TGT(db.Model):
id = db.Column(db.Integer, primary_key=True)
iou = db.Column(db.String(255), index=True)
tgt = db.Column(db.String(255))
timestamp = db.Column(db.DateTime, default=datetime.utcnow)
def fast_count_noexec(query):
return query.statement.with_only_columns([func.count()]).order_by(None)
def fast_count(query):
"""
Get count of queried items avoiding using subquery (like query.count() does)
"""
return query.session.execute(fast_count_noexec(query)).scalar()
from .helpers import notify_event # dirty hack to avoid cyclic reference
def columns_from_groups(instance, *groups):
"""Returns list of (column name, group) pairs from given groups"""
state = attributes.instance_state(instance)
return [
(c.key, c.group) for c in state.mapper.column_attrs
if c.group in groups
]
class Badges(db.Model, Fifa15Badges):
"""Model that store player's badges, e.g.
Naming:
"fifa15_xboxone_first_win" - badge id and attribute of this model
fifa15_xboxone - gametype (same as in poller)
first_win - unique name of badge for this game
"""
__tablename__ = "badges"
id = db.Column(db.Integer, primary_key=True)
player_id = db.Column(db.Integer, db.ForeignKey("player.id"))
player = db.relationship(Player, backref=db.backref("badges", uselist=False, cascade="delete"))
# TODO: use this if want to deactivate some badges for all players
inactive_badges = []
# list of ids of recent updated badges, special for notifications
# must be cleaned after reading notification
player_badges_updated = deferred(db.Column(db.PickleType, nullable=False, default=set))
def update_for_notifications(self, *badges_ids):
# use this method to update badges_ids for notifications
t = self.player_badges_updated.copy()
t.update(badges_ids)
self.player_badges_updated = t
def clean_notifications(self):
# don forget to clean after notifying and commit
self.player_badges_updated = set()
# General badges
# TODO: create real badges, remove test badges
first_win = deferred(
db.Column(db.MutaleDictPickleType,
default=BADGES["games_general_one_time"]["first_win"]["user_bounded"]),
group="games_general_one_time"
)
first_loss = deferred(
db.Column(db.MutaleDictPickleType,
default=BADGES["games_general_one_time"]["first_loss"]["user_bounded"]),
group="games_general_one_time"
)
# played_100_games, etc.
played_10_games = deferred(
db.Column(db.MutaleDictPickleType,
default=BADGES["games_general_count"]["played_10_games"]["user_bounded"]),
group="games_general_count"
)
| {"/v1/signals_definitions.py": ["/v1/main.py", "/v1/badges/__init__.py"], "/v1/polling.py": ["/config.py", "/v1/helpers.py", "/v1/models.py", "/v1/apis.py", "/v1/common.py"], "/v1/badges/__init__.py": ["/v1/badges/badges_description.py", "/v1/badges/fifa15.py"], "/v1/apis.py": ["/config.py", "/v1/helpers.py", "/v1/mock.py"], "/v1/__init__.py": ["/v1/main.py"], "/mobsite.py": ["/config.py"], "/v1/badges/fifa15.py": ["/v1/main.py", "/v1/badges/badges_description.py"], "/v1/helpers.py": ["/config.py", "/v1/models.py", "/v1/main.py", "/v1/common.py", "/v1/apis.py", "/v1/__init__.py"], "/v1/models.py": ["/v1/main.py", "/v1/common.py", "/v1/badges/__init__.py", "/config.py", "/v1/helpers.py", "/v1/routes.py", "/v1/polling.py"], "/poll.py": ["/main.py", "/v1/__init__.py"], "/v1/cas.py": ["/config.py", "/v1/main.py", "/v1/apis.py", "/v1/models.py", "/v1/common.py"], "/debug_console.py": ["/main.py", "/v1/models.py", "/v1/helpers.py", "/v1/routes.py"], "/v1/routes.py": ["/config.py", "/v1/signals_definitions.py", "/v1/models.py", "/v1/helpers.py", "/v1/apis.py", "/v1/polling.py", "/v1/main.py"], "/main.py": ["/config.py", "/v1/__init__.py", "/v1/main.py", "/v1/models.py"], "/v1/main.py": ["/config.py", "/v1/__init__.py", "/v1/admin.py"], "/v1/admin.py": ["/v1/models.py", "/v1/polling.py", "/v1/helpers.py"], "/observer.py": ["/config.py", "/v1/polling.py", "/v1/models.py", "/v1/apis.py"]} |
71,987 | topdevman/flask-betg | refs/heads/master | /poll.py | #!/usr/bin/env python3
import main, v1
if __name__ == '__main__':
# for db access to work
main.live().app_context().push()
v1.polling.poll_all()
| {"/v1/signals_definitions.py": ["/v1/main.py", "/v1/badges/__init__.py"], "/v1/polling.py": ["/config.py", "/v1/helpers.py", "/v1/models.py", "/v1/apis.py", "/v1/common.py"], "/v1/badges/__init__.py": ["/v1/badges/badges_description.py", "/v1/badges/fifa15.py"], "/v1/apis.py": ["/config.py", "/v1/helpers.py", "/v1/mock.py"], "/v1/__init__.py": ["/v1/main.py"], "/mobsite.py": ["/config.py"], "/v1/badges/fifa15.py": ["/v1/main.py", "/v1/badges/badges_description.py"], "/v1/helpers.py": ["/config.py", "/v1/models.py", "/v1/main.py", "/v1/common.py", "/v1/apis.py", "/v1/__init__.py"], "/v1/models.py": ["/v1/main.py", "/v1/common.py", "/v1/badges/__init__.py", "/config.py", "/v1/helpers.py", "/v1/routes.py", "/v1/polling.py"], "/poll.py": ["/main.py", "/v1/__init__.py"], "/v1/cas.py": ["/config.py", "/v1/main.py", "/v1/apis.py", "/v1/models.py", "/v1/common.py"], "/debug_console.py": ["/main.py", "/v1/models.py", "/v1/helpers.py", "/v1/routes.py"], "/v1/routes.py": ["/config.py", "/v1/signals_definitions.py", "/v1/models.py", "/v1/helpers.py", "/v1/apis.py", "/v1/polling.py", "/v1/main.py"], "/main.py": ["/config.py", "/v1/__init__.py", "/v1/main.py", "/v1/models.py"], "/v1/main.py": ["/config.py", "/v1/__init__.py", "/v1/admin.py"], "/v1/admin.py": ["/v1/models.py", "/v1/polling.py", "/v1/helpers.py"], "/observer.py": ["/config.py", "/v1/polling.py", "/v1/models.py", "/v1/apis.py"]} |
71,988 | topdevman/flask-betg | refs/heads/master | /migrations/versions/c20f5ca325f4_ticket_creation_datetime.py | """ticket creation datetime
Revision ID: c20f5ca325f4
Revises: ada299aa8c8a
Create Date: 2016-01-07 10:51:33.576689
"""
# revision identifiers, used by Alembic.
revision = 'c20f5ca325f4'
down_revision = 'ada299aa8c8a'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('ticket', sa.Column('created', sa.DateTime(), nullable=False))
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('ticket', 'created')
### end Alembic commands ###
| {"/v1/signals_definitions.py": ["/v1/main.py", "/v1/badges/__init__.py"], "/v1/polling.py": ["/config.py", "/v1/helpers.py", "/v1/models.py", "/v1/apis.py", "/v1/common.py"], "/v1/badges/__init__.py": ["/v1/badges/badges_description.py", "/v1/badges/fifa15.py"], "/v1/apis.py": ["/config.py", "/v1/helpers.py", "/v1/mock.py"], "/v1/__init__.py": ["/v1/main.py"], "/mobsite.py": ["/config.py"], "/v1/badges/fifa15.py": ["/v1/main.py", "/v1/badges/badges_description.py"], "/v1/helpers.py": ["/config.py", "/v1/models.py", "/v1/main.py", "/v1/common.py", "/v1/apis.py", "/v1/__init__.py"], "/v1/models.py": ["/v1/main.py", "/v1/common.py", "/v1/badges/__init__.py", "/config.py", "/v1/helpers.py", "/v1/routes.py", "/v1/polling.py"], "/poll.py": ["/main.py", "/v1/__init__.py"], "/v1/cas.py": ["/config.py", "/v1/main.py", "/v1/apis.py", "/v1/models.py", "/v1/common.py"], "/debug_console.py": ["/main.py", "/v1/models.py", "/v1/helpers.py", "/v1/routes.py"], "/v1/routes.py": ["/config.py", "/v1/signals_definitions.py", "/v1/models.py", "/v1/helpers.py", "/v1/apis.py", "/v1/polling.py", "/v1/main.py"], "/main.py": ["/config.py", "/v1/__init__.py", "/v1/main.py", "/v1/models.py"], "/v1/main.py": ["/config.py", "/v1/__init__.py", "/v1/admin.py"], "/v1/admin.py": ["/v1/models.py", "/v1/polling.py", "/v1/helpers.py"], "/observer.py": ["/config.py", "/v1/polling.py", "/v1/models.py", "/v1/apis.py"]} |
71,989 | topdevman/flask-betg | refs/heads/master | /v1/cas.py | from flask import request, g, make_response, url_for, redirect
from urllib.parse import urlencode
import requests
from xml.etree import ElementTree
from datetime import datetime, timedelta
import config
from .main import app
from .apis import WilliamHill
from .models import db, TGT
from .common import *
# this is a primary CAS login endpoint
# https://developer.williamhill.com/cas-implementation-guidelines-developers-0
@app.route('/cas/login')
def cas_login():
url = WilliamHill.CAS_HOST
url += '/cas/login?'+urlencode(dict(
service = config.SITE_BASE_URL+url_for('.cas_done'),
joinin_link = 'test', # FIXME remove this when going to production
))
return redirect(url);
@app.route('/cas/logout')
def cas_logout():
url = WilliamHill.CAS_HOST + '/cas/logout'
return redirect(url);
@app.route('/cas/done')
def cas_done():
ticket = request.args.get('ticket')
url = WilliamHill.CAS_HOST + '/cas/serviceValidate'
ret = requests.get(url, params=dict(
service = config.SITE_BASE_URL+url_for('.cas_done'),
ticket = ticket,
pgtUrl = config.SITE_BASE_URL+url_for('.cas_pgt'),
# TODO renew?
), verify=False) # FIXME
tree = ElementTree.fromstring(ret.text)
ns = {'cas': 'http://www.yale.edu/tp/cas'}
success = tree.find('cas:authenticationSuccess', ns)
failure = tree.find('cas:authenticationFailure', ns)
if failure is not None:
return 'Auth failure! Code: {}<br/>{}'.format(
failure.get('code', '<no code>'),
failure.text.strip(),
)
if success is None:
return 'Auth failure, unrecognized response'
log.debug(success.getchildren())
e_user = success.find('cas:user', ns)
e_pgt = success.find('cas:proxyGrantingTicket', ns)
if e_user is None or e_pgt is None:
return 'Auth failure, bad response'
user = e_user.text.strip()
pgt = e_pgt.text.strip()
o_tgt = TGT.query.filter_by(iou=pgt).first()
if not o_tgt:
return 'Auth failure - no PGT, please retry'
tgt = o_tgt.tgt
db.session.delete(o_tgt)
# and remove obsolete records
TGT.query.filter(
TGT.timestamp < (datetime.utcnow() - timedelta(minutes=5))
).delete()
db.session.commit()
# We use TGT token here and don't generate JWT at this stage.
# Client should then pass received token to /federated_login endpoint.
return redirect(url_for('.cas_result', token = tgt, user = user))
@app.route('/cas/pgt')
def cas_pgt():
log.debug('PGT endpoint: {}, vals={}, cookies={}'.format(
request.method,
request.values,
request.cookies,
))
iou = request.values.get('pgtIou')
pgtid = request.values.get('pgtId')
# save it
if iou and pgtid: # because they may call us without any data
tgt = TGT(iou=iou, tgt=pgtid)
db.session.add(tgt)
db.session.commit()
return 'PGT saved' # dummy
@app.route('/cas/result')
def cas_result():
user = request.values.get('user')
token = request.values.get('token')
return """
<html><head>
<title>{{"success":true, "token":"{token}"}}</title>
</head><body>
Login successful, user is {user}, tgt is {token}
</body></html>
""".format(token=token, user=user)
| {"/v1/signals_definitions.py": ["/v1/main.py", "/v1/badges/__init__.py"], "/v1/polling.py": ["/config.py", "/v1/helpers.py", "/v1/models.py", "/v1/apis.py", "/v1/common.py"], "/v1/badges/__init__.py": ["/v1/badges/badges_description.py", "/v1/badges/fifa15.py"], "/v1/apis.py": ["/config.py", "/v1/helpers.py", "/v1/mock.py"], "/v1/__init__.py": ["/v1/main.py"], "/mobsite.py": ["/config.py"], "/v1/badges/fifa15.py": ["/v1/main.py", "/v1/badges/badges_description.py"], "/v1/helpers.py": ["/config.py", "/v1/models.py", "/v1/main.py", "/v1/common.py", "/v1/apis.py", "/v1/__init__.py"], "/v1/models.py": ["/v1/main.py", "/v1/common.py", "/v1/badges/__init__.py", "/config.py", "/v1/helpers.py", "/v1/routes.py", "/v1/polling.py"], "/poll.py": ["/main.py", "/v1/__init__.py"], "/v1/cas.py": ["/config.py", "/v1/main.py", "/v1/apis.py", "/v1/models.py", "/v1/common.py"], "/debug_console.py": ["/main.py", "/v1/models.py", "/v1/helpers.py", "/v1/routes.py"], "/v1/routes.py": ["/config.py", "/v1/signals_definitions.py", "/v1/models.py", "/v1/helpers.py", "/v1/apis.py", "/v1/polling.py", "/v1/main.py"], "/main.py": ["/config.py", "/v1/__init__.py", "/v1/main.py", "/v1/models.py"], "/v1/main.py": ["/config.py", "/v1/__init__.py", "/v1/admin.py"], "/v1/admin.py": ["/v1/models.py", "/v1/polling.py", "/v1/helpers.py"], "/observer.py": ["/config.py", "/v1/polling.py", "/v1/models.py", "/v1/apis.py"]} |
71,990 | topdevman/flask-betg | refs/heads/master | /migrations/versions/ada299aa8c8a_tournament_params.py | """tournament params
Revision ID: ada299aa8c8a
Revises: c60e3b325e86
Create Date: 2016-01-07 04:02:45.300002
"""
# revision identifiers, used by Alembic.
revision = 'ada299aa8c8a'
down_revision = 'c60e3b325e86'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('tournament', sa.Column('gamemode', sa.String(length=64), nullable=False))
op.add_column('tournament', sa.Column('gametype', sa.String(length=64), nullable=False))
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('tournament', 'gametype')
op.drop_column('tournament', 'gamemode')
### end Alembic commands ###
| {"/v1/signals_definitions.py": ["/v1/main.py", "/v1/badges/__init__.py"], "/v1/polling.py": ["/config.py", "/v1/helpers.py", "/v1/models.py", "/v1/apis.py", "/v1/common.py"], "/v1/badges/__init__.py": ["/v1/badges/badges_description.py", "/v1/badges/fifa15.py"], "/v1/apis.py": ["/config.py", "/v1/helpers.py", "/v1/mock.py"], "/v1/__init__.py": ["/v1/main.py"], "/mobsite.py": ["/config.py"], "/v1/badges/fifa15.py": ["/v1/main.py", "/v1/badges/badges_description.py"], "/v1/helpers.py": ["/config.py", "/v1/models.py", "/v1/main.py", "/v1/common.py", "/v1/apis.py", "/v1/__init__.py"], "/v1/models.py": ["/v1/main.py", "/v1/common.py", "/v1/badges/__init__.py", "/config.py", "/v1/helpers.py", "/v1/routes.py", "/v1/polling.py"], "/poll.py": ["/main.py", "/v1/__init__.py"], "/v1/cas.py": ["/config.py", "/v1/main.py", "/v1/apis.py", "/v1/models.py", "/v1/common.py"], "/debug_console.py": ["/main.py", "/v1/models.py", "/v1/helpers.py", "/v1/routes.py"], "/v1/routes.py": ["/config.py", "/v1/signals_definitions.py", "/v1/models.py", "/v1/helpers.py", "/v1/apis.py", "/v1/polling.py", "/v1/main.py"], "/main.py": ["/config.py", "/v1/__init__.py", "/v1/main.py", "/v1/models.py"], "/v1/main.py": ["/config.py", "/v1/__init__.py", "/v1/admin.py"], "/v1/admin.py": ["/v1/models.py", "/v1/polling.py", "/v1/helpers.py"], "/observer.py": ["/config.py", "/v1/polling.py", "/v1/models.py", "/v1/apis.py"]} |
71,991 | topdevman/flask-betg | refs/heads/master | /debug_console.py | #!/usr/bin/env python3
import main, pdb, re
from random import choice
from faker import Faker
fake = Faker()
main.init_app()
with main.app.app_context():
from v1.models import *
from v1.helpers import *
from v1.routes import *
def add_tournaments():
dt = datetime.utcnow()
hour = timedelta(hours=1)
for i in range(3):
for j in range(3):
for m in range(4):
t = Tournament(j + 1, dt + hour * i, dt + hour * (i+1), dt + hour * (i+2), m+1)
db.session.add(t)
db.session.commit()
def add_test_players():
for i in range(10):
player = Player()
player.nickname = 'test_player_' + str(i)
player.email = player.nickname + '@example.com'
player.password = encrypt_password('111111')
db.session.add(player)
db.session.commit()
def add_fake_users(count=100):
fake_players = []
for i in range(count):
player = Player()
player.nickname = fake.name()
player.email = re.sub('\W+', '_', player.nickname) + '@example.com'
player.password = encrypt_password('111111')
db.session.add(player)
fake_players.append(player)
db.session.commit()
for i in range(count * 10):
p1 = choice(fake_players)
p2 = choice(fake_players)
while p1 == p2:
p2 = choice(fake_players)
game = Game()
game.gamemode = 'fake'
game.gametype = 'fake'
game.creator_id = p1.id
game.opponent_id = p2.id
if p1.winrate and p2.winrate and p1.winrate > p2.winrate:
game.winner = 'creator'
else:
game.winner = 'opponent'
game.state = 'finished'
game.bet = 0
db.session.add(game)
db.session.commit()
while True:
pdb.set_trace()
| {"/v1/signals_definitions.py": ["/v1/main.py", "/v1/badges/__init__.py"], "/v1/polling.py": ["/config.py", "/v1/helpers.py", "/v1/models.py", "/v1/apis.py", "/v1/common.py"], "/v1/badges/__init__.py": ["/v1/badges/badges_description.py", "/v1/badges/fifa15.py"], "/v1/apis.py": ["/config.py", "/v1/helpers.py", "/v1/mock.py"], "/v1/__init__.py": ["/v1/main.py"], "/mobsite.py": ["/config.py"], "/v1/badges/fifa15.py": ["/v1/main.py", "/v1/badges/badges_description.py"], "/v1/helpers.py": ["/config.py", "/v1/models.py", "/v1/main.py", "/v1/common.py", "/v1/apis.py", "/v1/__init__.py"], "/v1/models.py": ["/v1/main.py", "/v1/common.py", "/v1/badges/__init__.py", "/config.py", "/v1/helpers.py", "/v1/routes.py", "/v1/polling.py"], "/poll.py": ["/main.py", "/v1/__init__.py"], "/v1/cas.py": ["/config.py", "/v1/main.py", "/v1/apis.py", "/v1/models.py", "/v1/common.py"], "/debug_console.py": ["/main.py", "/v1/models.py", "/v1/helpers.py", "/v1/routes.py"], "/v1/routes.py": ["/config.py", "/v1/signals_definitions.py", "/v1/models.py", "/v1/helpers.py", "/v1/apis.py", "/v1/polling.py", "/v1/main.py"], "/main.py": ["/config.py", "/v1/__init__.py", "/v1/main.py", "/v1/models.py"], "/v1/main.py": ["/config.py", "/v1/__init__.py", "/v1/admin.py"], "/v1/admin.py": ["/v1/models.py", "/v1/polling.py", "/v1/helpers.py"], "/observer.py": ["/config.py", "/v1/polling.py", "/v1/models.py", "/v1/apis.py"]} |
71,992 | topdevman/flask-betg | refs/heads/master | /migrations/versions/c60e3b325e86_dispute_system.py | """dispute system
Revision ID: c60e3b325e86
Revises: 0cc69c6eee67
Create Date: 2016-01-06 09:23:59.714878
"""
# revision identifiers, used by Alembic.
revision = 'c60e3b325e86'
down_revision = '0cc69c6eee67'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('ticket',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('open', sa.Boolean(), server_default='1', nullable=False),
sa.Column('game_id', sa.Integer(), nullable=True),
sa.Column('type', sa.Enum('reports_mismatch'), nullable=False),
sa.ForeignKeyConstraint(['game_id'], ['game.id']),
sa.PrimaryKeyConstraint('id')
)
op.create_table('report',
sa.Column('game_id', sa.Integer(), nullable=False),
sa.Column('player_id', sa.Integer(), nullable=False),
sa.Column('ticket_id', sa.Integer(), nullable=True),
sa.Column('created', sa.DateTime(), nullable=False),
sa.Column('modified', sa.DateTime(), nullable=True),
sa.Column('result', sa.Enum('won', 'lost', 'draw'), nullable=False),
sa.ForeignKeyConstraint(['game_id'], ['game.id'], ),
sa.ForeignKeyConstraint(['player_id'], ['player.id'], ),
sa.ForeignKeyConstraint(['ticket_id'], ['ticket.id'], ),
sa.PrimaryKeyConstraint('game_id', 'player_id')
)
op.create_index(op.f('ix_report_game_id'), 'report', ['game_id'], unique=False)
op.create_index(op.f('ix_report_player_id'), 'report', ['player_id'], unique=False)
op.create_index(op.f('ix_report_ticket_id'), 'report', ['ticket_id'], unique=False)
op.add_column('chat_message', sa.Column('admin_message', sa.Boolean(), server_default='0', nullable=False))
op.add_column('chat_message', sa.Column('ticket_id', sa.Integer(), nullable=True))
op.create_index(op.f('ix_chat_message_ticket_id'), 'chat_message', ['ticket_id'], unique=False)
op.create_foreign_key('chat_message_ibfk_4', 'chat_message', 'ticket', ['ticket_id'], ['id'])
op.drop_column('game', 'report_try')
op.drop_column('game', 'report_creator_date')
op.drop_column('game', 'report_opponent_date')
op.drop_column('game', 'report_creator')
op.drop_column('game', 'report_opponent')
## end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('game', sa.Column('report_opponent', mysql.ENUM('creator', 'opponent', 'draw'), nullable=True))
op.add_column('game', sa.Column('report_creator', mysql.ENUM('creator', 'opponent', 'draw'), nullable=True))
op.add_column('game', sa.Column('report_opponent_date', mysql.DATETIME(), nullable=True))
op.add_column('game', sa.Column('report_creator_date', mysql.DATETIME(), nullable=True))
op.add_column('game', sa.Column('report_try', mysql.INTEGER(display_width=11), server_default=sa.text("'0'"), autoincrement=False, nullable=True))
op.drop_constraint('chat_message_ibfk_4', 'chat_message', type_='foreignkey')
op.drop_index(op.f('ix_chat_message_ticket_id'), table_name='chat_message')
op.drop_column('chat_message', 'ticket_id')
op.drop_column('chat_message', 'admin_message')
op.drop_index(op.f('ix_report_player_id'), table_name='report')
op.drop_index(op.f('ix_report_game_id'), table_name='report')
op.drop_index(op.f('ix_report_ticket_id'), table_name='report')
op.drop_table('report')
op.drop_table('ticket')
### end Alembic commands ###
| {"/v1/signals_definitions.py": ["/v1/main.py", "/v1/badges/__init__.py"], "/v1/polling.py": ["/config.py", "/v1/helpers.py", "/v1/models.py", "/v1/apis.py", "/v1/common.py"], "/v1/badges/__init__.py": ["/v1/badges/badges_description.py", "/v1/badges/fifa15.py"], "/v1/apis.py": ["/config.py", "/v1/helpers.py", "/v1/mock.py"], "/v1/__init__.py": ["/v1/main.py"], "/mobsite.py": ["/config.py"], "/v1/badges/fifa15.py": ["/v1/main.py", "/v1/badges/badges_description.py"], "/v1/helpers.py": ["/config.py", "/v1/models.py", "/v1/main.py", "/v1/common.py", "/v1/apis.py", "/v1/__init__.py"], "/v1/models.py": ["/v1/main.py", "/v1/common.py", "/v1/badges/__init__.py", "/config.py", "/v1/helpers.py", "/v1/routes.py", "/v1/polling.py"], "/poll.py": ["/main.py", "/v1/__init__.py"], "/v1/cas.py": ["/config.py", "/v1/main.py", "/v1/apis.py", "/v1/models.py", "/v1/common.py"], "/debug_console.py": ["/main.py", "/v1/models.py", "/v1/helpers.py", "/v1/routes.py"], "/v1/routes.py": ["/config.py", "/v1/signals_definitions.py", "/v1/models.py", "/v1/helpers.py", "/v1/apis.py", "/v1/polling.py", "/v1/main.py"], "/main.py": ["/config.py", "/v1/__init__.py", "/v1/main.py", "/v1/models.py"], "/v1/main.py": ["/config.py", "/v1/__init__.py", "/v1/admin.py"], "/v1/admin.py": ["/v1/models.py", "/v1/polling.py", "/v1/helpers.py"], "/observer.py": ["/config.py", "/v1/polling.py", "/v1/models.py", "/v1/apis.py"]} |
71,993 | topdevman/flask-betg | refs/heads/master | /v1/routes.py | from flask import request, jsonify, current_app, g, send_file, make_response, redirect
from flask import copy_current_request_context
from flask.ext import restful
from flask.ext.restful import fields, marshal
from flask.ext.socketio import send as sio_send, disconnect as sio_disconnect
from sqlalchemy.sql.expression import func
from sqlalchemy.exc import IntegrityError
from werkzeug.exceptions import HTTPException
from werkzeug.exceptions import MethodNotAllowed, Forbidden, NotFound
from werkzeug.exceptions import NotImplemented # noqa
import os
from io import BytesIO
from datetime import datetime, timedelta
import math
import json
import operator
import requests
from PIL import Image
import eventlet
import config
from v1.signals_definitions import game_badge_signal
from .models import * # noqa
from .helpers import * # noqa
from .apis import * # noqa
from .polling import * # noqa
from .helpers import MyRequestParser as RequestParser # instead of system one
from .main import app, db, api, socketio, redis
# Players
@api.resource(
'/players',
'/players/',
'/players/<id>',
)
class PlayerResource(restful.Resource):
@classproperty
def parser(cls):
parser = RequestParser()
partial = parser.partial = RequestParser()
login = parser.login = RequestParser()
fieldlist = [
# name, type, required
('_force', gamertag_force_field, False),
('nickname', None, True),
('email', email_validator, True),
('password', encrypt_password, True),
('facebook_token', federatedRenewFacebook, False), # should be last to avoid extra queries
('twitter_token', federatedRenewTwitter, False), # should be last to avoid extra queries
('bio', None, False),
]
identities = set()
for identity in Identity.all:
identities.add((identity.id, identity.checker, False))
fieldlist.extend(identities)
for name, type, required in fieldlist:
if hasattr(Player, name):
type = string_field(getattr(Player, name), ftype=type)
parser.add_argument(
name,
required=required,
type=type,
)
partial.add_argument(
name,
required=False,
type=type,
)
login.add_argument('push_token',
type=string_field(Device.push_token,
# 64 hex digits = 32 bytes
ftype=hex_field(64)),
required=False)
partial.add_argument('old_password', required=False)
return parser
@classmethod
def fields(cls, public=True, stat=False, leaders=False):
ret = dict(
id=fields.Integer,
nickname=fields.String,
email=fields.String,
facebook_connected=fields.Boolean(attribute='facebook_token'),
twitter_connected=fields.Boolean(attribute='twitter_token'),
bio=fields.String,
has_userpic=fields.Boolean,
ea_gamertag=fields.String,
fifa_team=fields.String,
riot_summonerName=fields.String,
steam_id=fields.String,
starcraft_uid=fields.String,
tibia_character=fields.String,
)
if not public: ret.update(dict(
balance=fields.Float,
balance_info=fields.Raw(attribute='balance_obj'), # because it is already JSON
devices=fields.List(fields.Nested(dict(
id=fields.Integer,
last_login=fields.DateTime,
))),
))
if stat: ret.update(dict(
# some stats
gamecount=fields.Integer, # FIXME: optimize query somehow?
winrate=fields.Float,
# popularity = fields.Integer,
))
if leaders: ret.update(dict(
leaderposition=fields.Integer,
))
return ret
@classmethod
def login_do(cls, player, args=None, created=False):
if not args:
args = cls.parser.login.parse_args()
dev = Device.query.filter_by(player=player,
push_token=args.push_token
).first()
if not dev:
dev = Device()
dev.player = player
dev.push_token = args.push_token
db.session.add(dev)
if args.push_token:
# remove that token from other devices
Device.query.filter(
Device.player != player,
Device.push_token == args.push_token,
).delete()
dev.last_login = datetime.utcnow()
db.session.commit() # to create device id
ret = jsonify(
player=marshal(player, cls.fields(public=False)),
token=makeToken(player, device=dev),
created=created,
)
if created:
ret.status_code = 201
return ret
@require_auth
def get(self, user, id=None):
if not id:
# Leaderboard mode
parser = RequestParser()
parser.add_argument('filter')
parser.add_argument('filt_op',
choices=['startswith', 'contains'],
default='startswith',
)
parser.add_argument(
'order',
choices=sum(
[[s, '-' + s]
for s in
('id',
'lastbet',
'popularity',
'winrate',
'gamecount',
)], []),
required=False,
)
parser.add_argument('gametype',
choices=Poller.all_gametypes,
required=False)
parser.add_argument('period',
required=False,
choices=[
'today', 'yesterday', 'week', 'month',
])
# parser.add_argument('names_only', type=boolean_field)
args = parser.parse_args()
if args.filter:
query = Player.search(args.filter, args.filt_op)
else:
query = Player.query
orders = []
if args.order:
ordername = args.order.lstrip('-')
if hasattr(Player, ordername + '_impl'):
# this parameter depends on games,
# so calculate and apply corresponding filters
filters = []
if args.gametype:
filters.append(Game.gametype == args.gametype)
if args.period:
till = None
if args.period == 'today':
since = timedelta(days=1)
elif args.period == 'yesterday':
since = timedelta(days=2)
till = timedelta(days=1)
elif args.period == 'week':
since = timedelta(weeks=1)
elif args.period == 'month':
since = timedelta(days=30)
else:
raise ValueError('unknown period ' + args.period)
now = datetime.utcnow()
filters.append(Game.accept_date >= now - since)
if till:
filters.append(Game.accept_date < now - till)
orders.append(getattr(Player, ordername + '_impl')(*filters))
g.winrate_filt = filters
else:
orders.append(getattr(Player, ordername))
# special handling for order by winrate:
if args.order.endswith('winrate'):
# sort also by game count
orders.append(Player.gamecount)
# ...and always add player.id to stabilize order
if not args.order or not args.order.endswith('id'):
orders.append(Player.id)
if args.order:
orders = map(
operator.methodcaller(
'desc' if args.order.startswith('-') else 'asc'
), orders
)
query = query.order_by(*orders)
query = query.limit(20)
return jsonify(
players=fields.List(
fields.Nested(
self.fields(public=True, stat=True,
leaders='winrate' in (args.order or ''))
)
).format(query),
)
parser = RequestParser()
parser.add_argument('with_stat', type=boolean_field, default=False)
args = parser.parse_args()
player = Player.find(id)
if not player:
raise NotFound
is_self = player == user
ret = marshal(player,
self.fields(public=not is_self,
stat=is_self or args.with_stat,
leaders=args.with_stat))
g.winrate_filt = None # reset
return ret
def post(self, id=None):
if id:
raise MethodNotAllowed
log.debug('NEW USER: ' + repr(request.get_data()))
args_login = self.parser.login.parse_args() # check before others
args = self.parser.parse_args()
player = Player()
for key, val in args.items():
if hasattr(player, key):
setattr(player, key, val)
if 'userpic' in request.files:
UserpicResource.upload(request.files['userpic'], player)
# TODO: validate fb token?
db.session.add(player)
db.session.commit()
self.greet(player)
datadog(
'New player registered',
'ID: {}, email: {}, nickname: {}'.format(
player.id,
player.email,
player.nickname,
),
**{
'user.id': player.id,
'user.nickname': player.nickname,
'user.email': player.email,
}
)
dd_stat.increment('user.registration')
return self.login_do(player, args_login, created=True)
def greet(self, user):
mailsend(user, 'greeting')
# we don't check result as it is not critical if this email is not sent
mailsend(user, 'greet_personal',
sender='Doug from BetGame <doug@betgame.co.uk>',
delayed=timedelta(days=1),
)
@require_auth(allow_nonfilled=True)
def patch(self, user, id=None):
if not id:
raise MethodNotAllowed
if Player.find(id) != user:
abort('You cannot edit another player\'s info', 403)
args = self.parser.partial.parse_args()
if args.password:
if not request.is_secure and not current_app.debug:
abort('Please use secure connection', 406)
# if only hash available then we have no password yet
# and will not check old password field
if len(user.password) > 16:
# if old password not specified, don't check it -
# it is not secure, but allows password recovery.
# TODO: use special token for password recovery?..
if args.old_password:
if not check_password(args.old_password, user.password):
abort('Previous password don\'t match')
hadmail = bool(user.email)
for key, val in args.items():
if val and hasattr(user, key):
setattr(user, key, val)
if not hadmail and key == 'email':
self.greet(user)
if 'userpic' in request.files:
UserpicResource.upload(request.files['userpic'], user)
db.session.commit()
return marshal(user, self.fields(public=False))
@app.route('/players/<id>/login', methods=['POST'])
def player_login(id):
parser = RequestParser()
parser.add_argument('password', required=True)
args = parser.parse_args()
player = Player.find(id)
if not player:
abort('Incorrect login or password', 404)
if not check_password(args.password, player.password):
abort('Incorrect login or password', 403)
datadog('Player regular login', 'nickname: {}'.format(player.nickname))
dd_stat.increment('user.login')
return PlayerResource.login_do(player)
@staticmethod
@app.route('/federated_login', methods=['POST'])
@secure_only
def federated():
parser = RequestParser()
parser.add_argument('svc', choices=['facebook', 'twitter', 'williamhill'],
default='facebook')
parser.add_argument('token', required=True)
args = parser.parse_args()
log.debug('fed: svc={}, token={}'.format(args.svc, args.token))
email = None
# get identity, name, email and userpic
if args.svc == 'facebook':
try:
args.token = federatedRenewFacebook(args.token)
except ValueError as e:
abort('[token]: {}'.format(e), problem='token')
# get identity and name
ret = requests.get(
'https://graph.facebook.com/v2.3/me',
params=dict(
access_token=args.token,
fields='id,email,name,picture',
),
)
jret = ret.json()
if 'error' in jret:
err = jret['error']
abort('Error fetching email from Facebook: {} {} ({})'.format(
err.get('code', ret.status_code),
err.get('type', ret.reason),
err.get('message', 'no details'),
))
if 'email' in jret:
identity = email = jret['email']
elif 'id' in jret:
identity = jret['id']
else:
abort('Facebook didn\'t return neither email nor user id')
userpic = jret.get('picture', {}).get('data')
if userpic:
userpic = None if userpic['is_silhouette'] else userpic['url']
name = jret.get('name')
elif args.svc == 'twitter':
# get identity and name
jret = Twitter.identity(args.token)
if 'error' in jret:
abort('Error fetching info from Twitter: {}'.format(
jret.get('error', 'no details')))
name = jret.get('screen_name')
email = jret.get('email')
identity = jret['id']
userpic = jret.get('profile_image_url')
elif args.svc == 'williamhill':
if not args.token.startswith('TGT-'):
abort('Wrong token format')
wh = WilliamHill(args.token)
jret = wh.request('GET', 'accounts/me', accept_simple=True)
log.debug(str(jret))
try:
jret = jret['whoAccounts']['account']
williamhill_currency = jret['currencyCode'] # TODO handle it
name = ' '.join(filter(None, [
jret.get('firstName'), jret.get('lastName'),
]))
email = jret['email']
identity = jret['accountId']
userpic = None # no userpic for WH
except KeyError:
abort('Failed to fetch account information from WilliamHill')
if name:
n = 1
oname = name
while Player.query.filter_by(nickname=name).count():
name = '{} {}'.format(oname, n)
n += 1
if email:
player = Player.query.filter_by(email=email).first()
else:
player = Player.query.filter_by(**{args.svc + '_id': identity}).first()
created = False
if not player:
created = True
player = Player()
player.email = email
player.password = encrypt_password(None) # random salt
player.nickname = name
db.session.add(player)
if userpic and not player.has_userpic:
UserpicResource.fromurl(userpic, player)
setattr(player, '{}_id'.format(args.svc), identity)
setattr(player, '{}_token'.format(args.svc), args.token)
datadog('Player federated ' + ('registration' if created else 'login'),
'nickname: {}, service: {}, id: {}, email: {}'.format(
player.nickname,
args.svc,
identity,
email,
),
service=args.svc)
dd_stat.increment('user.login_' + args.svc)
if created:
dd_stat.increment('user.registration')
return PlayerResource.login_do(player, created=created)
@app.route('/players/<id>/reset_password', methods=['POST'])
def reset_password(id):
player = Player.find(id)
if not player:
abort('Unknown nickname, gamertag or email', 404)
# send password recovery link
ret = mailsend(player, 'recover',
link='https://betgame.co.uk/password.html'
'#userid={}&token={}'.format(
player.id,
makeToken(player)
))
if not ret:
return jsonify(success=False, message='Couldn\'t send mail')
return jsonify(
success=True,
message='Password recovery link sent to your email address',
)
@app.route('/players/<id>/pushtoken', methods=['POST'])
@require_auth
def pushtoken(user, id):
if Player.find(id) != user:
raise Forbidden
if not g.device_id:
abort('No device id in auth token, please auth again', problem='token')
parser = RequestParser()
parser.add_argument('push_token',
type=hex_field(64), # = 32 bytes
required=True)
args = parser.parse_args()
# first try find device which already uses this token
dev = Device.query.filter_by(player=user,
push_token=args.push_token
).first()
# if we found it, then we will actually just update its last login date
if not dev:
# if not found - get current one (which most likely has no token)
dev = Device.query.get(g.device_id)
if not dev:
abort('Device id not found', 500)
if dev.push_token:
abort('This device already has push token specified')
dev.push_token = args.push_token
dev.failed = False # just to ensure
# and remove that token from other devices
Device.query.filter(
Device.player != user,
Device.push_token == args.push_token,
).delete()
# update last login as it may be another device object
# than one that was used for actual login
dev.last_login = datetime.utcnow()
db.session.commit()
return jsonify(success=True)
@app.route('/players/<id>/logout', methods=['POST'])
@require_auth
def logout(user, id):
if Player.find(id) != user:
raise Forbidden
if not g.device_id:
abort('No device id in auth token, please auth again', problem='token')
parser = RequestParser()
parser.add_argument('push_token',
type=hex_field(64), # = 32 bytes
required=False)
args = parser.parse_args()
# get current device (which most likely has push token)
dev = None
if args.push_token:
dev = Device.query.filter_by(
player=user,
push_token=args.push_token
).first()
if not dev:
dev = Device.query.get(g.device_id)
if not dev:
abort('No device record found')
if not dev.push_token:
return jsonify(
success=False,
reason='This device is already without push token',
)
dev.push_token = None
# TODO: delete device itself?
db.session.commit()
return jsonify(success=True)
@app.route('/players/<id>/recent_opponents')
@require_auth
def recent_opponents(user, id):
if Player.find(id) != user:
raise Forbidden
return jsonify(opponents=fields.List(fields.Nested(
PlayerResource.fields(public=True)
)).format(user.recent_opponents))
@app.route('/players/<id>/winratehist')
@require_auth
def winratehist(user, id):
if Player.find(id) != user:
raise Forbidden
parser = RequestParser()
parser.add_argument('range', type=int, required=True)
parser.add_argument('interval', required=True, choices=(
'day', 'week', 'month'))
args = parser.parse_args()
params = {
args.interval + 's': args.range,
}
return jsonify(
history=[
dict(
date=date,
games=total,
wins=float(wins),
rate=float(rate),
) for date, total, wins, rate in user.winratehist(**params)
],
)
@app.route('/players/<id>/leaderposition')
@require_auth
def leaderposition(user, id):
player = Player.find(id)
if not player:
raise NotFound
return jsonify(
position=player.leaderposition,
)
@api.resource(
'/friends',
'/friends/',
'/friends/<id>',
)
class FriendsResource(restful.Resource):
@require_auth
def get(self, user, id=None):
if id:
raise NotImplemented
# TODO: fetch this user's friends
# For now will just return set of predefined users
players = Player.query.filter(Player.nickname.like('test_player_%'))
return dict(
players=fields.List(
fields.Nested(
PlayerResource.fields(public=True)
)
).format(players),
)
# Userpic
class UploadableResource(restful.Resource):
PARAM = None
ROOT = os.path.dirname(__file__) + '/../uploads'
SUBDIR = None
ALLOWED = None
@classmethod
def url_for(cls, entity, ext):
return '/uploads/{}/{}'.format(
cls.SUBDIR,
'{}.{}'.format(entity.id, ext),
)
@classmethod
def file_for(cls, entity, ext):
return os.path.join(
cls.ROOT,
cls.SUBDIR,
'{}.{}'.format(entity.id, ext),
)
@classmethod
def findfile(cls, entity):
for ext in cls.ALLOWED:
f = cls.file_for(entity, ext)
if os.path.exists(f):
return f
return None
@classmethod
def onupload(cls, entity, ext):
pass
@classmethod
def ondelete(cls, entity):
pass
@classmethod
def found(cls, entity, ext):
pass
@classmethod
def notfound(cls, entity):
pass
@classmethod
def delfile(cls, entity):
deleted = False
for ext in cls.ALLOWED:
f = cls.file_for(entity, ext)
if os.path.exists(f):
os.remove(f)
log.debug('removed {}'.format(f))
deleted = True
cls.ondelete(entity)
return deleted
@classmethod
def upload(cls, f, entity):
ext = f.filename.lower().rsplit('.', 1)[-1]
if ext not in cls.ALLOWED:
abort('[{}]: {} files are not allowed'.format(
cls.PARAM, ext.upper()))
# FIXME: limit size
cls.delfile(entity)
f.save(cls.file_for(entity, ext))
cls.onupload(entity, ext)
datadog('{} uploaded'.format(cls.PARAM), 'original filename: {}'.format(
f.filename))
@classmethod
def fromurl(cls, url, entity):
if len(cls.ALLOWED) > 1:
raise ValueError('This is only applicable for single-ext resources')
cls.delfile(entity)
ret = requests.get(url, stream=True)
with open(cls.file_for(entity, cls.ALLOWED[0]), 'wb') as f:
for chunk in ret.iter_content(1024):
f.write(chunk)
cls.onupload(entity, cls.ALLOWED[0])
datadog('{} uploaded from url'.format(cls.PARAM), 'original filename: {}, url: {}'.format(
f.filename, url))
def get_entity(self, kwargs, is_put):
raise NotImplementedError # override this!
def get(self, **kwargs):
entity = self.get_entity(kwargs, False)
for ext in self.ALLOWED:
f = self.file_for(entity, ext)
if os.path.exists(f):
self.found(entity, ext)
response = make_response()
response.headers['X-Accel-Redirect'] = self.url_for(entity, ext)
response.headers['Content-Type'] = '' # autodetect by nginx
return response
else:
self.notfound(entity)
return (None, 204) # HTTP code 204 NO CONTENT
def put(self, **kwargs):
entity = self.get_entity(kwargs, True)
f = request.files.get(self.PARAM)
if not f:
abort('[{}]: please provide file!'.format(self.PARAM))
self.upload(f, entity)
return dict(success=True)
def post(self, *args, **kwargs):
return self.put(*args, **kwargs)
def delete(self, **kwargs):
return dict(
deleted=self.delfile(self.get_entity(kwargs, True)),
)
@api.resource('/players/<id>/userpic')
class UserpicResource(UploadableResource):
PARAM = 'userpic'
SUBDIR = 'userpics'
ALLOWED = ['png']
@require_auth
def get_entity(self, args, is_put, user):
player = Player.find(args['id'])
if not player:
raise NotFound
if is_put and player != user:
raise Forbidden
return player
# Balance
@app.route('/balance', methods=['GET'])
@require_auth
def balance_get(user):
return jsonify(
balance=user.balance_obj,
)
@app.route('/balance/history', methods=['GET'])
@require_auth
def balance_history(user):
parser = RequestParser()
parser.add_argument('page', type=int, default=1)
parser.add_argument('results_per_page', type=int, default=10)
args = parser.parse_args()
if args.results_per_page > 50:
abort('[results_per_page]: max is 50')
query = user.transactions
total_count = query.count()
query = query.paginate(args.page, args.results_per_page,
error_out=False).items
return jsonify(
transactions=fields.List(fields.Nested(dict(
id=fields.Integer,
date=fields.DateTime,
type=fields.String,
sum=fields.Float,
balance=fields.Float,
game_id=fields.Integer,
comment=fields.String,
))).format(query),
num_results=total_count,
total_pages=math.ceil(total_count / args.results_per_page),
page=args.page,
)
@app.route('/balance/deposit', methods=['POST'])
@require_auth
def balance_deposit(user):
parser = RequestParser()
parser.add_argument('payment_id', required=False)
parser.add_argument('total', type=float, required=True)
parser.add_argument('currency', required=True)
parser.add_argument('dry_run', type=boolean_field, default=False)
args = parser.parse_args()
datadog(
'Payment received',
' '.join(
['{}: {}'.format(k, v) for k, v in args.items()]
),
)
rate = Fixer.latest(args.currency, 'USD')
if not rate:
abort('[currency]: Unknown currency {}'.format(args.currency),
problem='currency')
coins = args.total * rate
if not args.dry_run:
if not args.payment_id:
abort('[payment_id]: required unless dry_run is true')
# verify payment...
ret = PayPal.call('GET', 'payments/payment/' + args.payment_id)
if ret.get('state') != 'approved':
abort('Payment not approved: {} - {}'.format(
ret.get('name', '(no error code)'),
ret.get('message', '(no error message)'),
), success=False)
transaction = None
for tr in ret.get('transactions', []):
amount = tr.get('amount')
if (
(float(amount['total']), amount['currency']) ==
(args.total, args.currency)
):
transaction = tr
break
else:
abort('No corresponding transaction found', success=False)
for res in transaction.get('related_resources', []):
sale = res.get('sale')
if not sale:
continue
if sale.get('state') == 'completed':
break
else:
abort('Sale is not completed', success=False)
# now payment should be verified
log.info('Payment approved, adding coins')
user.balance += coins
db.session.add(Transaction(
player=user,
type='deposit',
sum=coins,
balance=user.balance,
comment='Converted from {} {}'.format(args.total, args.currency),
))
db.session.commit()
return jsonify(
success=True,
dry_run=args.dry_run,
added=coins,
balance=user.balance_obj,
)
@app.route('/balance/withdraw', methods=['POST'])
@require_auth
def balance_withdraw(user):
parser = RequestParser()
parser.add_argument('coins', type=float, required=True)
parser.add_argument('currency', default='USD')
parser.add_argument('paypal_email', type=email, required=False)
parser.add_argument('dry_run', type=boolean_field, default=False)
args = parser.parse_args()
if args.coins < config.WITHDRAW_MINIMUM:
abort('Too small amount, minimum withdraw amount is {} coins'
.format(config.WITHDRAW_MINIMUM))
try:
amount = dict(
value=args.coins
* Fixer.latest('USD', args.currency)
* config.WITHDRAW_COEFFICIENT,
currency=args.currency,
)
except (TypeError, ValueError):
# for bad currencies, Fixer will return None
# and coins*None results in TypeError
abort('Unknown currency provided')
if user.available < args.coins:
abort('Not enough coins')
if args.dry_run:
return jsonify(
success=True,
paid=amount,
dry_run=True,
balance=user.balance_obj,
)
if not args.paypal_email:
abort('[paypal_email] should be specified unless you are running dry-run')
# first withdraw coins...
user.balance -= args.coins
db.session.add(Transaction(
player=user,
type='withdraw',
sum=-args.coins,
balance=user.balance,
comment='Converted to {} {}'.format(
amount,
args.currency,
),
))
db.session.commit()
# ... and only then do actual transaction;
# will return balance if failure happens
try:
ret = PayPal.call('POST', 'payments/payouts', dict(
sync_mode=True,
), dict(
sender_batch_header=dict(
# sender_batch_id = None,
email_subject='Payout from BetGame',
recipient_type='EMAIL',
),
items=[
dict(
recipient_type='EMAIL',
amount=amount,
receiver=args.paypal_email,
),
],
))
try:
trinfo = ret['items'][0]
except IndexError:
trinfo = None
stat = trinfo.get('transaction_status')
if stat == 'SUCCESS':
datadog(
'Payout succeeded to {}, {} coins'.format(
args.paypal_email, args.coins),
)
return jsonify(success=True,
dry_run=False,
paid=amount,
transaction_id=trinfo.get('payout_item_id'),
balance=user.balance_obj,
)
# TODO: add transaction id to our Transaction object
log.debug(str(ret))
log.warning('Payout failed to {}, {} coins, stat {}'.format(
args.paypal_email, args.coins, stat))
if stat in ['PENDING', 'PROCESSING']:
# TODO: wait and retry
pass
abort('Couldn\'t complete payout: ' +
trinfo.get('errors', {}).get('message', 'Unknown error'),
500,
status=stat,
transaction_id=trinfo.get('payout_item_id'),
paypal_code=ret.get('_code'),
success=False,
dry_run=False,
)
except Exception as e:
# restore balance
user.balance += args.coins
db.session.add(Transaction(
player=user,
type='withdraw',
sum=args.coins,
balance=user.balance,
comment='Withdraw operation aborted due to error',
))
db.session.commit()
log.error('Exception while performing payout', exc_info=True)
if isinstance(e, HTTPException):
raise
abort('Couldn\'t complete payout', 500,
success=False, dry_run=False)
_gamedata_cache = None
# Game types
@app.route('/gametypes', methods=['GET'])
def gametypes():
parser = RequestParser()
parser.add_argument('betcount', type=boolean_field, default=False)
parser.add_argument('latest', type=boolean_field, default=False)
parser.add_argument('identities', type=boolean_field, default=True)
parser.add_argument('filter')
parser.add_argument('filt_op',
choices=['startswith', 'contains'],
default='startswith',
)
args = parser.parse_args()
if args.filter:
args.identities = False
counts = {}
if args.betcount:
bca = (db.session.query(Game.gametype,
func.count(Game.gametype),
func.max(Game.create_date),
)
.group_by(Game.gametype).all())
counts = {k: (c, d) for k, c, d in bca}
times = []
if args.latest:
bta = (Game.query
.with_entities(Game.gametype, func.max(Game.create_date))
.group_by(Game.gametype)
.order_by(Game.create_date.desc())
.all())
times = bta # in proper order
global _gamedata_cache
if _gamedata_cache:
gamedata = _gamedata_cache.copy()
else:
gamedata = []
for poller in Poller.allPollers():
if poller is TestPoller:
continue
for gametype, gametype_name in poller.gametypes.items():
_getsub = lambda f: f.get(gametype) if isinstance(f, dict) else f
data = dict(
id=gametype,
name=gametype_name,
subtitle=_getsub(poller.subtitle),
category=_getsub(poller.category),
description=_getsub(poller.description),
)
if data['description']:
# strip enclosing whites,
# then replace single \n's with spaces
# and double \n's with single \n's
data['description'] = '\n'.join(map(
lambda para: ' '.join(map(
lambda line: line.strip(),
para.split('\n')
)),
data['description'].strip().split('\n\n')
))
if poller.identity or poller.twitch_identity or poller.honesty:
data.update(dict(
supported=True,
gamemodes=poller.gamemodes,
identity=poller.identity_id,
identity_name=poller.identity_name,
honesty_only=poller.honesty,
twitch=poller.twitch,
twitch_identity=None, # may be updated below
twitch_identity_name=None,
))
if poller.twitch_identity:
data['twitch_identity'] = poller.twitch_identity.id
data['twitch_identity_name'] = poller.twitch_identity.name
else: # DummyPoller
data.update(dict(
supported=False,
))
gamedata.append(data)
_gamedata_cache = gamedata.copy()
if args.betcount:
for data in gamedata:
data['betcount'], data['lastbet'] = \
counts.get(data['id'], (0, None))
if args.filter:
args.filter = args.filter.casefold()
if args.filt_op == 'contains':
args.filt_op = '__contains__'
gamedata = list(filter(
# search string in name or title
lambda item: (
getattr(
item['name'].casefold(),
args.filt_op
)(args.filter)
or getattr(
(item.get('subtitle') or '').casefold(),
args.filt_op
)(args.filter)
),
gamedata,
))
ret = dict(
gametypes=gamedata,
)
if args.identities:
ret['identities'] = {i.id: i.name for i in Identity.all}
if args.latest:
ret['latest'] = [
dict(
gametype=gametype,
date=date,
) for gametype, date in times
]
return jsonify(**ret)
@app.route('/gametypes/<id>/image')
@app.route('/gametypes/<id>/background')
def gametype_image(id):
if id not in Poller.all_gametypes:
raise NotFound
parser = RequestParser()
parser.add_argument('w', type=int, required=False)
parser.add_argument('h', type=int, required=False)
args = parser.parse_args()
filename = 'images/{}{}.png'.format(
'bg/' if request.path.endswith('/background') else '',
id,
)
try:
img = Image.open(filename)
except FileNotFoundError:
raise NotFound # 404
ow, oh = img.size
if args.w or args.h:
if not args.h or (args.w and args.h and (args.w / args.h) > (ow / oh)):
dw = args.w
dh = round(oh / ow * dw)
else:
dh = args.h
dw = round(ow / oh * dh)
# resize
img = img.resize((dw, dh), Image.ANTIALIAS)
# crop if needed
if args.w and args.h:
if args.w != dw:
# crop horizontally
cw = (dw - args.w) / 2
cl, cr = math.floor(cw), math.ceil(cw)
img = img.crop(box=(cl, 0, img.width - cr, img.height))
elif args.h != dh:
# crop vertically
ch = (dh - args.h) / 2
cu, cd = math.floor(ch), math.ceil(ch)
img = img.crop(box=(0, cu, img.width, img.height - cd))
img_file = BytesIO()
img.save(img_file, 'png')
img_file.seek(0)
return send_file(img_file, mimetype='image/png')
@app.route('/identities', methods=['GET'])
def identities():
os.path.dirname(__file__)
return jsonify(
identities=[
dict(
id=i.id,
name=i.name,
choices=i.choices,
) for i in Identity.all
],
)
# Games
@api.resource(
'/games',
'/games/',
'/games/<int:id>',
)
class GameResource(restful.Resource):
@classproperty
def fields_lite(cls):
return {
'id': fields.Integer,
'creator': fields.Nested(PlayerResource.fields(public=True)),
'opponent': fields.Nested(PlayerResource.fields(public=True)),
'parent_id': fields.Integer,
'is_root': fields.Boolean,
'gamertag_creator': fields.String(attribute='gamertag_creator_text'),
'gamertag_opponent': fields.String(attribute='gamertag_creator_text'),
'identity_id': fields.String,
'identity_name': fields.String,
'twitch_handle': fields.String,
'twitch_identity_creator': fields.String,
'twitch_identity_opponent': fields.String,
'twitch_identity_id': fields.String,
'twitch_identity_name': fields.String,
'gametype': fields.String,
'gamemode': fields.String,
'is_ingame': fields.Boolean,
'bet': fields.Float,
'has_message': fields.Boolean,
'create_date': fields.DateTime,
'state': fields.String,
'accept_date': fields.DateTime,
'aborter': fields.Nested(PlayerResource.fields(public=True),
allow_null=True),
'winner': fields.String,
'details': fields.String,
'finish_date': fields.DateTime,
'tournament_id': fields.Integer,
}
@classproperty
def fields(cls):
ret = cls.fields_lite.copy()
ret.update({
'children': fields.List(fields.Nested(cls.fields_lite)),
})
return ret
@require_auth
def get(self, user, id=None):
if id:
game = Game.query.get_or_404(id)
# TODO: allow?
if not game.is_game_player(user):
raise Forbidden
return marshal(game, self.fields)
parser = RequestParser()
parser.add_argument('page', type=int, default=1)
parser.add_argument('results_per_page', type=int, default=10)
parser.add_argument(
'order',
choices=sum(
[[s, '-' + s]
for s in
('create_date',
'accept_date',
'gametype',
'creator_id',
'opponent_id',
)], []),
required=False,
)
args = parser.parse_args()
# cap
if args.results_per_page > 50:
abort('[results_per_page]: max is 50')
query = user.games
# TODO: filters
if args.order:
if args.order.startswith('-'):
order = getattr(Game, args.order[1:]).desc()
else:
order = getattr(Game, args.order).asc()
query = query.order_by(order)
total_count = query.count()
query = query.paginate(args.page, args.results_per_page,
error_out=False)
return dict(
games=fields.List(fields.Nested(self.fields)).format(query.items),
num_results=total_count,
total_pages=math.ceil(total_count / args.results_per_page),
page=args.page,
)
@classproperty
def postparser(cls):
parser = RequestParser()
parser.add_argument('root_id',
type=lambda id: Game.query.filter_by(id=id).one(),
required=False, dest='root')
parser.add_argument('opponent_id', type=Player.find_or_fail,
required=False, dest='opponent')
parser.add_argument('gamertag_creator', required=False)
parser.add_argument('savetag', default='never', choices=(
'never', 'ignore_if_exists', 'fail_if_exists', 'replace'))
parser.add_argument('gamertag_opponent', required=False)
parser.add_argument('twitch_handle',
type=Twitch.check_handle,
required=False)
parser.add_argument('twitch_identity_creator', required=False)
parser.add_argument('twitch_identity_opponent', required=False)
parser.add_argument('gametype', choices=Poller.all_gametypes,
required=False)
parser.add_argument('bet', type=float, required=False)
parser.add_argument('tournament_id', type=Tournament.query.get_or_404,
required=False, dest='tournament')
return parser
@classmethod
def post_parse_args(cls):
args = cls.postparser.parse_args()
args.gamemode = None # will be handled below
return args
@classmethod
def post_parse_poller_args(cls, poller):
if poller.gamemodes:
gmparser = RequestParser()
gmparser.add_argument('gamemode', choices=poller.gamemodes,
required=False)
gmargs = gmparser.parse_args()
return gmargs
return {}
@classmethod
def load_save_identities(cls, poller, args, role, user,
optional=False, game=None):
"""
Check passed identities (in args),
load them from user profiles if needed,
and update profile's identities if required.
:param poller: poller class for current game
:param args: arguments to work with
:param role: role to handle identities for (creator or opponent)
:param user: current role's user object.
:param optional: is it allowed to omit this identity;
also will not update user's field if this is True.
If not passed then will just validate identities.
"""
had_creatag = args.get('gamertag_creator')
for name, identity, required in (
('gamertag', poller.identity, not poller.honesty),
('twitch_identity', poller.twitch_identity, poller.twitch == 2),
):
argname = '{}_{}'.format(name, role)
# if certain identity is not supported for this game
# then check its absence in args
if not identity:
if args.get(argname):
abort('[{}]: not supported for this game type'.format(
argname), problem=argname)
continue # no need to check other clauses
if args.get(argname):
# was passed -> validate and maybe save
try:
args[argname] = identity.checker(args[argname])
except ValueError as e:
abort('[{}]: Invalid {}: {}'.format(
argname, identity.name, e
), problem=argname)
else:
# try load this from user object
args[argname] = getattr(user, identity.id)
if required and not optional and not args[argname]:
abort('Please specify your {}'.format(
identity.name,
), problem=argname)
# Update creator's identity if requested
if had_creatag and poller.identity \
and not optional and args.get('savetag'):
if args.savetag == 'replace':
repl = True
elif args.savetag == 'never':
repl = False
elif args.savetag == 'ignore_if_exists':
repl = not getattr(user, poller.identity.id)
elif args.savetag == 'fail_if_exists':
repl = True
if getattr(user, poller.identity.id) != args.gamertag_creator:
abort('{} is already set and is different!'.format(
poller.identity.name), problem='savetag')
if repl:
setattr(user, poller.identity.id, args.gamertag_creator)
@classmethod
def check_identity_equality(cls, poller, creators, opponents):
"""
:param creators: object to get creator's identity from
:param opponents: object to get opponent's identity from
"""
for name, identity in (
('gamertag', poller.identity),
('twitch_identity', poller.twitch_identity)
):
creaname, opponame = ('{}_{}'.format(name, role)
for role in ('creator', 'opponent'))
if getattr(creators, creaname) == getattr(opponents, opponame):
abort('You cannot specify {} same as your opponent\'s!'.format(
identity.name,
))
@classmethod
def check_same_region(cls, poller, crea, oppo):
# crea & oppo are identities (primary ones, not twitch)
if not poller.sameregion:
# no need to check
return
if not oppo:
# opponent identity not passed - cannot check
return
# this is an additional check for regions
region1 = crea.split('/', 1)[0]
region2 = oppo.split('/', 1)[0]
if region1 != region2:
abort('You and your opponent should be in the same region; '
'but actually you are in {} and your opponent is in {}'.format(
region1, region2))
@classmethod
def check_bet_amount(cls, bet, user):
if bet < 0.99: # FIXME: hardcoded min bet
abort('Bet is too low', problem='bet')
if bet > user.available:
abort('You don\'t have enough coins', problem='coins')
@require_auth
def post(self, user, id=None):
if id:
raise MethodNotAllowed
args = self.post_parse_args()
poller = Poller.findPoller(args.gametype)
if not poller or poller == DummyPoller:
abort('Support for this game is coming soon!')
args.update(self.post_parse_poller_args(poller))
# check tournament-related settings
if args.tournament:
if args.bet or args.opponent:
abort('Bet and opponent shall not be provided in tournament mode')
else:
if not (args.bet and args.opponent):
abort('Please provide bet amount and choose your opponent '
'when not in tournament mode')
if not (args.gamemode and args.gametype):
abort('Please provide gamemode and gametype '
'when not in tournament mode')
if args.tournament:
# request opponent from tournament
args.opponent = args.tournament.get_opponent(user)
if args.opponent == user:
abort('You cannot compete with yourself')
# determine identities and update them on args
self.load_save_identities(poller, args, 'creator', user)
self.load_save_identities(poller, args, 'opponent', args.opponent,
optional=True)
self.check_identity_equality(poller, args, args)
# Perform sameregion check
self.check_same_region(
poller,
args.gamertag_creator,
args.gamertag_opponent)
# check twitch parameter if needed
if poller.twitch == 2 and not args.twitch_handle:
abort('Please specify your twitch stream URL',
problem='twitch_handle')
if args.twitch_handle and not poller.twitch:
abort('Twitch streams are not yet supported for this gametype')
if not args.tournament:
# check bet amount
self.check_bet_amount(args.bet, user)
game = Game()
game.creator = user
game.opponent = args.opponent
log.debug('setting parent')
if args.root:
game.parent = args.root.root # ensure we use real root
game.gamertag_creator = args.gamertag_creator
game.gamertag_opponent = args.gamertag_opponent
game.twitch_handle = args.twitch_handle
game.twitch_identity_creator = args.twitch_identity_creator
game.twitch_identity_opponent = args.twitch_identity_opponent
if args.tournament:
game.bet = 0
game.tournament = args.tournament
game.gametype = args.tournament.gametype
game.gamemode = args.tournament.gamemode
else:
game.gametype = args.gametype
game.gamemode = args.gamemode
game.bet = args.bet
db.session.add(game)
db.session.commit()
log.debug('notifying')
notify_users(game)
return marshal(game, self.fields), 201
def patch(self, id=None):
if not id:
raise MethodNotAllowed
parser = RequestParser()
parser.add_argument('state', choices=[
'accepted', 'declined', 'cancelled'
], required=True)
parser.add_argument('gamertag_opponent', required=False)
parser.add_argument('twitch_identity_opponent', required=False)
args = parser.parse_args()
game = Game.query.get_or_404(id)
user = check_auth()
if user == game.creator:
if args.state not in ['cancelled']:
abort('Only {} can accept or decline this challenge'.format(
game.opponent.nickname,
))
elif user == game.opponent:
if args.state not in ['accepted', 'declined']:
abort('Only {} can cancel this challenge'.format(
game.creator.nickname,
))
else:
abort('You cannot access this challenge', 403)
if game.state != 'new':
abort('This challenge is already {}'.format(game.state))
if args.state == 'accepted':
self.check_bet_amount(game.bet, user)
poller = Poller.findPoller(game.gametype)
if args.state == 'accepted':
# handle identities
self.load_save_identities(poller, args, 'opponent', user, game=game)
self.check_identity_equality(poller, game, args)
for name in 'gamertag', 'twitch_identity':
argname = '{}_opponent'.format(name)
if not args[argname]:
continue # was already checked -> not needed here
if getattr(game, argname) != args[argname]:
log.warning(
'Game {}: changing {} opponent identity '
'from {} to {}'.format(
game.id,
'primary' if name == 'gamertag' else 'secondary',
getattr(game, argname),
args[argname],
)
)
setattr(game, argname, args[argname])
# Perform sameregion check
self.check_same_region(
poller,
args.gamertag_opponent,
game.gamertag_creator)
# now all checks are done, perform actual logic
if args.state == 'accepted':
try:
poller.gameStarted(game)
except Exception as e:
log.exception('Error in gameStarted for {}: {}'.format(
poller, e))
abort('Failed to initialize poller, please contact support!', 500)
# Now, before we save state change, start twitch stream if required
# so that we can abort request if it failed
if game.twitch_handle and args.state == 'accepted':
try:
ret = requests.put(
'{}/streams/{}/{}'.format(
config.OBSERVER_URL,
game.twitch_handle,
game.gametype,
),
data=dict(
game_id=game.id,
creator=game.twitch_identity_creator
if poller.twitch_identity else
game.gamertag_creator,
opponent=game.twitch_identity_opponent
if poller.twitch_identity else
game.gamertag_opponent,
),
)
except Exception:
log.exception('Failed to start twitch stream!')
abort('Cannot start twitch observing - internal error', 500)
if ret.status_code not in (200, 201):
jret = ret.json()
if ret.status_code == 409: # dup
# TODO: check it on creation??
abort('This twitch stream is already watched '
'for another game (or another players)')
elif ret.status_code == 507: # full
abort('Cannot start twitch observing, all servers are busy now; '
'please retry later', 500)
abort('Couldn\'t start Twitch: ' + jret.get('error', 'Unknown err'))
game.state = args.state
game.accept_date = datetime.utcnow()
if args.state == 'accepted':
# bet is locked on creator's account; lock it on opponent's as well
game.opponent.locked += game.bet
else:
# bet was locked on creator's account; unlock it
game.creator.locked -= game.bet
db.session.commit()
notify_users(game)
return marshal(game, self.fields)
@require_auth
def delete(self, user, id=None):
if not id:
raise MethodNotAllowed
game = Game.query.get_or_404(id)
if not game.is_game_player(user):
raise Forbidden('You cannot access this challenge')
if not game.aborter or game.aborter == user:
# aborting not started, so initiate it.
# or maybe it is already started, so just ask again
# (make another event)
game.aborter = user
notify_event(
game.root, 'abort',
game=game,
)
return dict(
started=True,
)
if game.aborter != game.other(user):
abort('Internal error, wrong aborter', 500)
Poller.gameDone(game, 'aborted',
details='Challenge was aborted by request of ' + game.aborter.nickname,
)
return dict(
aborted=True,
)
@api.resource('/games/<int:game_id>/report')
class GameReportResource(restful.Resource):
fields = {
'result': fields.String,
'created': fields.DateTime,
'modified': fields.DateTime,
'match': fields.Boolean,
'ticket_id': fields.Integer,
}
def get_game(self, user, game_id):
game = Game.query.get_or_404(game_id)
if not game.is_game_player(user):
raise Forbidden
return game
def get_report(self, user, game):
report = Report.query.filter(Report.game == game, Report.player == user).first()
if not report:
raise NotFound
return report
def check_report(self, report, game):
report.match = report.check_reports()
if not report.match:
ticket = None
for t in game.tickets:
if t.type == 'reports_mismatch':
ticket = t
if not ticket:
ticket = Ticket(game, 'reports_mismatch')
db.session.add(ticket)
db.session.flush()
report.ticket = ticket
if report.other_report:
report.other_report.ticket = ticket
db.session.commit()
notify_event(game, 'report', message='reports don\' match, ticket {id} created'.format(
id=ticket.id
))
else:
if report.match and report.other_report:
winner = None
if report.result == 'won':
winner = report.player
if report.other_report.result == 'won':
winner = report.other_report.player
game_winner = 'draw'
if winner == game.creator:
game_winner = 'creator'
if winner == game.opponent:
game_winner = 'opponent'
poller = Poller.findPoller(game.gametype)
endtime = min(report.created, report.other_report.created)
poller.gameDone(game, game_winner, endtime)
@property
def result(self):
parser = RequestParser()
parser.add_argument('result', choices=[
'won', 'lost', 'draw',
], required=False)
args = parser.parse_args()
return args.result
@require_auth
def post(self, user, game_id):
game = self.get_game(user, game_id)
db.session.flush()
try:
report = Report(game, user, self.result)
db.session.add(report)
db.session.flush()
except IntegrityError:
abort('You have already reported this game', problem='duplicate')
return
# update badges for participants of this game
game_badge_signal.send(game)
db.session.commit()
notify_event(game, 'report', message='{user} reported {result}'.format(
user=user.nickname,
result=report.result,
))
self.check_report(report, game)
return marshal(report, self.fields)
@require_auth
def get(self, user, game_id):
game = self.get_game(user, game_id) # check if such game exists and accessible for this user
report = self.get_report(user, game_id)
self.check_report(report, game)
return marshal(report, self.fields)
@require_auth
def patch(self, user, game_id):
game = self.get_game(user, game_id) # check if such game exists and accessible for this user
report = self.get_report(user, game)
report.modify(self.result)
db.session.commit()
notify_event(game, 'report', message='{user} changed his report to {result}'.format(
user=user.nickname,
result=report.result,
))
self.check_report(report, game)
return marshal(report, self.fields)
@api.resource(
'/games/<int:game_id>/tickets',
'/tickets/<int:ticket_id>'
)
class TicketResource(restful.Resource):
@property
def fields(self):
return {
'id': fields.Integer,
'open': fields.Boolean,
'game_id': fields.Integer,
'type': fields.String,
'messages': fields.List(fields.Nested(ChatMessageResource.fields))
}
@require_auth
def get(self, user, game_id=None, ticket_id=None):
if ticket_id:
ticket = Ticket.query.get_or_404(ticket_id)
if not ticket.game.is_game_player(user):
raise Forbidden
return marshal(ticket, self.fields)
if game_id:
game = Game.query.get_or_404(game_id)
if not game.is_game_player(user):
raise Forbidden
return marshal(game.tickets, fields.List(self.fields))
raise NotFound
@api.resource(
'/games/<int:id>/msg',
'/games/<int:id>/msg.mp4',
'/games/<int:id>/msg.m4a',
)
class GameMessageResource(UploadableResource):
PARAM = 'msg'
SUBDIR = 'messages'
ALLOWED = ['mpg', 'mp3', 'ogg', 'ogv', 'mp4', 'm4a']
@require_auth
def get_entity(self, args, is_put, user):
game = Game.query.get_or_404(args['id'])
if not game.is_game_player(user):
raise Forbidden
if is_put and user != game.creator:
raise Forbidden
if is_put and game.state != 'new':
abort('This game is already {}'.format(game.state))
return game
# Messaging
@api.resource(
'/players/<player_id>/messages',
'/players/<player_id>/messages/',
'/players/<player_id>/messages/<int:id>',
'/games/<int:game_id>/messages',
'/games/<int:game_id>/messages/',
'/games/<int:game_id>/messages/<int:id>',
'/tickets/<int:ticket_id>/messages',
'/tickets/<int:ticket_id>/messages/',
'/tickets/<int:ticket_id>/messages/<int:id>',
'/messages/<int:id>'
)
class ChatMessageResource(restful.Resource):
@classproperty
def fields(cls):
return dict(
id=fields.Integer,
sender=fields.Nested(PlayerResource.fields()),
receiver=fields.Nested(PlayerResource.fields()),
# game = fields.Nested(GameResource.fields),
text=fields.String,
time=fields.DateTime,
has_attachment=fields.Boolean,
viewed=fields.Boolean,
)
def get_single(self, user, game_id=None, player_id=None, ticket_id=None, id=None):
msg = ChatMessage.query.get_or_404(id)
if not msg.is_for(user):
raise Forbidden
if game_id and game_id != msg.game_id:
return redirect(api.url_for(ChatMessageResource, game_id=msg.game_id, id=id), 301)
if player_id and player_id != msg.sender_id:
return redirect(api.url_for(ChatMessageResource, player_id=msg.sender_id, id=id), 301)
if ticket_id and ticket_id != msg.ticket_id:
return redirect(api.url_for(ChatMessageResource, ticket_id=msg.ticket_id, id=id), 301)
return marshal(msg, self.fields)
@require_auth
def get(self, user, game_id=None, player_id=None, ticket_id=None, id=None):
if id:
return self.get_single(game_id, player_id, ticket_id, id)
player = None
if player_id:
player = Player.find(player_id)
if not player:
raise NotFound('wrong player id')
game = None
if game_id:
game = Game.query.get_or_404(game_id)
elif ticket_id:
ticket = Ticket.query.get_or_404(game_id)
game = ticket.game
if not game:
raise NotFound('wrong ticket id')
if game and not game.is_game_player(user):
abort('You cannot access this game', 403)
if player:
if user == player:
# TODO:
# SELECT * FROM messages
# WHERE is_for(user)
# GROUP BY other(user)
# ORDER BY time DESC
messages = ChatMessage.for_user(player)
else:
messages = ChatMessage.for_users(player, user)
messages = messages.filter_by(game_id=None)
elif game:
messages = ChatMessage.query.filter_by(game_id=game.id)
else:
raise ValueError('no player nor game')
parser = RequestParser()
parser.add_argument('page', type=int, default=1)
parser.add_argument('results_per_page', type=int, default=10)
parser.add_argument(
'order', default='time',
choices=sum(
[[s, '-' + s]
for s in (
'time',
)], []),
)
args = parser.parse_args()
if args.results_per_page > 50:
abort('[results_per_page]: max is 50')
# TODO: filtering
if args.order.startswith('-'):
order = getattr(ChatMessage, args.order[1:]).desc()
else:
order = getattr(ChatMessage, args.order).asc()
messages = messages.order_by(order)
total_count = messages.count()
messages = messages.paginate(args.page, args.results_per_page,
error_out=False).items
ret = marshal(
dict(messages=messages),
dict(messages=fields.List(fields.Nested(self.fields))),
)
ret.update(dict(
num_results=total_count,
total_pages=math.ceil(total_count / args.results_per_page),
page=args.page,
))
return ret
@require_auth
def post(self, user, game_id=None, player_id=None, ticket_id=None, id=None):
if id:
raise MethodNotAllowed
game = None
player = None
ticket = None
if player_id:
player = Player.find(player_id)
if not player:
raise NotFound('wrong player id')
if player == user:
abort('You cannot send message to yourself')
elif game_id:
game = Game.query.get_or_404(game_id)
player = game.other(user)
if not player:
raise Forbidden('You cannot access this game', 403)
game = game.root # always attach messages to root game in session
elif ticket_id:
ticket = Ticket.query.get_or_404(game_id)
if not ticket.game.is_game_player(user):
raise Forbidden('You cannot access this ticket', 403)
parser = RequestParser()
parser.add_argument('text', required=False)
args = parser.parse_args()
msg = ChatMessage()
msg.game = game
msg.ticket = ticket
msg.sender = user
msg.receiver = player
msg.text = args.text
db.session.add(msg)
if 'attachment' in request.files:
db.session.commit() # for id
ChatMessageAttachmentResource.upload(
request.files['attachment'],
msg)
elif not msg.text:
db.session.expunge(msg)
abort('Please provide either text or attachment, or both')
db.session.commit()
notify_chat(msg)
return marshal(msg, self.fields)
@require_auth
def patch(self, user, game_id=None, player_id=None, ticket_id=None, id=None):
if not id or any(game_id, player_id, ticket_id):
raise MethodNotAllowed
msg = ChatMessage.query.get_or_404(id)
if msg.receiver_id != user.id:
raise Forbidden(
'You cannot patch message which is not addressed to you')
parser = RequestParser()
parser.add_argument('viewed', type=boolean_field, required=True)
# we allow marking message as unread
args = parser.parse_args()
msg.viewed = args.viewed
db.session.commit()
return marshal(msg, self.fields)
@api.resource(
'/players/<player_id>/messages/<int:id>/attachment',
'/games/<int:game_id>/messages/<int:id>/attachment',
'/tickets/<int:ticket_id>/messages/<int:id>/attachment',
)
class ChatMessageAttachmentResource(UploadableResource):
PARAM = 'attachment'
SUBDIR = 'attachments'
ALLOWED = ['mp4', 'm4a', 'mov', 'png', 'jpg']
@require_auth
def get_entity(self, args, is_put, user):
msg = ChatMessage.query.get_or_404(args['id'])
if not msg.is_for(user):
raise Forbidden
if 'player_id' in args:
player = Player.find(args['player_id'])
if not player:
raise NotFound
if player != user and not msg.is_for(player):
abort('Player ID mismatch')
elif 'game_id' in args:
game = Game.query.get(args['game_id'])
if not game:
raise NotFound('wrong game id')
if not game.is_game_player(user):
raise Forbidden('You cannot access this game')
elif 'ticket_id' in args:
ticket = Ticket.query.get_or_404(args['ticket_id'])
game = ticket.game
if not game:
raise NotFound('wrong game id')
if not game.is_game_player(user):
raise Forbidden('You cannot access this ticket')
else:
raise ValueError('no ids')
return msg
@classmethod
def onupload(cls, entity, ext):
if not entity.has_attachment:
entity.has_attachment = True
db.session.commit()
@classmethod
def ondelete(cls, entity):
if entity.has_attachment:
entity.has_attachment = False
db.session.commit()
found = onupload
notfound = ondelete
# Events
@api.resource(
'/games/<int:game_id>/events',
'/games/<int:game_id>/events/',
'/games/<int:game_id>/events/<int:id>',
)
class EventResource(restful.Resource):
@classproperty
def fields(cls):
return {
'id': fields.Integer,
'root_id': fields.Integer,
'time': fields.DateTime,
'type': fields.String,
'message': fields.Nested(ChatMessageResource.fields,
allow_null=True),
'text': fields.String,
'game': fields.Nested(GameResource.fields_lite,
allow_null=True),
}
@classproperty
def fields_more(cls):
# for push notifications
ret = cls.fields.copy()
ret['root'] = fields.Nested(GameResource.fields)
return ret
@require_auth
def get(self, user, game_id, id=None):
root = Game.query.get_or_404(game_id)
if not root.is_root:
abort('This game is not root of hierarchy, use id %d' % root.root.id)
if id:
event = Event.query.filter_by(root=root, id=id).first_or_404()
return marshal(event, self.fields)
# TODO custom filters, pagination
events = Event.query.filter(
Event.root_id == root.id,
).order_by(
Event.time,
)
return marshal(
dict(events=events),
dict(events=fields.List(fields.Nested(self.fields))),
)
# Beta testers
@api.resource(
'/betatesters',
'/betatesters/<int:id>',
)
class BetaResource(restful.Resource):
@classproperty
def fields(cls):
return dict(
id=fields.Integer,
email=fields.String,
name=fields.String,
gametypes=CommaListField,
platforms=CommaListField,
console=CommaListField,
create_date=fields.DateTime,
flags=JsonField,
)
@require_auth
def get(self, user, id=None):
if id:
raise MethodNotAllowed
user = check_auth()
if user.id not in config.ADMIN_IDS:
raise Forbidden
return jsonify(
betatesters=fields.List(fields.Nested(self.fields)).format(
Beta.query,
),
)
def post(self, id=None):
if id:
raise MethodNotAllowed
def nonempty(val):
if not val:
raise ValueError('Should not be empty')
return val
parser = RequestParser()
parser.add_argument('email', type=email, required=True)
parser.add_argument('name', type=nonempty, required=True)
parser.add_argument('games',
default='')
parser.add_argument('platforms',
type=multival_field(Beta.PLATFORMS, True),
default='')
parser.add_argument('console', default='')
args = parser.parse_args()
beta = Beta()
beta.email = args.email
beta.name = args.name
beta.gametypes = args.games
beta.platforms = ','.join(args.platforms)
beta.console = args.console
db.session.add(beta)
db.session.commit()
datadog('Beta registration', repr(args))
dd_stat.increment('beta.registration')
return jsonify(
success=True,
betatester=marshal(
beta,
self.fields,
),
)
@require_auth
def patch(self, user, id=None):
if not id:
raise MethodNotAllowed
beta = Beta.query.get_or_404(id)
parser = RequestParser()
parser.add_argument('flags')
args = parser.parse_args()
for k, v in args.items():
if v is not None and hasattr(beta, k):
setattr(beta, k, v)
log.info('flags for {}: {}'.format(beta.id, beta.flags))
# and create backup for flags
def merge(src, dst):
for k, v in src.items():
if isinstance(v, dict):
node = dst.setdefault(k, {})
merge(v, node)
elif isinstance(v, list):
dst.setdefault(k, [])
dst[k] = list(set(dst[k] + v)) # merge items
else:
dst[k] = v
return dst
try:
src = json.loads(beta.flags)
try:
dst = json.loads(beta.backup or '')
except ValueError:
dst = {}
merge(src, dst)
beta.backup = json.dumps(dst)
except ValueError:
pass
db.session.commit()
return marshal(beta, self.fields)
@socketio.on('connect')
def socketio_conn():
log.info('socket connected')
# TODO check auth...
#return False # if auth failed
_sockets = {} # sid -> sender
@socketio.on('auth')
def socketio_auth(token=None):
log.info('Auth request for socket {}, token {}'.format(
request.sid, token))
if request.sid in _sockets:
# already authorized
log.info('already authorized')
return False
try:
user = parseToken(token)
except Exception:
log.exception('Socket auth failed')
sio_disconnect()
return
log.info('Socket auth success for {}'.format(request.sid))
@copy_current_request_context
def sender():
p = redis.pubsub()
redis_base = '{}.event.%s'.format('test' if config.TEST else 'prod')
p.subscribe(redis_base % user.id)
try:
while True:
msg = p.get_message()
if not msg:
eventlet.sleep(.5)
continue
log.debug('got msg: %s'%msg)
if 'message' not in msg.get('type', ''): # msg or pmsg
continue
mdata = msg.get('data')
try:
if isinstance(mdata, bytes):
mdata = mdata.decode()
data = json.loads(mdata)
except ValueError:
log.warning('Bad msg, not a json: '+str(mdata))
continue
log.debug('handling msg')
sio_send(data)
finally:
p.unsubscribe()
_sockets[request.sid] = eventlet.spawn(sender)
@socketio.on('disconnect')
def socketio_disconn():
sender = _sockets.pop(request.sid, None)
log.debug('socket disconnected, will kill? - {} {}'.format(sender, request.sid))
if sender:
sender.kill()
@api.resource(
'/tournaments',
'/tournaments/',
'/tournaments/<int:id>',
'/tournaments/<int:id>/',
)
class TournamentResource(restful.Resource):
participant_fields = {
'player': fields.Nested(PlayerResource.fields(), allow_null=True),
'round': fields.Integer,
'defeated': fields.Boolean,
}
round_fields = {
'start': fields.DateTime,
'end': fields.DateTime,
}
fields_single = {
'id': fields.Integer,
'open_date': fields.DateTime,
'start_date': fields.DateTime,
'finish_date': fields.DateTime,
'rounds_dates': fields.List(fields.Nested(round_fields)),
'participants_by_round': fields.List(fields.List(
fields.Nested(participant_fields, allow_null=True)
)),
'participants_cap': fields.Integer,
'participants_count': fields.Integer,
'gamemode': fields.String,
'gametype': fields.String,
}
fields_many = {
'id': fields.Integer,
'open_date': fields.DateTime,
'start_date': fields.DateTime,
'finish_date': fields.DateTime,
'participants_cap': fields.Integer,
'participants_count': fields.Integer,
'gamemode': fields.String,
'gametype': fields.String,
}
@require_auth
def post(self, user, id=None):
if id:
raise MethodNotAllowed
parser = RequestParser()
parser.add_argument('rounds_count', type=int)
parser.add_argument('open_date', type=lambda s: datetime.fromtimestamp(int(s)))
parser.add_argument('start_date', type=lambda s: datetime.fromtimestamp(int(s)))
parser.add_argument('finish_date', type=lambda s: datetime.fromtimestamp(int(s)))
parser.add_argument('finish_date', type=lambda s: datetime.fromtimestamp(int(s)))
parser.add_argument('finish_date', type=lambda s: datetime.fromtimestamp(int(s)))
parser.add_argument('buy_in', type=float)
parser.add_argument('gametype', choices=Poller.all_gametypes, required=True)
parser.add_argument('gamemode', type=str, required=True)
args = parser.parse_args()
poller = Poller.findPoller(args.gametype)
if not poller or poller == DummyPoller:
abort('Support for this game is coming soon!')
if args.gamemode not in poller.gamemodes:
abort('Unknown gamemode')
if args.rounds_count < 1:
abort('Tournament must have 1 or more rounds', problem='rounds_count')
if args.buy_in < 0.99:
abort('Buy in too low', problem='buy_in')
# TODO: check dates
tournament = Tournament(
rounds_count=args.rounds_count,
open_date=args.open_date,
start_date=args.start_date,
finish_date=args.finish_date,
payin=args.buy_in,
gamemode=args.gamemode,
gametype=args.gametype,
)
db.session.add(tournament)
db.session.commit()
return marshal(tournament, self.fields_single)
@require_auth
def patch(self, user, id=None):
"""
participate in tournament
"""
if not id:
raise MethodNotAllowed
tournament = Tournament.query.get_or_404(id)
success, message, problem = tournament.add_player(user)
if success:
return self.get_single(id)
else:
abort(message, problem=problem)
def get_single(self, id):
return marshal(Tournament.query.get_or_404(id), self.fields_single)
def get_many(self):
parser = RequestParser()
parser.add_argument('page', type=int, default=1)
parser.add_argument('results_per_page', type=int, default=10)
parser.add_argument('order', default='id', choices=sum([
[s, '-' + s]
for s in (
'id',
'open_date',
'start_date',
'finish_date',
)
], [])
)
args = parser.parse_args()
# cap
if args.results_per_page > 50:
abort('[results_per_page]: max is 50')
query = Tournament.query.filter(Tournament.available == True)
# TODO: filters
if args.order:
if args.order.startswith('-'):
order = getattr(Tournament, args.order[1:]).desc()
else:
order = getattr(Tournament, args.order).asc()
query = query.order_by(order)
total_count = query.count()
query = query.paginate(args.page, args.results_per_page,
error_out=False)
return dict(
tournaments=fields.List(fields.Nested(self.fields_many)).format(query.items),
num_results=total_count,
total_pages=math.ceil(total_count / args.results_per_page),
page=args.page,
)
def get(self, id=None):
if id:
return self.get_single(id)
return self.get_many()
# Debugging-related endpoints
@app.route('/debug/push_state/<state>', methods=['POST'])
@require_auth
def push_state(state, user):
if state not in Game.state.prop.columns[0].type.enums:
abort('Unknown state ' + state, 404)
parser = GameResource.postparser.copy()
parser.remove_argument('opponent_id')
args = parser.parse_args()
game = Game()
game.creator = game.opponent = user
game.state = state
for k, v in args.items():
if hasattr(game, k):
setattr(game, k, v)
result = notify_users(game, justpush=True)
return jsonify(
pushed=result,
game=marshal(game, GameResource.fields)
)
@app.route('/debug/push_event/<int:root_id>/<etype>', methods=['POST'])
@require_auth
def push_event(root_id, etype, user):
root = Game.query.get_or_404(root_id).root
parser = RequestParser()
parser.add_argument('message', type=int)
parser.add_argument('game', type=int)
parser.add_argument('text')
parser.add_argument('newstate')
parser.add_argument('aborter', type=int)
args = parser.parse_args()
if args.message:
args.message = ChatMessage.query.get_or_404(args.message)
if args.game:
args.game = Game.query.get_or_404(args.game)
if args.aborter:
args.game.aborter = Player.query.get_or_404(args.aborter)
try:
success = notify_event(root, etype, debug=True, **args)
except ValueError as e:
abort(str(e))
return jsonify(success=success)
@app.route('/debug/echo')
def debug_echo():
return '<{}>\n{}\n'.format(
repr(request.get_data()),
repr(request.form),
)
@app.route('/debug/pdb')
def debug_pdb():
import pdb
pdb.set_trace()
@app.route('/debug/raise')
def debug_raise():
raise Forbidden('Hello World!')
@app.route('/debug/datadog')
def debug_datadog():
datadog('Debug', 'Debug received')
dd_stat.increment('player.registered')
return ''
@app.route('/debug/money')
@require_auth
def debug_money(user):
# Allow this endpoint only for users whose first transaction was "other"
tran = user.transactions.first()
if tran.type != 'other':
raise Forbidden
SUM = 100
user.balance += SUM
db.session.add(Transaction(
player=user,
type='deposit',
sum=SUM,
balance=user.balance,
comment='Debugging income',
))
db.session.commit()
return jsonify(success=True)
@app.route('/debug/@llg@mes')
def debug_allgames():
games = Game.query.filter_by(state='accepted').order_by(Game.id.desc())
return """<html><head><script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script><script>
$(function() {
$('body').on('click', 'a[data-id]', function(e) {
e.preventDefault();
var id = $(this).data('id'),
winner = $(this).attr('class');
$.ajax({
type: 'POST',
url: '/v1/debug/f@keg@me/'+id+'/'+winner,
success: function(ret) {
$('span[data-id='+id+'].actions').addClass('finished');
$('span[data-id='+id+'].state').text('finished');
$('span[data-id='+id+'].winner').text(winner);
},
error: function(xhr) {
alert(xhr.responseJSON.error);
},
});
});
});
</script><style>
span.new, span.finished, span.declined {
display: none;
}
</style></head><body><table border=1>
<tr>
<th>Game ID</th>
<th>Creator</th>
<th>Opponent</th>
<th>Stream</th>
<th>When created</th>
<th>Bet</th>
<th>State</th>
<th>Winner</th>
</tr>
""" + '\n\n'.join([
"""
<tr>
<th>{id}</th>
<th>{creator} / {twitch_identity_creator}</th>
<th>{opponent} / {twitch_identity_opponent}</th>
<th><a href="http://twitch.tv/{twitch_handle}">{twitch_handle}</a></th>
<th>{create_date}</th>
<th>{bet}</th>
<th><span data-id="{id}" class="state">{state}</span>
<th>
<span data-id="{id}" class="winner">{winner}</span>
<span data-id="{id}" class="actions {state}">- set to
<a href="#" data-id="{id}" class="creator">creator</a>,
<a href="#" data-id="{id}" class="opponent">opponent</a>,
<a href="#" data-id="{id}" class="draw">draw</a>
</span>
</th>
<tr/>
""".format(
id=game.id,
creator=game.creator.nickname,
opponent=game.opponent.nickname,
twitch_handle=game.twitch_handle or '',
twitch_identity_creator=game.twitch_identity_creator,
twitch_identity_opponent=game.twitch_identity_opponent,
create_date=game.create_date,
bet=game.bet,
state=game.state,
winner=game.winner,
) for game in games
])
@app.route('/debug/f@keg@me/<int:id>/<winner>', methods=['POST'])
def debug_fake_result(id, winner):
game = Game.query.get_or_404(id)
if winner not in ('creator', 'opponent', 'draw'):
abort('Bad winner ' + winner)
if game.state != 'accepted':
abort('Unexpected game state ' + game.state)
poller = Poller.findPoller(game.gametype)
if not poller:
abort('No poller found for gt ' + game.gametype)
poller.gameDone(game, winner, datetime.utcnow())
return jsonify(success=True)
@app.route('/debug/socksend')
def debug_socksend():
socketio.send({'hello': 'world'})
return 'ok'
@app.route('/debug/redissend')
@require_auth
def debug_redissend(user):
redis_base = '{}.event.%s'.format('test' if config.TEST else 'prod')
redis.publish(redis_base%user.id, json.dumps(
{'data':'Hello World.'}
))
return 'ok'
@app.route('/debug/revision')
def debug_revision():
import subprocess
return subprocess.check_output('/usr/bin/git rev-parse HEAD'.split())
| {"/v1/signals_definitions.py": ["/v1/main.py", "/v1/badges/__init__.py"], "/v1/polling.py": ["/config.py", "/v1/helpers.py", "/v1/models.py", "/v1/apis.py", "/v1/common.py"], "/v1/badges/__init__.py": ["/v1/badges/badges_description.py", "/v1/badges/fifa15.py"], "/v1/apis.py": ["/config.py", "/v1/helpers.py", "/v1/mock.py"], "/v1/__init__.py": ["/v1/main.py"], "/mobsite.py": ["/config.py"], "/v1/badges/fifa15.py": ["/v1/main.py", "/v1/badges/badges_description.py"], "/v1/helpers.py": ["/config.py", "/v1/models.py", "/v1/main.py", "/v1/common.py", "/v1/apis.py", "/v1/__init__.py"], "/v1/models.py": ["/v1/main.py", "/v1/common.py", "/v1/badges/__init__.py", "/config.py", "/v1/helpers.py", "/v1/routes.py", "/v1/polling.py"], "/poll.py": ["/main.py", "/v1/__init__.py"], "/v1/cas.py": ["/config.py", "/v1/main.py", "/v1/apis.py", "/v1/models.py", "/v1/common.py"], "/debug_console.py": ["/main.py", "/v1/models.py", "/v1/helpers.py", "/v1/routes.py"], "/v1/routes.py": ["/config.py", "/v1/signals_definitions.py", "/v1/models.py", "/v1/helpers.py", "/v1/apis.py", "/v1/polling.py", "/v1/main.py"], "/main.py": ["/config.py", "/v1/__init__.py", "/v1/main.py", "/v1/models.py"], "/v1/main.py": ["/config.py", "/v1/__init__.py", "/v1/admin.py"], "/v1/admin.py": ["/v1/models.py", "/v1/polling.py", "/v1/helpers.py"], "/observer.py": ["/config.py", "/v1/polling.py", "/v1/models.py", "/v1/apis.py"]} |
71,994 | topdevman/flask-betg | refs/heads/master | /v1/badges/badges_description.py | """
Describe new badges here.
User bounded properties must be in dict inside lambda function to prevent
unwanted objects mutations.
You can only ADD new user_bounded properties.
All changes in existing user_bounded properties will be ignored
after first update(insert).
Badge static properties:
- "type": "one_time", "count"
- type-specific-for-chosen-type, e.g. "one_time_type", "count_type"
- if "type"=="count":
- max_value # maximum value receive badge
- name # user friendly badge name
- image_path # path to badge image
Types of badges:
1) one_time:
one_time_type:
- "win"
- "loss"
- "draw"
- "all"
2) count:
count_type:
- "win"
- "loss"
- "draw"
- "all"
User bounded (this part will be stored in DB!) values for type:
1) one_time:
- received: bool # required
2) count:
- received: bool # required
- value: int # required
All dicts must be flat.
Look below if you understood nothing.
"""
GAMES_GENERAL_ONE_TIME_BADGES = {
"group_name": "games_general_one_time",
"badges": {
"first_win": {
"type": "one_time",
"one_time_type": "win",
"name": "First win!",
"image_path": "path_to_image",
"user_bounded": (lambda: {
"received": False
})
},
"first_loss": {
"type": "one_time",
"one_time_type": "loss",
"name": "First loss!",
"image_path": "path_to_image",
"user_bounded": (lambda: {
"received": False
})
}
}
}
GAMES_GENERAL_COUNT = {
"group_name": "games_general_count",
"badges": {
"played_10_games": {
"type": "count",
"count_type": "all",
"max_value": 10,
"name": "10 games!",
"image_path": "path_to_image",
"user_bounded": (lambda: {
"value": 0,
"received": False
})
}
}
}
FIFA15_BADGES = {
"group_name": "fifa15_xboxone",
"badges": {
"fifa15_xboxone_first_win": {
"type": "one_time",
"one_time_type": "win",
"name": "Badge 1",
"image_path": "path_to_image",
"user_bounded": (lambda: {
"received": False
})
},
"fifa15_xboxone_10_wins": {
"type": "count",
"count_type": "win",
"max_value": 10,
"image_path": "path_to_image",
"user_bounded": (lambda: {
"value": 0,
"received": False
})
},
"fifa15_xboxone_first_loss": {
"type": "one_time",
"one_time_type": "loss",
"name": "Badge 1",
"image_path": "path_to_image",
"user_bounded": (lambda: {
"received": False
})
}
}
}
# contains all badges by groups
BADGES = {
GAMES_GENERAL_ONE_TIME_BADGES["group_name"]: GAMES_GENERAL_ONE_TIME_BADGES["badges"],
GAMES_GENERAL_COUNT["group_name"]: GAMES_GENERAL_COUNT["badges"],
FIFA15_BADGES["group_name"]: FIFA15_BADGES["badges"],
}
| {"/v1/signals_definitions.py": ["/v1/main.py", "/v1/badges/__init__.py"], "/v1/polling.py": ["/config.py", "/v1/helpers.py", "/v1/models.py", "/v1/apis.py", "/v1/common.py"], "/v1/badges/__init__.py": ["/v1/badges/badges_description.py", "/v1/badges/fifa15.py"], "/v1/apis.py": ["/config.py", "/v1/helpers.py", "/v1/mock.py"], "/v1/__init__.py": ["/v1/main.py"], "/mobsite.py": ["/config.py"], "/v1/badges/fifa15.py": ["/v1/main.py", "/v1/badges/badges_description.py"], "/v1/helpers.py": ["/config.py", "/v1/models.py", "/v1/main.py", "/v1/common.py", "/v1/apis.py", "/v1/__init__.py"], "/v1/models.py": ["/v1/main.py", "/v1/common.py", "/v1/badges/__init__.py", "/config.py", "/v1/helpers.py", "/v1/routes.py", "/v1/polling.py"], "/poll.py": ["/main.py", "/v1/__init__.py"], "/v1/cas.py": ["/config.py", "/v1/main.py", "/v1/apis.py", "/v1/models.py", "/v1/common.py"], "/debug_console.py": ["/main.py", "/v1/models.py", "/v1/helpers.py", "/v1/routes.py"], "/v1/routes.py": ["/config.py", "/v1/signals_definitions.py", "/v1/models.py", "/v1/helpers.py", "/v1/apis.py", "/v1/polling.py", "/v1/main.py"], "/main.py": ["/config.py", "/v1/__init__.py", "/v1/main.py", "/v1/models.py"], "/v1/main.py": ["/config.py", "/v1/__init__.py", "/v1/admin.py"], "/v1/admin.py": ["/v1/models.py", "/v1/polling.py", "/v1/helpers.py"], "/observer.py": ["/config.py", "/v1/polling.py", "/v1/models.py", "/v1/apis.py"]} |
71,995 | topdevman/flask-betg | refs/heads/master | /main.py | #!/usr/bin/env python
from flask import Flask, jsonify
from flask.ext.restful.utils import http_status_message
from flask.ext.cors import CORS
from flask.ext.script import Manager
from flask.ext.migrate import MigrateCommand, Migrate
from werkzeug.exceptions import default_exceptions
import logging
from logging.handlers import SysLogHandler
import socket
import datadog
import config
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = config.DB_URL
app.config['ERROR_404_HELP'] = False # disable this flask_restful feature
app.config['MAX_CONTENT_LENGTH'] = 32 * 1024 * 1024 # limit upload size for userpics
app.config['SECRET_KEY'] = config.SECRET_KEY
datadog.initialize(api_key=config.DATADOG_API_KEY)
# Fix request context's remote_addr property to respect X-Real-IP header
from flask import Request
from werkzeug.utils import cached_property
class MyRequest(Request):
@cached_property
def remote_addr(self):
"""The remote address of the client, with respect to X-Real-IP header"""
return self.headers.get('X-Real-IP') or super().remote_addr
app.request_class = MyRequest
# JSONful error handling
def make_json_error(ex):
code = getattr(ex, 'code', 500)
if hasattr(ex, 'data'):
response = jsonify(**ex.data)
else:
response = jsonify(
error_code = code,
error = ex.__dict__.get('description') # __dict__ to avoid using classwide default
or http_status_message(code),
)
response.status_code = code
return response
for code in default_exceptions.keys():
# apply decorator
app.errorhandler(code)(make_json_error)
def init_app(app=app):
if not app.logger:
raise ValueError('no logger')
import v1
v1.init_app(app)
# disable logging for cors beforehand
logging.getLogger(app.logger_name+'.cors').disabled = True
CORS(app, origins=config.CORS_ORIGINS)
return app
def setup_logging(app, f = None, level = logging.DEBUG):
app.logger.setLevel(level)
logger = logging.FileHandler(f) if f else logging.StreamHandler()
logger.setFormatter(logging.Formatter('[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s'))
logger.setLevel(level)
app.logger.addHandler(logger)
return # no PaperTrail support for now
if config.LOCAL:
return
class ContextFilter(logging.Filter):
hostname = socket.gethostname()
def filter(self, record):
record.hostname = self.hostname
return True
# papertail logging
logger = SysLogHandler(address=(config.PT_HOSTNAME, config.PT_PORT))
logger.setFormatter(logging.Formatter(
'%(asctime)s BetGameAPI{}: '
'[%(levelname)s] %(message)s'.format('-test' if config.TEST else ''),
datefmt='%b %d %H:%M:%S'))
logger.setLevel(level)
app.logger.addFilter(ContextFilter())
app.logger.addHandler(logger)
def live(logfile=None):
setup_logging(app, logfile)
return init_app()
def debug():
app.debug = True #-- this breaks exception handling?..
setup_logging(app)
return init_app()
if __name__ == '__main__':
init_app(app)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
from v1.main import db
migrate = Migrate(app, db)
# TODO: move manager to separate file manage.py
# TODO: separate manager for updating badges
@manager.command
def insert_badges():
"""Set Badges for every Player
Run only once, after applying migration.
"""
from v1.models import Badges, Player
for player in Player.query.all():
player.badges = Badges()
db.session.add(player.badges)
db.session.commit()
@manager.command
def update_badges():
"""This command will add new badges for every player.
If you need to update existent badges info (from column "default")
use "update_badges_info" command
"""
# player.__table__._columns["locked"].default.arg
pass
@manager.command
def update_badges_info(*column_names):
"""Updates existent values for badges.
New value will be taken from column "default".
You cant update user bounded values, such as: "received", "value"
:param column_names: column names that need update
"""
pass
manager.run()
| {"/v1/signals_definitions.py": ["/v1/main.py", "/v1/badges/__init__.py"], "/v1/polling.py": ["/config.py", "/v1/helpers.py", "/v1/models.py", "/v1/apis.py", "/v1/common.py"], "/v1/badges/__init__.py": ["/v1/badges/badges_description.py", "/v1/badges/fifa15.py"], "/v1/apis.py": ["/config.py", "/v1/helpers.py", "/v1/mock.py"], "/v1/__init__.py": ["/v1/main.py"], "/mobsite.py": ["/config.py"], "/v1/badges/fifa15.py": ["/v1/main.py", "/v1/badges/badges_description.py"], "/v1/helpers.py": ["/config.py", "/v1/models.py", "/v1/main.py", "/v1/common.py", "/v1/apis.py", "/v1/__init__.py"], "/v1/models.py": ["/v1/main.py", "/v1/common.py", "/v1/badges/__init__.py", "/config.py", "/v1/helpers.py", "/v1/routes.py", "/v1/polling.py"], "/poll.py": ["/main.py", "/v1/__init__.py"], "/v1/cas.py": ["/config.py", "/v1/main.py", "/v1/apis.py", "/v1/models.py", "/v1/common.py"], "/debug_console.py": ["/main.py", "/v1/models.py", "/v1/helpers.py", "/v1/routes.py"], "/v1/routes.py": ["/config.py", "/v1/signals_definitions.py", "/v1/models.py", "/v1/helpers.py", "/v1/apis.py", "/v1/polling.py", "/v1/main.py"], "/main.py": ["/config.py", "/v1/__init__.py", "/v1/main.py", "/v1/models.py"], "/v1/main.py": ["/config.py", "/v1/__init__.py", "/v1/admin.py"], "/v1/admin.py": ["/v1/models.py", "/v1/polling.py", "/v1/helpers.py"], "/observer.py": ["/config.py", "/v1/polling.py", "/v1/models.py", "/v1/apis.py"]} |
71,996 | topdevman/flask-betg | refs/heads/master | /v1/main.py | from flask import Blueprint, current_app
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext import restful
from flask.ext.socketio import SocketIO
from flask.ext.redis import FlaskRedis
from sqlalchemy.ext.mutable import Mutable
import config
app = Blueprint('v1', __name__)
db = SQLAlchemy()
api = restful.Api(prefix='/v1')
socketio = SocketIO()
redis = FlaskRedis()
_before1req = []
def before_first_request(func):
""" decorator to launch func before 1st request """
_before1req.append(func)
def init_app(flask_app):
db.init_app(flask_app)
api.init_app(flask_app)
init_admin(flask_app)
# FIXME! Socketio requires resource name to match on client and on server
# so Nginx rewriting breaks it
socketio.init_app(flask_app, resource='{}/v1/socket.io'.format(
'/test' if config.TEST else ''
))
redis.init_app(flask_app)
flask_app.register_blueprint(app, url_prefix='/v1')
flask_app.before_first_request_funcs.extend(_before1req)
# special column with mutation tracking
# TODO: move in some helpers module, after refactoring
class MutableDict(Mutable, dict):
"""http://docs.sqlalchemy.org/en/latest/orm/extensions/mutable.html"""
@classmethod
def coerce(cls, key, value):
"""Convert plain dictionaries to MutableDict."""
if not isinstance(value, MutableDict):
if isinstance(value, dict):
return MutableDict(value)
# this call will raise ValueError
return Mutable.coerce(key, value)
else:
return value
def __setitem__(self, key, value):
"""Detect dictionary set events and emit change events."""
dict.__setitem__(self, key, value)
self.changed()
def __delitem__(self, key):
"""Detect dictionary del events and emit change events."""
dict.__delitem__(self, key)
self.changed()
def __getstate__(self):
return dict(self)
def __setstate__(self, state):
self.update(state)
class MutaleDictPickleType(db.PickleType):
"""
Column with pickle support and mutations tracking in dicts.
For usecase look at Badges model.
"""
pass
MutableDict.associate_with(MutaleDictPickleType)
db.MutaleDictPickleType = MutaleDictPickleType
####
# now apply routes
from . import routes
from . import cas
from .admin import init as init_admin
| {"/v1/signals_definitions.py": ["/v1/main.py", "/v1/badges/__init__.py"], "/v1/polling.py": ["/config.py", "/v1/helpers.py", "/v1/models.py", "/v1/apis.py", "/v1/common.py"], "/v1/badges/__init__.py": ["/v1/badges/badges_description.py", "/v1/badges/fifa15.py"], "/v1/apis.py": ["/config.py", "/v1/helpers.py", "/v1/mock.py"], "/v1/__init__.py": ["/v1/main.py"], "/mobsite.py": ["/config.py"], "/v1/badges/fifa15.py": ["/v1/main.py", "/v1/badges/badges_description.py"], "/v1/helpers.py": ["/config.py", "/v1/models.py", "/v1/main.py", "/v1/common.py", "/v1/apis.py", "/v1/__init__.py"], "/v1/models.py": ["/v1/main.py", "/v1/common.py", "/v1/badges/__init__.py", "/config.py", "/v1/helpers.py", "/v1/routes.py", "/v1/polling.py"], "/poll.py": ["/main.py", "/v1/__init__.py"], "/v1/cas.py": ["/config.py", "/v1/main.py", "/v1/apis.py", "/v1/models.py", "/v1/common.py"], "/debug_console.py": ["/main.py", "/v1/models.py", "/v1/helpers.py", "/v1/routes.py"], "/v1/routes.py": ["/config.py", "/v1/signals_definitions.py", "/v1/models.py", "/v1/helpers.py", "/v1/apis.py", "/v1/polling.py", "/v1/main.py"], "/main.py": ["/config.py", "/v1/__init__.py", "/v1/main.py", "/v1/models.py"], "/v1/main.py": ["/config.py", "/v1/__init__.py", "/v1/admin.py"], "/v1/admin.py": ["/v1/models.py", "/v1/polling.py", "/v1/helpers.py"], "/observer.py": ["/config.py", "/v1/polling.py", "/v1/models.py", "/v1/apis.py"]} |
71,997 | topdevman/flask-betg | refs/heads/master | /config.py | from datetime import timedelta
from secret import DB_URL, JWT_SECRET
from secret import SECRET_KEY
#from secret import NEXMO_API_KEY, NEXMO_API_SECRET
#from secret import GOOGLE_PUSH_API_KEY, APPLE_PUSH_API_KEY
#from secret import GOOGLE_AUTH_API_KEY
#from secret import GOOGLE_AUTH_CLIENT_ID, GOOGLE_AUTH_CLIENT_SECRET
from secret import FACEBOOK_AUTH_CLIENT_ID, FACEBOOK_AUTH_CLIENT_SECRET
from secret import TWITTER_API_KEY, TWITTER_API_SECRET
#from secret import ADMIN_USERS
from secret import PAYPAL_CLIENT, PAYPAL_SECRET, PAYPAL_SANDBOX
from secret import MAILGUN_KEY
from secret import WH_KEY, WH_SECRET, WH_SANDBOX
try:
from secret import LOCAL
except ImportError:
LOCAL = False
try:
from secret import TEST
except ImportError:
TEST = False
try:
from secret import APNS_CERT
except ImportError:
APNS_CERT = 'sandbox'
from secret import ADMIN_IDS
from secret import RIOT_KEY, STEAM_KEY, BATTLENET_KEY, SC2RANKS_KEY
from secret import DATADOG_API_KEY
# DB_URL format: "mysql+mysqlconnector://USER:PASSWORD@HOST/DATABASE"
JWT_LIFETIME = timedelta(days=365)
# for Nexmo phone number verification
SMS_BRAND = "Bet Game"
SMS_SENDER = "BetGame"
# for mail sending
MAIL_DOMAIN = 'mg.betgame.co.uk'
MAIL_SENDER = 'BetGame <noreply@betgame.co.uk>'
CORS_ORIGINS = [
'https://betgame.co.uk',
'http://betgame.co.uk',
'https://www.betgame.co.uk',
'http://www.betgame.co.uk',
'http://dev.betgame.co.uk',
'http://127.0.0.1:8080',
'http://localhost:8080',
'http://127.0.0.1:3000',
'http://localhost:3000',
]
if 'test' in __file__:
CORS_ORIGINS.append('http://test.betgame.co.uk')
# Papertail logging
#PT_HOSTNAME = 'logs3.papertrailapp.com'
#PT_PORT = 12345
# in coins
WITHDRAW_MINIMUM = 40
# means comission of 10 %
WITHDRAW_COEFFICIENT = 0.90
OBSERVER_URL = 'http://localhost:8021'
SITE_BASE_URL = 'https://betgame.co.uk'
| {"/v1/signals_definitions.py": ["/v1/main.py", "/v1/badges/__init__.py"], "/v1/polling.py": ["/config.py", "/v1/helpers.py", "/v1/models.py", "/v1/apis.py", "/v1/common.py"], "/v1/badges/__init__.py": ["/v1/badges/badges_description.py", "/v1/badges/fifa15.py"], "/v1/apis.py": ["/config.py", "/v1/helpers.py", "/v1/mock.py"], "/v1/__init__.py": ["/v1/main.py"], "/mobsite.py": ["/config.py"], "/v1/badges/fifa15.py": ["/v1/main.py", "/v1/badges/badges_description.py"], "/v1/helpers.py": ["/config.py", "/v1/models.py", "/v1/main.py", "/v1/common.py", "/v1/apis.py", "/v1/__init__.py"], "/v1/models.py": ["/v1/main.py", "/v1/common.py", "/v1/badges/__init__.py", "/config.py", "/v1/helpers.py", "/v1/routes.py", "/v1/polling.py"], "/poll.py": ["/main.py", "/v1/__init__.py"], "/v1/cas.py": ["/config.py", "/v1/main.py", "/v1/apis.py", "/v1/models.py", "/v1/common.py"], "/debug_console.py": ["/main.py", "/v1/models.py", "/v1/helpers.py", "/v1/routes.py"], "/v1/routes.py": ["/config.py", "/v1/signals_definitions.py", "/v1/models.py", "/v1/helpers.py", "/v1/apis.py", "/v1/polling.py", "/v1/main.py"], "/main.py": ["/config.py", "/v1/__init__.py", "/v1/main.py", "/v1/models.py"], "/v1/main.py": ["/config.py", "/v1/__init__.py", "/v1/admin.py"], "/v1/admin.py": ["/v1/models.py", "/v1/polling.py", "/v1/helpers.py"], "/observer.py": ["/config.py", "/v1/polling.py", "/v1/models.py", "/v1/apis.py"]} |
71,998 | topdevman/flask-betg | refs/heads/master | /v1/admin.py | from flask import redirect, url_for, request, session
from flask_admin import Admin, BaseView, expose
from flask_admin.contrib.sqla import ModelView
from flask_admin.model.base import get_redirect_target, get_mdict_item_or_list, flash, gettext
from flask.ext.basicauth import BasicAuth
from flask.ext.login import LoginManager, login_user, current_user, logout_user
from sqlalchemy.orm.exc import NoResultFound
from .models import ChatMessage, Ticket, Player, db
from .polling import Poller
from datetime import datetime
admin = Admin(name='admin', template_mode='bootstrap3')
login_manager = LoginManager()
@login_manager.user_loader
def load_user(user_id):
try:
return Player.query.get(user_id)
except NoResultFound:
return None
def init(app):
admin.init_app(app)
login_manager.init_app(app)
admin.add_view(TicketView(Ticket, db.session))
admin.add_view(LoginView(name='Login', endpoint='login'))
admin.add_view(LogoutView(name='Logout', endpoint='logout'))
class LoginView(BaseView):
def is_visible(self):
return not current_user.is_authenticated
@expose('/', methods=('GET', 'POST'))
def index(self):
from .models import Player # avoiding cyclic reference =(
from .helpers import check_password
if request.form and 'login' in request.form and 'password' in request.form:
user = Player.find(request.form['login'])
if user and check_password(request.form['password'], user.password) and login_user(user):
return redirect(url_for('admin.index'))
return self.render('admin/login.html')
class AdminView(BaseView):
def is_visible(self):
return current_user.is_authenticated and current_user.is_active
def is_accessible(self):
return current_user.is_authenticated and current_user.is_active
class LogoutView(AdminView):
@expose('/')
def index(self):
logout_user()
return redirect(url_for('admin.index'))
class TicketView(ModelView, AdminView):
can_create = False
can_delete = False
can_edit = False
can_view_details = True
details_template = 'admin/ticket/details.html'
@expose('/reopen/', methods=['POST'])
def reopen_ticket(self):
return_url = get_redirect_target() or self.get_url('.index_view')
id = get_mdict_item_or_list(request.args, 'id')
if id is None:
return redirect(return_url)
ticket = self.get_one(id)
if ticket is None:
flash(gettext('Record does not exist.'))
return redirect(return_url)
if ticket.open:
flash('Ticket already open.')
return redirect(return_url)
ticket.open = True
db.session.commit()
return redirect(url_for('.details_view', id=id))
@expose('/resolve/', methods=['POST'])
def resolve_ticket(self):
return_url = get_redirect_target() or self.get_url('.index_view')
id = get_mdict_item_or_list(request.args, 'id')
if id is None:
return redirect(return_url)
ticket = self.get_one(id)
if ticket is None:
flash(gettext('Record does not exist.'))
return redirect(return_url)
if not ticket.open:
flash('Ticket already closed.')
return redirect(return_url)
winner_id = request.form.get('winner_id', None)
draw = request.form.get('draw', None)
game_winner = 'draw'
if winner_id and not draw:
winner = Player.query.get(winner_id)
if winner == ticket.game.creator:
game_winner = 'creator'
if winner == ticket.game.opponent:
game_winner = 'opponent'
poller = Poller.findPoller(ticket.game.gametype)
poller.gameDone(ticket.game, game_winner, datetime.utcnow())
ticket.open = False
db.session.commit()
return redirect(url_for('.details_view', id=id))
@expose('/send_msg/', methods=['POST'])
def send_msg(self):
return_url = get_redirect_target() or self.get_url('.index_view')
id = get_mdict_item_or_list(request.args, 'id')
if id is None:
return redirect(return_url)
ticket = self.get_one(id)
if ticket is None:
flash(gettext('Record does not exist.'))
return redirect(return_url)
receiver_id = request.form.get('receiver_id', None)
text = request.form.get('text', None)
if receiver_id and text:
try:
receiver = Player.query.get(receiver_id)
except NoResultFound:
return redirect(return_url)
message = ChatMessage()
message.admin_message = True
message.receiver = receiver
message.text = text
message.ticket = ticket
db.session.add(message)
db.session.commit()
return redirect(url_for('.details_view', id=id))
@expose('/details/')
def details_view(self):
"""
Details model view
"""
return_url = get_redirect_target() or self.get_url('.index_view')
if not self.can_view_details:
return redirect(return_url)
id = get_mdict_item_or_list(request.args, 'id')
if id is None:
return redirect(return_url)
ticket = self.get_one(id)
if ticket is None:
flash(gettext('Record does not exist.'))
return redirect(return_url)
if self.details_modal and request.args.get('modal'):
template = self.details_modal_template
else:
template = self.details_template
players = [report.player for report in ticket.game.reports]
for message in ticket.messages:
if not message.admin_message:
message.viewed = True
db.session.commit()
return self.render(template,
model=ticket,
game=ticket.game,
players=players,
details_columns=self._details_columns,
get_value=self.get_list_value,
return_url=return_url) | {"/v1/signals_definitions.py": ["/v1/main.py", "/v1/badges/__init__.py"], "/v1/polling.py": ["/config.py", "/v1/helpers.py", "/v1/models.py", "/v1/apis.py", "/v1/common.py"], "/v1/badges/__init__.py": ["/v1/badges/badges_description.py", "/v1/badges/fifa15.py"], "/v1/apis.py": ["/config.py", "/v1/helpers.py", "/v1/mock.py"], "/v1/__init__.py": ["/v1/main.py"], "/mobsite.py": ["/config.py"], "/v1/badges/fifa15.py": ["/v1/main.py", "/v1/badges/badges_description.py"], "/v1/helpers.py": ["/config.py", "/v1/models.py", "/v1/main.py", "/v1/common.py", "/v1/apis.py", "/v1/__init__.py"], "/v1/models.py": ["/v1/main.py", "/v1/common.py", "/v1/badges/__init__.py", "/config.py", "/v1/helpers.py", "/v1/routes.py", "/v1/polling.py"], "/poll.py": ["/main.py", "/v1/__init__.py"], "/v1/cas.py": ["/config.py", "/v1/main.py", "/v1/apis.py", "/v1/models.py", "/v1/common.py"], "/debug_console.py": ["/main.py", "/v1/models.py", "/v1/helpers.py", "/v1/routes.py"], "/v1/routes.py": ["/config.py", "/v1/signals_definitions.py", "/v1/models.py", "/v1/helpers.py", "/v1/apis.py", "/v1/polling.py", "/v1/main.py"], "/main.py": ["/config.py", "/v1/__init__.py", "/v1/main.py", "/v1/models.py"], "/v1/main.py": ["/config.py", "/v1/__init__.py", "/v1/admin.py"], "/v1/admin.py": ["/v1/models.py", "/v1/polling.py", "/v1/helpers.py"], "/observer.py": ["/config.py", "/v1/polling.py", "/v1/models.py", "/v1/apis.py"]} |
71,999 | topdevman/flask-betg | refs/heads/master | /observer.py | #!/usr/bin/env python3
# Observer daemon:
# listens on some port/path,
# may have some children configured,
# knows how many streams can it handle.
# Also each host accepts connections only from its known siblings.
#
# Messaging flow:
#
# Client -> Master: Please watch the stream with URL ... for game ...
# Master: checks if this stream is already watched
# Master -> Slave1: Can you watch one more stream? (details)
# Slave1 -> Master: no
# Master -> Slave2: Can you watch one more stream? (details)
# Slave2 -> Master: yes
# (or if none agreed - tries to watch itself)
# ...
# Slave2 -> Master: stream X finished, result is Xres
# Master -> Poller: stream X done
# API:
# PUT /streams/id - watch the stream (client->master->slave)
# GET /streams/id - check stream status (master->slave)
import eventlet
eventlet.monkey_patch() # before loading flask
from flask import Flask, jsonify, request, abort as flask_abort
from flask.ext import restful
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.restful import fields, marshal
from flask.ext.restful.reqparse import RequestParser
from flask.ext.restful.utils import http_status_message
from werkzeug.exceptions import default_exceptions
from werkzeug.exceptions import HTTPException, BadRequest, MethodNotAllowed, Forbidden, NotImplemented, NotFound
import os
import signal
from datetime import datetime, timedelta
import itertools
from eventlet.green import subprocess
import requests
import logging
import config
from observer_conf import SELF_URL, PARENT, CHILDREN, MAX_STREAMS
# if stream happens to be online, wait some time...
WAIT_DELAY = 30 # seconds between retries
WAIT_MAX = 360 # 3 hours
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = config.DB_URL
app.config['ERROR_404_HELP'] = False # disable this flask_restful feature
db = SQLAlchemy(app)
api = restful.Api(app)
# Fix request context's remote_addr property to respect X-Real-IP header
from flask import Request
from werkzeug.utils import cached_property
class MyRequest(Request):
@cached_property
def remote_addr(self):
"""The remote address of the client, with respect to X-Real-IP header"""
return self.headers.get('X-Real-IP') or super().remote_addr
app.request_class = MyRequest
# JSONful error handling
log = app.logger
# allow 507 error code
class InsufficientStorage(HTTPException):
code = 507
description = 'No observers available'
# FIXME: for some reason this exception gets propagated to stdout
# rather than handled by make_json_error
flask_abort.mapping[507] = InsufficientStorage
def make_json_error(ex):
code = getattr(ex, 'code', 500)
if hasattr(ex, 'data'):
response = jsonify(**ex.data)
else:
response = jsonify(error_code = code, error = http_status_message(code))
response.status_code = code
return response
for code in flask_abort.mapping.keys():
app.error_handler_spec[None][code] = make_json_error
def abort(message, code=400, **kwargs):
data = {'error_code': code, 'error': message}
if kwargs:
data.update(kwargs)
log.warning('Aborting request {} /{}: {}'.format(
# GET /v1/smth
request.method,
request.base_url.split('//',1)[-1].split('/',1)[-1],
', '.join(['{}: {}'.format(*i) for i in data.items()])))
try:
flask_abort(code)
except HTTPException as e:
e.data = data
raise
restful.abort = lambda code,message: abort(message,code) # monkey-patch to use our approach to aborting
restful.utils.error_data = lambda code: {
'error_code': code,
'error': http_status_message(code)
}
# Restrict list of allowed hosts
def getsiblings():
import socket
ret = set()
for host in list(CHILDREN.values()) + ([PARENT[1], 'localhost']
if PARENT else
['localhost']):
if not host:
continue # skip empty addrs, e.g. parent for master node
host = host.split('://',1)[-1].split(':',1)[0] # cut off protocol and port
h, a, ips = socket.gethostbyname_ex(host)
ret.update(ips)
return ret
NEIGHBOURS = getsiblings()
@app.before_request
def restrict_siblings():
if request.remote_addr not in NEIGHBOURS:
log.debug('Attempt to request from unknown address '+request.remote_addr)
raise Forbidden
def init_app(logfile=None):
app.logger.setLevel(logging.DEBUG)
logger = logging.FileHandler(logfile) if logfile else logging.StreamHandler()
logger.setFormatter(logging.Formatter('[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s'))
logger.setLevel(logging.DEBUG)
app.logger.addHandler(logger)
# now restart all active streams
# and remove stale records
with app.test_request_context():
for stream in Stream.query:
log.info('restarting stream {}/{}'.format(stream.handle, stream.gametype))
if stream.state in ('waiting', 'watching'):
add_stream(stream)
elif stream.state in ('found', 'failed'):
# was not yet deleted - delete now
# FIXME: maybe send result (again)?
db.session.delete(stream)
db.session.commit()
else:
log.warning('Unexpected stream state '+stream.state)
return app
# declare model
class Stream(db.Model):
id = db.Column(db.Integer, primary_key=True)
# Twitch stream handle
handle = db.Column(db.String(64), nullable=False)
gametype = db.Column(db.String(64), default=None)
# Which child watches this stream? None if self
child = db.Column(db.String(64), default=None)
# other metadata goes below
# this is an ID of the primary Game object for this stream.
# We don't use foreign key because we may reside on separate server
# and use separate db.
game_id = db.Column(db.Integer, unique=True)
# supplementary game IDs - ones which follow the same stream.
# Some of them might be reversed (winner for them should be inverted).
# Format: 10,-20,15,3,-17
# -n means reversed game
game_ids_supplementary = db.Column(db.String, default='')
state = db.Column(db.Enum('waiting', 'watching', 'found', 'failed'),
default='waiting')
creator = db.Column(db.String(128))
opponent = db.Column(db.String(128))
__table_args__ = (
db.UniqueConstraint('handle', 'gametype', name='_handle_gametype_uc'),
)
@classmethod
def find(cls, id, gametype=None):
q = cls.query.filter_by(handle=id)
if gametype:
q = q.filter_by(gametype=gametype)
return q.first()
def iter_games_revinfo(self):
"""
Master node only!
Iterate over all game objects related to this stream.
Yields tuples of (Game, bool)
where bool=True means current game is "inversed" (crea=oppo).
"""
from v1.models import Game
for gid in itertools.chain(
[self.game_id],
map(
int,
filter(
None,
self.game_ids_supplementary.split(','),
),
),
):
if gid < 0:
gid = -gid
reverse = True
else:
reverse = False
game = Game.query.get(gid)
if not game:
log.warning('Bad game id %d' % gid)
yield game, reverse
def iter_games(self):
yield from (g for g,r in self.iter_games_revinfo())
# Main logic
ROOT = os.path.dirname(os.path.abspath(__file__))
class Handler:
"""
This hierarchy is similar to Poller's one
"""
gametypes = []
path = None
env = None
process = None
quorum = 5 # min results, or
maxdelta = timedelta(seconds=10)
onlylastresult = False
@classmethod
def find(cls, gametype):
if gametype in cls.gametypes:
return cls
for sub in cls.__subclasses__():
ret = sub.find(gametype)
if ret:
return ret
def __init__(self, stream):
self.stream = stream
self.handle = stream.handle
self.gametype = stream.gametype
self.sub = None
self._sysevts = set()
def start(self):
log.info('spawning handler')
self.thread = eventlet.spawn(self.watch_tc)
pool[self.handle, self.gametype] = self
def abort(self):
self.thread.kill()
# this will automatically execute `finally` clause in `watch_tc`
# which will remove us from pool
# if subprocess is still alive, kill it
if self.sub and self.sub.poll() is None: # still running?
self.murderchild(self.sub)
def murderchild(self, sub=None):
sub = sub or self.sub
if not sub:
log.warning('Trying to kill subprocess but no one present')
return
exitcode = sub.poll()
if exitcode is not None:
log.warning('Trying to kill subprocess but it is already dead {}'.format(
exitcode))
return
pgid = os.getpgid(sub.pid)
log.info('Killing subprocess')
os.killpg(pgid, signal.SIGTERM)
eventlet.spawn_after(3, os.killpg, pgid, signal.SIGKILL)
def sysevent(self, text):
"""
Notify all related games about certain event
"""
log.debug('Handler {} has event {}'.format(
self, text))
# propagate result to master
requests.patch(
'{}/streams/{}/{}'.format(SELF_URL, self.stream.handle, self.stream.gametype),
data = dict(
event = text,
),
)
log.debug('Event sent.')
def sysevent_once(self, text, key=None):
"""
Notify all related games about certain event unless already notified.
Returns True if this was first call with given key/text, False otherwise.
"""
if (key or text) in self._sysevts:
return False
self._sysevts.add(key or text)
self.sysevent(text)
return True
def check_current_game(self):
'''Check if the game currently playing on the stream
matches one requested for this handler,
and if the stream is online at all'''
from v1.polling import Poller
from v1.apis import Twitch
poller = Poller.findPoller(self.stream.gametype)
tgtype = poller.twitch_gametypes.get(self.stream.gametype)
if not tgtype:
raise ValueError('Invalid poller?? no gt for '+self.stream.gametype)
# for debugging:
if tgtype == 'None':
tgtype = None
cinfo = Twitch.channel(self.stream.handle)
if cinfo['game'] != tgtype:
log.info('Stream {}: expected game {}, got {} - will wait'.format(
self.stream.handle, tgtype, cinfo['game']))
return False
# TODO: check if it is online
return True
def wait_for_correct_game(self, minutes=None):
log.info('Waiting for correct game')
waits = 0
if not self.check_current_game():
# log this only once
self.sysevent('Twitch: wrong game running, waiting')
while not self.check_current_game():
eventlet.sleep(60) # check every minute
waits += 1
if tries and waits > minutes:
log.info('Abandoning waiting')
self.sysevent('Twitch: wrong game lasted for too long, aborting')
return False
log.info('Correct game detected')
return True
def watch_tc(self):
log.info('watch_tc started')
try:
if not self.wait_for_correct_game(minutes=60): # 1 hour
raise Exception('Wrong game is set for too long, abandoning '+
self.stream.handle)
result = self.watch()
waits = 0
while result == 'offline':
# re-add stream to session if needed
# to avoid DetachedInstanceError
# FIXME: why is it detached after watch() but not before?
if not db.session.object_session(self.stream):
db.session.add(self.stream)
if waits > WAIT_MAX:
# will be caught below
self.sysevent('Twitch: stream was offline for too long, aborting')
raise Exception('We waited for too long, '
'abandoning stream '+self.stream.handle)
log.info('Stream {} is offline, waiting'
.format(self.stream.handle))
self.stream.state = 'waiting'
db.session.commit()
self.sysevent_once('Twitch: stream is offline, waiting',
'offline_wait')
# wait & retry
eventlet.sleep(WAIT_DELAY)
# check if currently plaing game is (still) correct
self.wait_for_correct_game()
result = self.watch()
waits += 1
return result
except Exception: # will not catch GreenletExit
log.exception('Watching failed')
try: # will fail if stream is deleted
self.stream.state = 'failed'
db.session.commit()
# mark it as Done anyway
self.done('failed', datetime.utcnow().timestamp(),
'Watching failed due to internal error')
except Exception: # stream was deleted?
log.exception('Failed to mark stream as done-anyway')
except eventlet.greenlet.GreenletExit:
# do nothing (just perform `finally` block) but don't print traceback
log.info('Watcher aborted for handle '+self.handle)
finally:
# kill subprocess if any
if self.sub and self.sub.poll() == None:
self.murderchild(self.sub)
# mark that this stream has stopped
# stream may be already deleted from db, so use saved handle
# FIXME: for some reason this will be called twice for streams
# which were waiting for correct gametype..
if (self.handle, self.gametype) in pool:
del pool[self.handle, self.gametype]
else:
log.warning('For some reason, was already deleted')
def watch(self):
# start subprocess and watch its output
# first, chdir to this script's directory
os.chdir(ROOT)
# then, if required, chdir handler's requested dir (relative to script's)
if self.path:
os.chdir(self.path)
cmd = 'exec ' + self.process.format(handle = self.stream.handle)
if self.env:
cmd = 'VIRTUAL_ENV_DISABLE_PROMPT=1 . {}/bin/activate; {}'.format(
self.env, cmd)
log.info('starting process...')
sub = self.sub = subprocess.Popen(
cmd,
bufsize = 1, # line buffered
universal_newlines = True, # text mode
shell = True, # interpret ';'-separated commands
stdout = subprocess.PIPE, # intercept it!
stderr = subprocess.STDOUT, # intercept it as well
preexec_fn = os.setsid,
)
log.info('process started')
self.stream.state = 'watching'
db.session.commit()
# and now the main loop starts
results = []
last_res = None
log.info('waiting for output')
self.started()
self.sysevent('Twitch Running')
for line in sub.stdout:
line = line.strip().decode()
try:
result = self.check(line)
except Exception as e:
log.exception('Error during checking line!')
result = None # just skip this line
else:
log.info('Got line result: {}'.format(result))
if isinstance(result, tuple):
outcome = result[0]
else:
outcome = result
if outcome == 'offline':
# handle it specially:
# force stop this process and retry in 30 seconds
# (will be done in watch_tc)
return 'offline'
if outcome == 'abandon':
# abandon previously retrieved data
results = []
last_res = None
self.stream.state = 'watching' # roll back from 'found'
continue
if outcome is not None and outcome != 'done':
if not isinstance(result, tuple):
log.warning('Invalid outcome, no details available: '+str(result))
result = (result, False, None) # consider it weak
self.stream.state = 'found'
if self.onlylastresult:
results = []
results.append(result) # tuple
#if not last_res:
last_res = datetime.utcnow()
# consider game done when either got quorum results
# or maxdelta passed since first result
# (in case they are enabled for this particular streamer)
# or when outcome is 'done'
log.debug('have for now: r: {}, '
'now: {}, '
'lr: {}, '
'md: {}'.format(
results,
datetime.utcnow(),
last_res,
(last_res + self.maxdelta) if last_res else '..',
))
if (outcome == 'done') or results and (
(self.quorum and len(results) >= self.quorum) or
(self.maxdelta and datetime.utcnow() > last_res + self.maxdelta)
):
# FIXME: this clause is executed only on next line,
# so if we got 3 results (<quorum) and none after that
# then we will wait until next line,
# which may be not soon.
# kill the process as we don't need more results
self.murderchild(sub)
break # don't handle remaining output
# now that process is stopped, handle results found
if not results:
log.warning('process failed with status {}, considering draw'.format(
sub.poll()))
results = [('failed', True,
'Observer terminated without returning any result! '
'Please contact support.')]
self.sysevent('Twitch: stream finished but no results were retrieved')
# FIXME: maybe better restart it?
self.stream.state = 'failed'
last_res = datetime.utcnow()
log.debug('results list: '+str(results))
# if there is any strong result, drop all weak ones
for r in results:
if r[1]: # strong
# drop all weak results
results = list(filter(lambda r: r[1], results))
break
# calculate most trusted result
freqs = {}
for r in results:
freqs[r] = freqs.get(r, 0) + 1
# Sort by frequency descending - i.e. most frequent goes first
pairs = sorted(freqs.items(), key=lambda p: p[1], reverse=True)
# use most frequently occuring result
result = pairs[0][0]
outcome, strong, details = result # decode it
log.debug('got result: {}'.format(result))
# handle result
db.session.commit()
self.done(outcome, last_res.timestamp(), details)
def started(self):
pass
def check(self, line):
"""
To be overriden.
Takes one line from script\'s output;
returns tuple: outcome, is_strong, details.
For 'offline' and None outcomes can return just outcome.
If outcome is weak, it will only be considered if there are stronger outcomes.
"""
raise NotImplementedError('This should be overriden!')
def done(self, result, timestamp, details=None):
log.debug('Handler {} done, result {}, details {}'.format(
self, result, details))
# propagate result to master
requests.patch(
'{}/streams/{}/{}'.format(SELF_URL, self.stream.handle, self.stream.gametype),
data = dict(
winner = result,
details = details,
timestamp = timestamp,
),
)
log.debug('Result sent.')
class FifaOldHandler(Handler):
gametypes = [
'fifa14-xboxone',
'fifa15-xboxone',
]
gametypes = []
path = 'fifastreamer'
env = '../../env2'
process = 'python2 -u fifa_streamer.py "http://twitch.tv/{handle}"'
def check(self, line):
log.debug('checking line: '+line)
if 'Stream is offline' in line:
return 'offline'
if 'Impossible to recognize who won' in line:
log.warning('Couldn\'t get result, skipping')
return None #'draw'
if 'Score:' in line:
# this may raise an exception
# if only one player name is present;
# it will be catched in watch().
if 'Players:' not in line:
log.warning('No players data?..')
return None
left, right = line.split('Score: ',1)[1].split('Players:',1)
rights = right.strip().split('\t\t', 1)
if len(rights) == 2:
onick1, onick2 = rights # o means original
else:
onick1 = onick2 = rights # only one nickname retrieved?..
scores = [p for p in left.split()
if '-' in p and p[0].isdigit() and p[-1].isdigit()][0]
score1, score2 = scores.split('-')
team1, team2 = map(lambda x: x.strip(), left.split(scores))
nick1, nick2 = map(lambda x: x.lower(), (onick1, onick2))
score1, score2 = map(int, (score1, score2))
details = '{} ({}) vs {} ({}): {} - {}'.format(
onick1, team1,
onick2, team2,
score1, score2,
)
log.info('Got score data. Nicks {} / {}, scores {} / {}'.format(
nick1, nick2, score1, score2))
if score1 == score2:
log.info('draw detected')
return 'draw', True, details
cl = self.stream.creator.lower()
ol = self.stream.opponent.lower()
log.debug('cl: {}, ol: {}'.format(cl, ol))
creator = opponent = None
if cl == nick1:
creator = 1
elif cl == nick2:
creator = 2
if ol == nick1:
opponent = 1
elif ol == nick2:
opponent = 2
if not creator and not opponent:
log.warning('Wrong gamertags / good gamertag not detected! '
'Defaulting to draw.')
return 'draw', False, 'Gamertags don\'t match -> draw... '+details
if not creator:
creator = 1 if opponent == 2 else 2
if score1 > score2:
winner = 1
else:
winner = 2
return('creator' if winner == creator else 'opponent',
True,
details)
return None
class FifaHandler(Handler):
gametypes = [
'fifa14-xboxone',
'fifa15-xboxone',
]
# gametypes = []
path = 'fifanewstreamer'
process = ('livestreamer -p "./ocr_test -debug -abc -skip 30" '
'--player-continuous-http --verbose-player '
'"http://twitch.tv/{handle}" best')
# disable quorum-based mechanics
quorum = None
maxdelta = timedelta(minutes=1)
onlylastresult = True
def started(self):
self.__approaching = False
self.__teamcheck = list()
def check(self, line):
log.debug('checking line: '+line)
if 'error: No streams found on this URL' in line:
# stream is offline
return 'offline'
if 'Failed to read the frame from the stream' in line:
# stream possibly went offline
return 'done'
# TODO: maybe consider this as game-end?
if 'HTTP connection closed' in line or 'Stream ended' in line:
# stream went offline
return 'done'
#if 'Impossible to recognize who won' in line:
# log.warning('Couldn\'t get result, skipping')
# return None #'draw'
if not line.endswith('in-game') or 'non in-game' in line:
if self.__approaching and 'non in-game' in line:
# FIXME for now consider this state a proper game-end
#return 'done'
log.warning('approaching and stopped')
return None
# FIXME penalties
parts = line.split()
_, time, team1, score1, _m, team2, score2, *_ = parts
if _m != '-':
log.debug('Line not recognized: '+line)
return None
if team1 == '@@@' or team2 == '@@@':
log.debug('Teams not recognized: '+line)
return None
if ':' not in time:
log.debug('Time not recognized: '+line)
return None
time = tuple(map(int, time.split(':'))) # (hh, mm) - may in theory raise ValueErr for 0:1:2 or x:y
if time[0] < 0 or time[1] < 0:
log.debug('Negative time: '+line)
return None
score1, score2 = map(int, (score1, score2))
if score1 < 0 or score2 < 0:
log.debug('Negative scores: '+line)
return None
if len(team1) not in (2,3) or len(team2) not in (2,3):
log.debug('Bad team names, expected 3 chars: '+line)
return None
team1l, team2l = map(lambda t: t.casefold().translate({
ord(n): '@' for n in '0123456789'
}), (team1, team2))
details = '{} vs {}: {} - {}'.format(
team1, team2,
score1, score2,
)
log.debug('Got score data. Teams {} / {}, scores {} / {}'.format(
team1, team2, score1, score2))
self.sysevent_once('Twitch: got score info', 'score_got')
self.sysevent_once('Twitch: score changed: {} ({}) / {} ({})'.format(
score1, team1, score2, team2,
), 'score_{}_{}'.format(score1, score2))
if len(self.__teamcheck) < 10:
have = set((team1l, team2l))
self.__teamcheck.append(have)
if len(self.__teamcheck) == 10:
# do the check
cl, ol = map(lambda u: u.casefold().translate({
ord(n): '@' for n in '0123456789'
}), (self.stream.creator, self.stream.opponent))
need = set((cl, ol))
haveprobs = dict()
for have in self.__teamcheck:
haveprobs[have] = haveprobs.get(have, 0)+1
have = max(haveprobs.items(), key=lambda i: i[1])[0]
# now `have` is most probable one, do check it
if have != need:
self.sysevent('Unexpected teams! Requested {}, found {}'.format(
'/'.join(need),
'/'.join(have),
))
if len(need-have) == 1:
# one team is bad, other is good; notify bad-team player
diffteam = (need-have)[0]
wronger = 'creator' if diffteam == cl else 'opponent'
self.sysevent(
'{%s}, did you choose another team?' % wronger
)
# TODO: probably pre-handle & remember team names here
# to check if stream went wrong
if time[0] < 88:
return None # too early anyway
if time[0] in [88, 89]:
log.debug('Approaching 90! {}'.format(time))
self.__approaching = True
return None
if time[0] > 90:
if time[0] < 100 and self.__approaching:
self.__approaching = False
return 'abandon'
if time[0] < 118:
return None # too early again
if time[0] in [118, 119]:
log.debug('Approaching 120! {}'.format(time))
self.__approaching = True
return None
# TODO: penalties
if not self.__approaching:
log.info('Probably unexpected line (time {} but not approaching)'.format(time))
#return None
# Now we suppose we have correct result
# so calculate it
if score1 == score2:
log.info('draw detected')
return 'draw', True, details
cl, ol = map(lambda u: u.casefold().translate({
ord(n): '@' for n in '0123456789'
}), (self.stream.creator, self.stream.opponent))
log.debug('cl: {}, ol: {}'.format(cl, ol))
creator = opponent = None
if cl == team1l:
creator = 1
elif cl == team2l:
creator = 2
if ol == team1l:
opponent = 1
elif ol == team2l:
opponent = 2
if not creator and not opponent:
log.warning('Wrong team names / good team name not detected! '
'Defaulting to draw.')
return 'draw', False, 'Gamertags don\'t match -> draw... '+details
if not creator:
creator = 1 if opponent == 2 else 2
if score1 > score2:
winner = 1
else:
winner = 2
return('creator' if winner == creator else 'opponent',
True,
details)
class TestHandler(Handler):
gametypes = [
'test',
]
process = './test.sh'
def check(self, line):
print('line:',line)
outcomes = dict(
c='creator',
o='opponent',
d='draw',
)
if 'Done' in line:
return outcomes.get(line[-1], None)
pool = {}
def add_stream(stream):
"""
Tries to append given stream object (which is not yet committed) to watchlist.
Returns string on failure (e.g. if list is full).
"""
if len(pool) >= MAX_STREAMS:
return 'busy'
handler = Handler.find(stream.gametype)
if not handler:
return 'unsupported'
log.info('Adding stream')
handler(stream).start() # will add stream to pool
return True
def abort_stream(stream):
"""
If stream is running, abort it. Else do nothing.
"""
if (stream.handle, stream.gametype) not in pool:
return False
pool[stream.handle, stream.gametype].abort()
# will remove itself
return True
def abort_all(*args):
# FIXME: does it work at all?
for stream in list(pool.values()): # we create copy as abort() will remove stream from pool
# this considers we already got game result from somewhere -
# or will restart soon
stream.abort()
log.info('All stream watchers aborted for restart')
# Now we should somehow propagate that SIGTERM to gunicorn worker
# but we cannot, so we'll just set it to system default (FIXME!)
signal.signal(signal.SIGTERM, signal.SIG_DFL)
signal.signal(signal.SIGTERM, abort_all) # fire when gunicorn worker is terminated
def stream_done(stream, winner, timestamp, details=None):
"""
Runs on master node only.
Marks given stream as done, and notifies clients etc.
"""
from v1.polling import Poller
for game, reverse in stream.iter_games_revinfo():
poller = Poller.findPoller(stream.gametype)
if winner == 'failed':
if poller.twitch == 2: # mandatory
log.warning('Watching failed, considering it a draw')
winner = 'draw'
elif poller.twitch == 1: # optional
log.warning('Watching failed, not updating game')
winner = None # will be fetched by Polling later
if winner:
if winner in ['creator','opponent'] and reverse:
winner = 'creator' if winner == 'opponent' else 'opponent'
Poller.gameDone(game, winner, int(timestamp), details)
# and anyway issue DELETE request, because this stream is unneeded anymore
# (even if no games were changed)
# no need to remove from pool, because we are on master
# and it was already removed from pool anyway
# but now let's delete it from DB
# Notice: this is DELETE request to ourselves.
# But we are still handling PATCH request, so it will hang.
# So launch it as a green thread immediately after we finish
eventlet.spawn(requests.delete,
'{}/streams/{}/{}'.format(SELF_URL, stream.handle, stream.gametype))
return True
def stream_event(stream, text):
"""
Runs on master node only.
Notifies clients about some event happened on the stream.
"""
from v1.polling import Poller
if '{' in text:
game = next(stream.iter_games())
text = text.format(creator=game.creator.nickname, opponent=game.opponent.nickname)
# FIXME: avoid dupes somehow, maybe exclude ingames?
for game in stream.iter_games():
#if not game.is_ingame:
Poller.gameEvent(game, text)
def current_load():
streams = len(pool)
maximum = MAX_STREAMS
# TODO: use load average as a base, and add some cap on it
load = streams / maximum
return load, streams, maximum
# now define our endpoints
def child_url(cname, sid=None, gametype=None):
if cname in CHILDREN:
return '{host}/streams/{sid}'.format(
host = CHILDREN[cname],
sid = '{}/{}'.format(sid, gametype) if sid else '',
)
return None
@api.resource(
'/streams',
'/streams/',
'/streams/<id>/<gametype>',
)
class StreamResource(restful.Resource):
fields = dict(
handle = fields.String,
gametype = fields.String,
game_id = fields.Integer,
game_ids_supplementary = fields.String,
state = fields.String,
creator = fields.String,
opponent = fields.String,
)
def get(self, id=None, gametype=None):
"""
Returns details (current state) for certain stream.
"""
if not id:
# at least for debugging
q = Stream.query
return dict(
streams = fields.List(fields.Nested(self.fields)).format(q),
)
log.info('Stream queried with id '+id)
stream = Stream.find(id, gametype)
if not stream:
raise NotFound
if stream.child:
# forward request
return requests.get(child_url(stream.child, stream.handle, stream.gametype)).json()
return marshal(stream, self.fields)
def put(self, id=None, gametype=None):
"""
Returns 409 if stream with this handle exists with different parameters.
Returns 507 if no slots are available.
Returns newly created stream id otherwise.
Will return 201 code if new stream was added
or 200 code if game was added to existing stream.
"""
if not id or not gametype:
raise MethodNotAllowed
log.info('Stream put with id {}, gt {}'.format(id, gametype))
parser = RequestParser(bundle_errors=True)
parser.add_argument('game_id', type=int, required=True)
parser.add_argument('creator', required=True)
parser.add_argument('opponent', required=True)
# TODO...
args = parser.parse_args()
if Stream.query.filter_by(game_id = args.game_id).first():
# FIXME: handle dup ID in supplementaries?
abort('This game ID is already watched in some another stream')
stream = Stream.find(id, gametype)
if stream:
# stream already exists; add this game to it as a supplementary game
new = False
if args.creator.casefold() == stream.creator.casefold():
if args.opponent.casefold() != stream.opponent.casefold():
abort('Duplicate stream ID with wrong opponent nickname', 409)
game = args.game_id
elif args.opponent.casefold() == stream.creator.casefold():
if args.creator.casefold() != stream.opponent.casefold():
abort('Duplicate stream ID with wrong reverse oppo nickname', 409)
game = -args.game_id # reversed result
else:
abort('Duplicate stream ID with different players', 409)
# now add game id
if stream.game_ids_supplementary:
stream.game_ids_supplementary += ','
else:
stream.game_ids_supplementary = ''
stream.game_ids_supplementary += str(game)
else:
# new stream
new = True
stream = Stream()
stream.handle = id
stream.gametype = gametype
for k, v in args.items():
setattr(stream, k, v)
ret = None
# now find the child who will handle this stream
for child, host in CHILDREN.items():
# try to delegate this stream to that child
# FIXME: implement some load balancing
result = requests.put('{}/streams/{}/{}'.format(host, id, gametype),
data = args)
if result.status_code == 200: # accepted?
ret = result.json()
# remember which child accepted this stream
stream.child = child
break
else:
# nobody accepted? try to handle ourself
try:
result = add_stream(stream)
except Exception as e:
abort('Error adding stream: '+str(e))
if result == True:
stream.child = None
elif result == 'busy':
abort('All observers are busy', 507) # 507 Insufficient Stroage
elif result == 'unsupported':
abort('Gametype not supported')
else:
abort('Unknown error '+result, 500)
if new:
db.session.add(stream)
db.session.commit()
if ret:
return ret
return marshal(stream, self.fields), 201 if new else 200
def patch(self, id=None, gametype=None):
"""
Used to propagate stream result (or status update) from child to parent.
Plese provide either (winner,details,timestamp) or (event)!
"""
if not id or not gametype:
raise MethodNotAllowed
log.info('Stream patched with id {}, gt {}'.format(id, gametype))
# this is called from child to parent
stream = Stream.find(id, gametype)
if not stream:
raise NotFound
parser = RequestParser(bundle_errors=True)
parser.add_argument('winner')
parser.add_argument('details', default=None)
parser.add_argument('timestamp', type=float)
parser.add_argument('event')
args = parser.parse_args()
if PARENT:
# send this request upstream
return requests.patch('{}/streams/{}/{}'.format(PARENT[1], id, gametype),
data = args).json()
else:
if args.event:
stream_event(stream, args.event)
else:
stream_done(stream, args.winner, args.timestamp, args.details)
return jsonify(success = True)
def delete(self, id=None, gametype=None):
"""
Deletes all records for given stream.
Also aborts watching if stream is still watched.
"""
if not id or not gametype:
raise MethodNotAllowed
log.info('Stream delete for id {}, gt {}'.format(id, gametype))
stream = Stream.find(id, gametype)
if not stream:
raise NotFound
if stream.child:
ret = requests.delete(child_url(stream.child, id, stream.gametype))
if ret.status_code != 200:
abort('Couldn\'t delete stream', ret.status_code, details=ret)
else: # watching ourself:
abort_stream(stream)
db.session.delete(stream)
db.session.commit()
return jsonify(deleted=True)
@app.route('/load')
def load_ep():
# TODO: allow querying `load average` of each child
load, streams, maximum = current_load()
for child in CHILDREN.values():
ret = requests.get(child+'/load').json()
load += ret.get('total', 0)
streams += ret.get('current_streams', 0)
maximum += ret.get('max_streams', 0)
return jsonify(
total = load / (len(CHILDREN)+1),
current_streams = streams,
max_streams = maximum,
)
if __name__ == '__main__':
init_app()
app.run(port=8021, debug=False, use_debugger=False, use_reloader=False)
| {"/v1/signals_definitions.py": ["/v1/main.py", "/v1/badges/__init__.py"], "/v1/polling.py": ["/config.py", "/v1/helpers.py", "/v1/models.py", "/v1/apis.py", "/v1/common.py"], "/v1/badges/__init__.py": ["/v1/badges/badges_description.py", "/v1/badges/fifa15.py"], "/v1/apis.py": ["/config.py", "/v1/helpers.py", "/v1/mock.py"], "/v1/__init__.py": ["/v1/main.py"], "/mobsite.py": ["/config.py"], "/v1/badges/fifa15.py": ["/v1/main.py", "/v1/badges/badges_description.py"], "/v1/helpers.py": ["/config.py", "/v1/models.py", "/v1/main.py", "/v1/common.py", "/v1/apis.py", "/v1/__init__.py"], "/v1/models.py": ["/v1/main.py", "/v1/common.py", "/v1/badges/__init__.py", "/config.py", "/v1/helpers.py", "/v1/routes.py", "/v1/polling.py"], "/poll.py": ["/main.py", "/v1/__init__.py"], "/v1/cas.py": ["/config.py", "/v1/main.py", "/v1/apis.py", "/v1/models.py", "/v1/common.py"], "/debug_console.py": ["/main.py", "/v1/models.py", "/v1/helpers.py", "/v1/routes.py"], "/v1/routes.py": ["/config.py", "/v1/signals_definitions.py", "/v1/models.py", "/v1/helpers.py", "/v1/apis.py", "/v1/polling.py", "/v1/main.py"], "/main.py": ["/config.py", "/v1/__init__.py", "/v1/main.py", "/v1/models.py"], "/v1/main.py": ["/config.py", "/v1/__init__.py", "/v1/admin.py"], "/v1/admin.py": ["/v1/models.py", "/v1/polling.py", "/v1/helpers.py"], "/observer.py": ["/config.py", "/v1/polling.py", "/v1/models.py", "/v1/apis.py"]} |
72,000 | topdevman/flask-betg | refs/heads/master | /v1/mock.py | from types import SimpleNamespace
import traceback
class log:
def debug_print(meth):
def doprint(cls, msg, exc_info=(meth=='exception')):
print('{}: {}'.format(meth.upper(), msg))
if exc_info:
import traceback
traceback.print_exc()
return doprint
for meth in 'debug info warning error exception'.split():
locals()[meth] = classmethod(debug_print(meth))
config = SimpleNamespace(
PAYPAL_SANDBOX = None,
# just dummy address, as we have no observer here
OBSERVER_URL = 'http://localhost/',
)
def dummyfunc(message, order=[], ondone=None):
def func(*args, **kwargs):
for arg in order:
if arg in kwargs:
args.append(kwargs.pop(arg))
print(message.format(*args, **kwargs))
if ondone:
ondone()
return func
db = SimpleNamespace(
session = SimpleNamespace()
)
db.session.add = dummyfunc('** Adding object {} to database session')
db.session.commit = dummyfunc('** Commiting DB')
| {"/v1/signals_definitions.py": ["/v1/main.py", "/v1/badges/__init__.py"], "/v1/polling.py": ["/config.py", "/v1/helpers.py", "/v1/models.py", "/v1/apis.py", "/v1/common.py"], "/v1/badges/__init__.py": ["/v1/badges/badges_description.py", "/v1/badges/fifa15.py"], "/v1/apis.py": ["/config.py", "/v1/helpers.py", "/v1/mock.py"], "/v1/__init__.py": ["/v1/main.py"], "/mobsite.py": ["/config.py"], "/v1/badges/fifa15.py": ["/v1/main.py", "/v1/badges/badges_description.py"], "/v1/helpers.py": ["/config.py", "/v1/models.py", "/v1/main.py", "/v1/common.py", "/v1/apis.py", "/v1/__init__.py"], "/v1/models.py": ["/v1/main.py", "/v1/common.py", "/v1/badges/__init__.py", "/config.py", "/v1/helpers.py", "/v1/routes.py", "/v1/polling.py"], "/poll.py": ["/main.py", "/v1/__init__.py"], "/v1/cas.py": ["/config.py", "/v1/main.py", "/v1/apis.py", "/v1/models.py", "/v1/common.py"], "/debug_console.py": ["/main.py", "/v1/models.py", "/v1/helpers.py", "/v1/routes.py"], "/v1/routes.py": ["/config.py", "/v1/signals_definitions.py", "/v1/models.py", "/v1/helpers.py", "/v1/apis.py", "/v1/polling.py", "/v1/main.py"], "/main.py": ["/config.py", "/v1/__init__.py", "/v1/main.py", "/v1/models.py"], "/v1/main.py": ["/config.py", "/v1/__init__.py", "/v1/admin.py"], "/v1/admin.py": ["/v1/models.py", "/v1/polling.py", "/v1/helpers.py"], "/observer.py": ["/config.py", "/v1/polling.py", "/v1/models.py", "/v1/apis.py"]} |
72,001 | topdevman/flask-betg | refs/heads/master | /migrations/versions/87ddc7aff543_badges.py | """badges
Revision ID: 87ddc7aff543
Revises: c20f5ca325f4
Create Date: 2016-01-08 19:47:42.060598
"""
# revision identifiers, used by Alembic.
revision = '87ddc7aff543'
down_revision = 'c20f5ca325f4'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('badges',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('player_id', sa.Integer(), nullable=True),
sa.Column('player_badges_updated', sa.PickleType(), nullable=False),
sa.Column('first_win', sa.PickleType(), nullable=True),
sa.Column('first_loss', sa.PickleType(), nullable=True),
sa.Column('played_10_games', sa.PickleType(), nullable=True),
sa.Column('fifa15_xboxone_first_win', sa.PickleType(), nullable=True),
sa.Column('fifa15_xboxone_first_loss', sa.PickleType(), nullable=True),
sa.Column('fifa15_xboxone_10_wins', sa.PickleType(), nullable=True),
sa.ForeignKeyConstraint(['player_id'], ['player.id'], ),
sa.PrimaryKeyConstraint('id')
)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_table('badges')
### end Alembic commands ###
| {"/v1/signals_definitions.py": ["/v1/main.py", "/v1/badges/__init__.py"], "/v1/polling.py": ["/config.py", "/v1/helpers.py", "/v1/models.py", "/v1/apis.py", "/v1/common.py"], "/v1/badges/__init__.py": ["/v1/badges/badges_description.py", "/v1/badges/fifa15.py"], "/v1/apis.py": ["/config.py", "/v1/helpers.py", "/v1/mock.py"], "/v1/__init__.py": ["/v1/main.py"], "/mobsite.py": ["/config.py"], "/v1/badges/fifa15.py": ["/v1/main.py", "/v1/badges/badges_description.py"], "/v1/helpers.py": ["/config.py", "/v1/models.py", "/v1/main.py", "/v1/common.py", "/v1/apis.py", "/v1/__init__.py"], "/v1/models.py": ["/v1/main.py", "/v1/common.py", "/v1/badges/__init__.py", "/config.py", "/v1/helpers.py", "/v1/routes.py", "/v1/polling.py"], "/poll.py": ["/main.py", "/v1/__init__.py"], "/v1/cas.py": ["/config.py", "/v1/main.py", "/v1/apis.py", "/v1/models.py", "/v1/common.py"], "/debug_console.py": ["/main.py", "/v1/models.py", "/v1/helpers.py", "/v1/routes.py"], "/v1/routes.py": ["/config.py", "/v1/signals_definitions.py", "/v1/models.py", "/v1/helpers.py", "/v1/apis.py", "/v1/polling.py", "/v1/main.py"], "/main.py": ["/config.py", "/v1/__init__.py", "/v1/main.py", "/v1/models.py"], "/v1/main.py": ["/config.py", "/v1/__init__.py", "/v1/admin.py"], "/v1/admin.py": ["/v1/models.py", "/v1/polling.py", "/v1/helpers.py"], "/observer.py": ["/config.py", "/v1/polling.py", "/v1/models.py", "/v1/apis.py"]} |
72,002 | bestjunh/Rethinking_Audio-Classification | refs/heads/master | /preprocessing/preprocessingGTZAN.py | import librosa
import argparse
import pandas as pd
import numpy as np
import pickle as pkl
import torch
import torchaudio
import torchvision
from PIL import Image
import os
from joblib import dump
parser = argparse.ArgumentParser()
parser.add_argument("--data_dir", type=str)
parser.add_argument("--store_dir", type=str)
parser.add_argument("--sampling_rate", default=22050, type=int)
def extract_spectrogram(values, clip, target):
num_channels = 3
window_sizes = [25, 50, 100]
hop_sizes = [10, 25, 50]
specs = []
for i in range(num_channels):
window_length = int(round(window_sizes[i]*args.sampling_rate/1000))
hop_length = int(round(hop_sizes[i]*args.sampling_rate/1000))
clip = torch.Tensor(clip)
spec = torchaudio.transforms.MelSpectrogram(sample_rate=args.sampling_rate, n_fft=2205, win_length=window_length, hop_length=hop_length, n_mels=128)(clip) #Check this otherwise use 2400
eps = 1e-6
spec = spec.numpy()
spec = np.log(spec+ eps)
spec = np.asarray(torchvision.transforms.Resize((128, 1500))(Image.fromarray(spec)))
specs.append(spec)
new_entry = {}
new_entry["audio"] = clip.numpy()
new_entry["values"] = np.array(specs)
new_entry["target"] = target
values.append(new_entry)
def extract_features(audios):
values = []
for audio in audios:
try:
clip, sr = librosa.load(audio["name"], sr=args.sampling_rate)
except:
continue
extract_spectrogram(values, clip, audio["class_idx"])
print("Finished audio {}".format(audio))
return values
if __name__=="__main__":
args = parser.parse_args()
root_dir = args.data_dir
training_audios = []
validation_audios = []
for root, dirs, files in os.walk(root_dir):
class_names = dirs
break
for _class in class_names:
class_dir = os.path.join(root_dir, _class)
class_audio = []
for root, dirs, files in os.walk(class_dir):
for file in files:
if file.endswith('.wav'):
class_audio.append({"name":os.path.join(root, file), "class_idx": class_names.index(_class)})
training_audios.extend(class_audio[:int(len(class_audio)*4/5)])
validation_audios.extend(class_audio[int(len(class_audio)*4/5):])
training_values = extract_features(training_audios)
with open("{}training128mel1.pkl".format(args.store_dir),"wb") as handler:
pkl.dump(training_values, handler, protocol=pkl.HIGHEST_PROTOCOL)
validation_values = extract_features(validation_audios)
with open("{}validation128mel1.pkl".format(args.store_dir),"wb") as handler:
pkl.dump(validation_values, handler, protocol=pkl.HIGHEST_PROTOCOL) | {"/train.py": ["/utils.py", "/validate.py", "/models/resnet.py", "/models/inception.py", "/dataloaders/datasetaug.py", "/dataloaders/datasetnormal.py"]} |
72,003 | bestjunh/Rethinking_Audio-Classification | refs/heads/master | /validate.py | import torch
def evaluate(model, device, test_loader):
correct = 0
total = 0
model.eval()
with torch.no_grad():
for batch_idx, data in enumerate(test_loader):
inputs = data[0].to(device)
target = data[1].squeeze(1).to(device)
outputs = model(inputs)
_, predicted = torch.max(outputs.data, 1)
total += target.size(0)
correct += (predicted == target).sum().item()
return (100*correct/total) | {"/train.py": ["/utils.py", "/validate.py", "/models/resnet.py", "/models/inception.py", "/dataloaders/datasetaug.py", "/dataloaders/datasetnormal.py"]} |
72,004 | bestjunh/Rethinking_Audio-Classification | refs/heads/master | /dataloaders/datasetnormal.py | from torch.utils.data import Dataset, DataLoader
import lmdb
import torchvision
import pandas as pd
import numpy as np
import pickle
import torch
from PIL import Image
class AudioDataset(Dataset):
def __init__(self, pkl_dir, dataset_name, transforms=None):
self.data = []
self.length = 1500 if dataset_name=="GTZAN" else 250
self.transforms = transforms
with open(pkl_dir, "rb") as f:
self.data = pickle.load(f)
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
entry = self.data[idx]
output_data = {}
values = entry["values"].reshape(-1, 128, self.length)
values = torch.Tensor(values)
if self.transforms:
values = self.transforms(values)
target = torch.LongTensor([entry["target"]])
return (values, target)
def fetch_dataloader(pkl_dir, dataset_name, batch_size, num_workers):
dataset = AudioDataset(pkl_dir, dataset_name)
dataloader = DataLoader(dataset, shuffle=True, batch_size=batch_size, num_workers=num_workers)
return dataloader | {"/train.py": ["/utils.py", "/validate.py", "/models/resnet.py", "/models/inception.py", "/dataloaders/datasetaug.py", "/dataloaders/datasetnormal.py"]} |
72,005 | bestjunh/Rethinking_Audio-Classification | refs/heads/master | /models/inception.py | import torch
import torch.nn as nn
import torchvision.models as models
from torchsummary import summary
class Inception(nn.Module):
def __init__(self, dataset, pretrained=True):
super(Inception, self).__init__()
num_classes = 50 if dataset=="ESC" else 10
self.model = models.inception_v3(pretrained=pretrained, aux_logits=False)
self.model.fc = nn.Linear(2048, num_classes)
def forward(self, x):
output = self.model(x)
return output
| {"/train.py": ["/utils.py", "/validate.py", "/models/resnet.py", "/models/inception.py", "/dataloaders/datasetaug.py", "/dataloaders/datasetnormal.py"]} |
72,006 | bestjunh/Rethinking_Audio-Classification | refs/heads/master | /preprocessing/preprocessingUSC.py | import librosa
import argparse
import pandas as pd
import numpy as np
import pickle as pkl
import torch
import torchaudio
import torchvision
from PIL import Image
parser = argparse.ArgumentParser()
parser.add_argument("--csv_file", type=str)
parser.add_argument("--data_dir", type=str)
parser.add_argument("--store_dir", type=str)
def extract_spectrogram(values, clip, entries, sr):
for data in entries:
num_channels = 3
window_sizes = [25, 50, 100]
hop_sizes = [10, 25, 50]
# Zero-padding for clip(size <= 2205)
if len(clip) <= 2205:
clip = np.concatenate((clip, np.zeros(2205 - len(clip) + 1)))
specs = []
for i in range(num_channels):
window_length = int(round(window_sizes[i]*sr/1000))
hop_length = int(round(hop_sizes[i]*sr/1000))
clip = torch.Tensor(clip)
spec = torchaudio.transforms.MelSpectrogram(sample_rate=sr, n_fft=2205, win_length=window_length, hop_length=hop_length, n_mels=128)(clip)
eps = 1e-6
spec = spec.numpy()
spec = np.log(spec+ eps)
spec = np.asarray(torchvision.transforms.Resize((128, 250))(Image.fromarray(spec)))
specs.append(spec)
new_entry = {}
new_entry["audio"] = clip.numpy()
new_entry["values"] = np.array(specs)
new_entry["target"] = data["classID"]
values.append(new_entry)
def extract_features(audios):
audio_names = list(audios.slice_file_name.unique())
values = []
for audio in audio_names:
entries = audios.loc[audios["slice_file_name"]==audio].to_dict(orient="records")
clip, sr = librosa.load("{}fold{}/{}".format(args.data_dir, entries[0]["fold"], audio)) #All audio all sampled to a sampling rate of 22050
extract_spectrogram(values, clip, entries, sr)
print("Finished audio {}".format(audio))
return values
if __name__=="__main__":
args = parser.parse_args()
audios = pd.read_csv(args.csv_file, skipinitialspace=True)
num_folds = 10
for i in range(1, num_folds+1):
training_audios = audios.loc[audios["fold"]!=i]
validation_audios = audios.loc[audios["fold"]==i]
training_values = extract_features(training_audios)
with open("{}training128mel{}.pkl".format(args.store_dir, i),"wb") as handler:
pkl.dump(training_values, handler, protocol=pkl.HIGHEST_PROTOCOL)
validation_values = extract_features(validation_audios)
with open("{}validation128mel{}.pkl".format(args.store_dir, i),"wb") as handler:
pkl.dump(validation_values, handler, protocol=pkl.HIGHEST_PROTOCOL) | {"/train.py": ["/utils.py", "/validate.py", "/models/resnet.py", "/models/inception.py", "/dataloaders/datasetaug.py", "/dataloaders/datasetnormal.py"]} |
72,007 | bestjunh/Rethinking_Audio-Classification | refs/heads/master | /models/resnet.py | import torch
import torch.nn as nn
import torchvision.models as models
class ResNet(nn.Module):
def __init__(self, dataset, pretrained=True):
super(ResNet, self).__init__()
num_classes = 50 if dataset=="ESC" else 10
self.model = models.resnet50(pretrained=pretrained)
self.model.fc = nn.Linear(2048, num_classes)
def forward(self, x):
output = self.model(x)
return output | {"/train.py": ["/utils.py", "/validate.py", "/models/resnet.py", "/models/inception.py", "/dataloaders/datasetaug.py", "/dataloaders/datasetnormal.py"]} |
72,008 | bestjunh/Rethinking_Audio-Classification | refs/heads/master | /train.py | import torch
import torchvision
import torch.nn as nn
import numpy as np
import json
import utils
import validate
import argparse
import models.densenet
import models.resnet
import models.inception
import time
import dataloaders.datasetaug
import dataloaders.datasetnormal
from tqdm import tqdm
from tensorboardX import SummaryWriter
parser = argparse.ArgumentParser()
parser.add_argument("--config_path", type=str)
def train(model, device, data_loader, optimizer, loss_fn):
model.train()
loss_avg = utils.RunningAverage()
with tqdm(total=len(data_loader)) as t:
for batch_idx, data in enumerate(data_loader):
inputs = data[0].to(device)
target = data[1].squeeze(1).to(device)
outputs = model(inputs)
loss = loss_fn(outputs, target)
optimizer.zero_grad()
loss.backward()
optimizer.step()
loss_avg.update(loss.item())
t.set_postfix(loss='{:05.3f}'.format(loss_avg()))
t.update()
return loss_avg()
def train_and_evaluate(model, device, train_loader, val_loader, optimizer, loss_fn, writer, params, split, scheduler=None):
best_acc = 0.0
for epoch in range(params.epochs):
avg_loss = train(model, device, train_loader, optimizer, loss_fn)
acc = validate.evaluate(model, device, val_loader)
print("Epoch {}/{} Loss:{} Valid Acc:{}".format(epoch, params.epochs, avg_loss, acc))
is_best = (acc > best_acc)
if is_best:
best_acc = acc
if scheduler:
scheduler.step()
utils.save_checkpoint({"epoch": epoch + 1,
"model": model.state_dict(),
"optimizer": optimizer.state_dict()}, is_best, split, "{}".format(params.checkpoint_dir))
writer.add_scalar("data{}/trainingLoss{}".format(params.dataset_name, split), avg_loss, epoch)
writer.add_scalar("data{}/valLoss{}".format(params.dataset_name, split), acc, epoch)
writer.close()
if __name__ == "__main__":
args = parser.parse_args()
params = utils.Params(args.config_path)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)
for i in range(1, params.num_folds+1):
if params.dataaug:
train_loader = dataloaders.datasetaug.fetch_dataloader( "{}training128mel{}.pkl".format(params.data_dir, i), params.dataset_name, params.batch_size, params.num_workers, 'train')
val_loader = dataloaders.datasetaug.fetch_dataloader("{}validation128mel{}.pkl".format(params.data_dir, i), params.dataset_name, params.batch_size, params.num_workers, 'validation')
else:
train_loader = dataloaders.datasetnormal.fetch_dataloader( "{}training128mel{}.pkl".format(params.data_dir, i), params.dataset_name, params.batch_size, params.num_workers)
val_loader = dataloaders.datasetnormal.fetch_dataloader("{}validation128mel{}.pkl".format(params.data_dir, i), params.dataset_name, params.batch_size, params.num_workers)
writer = SummaryWriter(comment=params.dataset_name)
if params.model=="densenet":
model = models.densenet.DenseNet(params.dataset_name, params.pretrained).to(device)
elif params.model=="resnet":
model = models.resnet.ResNet(params.dataset_name, params.pretrained).to(device)
elif params.model=="inception":
model = models.inception.Inception(params.dataset_name, params.pretrained).to(device)
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=params.lr, weight_decay=params.weight_decay)
if params.scheduler:
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, 30, gamma=0.1)
else:
scheduler = None
train_and_evaluate(model, device, train_loader, val_loader, optimizer, loss_fn, writer, params, i, scheduler)
| {"/train.py": ["/utils.py", "/validate.py", "/models/resnet.py", "/models/inception.py", "/dataloaders/datasetaug.py", "/dataloaders/datasetnormal.py"]} |
72,009 | bestjunh/Rethinking_Audio-Classification | refs/heads/master | /dataloaders/datasetaug.py | from torch.utils.data import Dataset, DataLoader
import lmdb
import torchvision
import pandas as pd
import numpy as np
import pickle
import torch
import librosa
import torchaudio
import random
from PIL import Image
class MelSpectrogram(object):
def __init__(self, bins, mode, dataset):
self.window_length = [25, 50, 100]
self.hop_length = [10, 25, 50]
self.fft = 4410 if dataset=="ESC" else 2205
self.melbins = bins
self.mode = mode
self.sr = 44100 if dataset=="ESC" else 22050
self.length = 1500 if dataset=="GTZAN" else 250
def __call__(self, value):
sample = value
limits = ((-2, 2), (0.9, 1.2))
if self.mode=="train":
pitch_shift = np.random.randint(limits[0][0], limits[0][1] + 1)
time_stretch = np.random.random() * (limits[1][1] - limits[1][0]) + limits[1][0]
new_audio = librosa.effects.time_stretch(librosa.effects.pitch_shift(sample, sr=self.sr, n_steps=pitch_shift), rate=time_stretch)
else:
pitch_shift = 0
time_stretch = 1
new_audio = sample
specs = []
for i in range(len(self.window_length)):
clip = torch.Tensor(new_audio)
window_length = int(round(self.window_length[i]*self.sr/1000))
hop_length = int(round(self.hop_length[i]*self.sr/1000))
spec = torchaudio.transforms.MelSpectrogram(sample_rate=self.sr, n_fft=self.fft, win_length=window_length, hop_length=hop_length, n_mels=self.melbins)(clip)
eps = 1e-6
spec = spec.numpy()
spec = np.log(spec+ eps)
spec = np.asarray(torchvision.transforms.Resize((128, self.length))(Image.fromarray(spec)))
specs.append(spec)
specs = np.array(specs).reshape(-1, 128, self.length)
specs = torch.Tensor(specs)
return specs
class AudioDataset(Dataset):
def __init__(self, pkl_dir, dataset_name, transforms=None):
self.transforms = transforms
self.data = []
self.length = 1500 if dataset_name=="GTZAN" else 250
with open(pkl_dir, "rb") as f:
self.data = pickle.load(f)
def __len__(self):
if self.transforms.mode == "train":
return 2*len(self.data)
else:
return len(self.data)
def __getitem__(self, idx):
if idx >= len(self.data):
new_idx = idx - len(self.data)
entry = self.data[new_idx]
if self.transforms:
values = self.transforms(entry["audio"])
else:
entry = self.data[idx]
values = torch.Tensor(entry["values"].reshape(-1, 128, self.length))
target = torch.LongTensor([entry["target"]])
return (values, target)
def fetch_dataloader(pkl_dir, dataset_name, batch_size, num_workers, mode):
transforms = MelSpectrogram(128, mode, dataset_name)
dataset = AudioDataset(pkl_dir, dataset_name, transforms=transforms)
dataloader = DataLoader(dataset,shuffle=True, batch_size=batch_size, num_workers=num_workers)
return dataloader
| {"/train.py": ["/utils.py", "/validate.py", "/models/resnet.py", "/models/inception.py", "/dataloaders/datasetaug.py", "/dataloaders/datasetnormal.py"]} |
72,010 | bestjunh/Rethinking_Audio-Classification | refs/heads/master | /utils.py | import shutil
import json
import os
import torch
import torch.nn as nn
class Params():
def __init__(self, json_path):
with open(json_path) as f:
params = json.load(f)
self.__dict__.update(params)
def save(self, json_path):
with open(json_path, 'w') as f:
params = json.dump(self.__dict__, f, indent=4)
def update(self, json_path):
with open(json_path) as f:
params = json.load(f)
self.__dict__.update(params)
@property
def dict(self):
return self.__dict__
class RunningAverage():
def __init__(self):
self.total = 0
self.steps = 0
def update(self, loss):
self.total += loss
self.steps += 1
def __call__(self):
return (self.total/float(self.steps))
def save_checkpoint(state, is_best, split, checkpoint):
filename = os.path.join(checkpoint, 'last{}.pth.tar'.format(split))
if not os.path.exists(checkpoint):
print("Checkpoint Directory does not exist")
os.mkdir(checkpoint)
torch.save(state, filename)
if is_best:
shutil.copyfile(filename, os.path.join(checkpoint, "model_best_{}.pth.tar".format(split)))
def load_checkpoint(checkpoint, model, optimizer=None, parallel=False):
if not os.path.exists(checkpoint):
raise("File Not Found Error {}".format(checkpoint))
checkpoint = torch.load(checkpoint)
if parallel:
model.module.load_state_dict(checkpoint["model"])
else:
model.load_state_dict(checkpoint["model"])
if optimizer:
optimizer.load_state_dict(checkpoint["optimizer"])
return checkpoint
def initialize_weights(m):
classname = m.__class__.__name__
print(classname)
if classname.find('Linear') != -1:
nn.init.ones_(m.weight.data)
| {"/train.py": ["/utils.py", "/validate.py", "/models/resnet.py", "/models/inception.py", "/dataloaders/datasetaug.py", "/dataloaders/datasetnormal.py"]} |
72,015 | vishnu2981997/cass_migrate | refs/heads/master | /cass_migrate.py | import glob
import json
import os
import time
import uuid
from cassandra.auth import PlainTextAuthProvider
from cassandra.cluster import Cluster
from cassandra.policies import DCAwareRoundRobinPolicy
from parsers import parse_cql
class Cassandra:
"""
"""
response = None
def __init__(self, host, user_name, password, port, key_space, application_name, env_name,
cql_files_path, mode, logger, rollback_version=None):
"""
:param host:
:param user_name:
:param password:
:param port:
:param key_space:
:param application_name:
:param env_name:
:param cql_files_path:
:param mode:
:param logger:
:param rollback_version:
"""
self._host = host
self._user_name = user_name
self._password = password
self._port = port
self._key_space = key_space
self._application_name = application_name
self._env_name = env_name
self._cql_files_path = cql_files_path
self._mode = mode
self._log = logger
self._rollback_version = rollback_version
self._session = None
self._file_path = None
self._file_name = None
self._migration_file_path = None
self._scripts = None
self._id = None
self._version = None
self._content = None
self._up_scripts = []
self._down_scripts = []
self._success_scripts = []
self._processed_script_names = []
self._migrations_table_name = "database_migrations"
self.response = {"data": "success"}
@property
def host(self):
return self._host
@host.setter
def host(self, host):
self._host = host
@host.deleter
def host(self):
del self._host
@property
def user_name(self):
return self._user_name
@user_name.setter
def user_name(self, user_name):
self._user_name = user_name
@user_name.deleter
def user_name(self):
del self._user_name
@property
def password(self):
return self._password
@password.setter
def password(self, password):
self._password = password
@password.deleter
def password(self):
del self._password
@property
def port(self):
return self._port
@port.setter
def port(self, port):
self._port = port
@port.deleter
def port(self):
del self._port
@property
def key_space(self):
return self._key_space
@key_space.setter
def key_space(self, key_space):
self._key_space = key_space
@key_space.deleter
def key_space(self):
del self._key_space
@property
def application_name(self):
return self._application_name
@application_name.setter
def application_name(self, application_name):
self._application_name = application_name
@application_name.deleter
def application_name(self):
del self._application_name
@property
def env_name(self):
return self._env_name
@env_name.setter
def env_name(self, env_name):
self._env_name = env_name
@env_name.deleter
def env_name(self):
del self._env_name
@property
def cql_files_path(self):
return self._cql_files_path
@cql_files_path.setter
def cql_files_path(self, cql_files_path):
self._cql_files_path = cql_files_path
@cql_files_path.deleter
def cql_files_path(self):
del self._cql_files_path
@property
def mode(self):
return self._mode
@mode.setter
def mode(self, mode):
self._mode = mode
@mode.deleter
def mode(self):
del self._mode
def establish_connection(self):
"""
:return:
"""
self._log.log("establishing connection with config : " + json.dumps(self.__repr__()))
try:
auth_provider = PlainTextAuthProvider(username=self._user_name, password=self._password)
cluster = Cluster(
contact_points=self._host,
port=self._port,
auth_provider=auth_provider,
max_schema_agreement_wait=300,
control_connection_timeout=10,
connect_timeout=30,
load_balancing_policy=DCAwareRoundRobinPolicy()
)
self._session = cluster.connect()
self._session.set_keyspace(self._key_space)
self._log.log("connection established")
return True
except Exception as exe:
self.response["data"] = str(exe)
self._log.log("Invalid credentials or smthin went wrong", error=str(exe))
return False
def initiate_migration(self):
"""
:return:
"""
try:
success = False
self._log.log("migration initiated mode : " + self._mode)
if self._mode == "up":
success = self.create_migration()
elif self._mode == "down":
success = self.migrate()
if success:
self._log.log("migration success mode : " + self._mode)
except Exception as exe:
self.response["data"] = str(exe)
self._log.log(error=exe)
def create_migration(self):
"""
:return:
"""
if self.create_migrations_table():
if self.get_file_names():
if self.execute_up_scripts():
self.create_file_path()
self.create_file_name()
self.create_path()
self.create_file()
self.store_migration_details()
self.mark_processed()
return True
else:
self.exception_rollback()
return False
def migrate(self):
"""
:return:
"""
self.form_migrations_table()
if self._rollback_version:
if self.get_rollback_data_multiple():
if self.execute_down_scripts():
self.update_migration_table()
return True
else:
self.exception_rollback()
elif self.get_rollback_data():
if self.execute_down_scripts():
self.update_migration_table()
return True
else:
self.exception_rollback()
return False
def form_migrations_table(self):
"""
:return:
"""
self._log.log("forming migrations table name")
self._migrations_table_name += "_" + self._application_name + "_" + self._env_name
def create_migrations_table(self):
"""
:return:
"""
self._log.log("creating migration table")
try:
self.form_migrations_table()
cql = """
SELECT * FROM system_schema.tables
where keyspace_name='{key_space}' and
table_name='{migrations_table}';
"""
cql = cql.format(key_space=self._key_space, migrations_table=self._migrations_table_name)
data = self._session.execute(cql).current_rows
if not data:
cql = """
CREATE TABLE {table} (
id uuid,
applied_at timestamp,
version int,
name text,
content text,
PRIMARY KEY (id)
);
"""
cql = cql.format(table=self._migrations_table_name)
self._session.execute(cql)
return True
except Exception as exe:
self.response["data"] = str(exe)
self._log.log(error=exe)
return False
def get_file_names(self):
"""
:return:
"""
self._log.log("fetching file names")
self._scripts = glob.glob(
os.path.join(os.path.join(os.path.abspath("scripts"), self._cql_files_path), "*.cql"))
temp = glob.glob(
os.path.join(os.path.join(os.path.abspath("scripts"), self._cql_files_path), "*_processed.cql"))
if self._scripts and len(self._scripts) > len(temp):
return True
else:
self.response["data"] = "No unprocessed scripts in the specified path or path might be wrong"
self._log.log("No scripts in the specified path or path might be wrong")
return False
def execute_up_scripts(self):
"""
:return:
"""
self._log.log("executing up scripts")
script_name = None
try:
for script in self._scripts:
script_name = script.split("\\")[-1]
if not script_name.endswith("_rollback.cql") and not script_name.endswith("_processed.cql"):
up_script = self.read_file(script)
up_script = parse_cql(up_script)
self._up_scripts.append(up_script)
self._session.execute(up_script)
self._success_scripts.append(up_script)
self._processed_script_names.append(script)
down_script = script_name.split(".cql")[0] + "_rollback.cql"
base_path = "\\".join(i for i in script.split("\\")[:len(script.split("\\")) - 1])
script = os.path.join(base_path, down_script)
try:
down_script = self.read_file(script)
self._processed_script_names.append(script)
except Exception:
self.response["data"] = str("rollback file missing for : " + script_name)
self._log.log("rollback file missing for : " + script_name)
return False
down_script = parse_cql(down_script)
self._down_scripts.append(down_script)
return True
except Exception as exe:
self.response["data"] = str(exe)
self._log.log("error in script : " + script_name, error=str(exe))
return False
def create_file_path(self):
"""
:return:
"""
self._log.log("creating file path")
migrations_path = os.path.abspath("migrations")
if not os.path.exists(migrations_path):
os.mkdir(migrations_path)
file_path = os.path.join(migrations_path, self._application_name)
if not os.path.exists(file_path):
os.mkdir(file_path)
file_path = os.path.join(file_path, self._env_name)
if not os.path.exists(file_path):
os.mkdir(file_path)
self._file_path = file_path
def create_file_name(self):
"""
:return:
"""
self._log.log("creating file name")
self._file_name = time.strftime(
"%Y%m%d%H%M%S") + "_" + self._application_name + "_" + self._env_name + ".json"
def create_path(self):
"""
:return:
"""
self._log.log("creating path")
self._migration_file_path = os.path.join(self._file_path, self._file_name)
def create_file(self):
"""
:return:
"""
self._log.log("creating file")
json_data = {"data": []}
for up_script, down_script in zip(self._up_scripts, self._down_scripts):
json_data["data"].append({"up_script": up_script, "down_script": down_script})
self._content = json.dumps(json_data)
with open(self._migration_file_path, "w") as json_data_file:
json.dump(json_data, json_data_file, ensure_ascii=False, indent=4)
def store_migration_details(self):
"""
:return:
"""
self._log.log("storing migration details")
self.generate_id()
if self.generate_version():
self.insert_data()
def generate_id(self):
"""
:return:
"""
self._log.log("generating id")
self._id = uuid.uuid4()
def generate_version(self):
"""
:return:
"""
self._log.log("generating version")
try:
self._version = 1
cql = """SELECT MAX(version) FROM {table};"""
cql = cql.format(table=self._migrations_table_name)
data = self._session.execute(cql).current_rows
if data[0][0]:
version = data[0][0] + 1
self._version = version
return True
except Exception as exe:
self.response["data"] = str(exe)
self._log.log(error=exe)
return False
def insert_data(self):
"""
:return:
"""
self._log.log("inserting data into migration table")
try:
cql = """
INSERT INTO {table}
(id, version, name, content, applied_at)
VALUES ({id}, {version}, '{name}', '{content}', toTimestamp(now()))
"""
cql = cql.format(table=self._migrations_table_name, id=self._id,
version=self._version, name=self._file_name.strip(".json"), content=self._content)
self._session.execute(cql)
return True
except Exception as exe:
self.response["data"] = str(exe)
self._log.log(error=exe)
return False
@staticmethod
def read_file(script):
"""
:param script:
:return:
"""
with open(script, "r") as fp:
data = fp.read()
return data
def get_rollback_data(self):
"""
:return:
"""
self._log.log("fetching rollback data")
try:
cql = """SELECT MAX(version) FROM {table};"""
cql = cql.format(table=self._migrations_table_name)
data = self._session.execute(cql).current_rows
cql = """SELECT * FROM {table} WHERE version={version_number} ALLOW FILTERING;"""
cql = cql.format(table=self._migrations_table_name, version_number=data[0][0])
data = self._session.execute(cql).current_rows
if data:
self._down_scripts = [i["down_script"] for i in json.loads(data[-1].content)["data"]]
self._id = data[-1].id
return True
else:
self._log.log("No migrations to perform migration")
return False
except Exception as exe:
self.response["data"] = str(exe)
self._log.log(error=exe)
return False
def get_rollback_data_multiple(self):
self._log.log("fetching rollback data")
try:
cql = """SELECT MAX(version) FROM {table};"""
cql = cql.format(table=self._migrations_table_name)
data = self._session.execute(cql).current_rows
cql = """SELECT * FROM {table} WHERE version={version_number} ALLOW FILTERING;"""
cql = cql.format(table=self._migrations_table_name, version_number=data[0][0])
data = self._session.execute(cql).current_rows
if data:
if int(data[-1].version) > self._rollback_version:
temp_scripts = []
temp_ids = []
for i in range(int(data[-1].version), int(data[-1].version) - self._rollback_version - 1, -1):
cql = """SELECT * FROM {table} WHERE version={version_number} ALLOW FILTERING;"""
cql = cql.format(table=self._migrations_table_name, version_number=i)
data = self._session.execute(cql).current_rows
scripts = [i["down_script"] for i in json.loads(data[0].content)["data"]]
temp_scripts += scripts[::-1]
temp_ids.append(data[0].id)
self._down_scripts = temp_scripts[::-1]
self._id = temp_ids
return True
return False
else:
self._log.log("invalid version")
return False
except Exception as exe:
self.response["data"] = str(exe)
self._log.log(error=exe)
return False
def execute_down_scripts(self):
"""
:return:
"""
self._log.log("executing down scripts")
try:
for script in self._down_scripts[::-1]:
self._session.execute(script)
self._success_scripts.append(script)
return True
except Exception as exe:
self.response["data"] = str(exe)
self._log.log(error=exe)
return False
def update_migration_table(self):
"""
:return:
"""
self._log.log("updating migration table")
try:
cql_begin = """
BEGIN BATCH
"""
cql_end = """
APPLY BATCH ;
"""
if self._rollback_version:
for migration_id in self._id:
cql = """
DELETE FROM {table} WHERE id={migration_id};
"""
cql = cql.format(table=self._migrations_table_name, migration_id=migration_id)
cql_begin += cql
cql_begin += cql_end
self._session.execute(cql_begin)
return True
else:
cql = cql.format(table=self._migrations_table_name, migration_id=self._id)
self._session.execute(cql)
return True
except Exception as exe:
self.response["data"] = str(exe)
self._log.log(error=exe)
return False
def exception_rollback(self):
"""
:return:
"""
for script in self._success_scripts[::-1]:
self._session.execute(script)
def mark_processed(self):
for script in self._processed_script_names:
base_script = script.split(".cql")[0]
os.rename(script, base_script + "_processed.cql")
def __repr__(self):
return {
"host": self._host,
"user_name": self._user_name,
"password": self._password,
"port": self._port,
"key_space": self._key_space,
"application_name": self._application_name,
"env_name": self._env_name,
"cql_files_path": self._cql_files_path,
"mode": self._mode,
}
def __str__(self):
string = "Auth(host = {0}, user_name = {1}, password = {2}, " \
"port = {3}, key_space = {4}, application_name = {5}, " \
"env_name = {6}, cql_files_path = {7}, mode = {8})"
return string.format(self._host, self._user_name, self._password,
self._port, self._key_space, self._application_name,
self._env_name, self._cql_files_path, self._mode)
| {"/cass_migrate.py": ["/parsers.py"], "/manage.py": ["/cass_migrate.py", "/custom_logging.py"]} |
72,016 | vishnu2981997/cass_migrate | refs/heads/master | /manage.py | from cass_migrate import Cassandra
from custom_logging import CustomLogging
import sys
def main():
"""
:return:
"""
# config = {
# "host": ["127.0.0.1"],
# "user_name": "admin",
# "password": "12345@qwert",
# "port": 9042,
# "key_space": "test_1",
# "application_name": "app1",
# "env_name": "dev",
# "cql_files_path": "test_1",
# "mode": "up",
# }
config = {
"host": [sys.argv[1]],
"user_name": sys.argv[2],
"password": sys.argv[3],
"port": int(sys.argv[4]),
"key_space": sys.argv[5],
"application_name": sys.argv[6],
"env_name": sys.argv[7],
"mode": sys.argv[8],
"cql_files_path": None,
"rollback_version": None,
}
if config["mode"] == "up":
config["cql_files_path"] = sys.argv[9]
elif config["mode"] == "down":
if len(sys.argv) == 10:
config["rollback_version"] = int(sys.argv[9])
c = Cassandra(
host=config["host"],
user_name=config["user_name"],
password=config["password"],
port=config["port"],
key_space=config["key_space"],
application_name=config["application_name"],
env_name=config["env_name"],
cql_files_path=config["cql_files_path"],
mode=config["mode"],
logger=CustomLogging(
application_name=config["application_name"],
env_name=config["env_name"],
mode=config["mode"]
),
rollback_version=config["rollback_version"]
)
if c.establish_connection():
c.initiate_migration()
print(c.response)
if __name__ == "__main__":
main()
| {"/cass_migrate.py": ["/parsers.py"], "/manage.py": ["/cass_migrate.py", "/custom_logging.py"]} |
72,017 | vishnu2981997/cass_migrate | refs/heads/master | /custom_logging.py | """
"""
import datetime
import logging
import time
import os
class CustomLogging:
""""""
def __init__(self, application_name, env_name, mode):
"""
:param application_name:
:param env_name:
:param mode:
"""
self._application_name = application_name
self._env_name = env_name
self._mode = mode
self._logs_dir = "cassandra_migrate_logging"
self._time_stamp = time.strftime("%Y%m%d%H%M%S")
self._file_name = "{0}_{1}_{2}_{3}".format(str(self._time_stamp), self._application_name,
self._env_name, self._mode)
self._log_path = self.create_log_file()
logging.basicConfig(filename=os.path.join(self._log_path, self._file_name + ".log"), level=logging.INFO)
def create_log_file(self):
"""
:return:
"""
logs_path = os.path.abspath(self._logs_dir)
if not os.path.exists(logs_path):
os.mkdir(logs_path)
file_path = os.path.join(logs_path, self._application_name)
if not os.path.exists(file_path):
os.mkdir(file_path)
file_path = os.path.join(file_path, self._env_name)
if not os.path.exists(file_path):
os.mkdir(file_path)
return file_path
@staticmethod
def log(msg="", error=None):
"""
logs the given msg to the specified log file
:param msg: string
:param error: string
:return: None
"""
time_stamp = time.time()
content = datetime.datetime.fromtimestamp(time_stamp).strftime("%Y-%m-%d %H:%M:%S")
content += " " + str(msg)
if error:
content += " " + str(error)
logging.info(content)
| {"/cass_migrate.py": ["/parsers.py"], "/manage.py": ["/cass_migrate.py", "/custom_logging.py"]} |
72,018 | vishnu2981997/cass_migrate | refs/heads/master | /parsers.py | def parse_cql(cql_text):
"""
:param cql_text:
:return:
"""
cql_text = remove_block_comments(cql_text)
cmd = []
for line in cql_text.splitlines():
if line != "":
if not line.startswith('--') and not line.startswith("//"):
cmd.append(line)
cmd = "\n".join(i for i in cmd)
return cmd
def remove_block_comments(cql):
"""
:param cql:
:return:
"""
i = 0
while True:
start = cql.find("/*")
if start == -1:
break
end = cql.find("*/")
if end == -1:
print("ERROR: unclosed block comment")
break
cql = cql.replace(cql[start:end + 2], "")
i = i + 1
return cql
| {"/cass_migrate.py": ["/parsers.py"], "/manage.py": ["/cass_migrate.py", "/custom_logging.py"]} |
72,039 | mwilliammyers/voice-assistant | refs/heads/master | /test.py | from __future__ import print_function, unicode_literals
import json
import readline
from builtins import input, str
from main import action_from
from snips_nlu import SnipsNLUEngine
nlu_engine = SnipsNLUEngine().from_path("models/nlu/engine")
try:
while True:
text = str(input("> "))
parsed = nlu_engine.parse(text)
print(json.dumps(parsed, indent=4))
action_from(**parsed)()
except (KeyboardInterrupt, EOFError):
pass
| {"/test.py": ["/main.py"]} |
72,040 | mwilliammyers/voice-assistant | refs/heads/master | /main.py | from __future__ import print_function, unicode_literals
import timeit
from builtins import str
from pathlib import Path
from signal import pause
from subprocess import check_output
def cached(f):
cache = {}
def helper(x):
if x not in cache:
cache[x] = f(x)
return cache[x]
return helper
@cached
def init_led(line_num):
from gpiozero import LED
return LED(line_num)
def speak(text, engine=None, record=True):
if engine is None:
# TODO: support different engines..
import pyttsx3
# TODO: cache engine init?
engine = pyttsx3.init()
if record:
print("[spoken]", text)
engine.say(text)
engine.runAndWait()
def transcribe(source, recognizer=None, listening_led=5, **kwargs):
if recognizer is None:
import speech_recognition as sr
# TODO: cache recognizer init?
recognizer = sr.Recognizer()
kwargs.setdefault("language", "en-US-ptm")
# TODO: should we adjust for ambient noise?
# recognizer.adjust_for_ambient_noise(source)
led = init_led(listening_led)
led.on()
start = timeit.default_timer()
try:
audio = recognizer.listen(source)
led.blink()
return str(recognizer.recognize_sphinx(audio, **kwargs))
except sr.UnknownValueError:
speak("Sorry, I couldn't hear you.")
return ""
except sr.RequestError as e:
print(e)
speak("uh oh")
return ""
finally:
print("finished ASR {:.4f}".format(timeit.default_timer() - start))
led.off()
def action_from(intent=None, slots=None, input=None):
if intent is None:
intent = {}
if slots is None:
slots = []
if input is None:
input = ""
entities = {slot["slotName"]: slot for slot in slots}
def change_led_state(state, led=None):
if led is None:
led = 26
led = init_led(led)
speak("Okay, turning the LED {}".format(state))
getattr(led, state)()
def change_light_state(state, room=None):
room = "in the {}".format(room) if room is not None else ""
speak("Okay, turning the light {} {}".format(state, room))
if intent.get("intentName") == "turnLedOn":
led = entities.get("led", {}).get("value")
return lambda: change_led_state("on", led)
if intent.get("intentName") == "turnLedOff":
led = entities.get("led", {}).get("value")
return lambda: change_led_state("off", led)
if intent.get("intentName") == "turnLightOn":
room = entities.get("room", {}).get("value", {}).get("value")
return lambda: change_light_state("on", room)
if intent.get("intentName") == "turnLightOff":
room = entities.get("room", {}).get("value", {}).get("value")
return lambda: change_light_state("off", room)
if intent.get("intentName") == "getWeather":
location = entities.get("location", {}).get("value", {}).get("value")
loc = "in {}".format(location) if location else "here"
d = entities.get("dateTime", {}).get("rawValue", "")
# TODO: use actual weather API
return lambda: speak("It will be 32 degrees {} {}".format(loc, d))
if intent.get("intentName") == "setTemperature":
room = entities.get("room", {}).get("value")
r = "in the {}".format(room) if room else ""
t = entities.get("temperature", {}).get("rawValue", "")
# TODO: use actual thermostat API
return lambda: speak("OK setting the thermostat {} to {}".format(r, t))
if intent.get("intentName") == "searchFlight":
# TODO: use actual flight API
return lambda: speak("I found a flight for 350 dollars")
return lambda: speak("I didn't understand. Try saying it differently?")
if __name__ == "__main__":
import speech_recognition as sr
from gpiozero import Button
import requests
# TODO: fix nlu install
# from snips_nlu import SnipsNLUEngine
# hacky but it works
# cmd = ["git", "rev-parse", "--show-toplevel"]
# project_root = Path(check_output(cmd).decode().rstrip())
# model_dir = Path(project_root, "models/nlu/engine")
# nlu_engine = SnipsNLUEngine().from_path(model_dir)
with sr.Microphone(sample_rate=16000) as source:
button = Button(6)
def handle_button_press():
# keyword_entries=[("light", 0.2), ("turn", 0.1), ("on", 0.05)],
# transcript = nlu_engine.parse(transcribe(source))
raw_transcript = transcribe(source)
print(raw_transcript)
transcript = requests.get(
# "http://voxjar.ddns.net:9001/parse",
"http://192.168.1.169:9001/parse",
json={"text": raw_transcript},
).json()
print(transcript)
action_from(**transcript)()
button.when_pressed = handle_button_press
print("waiting for button press")
pause()
| {"/test.py": ["/main.py"]} |
72,041 | mylesdoolan/knn | refs/heads/master | /FileManagement.py | import csv
def openCSVFile(file):
with open(file, 'r') as csvfile:
print('reaches here')
dialect = csv.Sniffer().sniff(csvfile.read(1024))
csvfile.seek(0)
reader = csv.DictReader(csvfile)
for data in reader:
data.update("EuclideanValue", ev)
| {"/KNNTests.py": ["/KNN.py"]} |
72,042 | mylesdoolan/knn | refs/heads/master | /KNNTests.py | import unittest
import KNN
class MyTestCase(unittest.TestCase):
def test_something(self):
self.assertEqual(11.999999999999998, KNN.euclidean_distance(1, 4, 4, 1))
def test_k(self):
self.assertEqual(35, KNN.k(1200))
if __name__ == '__main__':
unittest.main()
| {"/KNNTests.py": ["/KNN.py"]} |
72,043 | mylesdoolan/knn | refs/heads/master | /KNN.py | #K Nearest Neighbour
import math
import csv
# C:\Users\Myles\Downloads\CFIR-dataset-2020.csv
def main():
unchecked = []
checked = []
k = 3
#change
print("Please supply the CSV file you wish to have KNN'd:\n")
file = input()
print("Opening: ", file)
with open(file, 'r') as csvfile:
csvfile.seek(0)
reader = csv.DictReader(csvfile)
data = list(reader)
k = k_calc(len(data))
for record in data:
if record.get('State') == '':
unchecked.append(record)
else:
checked.append(record)
results = status_calculator(unchecked, checked, k)
keys = results[0].keys()
with open('/results.csv', 'w', newline='') as output_file:
dict_writer = csv.DictWriter(output_file, keys)
dict_writer.writeheader()
dict_writer.writerows(results)
def status_calculator(unchecked, checked, k):
for uncheckedValue in unchecked:
euc_vals = []
for checkedValue in checked:
# print(uncheckedValue.get('x'))
euc_dist = euclidean_distance(uncheckedValue.get('x'), uncheckedValue.get('y'), checkedValue.get('x'), checkedValue.get('y'))
if (len(euc_vals) <= k):
euc_vals.append({'Host': checkedValue.get('Host'), 'State': checkedValue.get('State'), 'Distance': euc_dist})
else:
euc_vals = sorted(euc_vals, key=lambda i: i['Distance'])
if euc_vals[-1].get('Distance') > euc_dist:
euc_vals[-1] = {'Host': checkedValue.get('Host'), 'State': checkedValue.get('State'), 'Distance': euc_dist}
uncheckedValue['State'] = count_states(euc_vals, k)
return checked + unchecked
def euclidean_distance(x1, y1, x2, y2):
return math.sqrt((float(x1) - float(x2))**2 + (float(y1) - float(y2))**2)
def count_states(euc_vals, k):
normal = 0
for neighbour in euc_vals:
if neighbour.get('State') == 'Normal':
normal += 1
if normal > (k / 2):
return 'Normal'
else:
return 'Infected'
def k_calc(count):
return round(math.sqrt(count))
if __name__ == "__main__":
main() | {"/KNNTests.py": ["/KNN.py"]} |
72,051 | felipeduarte/SistemaSus | refs/heads/master | /teste_medico.py | import unittest
from should_dsl import should
from medico import Medico
class Teste_Medico(unittest. TestCase):
def setUp(self):
self.medico1 = Medico("diego", "202020", "pediatra")
def test_atributos(self):
self.medico1.nome |should| equal_to("diego")
self.medico1.matricula |should| equal_to("202020")
self.medico1.especialidade |should| equal_to("pediatra")
if __name__ == "__main__":
unittest.main()
| {"/teste_medico.py": ["/medico.py"], "/teste_paciente.py": ["/paciente.py"], "/teste_enfermeiro.py": ["/enfermeiro.py"], "/teste_hospital.py": ["/hospital.py", "/funcionario.py"], "/medico.py": ["/funcionario.py"], "/teste_funcionario.py": ["/funcionario.py", "/hospital.py"], "/teste_principal.py": ["/teste_enfermeiro.py", "/teste_funcionario.py", "/teste_hospital.py", "/teste_internacao.py", "/teste_medico.py", "/teste_paciente.py"], "/funcionario.py": ["/hospital.py"], "/enfermeiro.py": ["/funcionario.py"]} |
72,052 | felipeduarte/SistemaSus | refs/heads/master | /teste_paciente.py | import unittest
from should_dsl import should
from datetime import date
from paciente import Paciente
class Teste_Paciente(unittest.TestCase):
def setUp(self):
self.paciente = Paciente("Pedro", "Masculino", 1989, "123456")
def test_atributos(self):
self.paciente.nome |should| equal_to("Pedro")
self.paciente.sexo |should| equal_to("Masculino")
self.paciente.ano_de_nascimento |should| equal_to(1989)
self.paciente.codigo_do_seguro_social |should| equal_to("123456")
self.paciente.funcionarios |should| equal_to([])
def test_calcular_idade(self):
self.paciente.calcular_idade() |should| equal_to(24)
if __name__ == "__main__":
unittest.main()
| {"/teste_medico.py": ["/medico.py"], "/teste_paciente.py": ["/paciente.py"], "/teste_enfermeiro.py": ["/enfermeiro.py"], "/teste_hospital.py": ["/hospital.py", "/funcionario.py"], "/medico.py": ["/funcionario.py"], "/teste_funcionario.py": ["/funcionario.py", "/hospital.py"], "/teste_principal.py": ["/teste_enfermeiro.py", "/teste_funcionario.py", "/teste_hospital.py", "/teste_internacao.py", "/teste_medico.py", "/teste_paciente.py"], "/funcionario.py": ["/hospital.py"], "/enfermeiro.py": ["/funcionario.py"]} |
72,053 | felipeduarte/SistemaSus | refs/heads/master | /teste_enfermeiro.py | import unittest
from should_dsl import should
from enfermeiro import Enfermeiro
class Teste_Enfermeiro(unittest.TestCase):
def setUp(self):
self.enfermeiro1 = Enfermeiro("joao vitor", "242424" , "auxiliar")
def test_atributos(self):
self.enfermeiro1.nome |should| equal_to("joao vitor")
self.enfermeiro1.matricula |should| equal_to("242424")
self.enfermeiro1.cargo |should| equal_to("auxiliar")
if __name__ == "__main__":
unittest.main()
| {"/teste_medico.py": ["/medico.py"], "/teste_paciente.py": ["/paciente.py"], "/teste_enfermeiro.py": ["/enfermeiro.py"], "/teste_hospital.py": ["/hospital.py", "/funcionario.py"], "/medico.py": ["/funcionario.py"], "/teste_funcionario.py": ["/funcionario.py", "/hospital.py"], "/teste_principal.py": ["/teste_enfermeiro.py", "/teste_funcionario.py", "/teste_hospital.py", "/teste_internacao.py", "/teste_medico.py", "/teste_paciente.py"], "/funcionario.py": ["/hospital.py"], "/enfermeiro.py": ["/funcionario.py"]} |
72,054 | felipeduarte/SistemaSus | refs/heads/master | /teste_hospital.py | import unittest
from should_dsl import should
from hospital import Hospital
from funcionario import Funcionario
class Teste_Hospital(unittest.TestCase):
def setUp(self):
self.hospital1 = Hospital("santa casa", "123456", "Rua Ips")
def test_atributos(self):
self.hospital1.nome |should| equal_to("santa casa")
self.hospital1.codigo |should| equal_to("123456")
self.hospital1.endereco |should| equal_to("Rua Ips")
self.hospital1.funcionarios |should| equal_to([])
def test_vincular_funcionario(self):
#vinculando funcionario1:
funcionario1 = Funcionario("Joao", "654321")
self.hospital1.vincular_funcionarios(funcionario1)
self.hospital1.funcionarios |should| have(1).items
#vinculando funcionario2
funcionario2 = Funcionario("Pedro", "654321")
self.hospital1.vincular_funcionarios(funcionario2)
self.hospital1.funcionarios |should| have(2).items
#teste_bug
self.hospital1.vincular_funcionarios(funcionario1)
self.hospital1.funcionarios |should| have(2).items
def test_consultar_funcionario(self):
funcionario1 = Funcionario("Joao", "654321")
self.hospital1.vincular_funcionarios(funcionario1)
self.hospital1.consultar_funcionario(funcionario1).nome |should| equal_to("Joao")
if __name__ == "__main__":
unittest.main()
| {"/teste_medico.py": ["/medico.py"], "/teste_paciente.py": ["/paciente.py"], "/teste_enfermeiro.py": ["/enfermeiro.py"], "/teste_hospital.py": ["/hospital.py", "/funcionario.py"], "/medico.py": ["/funcionario.py"], "/teste_funcionario.py": ["/funcionario.py", "/hospital.py"], "/teste_principal.py": ["/teste_enfermeiro.py", "/teste_funcionario.py", "/teste_hospital.py", "/teste_internacao.py", "/teste_medico.py", "/teste_paciente.py"], "/funcionario.py": ["/hospital.py"], "/enfermeiro.py": ["/funcionario.py"]} |
72,055 | felipeduarte/SistemaSus | refs/heads/master | /hospital.py | class Hospital(object):
def __init__(self, nome, codigo, endereco):
self.nome = nome
self.codigo = codigo
self.endereco = endereco
self.funcionarios = []
def vincular_funcionarios(self, objeto_funcionario):
if self.consultar_funcionario(objeto_funcionario) == None:
self.funcionarios.append(objeto_funcionario)
def consultar_funcionario(self, objeto_funcionario):
for funcionario in self.funcionarios:
if funcionario == objeto_funcionario:
return objeto_funcionario
return None
| {"/teste_medico.py": ["/medico.py"], "/teste_paciente.py": ["/paciente.py"], "/teste_enfermeiro.py": ["/enfermeiro.py"], "/teste_hospital.py": ["/hospital.py", "/funcionario.py"], "/medico.py": ["/funcionario.py"], "/teste_funcionario.py": ["/funcionario.py", "/hospital.py"], "/teste_principal.py": ["/teste_enfermeiro.py", "/teste_funcionario.py", "/teste_hospital.py", "/teste_internacao.py", "/teste_medico.py", "/teste_paciente.py"], "/funcionario.py": ["/hospital.py"], "/enfermeiro.py": ["/funcionario.py"]} |
72,056 | felipeduarte/SistemaSus | refs/heads/master | /paciente.py | from time import localtime
class Paciente(object):
def __init__(self, nome, sexo, ano_de_nascimento, codigo_do_seguro_social):
self.nome = nome
self.sexo = sexo
self.ano_de_nascimento = ano_de_nascimento
self.codigo_do_seguro_social = codigo_do_seguro_social
self.funcionarios = []
def calcular_idade(self):
idade = 0
data_completa = localtime()
ano_atual = data_completa[0]
idade = ano_atual - self.ano_de_nascimento
return idade
def vincular_funcionario(self, objeto_funcionario):
self.funcionarios.append(objeto_funcionario)
| {"/teste_medico.py": ["/medico.py"], "/teste_paciente.py": ["/paciente.py"], "/teste_enfermeiro.py": ["/enfermeiro.py"], "/teste_hospital.py": ["/hospital.py", "/funcionario.py"], "/medico.py": ["/funcionario.py"], "/teste_funcionario.py": ["/funcionario.py", "/hospital.py"], "/teste_principal.py": ["/teste_enfermeiro.py", "/teste_funcionario.py", "/teste_hospital.py", "/teste_internacao.py", "/teste_medico.py", "/teste_paciente.py"], "/funcionario.py": ["/hospital.py"], "/enfermeiro.py": ["/funcionario.py"]} |
72,057 | felipeduarte/SistemaSus | refs/heads/master | /medico.py | from funcionario import Funcionario
class Medico(Funcionario):
def __init__(self, nome, matricula, especialidade):
Funcionario.__init__(self, nome, matricula)
self.especialidade = especialidade
| {"/teste_medico.py": ["/medico.py"], "/teste_paciente.py": ["/paciente.py"], "/teste_enfermeiro.py": ["/enfermeiro.py"], "/teste_hospital.py": ["/hospital.py", "/funcionario.py"], "/medico.py": ["/funcionario.py"], "/teste_funcionario.py": ["/funcionario.py", "/hospital.py"], "/teste_principal.py": ["/teste_enfermeiro.py", "/teste_funcionario.py", "/teste_hospital.py", "/teste_internacao.py", "/teste_medico.py", "/teste_paciente.py"], "/funcionario.py": ["/hospital.py"], "/enfermeiro.py": ["/funcionario.py"]} |
72,058 | felipeduarte/SistemaSus | refs/heads/master | /teste_funcionario.py | import unittest
from should_dsl import should
from funcionario import Funcionario
from hospital import Hospital
class Teste_Funcionario(unittest.TestCase):
def setUp(self):
self.funcionario = Funcionario("Joao", "654321")
def test_atributos(self):
self.funcionario.nome |should| equal_to("Joao")
self.funcionario.matricula |should| equal_to("654321")
self.funcionario.hospitais |should| equal_to([])
def test_vincular_hospitais(self):
hospital1 = Hospital("santa casa", "123456", "Rua Ips")
self.funcionario.vincular_hospitais(hospital1)
self.funcionario.hospitais |should| have(1).itens
hospital2 = Hospital("santa casa", "123456", "Rua Ips")
self.funcionario.vincular_hospitais(hospital2)
self.funcionario.hospitais |should| have(2).itens
hospital3 = Hospital("santa casa", "123456", "Rua Ips")
self.funcionario.vincular_hospitais(hospital3)
self.funcionario.hospitais |should| have(3).itens
if __name__ == "__main__":
unittest.main()
| {"/teste_medico.py": ["/medico.py"], "/teste_paciente.py": ["/paciente.py"], "/teste_enfermeiro.py": ["/enfermeiro.py"], "/teste_hospital.py": ["/hospital.py", "/funcionario.py"], "/medico.py": ["/funcionario.py"], "/teste_funcionario.py": ["/funcionario.py", "/hospital.py"], "/teste_principal.py": ["/teste_enfermeiro.py", "/teste_funcionario.py", "/teste_hospital.py", "/teste_internacao.py", "/teste_medico.py", "/teste_paciente.py"], "/funcionario.py": ["/hospital.py"], "/enfermeiro.py": ["/funcionario.py"]} |
72,059 | felipeduarte/SistemaSus | refs/heads/master | /teste_internacao.py | import unittest
from should_dsl import should
from datetime import date
from internacao import Internacao
from paciente import Paciente
class Teste_Internacao(unittest.TestCase):
def setUp(self):
self.paciente = Paciente("Pedro", "Masculino", "13/11/1986", "123456")
self.internacao1 = Internacao(date(2012, 02, 20), date(2012, 02, 25), self.paciente)
def test_atributos(self):
self.internacao1.hora_inicio |should| equal_to(date(2012, 02, 20))
self.internacao1.hora_alta |should| equal_to(date(2012, 02, 25))
self.internacao1.objeto_paciente |should| equal_to(self.paciente)
if __name__ == "__main__":
unittest.main()
| {"/teste_medico.py": ["/medico.py"], "/teste_paciente.py": ["/paciente.py"], "/teste_enfermeiro.py": ["/enfermeiro.py"], "/teste_hospital.py": ["/hospital.py", "/funcionario.py"], "/medico.py": ["/funcionario.py"], "/teste_funcionario.py": ["/funcionario.py", "/hospital.py"], "/teste_principal.py": ["/teste_enfermeiro.py", "/teste_funcionario.py", "/teste_hospital.py", "/teste_internacao.py", "/teste_medico.py", "/teste_paciente.py"], "/funcionario.py": ["/hospital.py"], "/enfermeiro.py": ["/funcionario.py"]} |
72,060 | felipeduarte/SistemaSus | refs/heads/master | /teste_principal.py | import unittest
from should_dsl import should
from teste_enfermeiro import Teste_Enfermeiro
from teste_funcionario import Teste_Funcionario
from teste_hospital import Teste_Hospital
from teste_internacao import Teste_Internacao
from teste_medico import Teste_Medico
from teste_paciente import Teste_Paciente
class Teste_Principal(unittest.TestCase):
Teste_Enfermeiro
Teste_Funcionario
Teste_Hospital
Teste_Internacao
Teste_Medico
Teste_Paciente
if __name__ == "__main__":
unittest.main()
| {"/teste_medico.py": ["/medico.py"], "/teste_paciente.py": ["/paciente.py"], "/teste_enfermeiro.py": ["/enfermeiro.py"], "/teste_hospital.py": ["/hospital.py", "/funcionario.py"], "/medico.py": ["/funcionario.py"], "/teste_funcionario.py": ["/funcionario.py", "/hospital.py"], "/teste_principal.py": ["/teste_enfermeiro.py", "/teste_funcionario.py", "/teste_hospital.py", "/teste_internacao.py", "/teste_medico.py", "/teste_paciente.py"], "/funcionario.py": ["/hospital.py"], "/enfermeiro.py": ["/funcionario.py"]} |
72,061 | felipeduarte/SistemaSus | refs/heads/master | /funcionario.py | from hospital import Hospital
class Funcionario(object):
def __init__(self, nome, matricula):
self.nome = nome
self.matricula = matricula
self.hospitais = []
def vincular_hospitais(self, objeto_hospital):
self.hospitais.append(objeto_hospital)
| {"/teste_medico.py": ["/medico.py"], "/teste_paciente.py": ["/paciente.py"], "/teste_enfermeiro.py": ["/enfermeiro.py"], "/teste_hospital.py": ["/hospital.py", "/funcionario.py"], "/medico.py": ["/funcionario.py"], "/teste_funcionario.py": ["/funcionario.py", "/hospital.py"], "/teste_principal.py": ["/teste_enfermeiro.py", "/teste_funcionario.py", "/teste_hospital.py", "/teste_internacao.py", "/teste_medico.py", "/teste_paciente.py"], "/funcionario.py": ["/hospital.py"], "/enfermeiro.py": ["/funcionario.py"]} |
72,062 | felipeduarte/SistemaSus | refs/heads/master | /internacao.py | class Internacao(object):
def __init__(self, hora_inicio, hora_alta, objeto_paciente):
self.hora_inicio = hora_inicio
self.hora_alta = hora_alta
self.objeto_paciente = objeto_paciente
| {"/teste_medico.py": ["/medico.py"], "/teste_paciente.py": ["/paciente.py"], "/teste_enfermeiro.py": ["/enfermeiro.py"], "/teste_hospital.py": ["/hospital.py", "/funcionario.py"], "/medico.py": ["/funcionario.py"], "/teste_funcionario.py": ["/funcionario.py", "/hospital.py"], "/teste_principal.py": ["/teste_enfermeiro.py", "/teste_funcionario.py", "/teste_hospital.py", "/teste_internacao.py", "/teste_medico.py", "/teste_paciente.py"], "/funcionario.py": ["/hospital.py"], "/enfermeiro.py": ["/funcionario.py"]} |
72,063 | felipeduarte/SistemaSus | refs/heads/master | /enfermeiro.py | from funcionario import Funcionario
class Enfermeiro(Funcionario):
def __init__(self, nome, matricula, cargo):
Funcionario.__init__(self, nome, matricula)
self.cargo = cargo
| {"/teste_medico.py": ["/medico.py"], "/teste_paciente.py": ["/paciente.py"], "/teste_enfermeiro.py": ["/enfermeiro.py"], "/teste_hospital.py": ["/hospital.py", "/funcionario.py"], "/medico.py": ["/funcionario.py"], "/teste_funcionario.py": ["/funcionario.py", "/hospital.py"], "/teste_principal.py": ["/teste_enfermeiro.py", "/teste_funcionario.py", "/teste_hospital.py", "/teste_internacao.py", "/teste_medico.py", "/teste_paciente.py"], "/funcionario.py": ["/hospital.py"], "/enfermeiro.py": ["/funcionario.py"]} |
72,080 | walterbrunetti/dentix | refs/heads/master | /dentix/apps/tratamiento/models.py | from django.db import models
from dentix.apps.paciente.models import Paciente
from dentix.apps.prestacion.models import Prestacion
from dentix.apps.presentacion.models import Presentacion, Ficha
ESTADOS = (
(1, 'Finalizado'),
(2, 'En Proceso'),
(3, 'Suspendido'),
)
class Diente(models.Model):
nombre = models.CharField(max_length=128)
nro_diente = models.CharField(max_length=128)
def __unicode__(self):
return u'%s - %s' % (self.nro_diente, self.nombre)
class Cara(models.Model):
nombre = models.CharField(max_length=128)
def __unicode__(self):
return self.nombre
class Tratamiento(models.Model):
fecha = models.DateField()
paciente = models.ForeignKey(Paciente)
estado = models.SmallIntegerField(choices=ESTADOS)
foto_f3 = models.FileField(upload_to='uploads_imgs', null=True, blank=True)
observaciones = models.TextField(max_length=1024, null=True, blank=True)
def foto_f3_tag(self):
if self.foto_f3:
return u'<a href="/media/%s" target="_blank"><img src="/media/%s" style="width:500px;" /></a>' % (self.foto_f3.name, self.foto_f3.name)
return u''
foto_f3_tag.short_description = 'Foto f3 preview'
foto_f3_tag.allow_tags = True
def __unicode__(self):
return u'%s, %s' % (self.paciente.apellido, self.paciente.nombre)
class DetallePrestacion(models.Model):
prestacion = models.ForeignKey(Prestacion)
diente = models.ForeignKey(Diente, null=True, blank=True)
cara = models.ForeignKey(Cara, null=True, blank=True)
tratamiento = models.ForeignKey(Tratamiento) # Un tratamiento tiene muchos detalles de prestacion
ficha = models.ForeignKey(Ficha, null=True, blank=True)
def __unicode__(self):
return u'%s %s %s' % (self.prestacion.nombre, self.diente, self.tratamiento.paciente)
class Visita(models.Model):
fecha = models.DateField()
observaciones = models.TextField(max_length=1024, null=True, blank=True)
tratamiento = models.ForeignKey(Tratamiento)
| {"/dentix/apps/tratamiento/models.py": ["/dentix/apps/paciente/models.py", "/dentix/apps/prestacion/models.py", "/dentix/apps/presentacion/models.py"], "/dentix/apps/presentacion/models.py": ["/dentix/apps/paciente/models.py"], "/dentix/apps/presentacion/admin.py": ["/dentix/apps/tratamiento/models.py"], "/dentix/apps/paciente/models.py": ["/dentix/apps/obrasocial/models.py"]} |
72,081 | walterbrunetti/dentix | refs/heads/master | /dentix/apps/obrasocial/models.py | from django.db import models
class ObraSocial(models.Model):
nombre = models.CharField(max_length=128)
telefono = models.CharField(max_length=128, null=True, blank=True)
direccion = models.CharField(max_length=128, null=True, blank=True)
observaciones = models.TextField(max_length=1024, null=True, blank=True)
def __unicode__(self):
return self.nombre
| {"/dentix/apps/tratamiento/models.py": ["/dentix/apps/paciente/models.py", "/dentix/apps/prestacion/models.py", "/dentix/apps/presentacion/models.py"], "/dentix/apps/presentacion/models.py": ["/dentix/apps/paciente/models.py"], "/dentix/apps/presentacion/admin.py": ["/dentix/apps/tratamiento/models.py"], "/dentix/apps/paciente/models.py": ["/dentix/apps/obrasocial/models.py"]} |
72,082 | walterbrunetti/dentix | refs/heads/master | /dentix/apps/presentacion/models.py | from django.db import models
from dentix.apps.paciente.models import Paciente
ENTIDADES = (
(1, 'Asor'),
(2, 'Ale vanucci'),
)
ESTADOS = (
(1, 'Pendiente'),
(2, 'Pagado'),
(3, 'No Pagado'),
)
class Presentacion(models.Model):
fecha = models.DateField()
entidad = models.SmallIntegerField(choices=ENTIDADES)
def __unicode__(self):
return u'%s - %s' % (self.fecha, ENTIDADES[self.entidad - 1][1])
class Ficha(models.Model):
paciente = models.ForeignKey(Paciente)
foto_f1 = models.FileField(upload_to='uploads_imgs', null=True, blank=True)
copago = models.DecimalField(max_digits=5, decimal_places=2)
estampilla = models.DecimalField(max_digits=5, decimal_places=2)
presentacion = models.ForeignKey(Presentacion)
importe_estimado = models.DecimalField(max_digits=10, decimal_places=2)
importe_cobrado = models.DecimalField(max_digits=10, decimal_places=2)
estado = models.SmallIntegerField(choices=ESTADOS)
def get_details_link(self):
if self.id:
return u'<a href="/admin/presentacion/ficha/%s" target="_blank">Detalle</a>' % self.id
return u''
get_details_link.allow_tags = True
def foto_f1_tag(self):
if self.foto_f1:
return u'<a href="/media/%s" target="_blank"><img src="/media/%s" style="width:500px;" /></a>' % (self.foto_f1.name, self.foto_f1.name)
return u''
foto_f1_tag.short_description = 'Foto f1 preview'
foto_f1_tag.allow_tags = True
def __unicode__(self):
return u'%s %s %s' % (self.paciente, self.presentacion.fecha, ENTIDADES[self.presentacion.entidad - 1][1])
| {"/dentix/apps/tratamiento/models.py": ["/dentix/apps/paciente/models.py", "/dentix/apps/prestacion/models.py", "/dentix/apps/presentacion/models.py"], "/dentix/apps/presentacion/models.py": ["/dentix/apps/paciente/models.py"], "/dentix/apps/presentacion/admin.py": ["/dentix/apps/tratamiento/models.py"], "/dentix/apps/paciente/models.py": ["/dentix/apps/obrasocial/models.py"]} |
72,083 | walterbrunetti/dentix | refs/heads/master | /dentix/apps/presentacion/admin.py | from django.contrib import admin
from models import Presentacion, Ficha
from dentix.apps.tratamiento.models import DetallePrestacion
class FichaInline(admin.TabularInline):
readonly_fields = ['get_details_link', ]
model = Ficha
raw_id_fields = ('paciente', )
class PresentacionAdmin(admin.ModelAdmin):
inlines = [
FichaInline,
]
list_display = ('fecha', 'entidad')
search_fields = ['fecha', ]
list_filter = ('entidad', )
class DetallePrestacionInline(admin.TabularInline):
model = DetallePrestacion
raw_id_fields = ('tratamiento', )
class FichaAdmin(admin.ModelAdmin):
inlines = [
DetallePrestacionInline,
]
list_display = ('presentacion', 'paciente', 'importe_estimado', 'importe_cobrado', 'estado')
search_fields = ['paciente__nombre', 'paciente__apellido', 'presentacion__fecha']
list_filter = ('estado', 'presentacion__entidad')
raw_id_fields = ('paciente', 'presentacion')
readonly_fields = ('foto_f1_tag',)
admin.site.register(Presentacion, PresentacionAdmin)
admin.site.register(Ficha, FichaAdmin)
| {"/dentix/apps/tratamiento/models.py": ["/dentix/apps/paciente/models.py", "/dentix/apps/prestacion/models.py", "/dentix/apps/presentacion/models.py"], "/dentix/apps/presentacion/models.py": ["/dentix/apps/paciente/models.py"], "/dentix/apps/presentacion/admin.py": ["/dentix/apps/tratamiento/models.py"], "/dentix/apps/paciente/models.py": ["/dentix/apps/obrasocial/models.py"]} |
72,084 | walterbrunetti/dentix | refs/heads/master | /dentix/apps/presentacion/migrations/0002_auto_20150518_1911.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('presentacion', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='ficha',
name='copago',
field=models.DecimalField(max_digits=5, decimal_places=2),
),
migrations.AlterField(
model_name='ficha',
name='estado',
field=models.SmallIntegerField(choices=[(1, b'Pendiente'), (2, b'Pagado'), (3, b'No Pagado')]),
),
migrations.AlterField(
model_name='ficha',
name='estampilla',
field=models.DecimalField(max_digits=5, decimal_places=2),
),
migrations.AlterField(
model_name='ficha',
name='foto_f1',
field=models.FileField(null=True, upload_to=b'dentix/uploads_imgs', blank=True),
),
migrations.AlterField(
model_name='ficha',
name='importe_cobrado',
field=models.DecimalField(max_digits=10, decimal_places=2),
),
migrations.AlterField(
model_name='ficha',
name='importe_estimado',
field=models.DecimalField(max_digits=10, decimal_places=2),
),
]
| {"/dentix/apps/tratamiento/models.py": ["/dentix/apps/paciente/models.py", "/dentix/apps/prestacion/models.py", "/dentix/apps/presentacion/models.py"], "/dentix/apps/presentacion/models.py": ["/dentix/apps/paciente/models.py"], "/dentix/apps/presentacion/admin.py": ["/dentix/apps/tratamiento/models.py"], "/dentix/apps/paciente/models.py": ["/dentix/apps/obrasocial/models.py"]} |
72,085 | walterbrunetti/dentix | refs/heads/master | /dentix/apps/tratamiento/migrations/0002_auto_20150518_1911.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('tratamiento', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Cara',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('nombre', models.CharField(max_length=128)),
],
),
migrations.AlterField(
model_name='detalleprestacion',
name='cara',
field=models.ForeignKey(blank=True, to='tratamiento.Cara', null=True),
),
]
| {"/dentix/apps/tratamiento/models.py": ["/dentix/apps/paciente/models.py", "/dentix/apps/prestacion/models.py", "/dentix/apps/presentacion/models.py"], "/dentix/apps/presentacion/models.py": ["/dentix/apps/paciente/models.py"], "/dentix/apps/presentacion/admin.py": ["/dentix/apps/tratamiento/models.py"], "/dentix/apps/paciente/models.py": ["/dentix/apps/obrasocial/models.py"]} |
72,086 | walterbrunetti/dentix | refs/heads/master | /dentix/apps/tratamiento/admin.py | from django.contrib import admin
from models import Diente, Tratamiento, DetallePrestacion, Visita
class DetallePrestacionInline(admin.TabularInline):
model = DetallePrestacion
raw_id_fields = ('ficha', )
class VisitaInline(admin.TabularInline):
model = Visita
class TratamientoAdmin(admin.ModelAdmin):
inlines = [
DetallePrestacionInline,
VisitaInline,
]
list_display = ('fecha', 'paciente', 'estado')
search_fields = ['fecha', 'paciente__nombre', 'paciente__apellido']
list_filter = ('estado', )
raw_id_fields = ('paciente', )
readonly_fields = ('foto_f3_tag',)
admin.site.register(Tratamiento, TratamientoAdmin)
admin.site.register(Diente)
#admin.site.register(DetallePrestacion)
#admin.site.register(Visita)
| {"/dentix/apps/tratamiento/models.py": ["/dentix/apps/paciente/models.py", "/dentix/apps/prestacion/models.py", "/dentix/apps/presentacion/models.py"], "/dentix/apps/presentacion/models.py": ["/dentix/apps/paciente/models.py"], "/dentix/apps/presentacion/admin.py": ["/dentix/apps/tratamiento/models.py"], "/dentix/apps/paciente/models.py": ["/dentix/apps/obrasocial/models.py"]} |
72,087 | walterbrunetti/dentix | refs/heads/master | /dentix/apps/prestacion/admin.py | from django.contrib import admin
from models import Prestacion
class PrestacionAdmin(admin.ModelAdmin):
list_display = ('nombre', 'codigo')
search_fields = ['nombre', 'codigo',]
admin.site.register(Prestacion, PrestacionAdmin)
| {"/dentix/apps/tratamiento/models.py": ["/dentix/apps/paciente/models.py", "/dentix/apps/prestacion/models.py", "/dentix/apps/presentacion/models.py"], "/dentix/apps/presentacion/models.py": ["/dentix/apps/paciente/models.py"], "/dentix/apps/presentacion/admin.py": ["/dentix/apps/tratamiento/models.py"], "/dentix/apps/paciente/models.py": ["/dentix/apps/obrasocial/models.py"]} |
72,088 | walterbrunetti/dentix | refs/heads/master | /dentix/apps/presentacion/migrations/0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('paciente', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Ficha',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('foto_f1', models.FileField(null=True, upload_to=b'uploads_imgs', blank=True)),
('copago', models.DecimalField(max_digits=16, decimal_places=2)),
('estampilla', models.DecimalField(max_digits=16, decimal_places=2)),
('importe_estimado', models.DecimalField(max_digits=16, decimal_places=2)),
('importe_cobrado', models.DecimalField(max_digits=16, decimal_places=2)),
('estado', models.SmallIntegerField(choices=[(1, b'Pendiente'), (2, b'Pagado'), (2, b'No Pagado')])),
('paciente', models.ForeignKey(to='paciente.Paciente')),
],
),
migrations.CreateModel(
name='Presentacion',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('fecha', models.DateField()),
('entidad', models.SmallIntegerField(choices=[(1, b'Asor'), (2, b'Ale vanucci')])),
],
),
migrations.AddField(
model_name='ficha',
name='presentacion',
field=models.ForeignKey(to='presentacion.Presentacion'),
),
]
| {"/dentix/apps/tratamiento/models.py": ["/dentix/apps/paciente/models.py", "/dentix/apps/prestacion/models.py", "/dentix/apps/presentacion/models.py"], "/dentix/apps/presentacion/models.py": ["/dentix/apps/paciente/models.py"], "/dentix/apps/presentacion/admin.py": ["/dentix/apps/tratamiento/models.py"], "/dentix/apps/paciente/models.py": ["/dentix/apps/obrasocial/models.py"]} |
72,089 | walterbrunetti/dentix | refs/heads/master | /walter/views.py | from django.shortcuts import render
def walter_home(request):
return render(request, 'static/index.html', {"foo": "bar"},
content_type="application/xhtml+xml")
| {"/dentix/apps/tratamiento/models.py": ["/dentix/apps/paciente/models.py", "/dentix/apps/prestacion/models.py", "/dentix/apps/presentacion/models.py"], "/dentix/apps/presentacion/models.py": ["/dentix/apps/paciente/models.py"], "/dentix/apps/presentacion/admin.py": ["/dentix/apps/tratamiento/models.py"], "/dentix/apps/paciente/models.py": ["/dentix/apps/obrasocial/models.py"]} |
72,090 | walterbrunetti/dentix | refs/heads/master | /dentix/apps/paciente/admin.py | from django.contrib import admin
from models import Paciente
class PacienteAdmin(admin.ModelAdmin):
list_display = ('dni', 'nombre', 'apellido', 'telefono', 'celular', 'obra_social')
search_fields = ['dni', 'nombre', 'apellido']
admin.site.register(Paciente, PacienteAdmin)
| {"/dentix/apps/tratamiento/models.py": ["/dentix/apps/paciente/models.py", "/dentix/apps/prestacion/models.py", "/dentix/apps/presentacion/models.py"], "/dentix/apps/presentacion/models.py": ["/dentix/apps/paciente/models.py"], "/dentix/apps/presentacion/admin.py": ["/dentix/apps/tratamiento/models.py"], "/dentix/apps/paciente/models.py": ["/dentix/apps/obrasocial/models.py"]} |
72,091 | walterbrunetti/dentix | refs/heads/master | /dentix/apps/obrasocial/admin.py | from django.contrib import admin
from models import ObraSocial
class ObraSocialAdmin(admin.ModelAdmin):
list_display = ('nombre', 'telefono', 'direccion')
search_fields = ['nombre', ]
admin.site.register(ObraSocial, ObraSocialAdmin)
| {"/dentix/apps/tratamiento/models.py": ["/dentix/apps/paciente/models.py", "/dentix/apps/prestacion/models.py", "/dentix/apps/presentacion/models.py"], "/dentix/apps/presentacion/models.py": ["/dentix/apps/paciente/models.py"], "/dentix/apps/presentacion/admin.py": ["/dentix/apps/tratamiento/models.py"], "/dentix/apps/paciente/models.py": ["/dentix/apps/obrasocial/models.py"]} |
72,092 | walterbrunetti/dentix | refs/heads/master | /dentix/apps/obrasocial/migrations/0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='ObraSocial',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('nombre', models.CharField(max_length=128)),
('telefono', models.CharField(max_length=128, null=True, blank=True)),
('direccion', models.CharField(max_length=128, null=True, blank=True)),
('observaciones', models.CharField(max_length=1024, null=True, blank=True)),
],
),
]
| {"/dentix/apps/tratamiento/models.py": ["/dentix/apps/paciente/models.py", "/dentix/apps/prestacion/models.py", "/dentix/apps/presentacion/models.py"], "/dentix/apps/presentacion/models.py": ["/dentix/apps/paciente/models.py"], "/dentix/apps/presentacion/admin.py": ["/dentix/apps/tratamiento/models.py"], "/dentix/apps/paciente/models.py": ["/dentix/apps/obrasocial/models.py"]} |
72,093 | walterbrunetti/dentix | refs/heads/master | /dentix/apps/paciente/models.py | from django.db import models
from dentix.apps.obrasocial.models import ObraSocial
SEXO = (
(1, 'masculino'),
(2, 'femenino'),
)
class Paciente(models.Model):
dni = models.IntegerField()
nombre = models.CharField(max_length=200)
apellido = models.CharField(max_length=200)
fecha_nacimiento = models.DateField()
domicilio = models.CharField(max_length=200, null=True, blank=True)
telefono = models.CharField(max_length=200)
celular = models.CharField(max_length=200, null=True, blank=True)
sexo = models.SmallIntegerField(choices=SEXO)
email = models.CharField(max_length=200, null=True, blank=True)
obra_social = models.ForeignKey(ObraSocial)
def __unicode__(self):
return u'%s, %s' % (self.apellido, self.nombre)
| {"/dentix/apps/tratamiento/models.py": ["/dentix/apps/paciente/models.py", "/dentix/apps/prestacion/models.py", "/dentix/apps/presentacion/models.py"], "/dentix/apps/presentacion/models.py": ["/dentix/apps/paciente/models.py"], "/dentix/apps/presentacion/admin.py": ["/dentix/apps/tratamiento/models.py"], "/dentix/apps/paciente/models.py": ["/dentix/apps/obrasocial/models.py"]} |
72,094 | walterbrunetti/dentix | refs/heads/master | /dentix/apps/tratamiento/migrations/0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('paciente', '0001_initial'),
('presentacion', '0001_initial'),
('prestacion', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='DetallePrestacion',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('cara', models.SmallIntegerField(blank=True, null=True, choices=[(1, b'Distal'), (2, b'Mesial'), (3, b'Oclusal'), (4, b'Incisal')])),
],
),
migrations.CreateModel(
name='Diente',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('nombre', models.CharField(max_length=128)),
('nro_diente', models.CharField(max_length=128)),
],
),
migrations.CreateModel(
name='Tratamiento',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('fecha', models.DateField()),
('estado', models.SmallIntegerField(choices=[(1, b'Finalizado'), (2, b'En Proceso'), (3, b'Suspendido')])),
('foto_f3', models.FileField(null=True, upload_to=b'uploads_imgs', blank=True)),
('observaciones', models.TextField(max_length=1024, null=True, blank=True)),
('paciente', models.ForeignKey(to='paciente.Paciente')),
],
),
migrations.CreateModel(
name='Visita',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('fecha', models.DateField()),
('observaciones', models.TextField(max_length=1024, null=True, blank=True)),
('tratamiento', models.ForeignKey(to='tratamiento.Tratamiento')),
],
),
migrations.AddField(
model_name='detalleprestacion',
name='diente',
field=models.ForeignKey(blank=True, to='tratamiento.Diente', null=True),
),
migrations.AddField(
model_name='detalleprestacion',
name='ficha',
field=models.ForeignKey(blank=True, to='presentacion.Ficha', null=True),
),
migrations.AddField(
model_name='detalleprestacion',
name='prestacion',
field=models.ForeignKey(to='prestacion.Prestacion'),
),
migrations.AddField(
model_name='detalleprestacion',
name='tratamiento',
field=models.ForeignKey(to='tratamiento.Tratamiento'),
),
]
| {"/dentix/apps/tratamiento/models.py": ["/dentix/apps/paciente/models.py", "/dentix/apps/prestacion/models.py", "/dentix/apps/presentacion/models.py"], "/dentix/apps/presentacion/models.py": ["/dentix/apps/paciente/models.py"], "/dentix/apps/presentacion/admin.py": ["/dentix/apps/tratamiento/models.py"], "/dentix/apps/paciente/models.py": ["/dentix/apps/obrasocial/models.py"]} |
72,095 | walterbrunetti/dentix | refs/heads/master | /dentix/apps/prestacion/models.py | from django.db import models
class Prestacion(models.Model):
nombre = models.CharField(max_length=128)
codigo = models.CharField(max_length=128)
def __unicode__(self):
return self.nombre
| {"/dentix/apps/tratamiento/models.py": ["/dentix/apps/paciente/models.py", "/dentix/apps/prestacion/models.py", "/dentix/apps/presentacion/models.py"], "/dentix/apps/presentacion/models.py": ["/dentix/apps/paciente/models.py"], "/dentix/apps/presentacion/admin.py": ["/dentix/apps/tratamiento/models.py"], "/dentix/apps/paciente/models.py": ["/dentix/apps/obrasocial/models.py"]} |
72,099 | HasratSingh/Pong | refs/heads/master | /scoreboard.py | from turtle import Turtle
ALIGN = "center"
FONT = ("Arial", 16, "normal")
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.penup()
self.color("white")
self.goto(0, 270)
self.hideturtle()
self.score_left = 0
self.score_right = 0
self.update_scoreboard()
def update_score_left(self):
self.score_left += 1
self.update_scoreboard()
def update_score_right(self):
self.score_right += 1
self.update_scoreboard()
def update_scoreboard(self):
self.clear()
self.write(f"Left:{self.score_left} Right:{self.score_right}", align=ALIGN, font=FONT)
def final_result(self):
if self.score_right > self.score_left:
winner = "Right"
else:
winner = "Left"
self.goto(0, 0)
self.write(f"Game Over. {winner} is Winner.", align=ALIGN, font=FONT)
| {"/main.py": ["/ball.py", "/scoreboard.py"]} |
72,100 | HasratSingh/Pong | refs/heads/master | /main.py | from turtle import Screen
from paddle import Paddle, PADDLE_SIZE
from ball import Ball
from scoreboard import Scoreboard
from time import sleep
# Screen Setup
screen = Screen()
screen.bgcolor("black")
screen.setup(width=800, height=600)
screen.title("Pong")
screen.tracer(False)
# Setup Paddles,Ball and Scoreboard
paddle_right = Paddle(position=(380, 0))
paddle_left = Paddle(position=(-380, 0))
ball = Ball()
scoreboard = Scoreboard()
screen.update()
# Setup listeners
screen.listen()
def listener(fun, key):
if key == "up":
if fun.ycor() < 230:
fun.move_up()
else:
if fun.ycor() > -230:
fun.move_down()
screen.update()
screen.onkeypress(fun=lambda: listener(paddle_left, 'up'), key="w")
screen.onkeypress(fun=lambda: listener(paddle_left, 'down'), key="s")
screen.onkeypress(fun=lambda: listener(paddle_right, 'up'), key="Up")
screen.onkeypress(fun=lambda: listener(paddle_right, 'down'), key="Down")
# Main game Loop
game_not_over = True
while game_not_over:
ball.move()
if ball.ycor() > 285 or ball.ycor() < -280: # When ball hits top or bottom wall
ball.bounce_wall()
elif ball.xcor() > 360 and -PADDLE_SIZE/2 < (ball.ycor() - paddle_right.ycor()) < PADDLE_SIZE/2:
if 0 < ball.heading() < 90 or 270 < ball.heading() < 360: # So that ball changes direction only once
ball.bounce_paddle()
elif ball.xcor() < -360 and -PADDLE_SIZE/2 < (ball.ycor() - paddle_left.ycor()) < PADDLE_SIZE/2:
if 90 < ball.heading() < 270: # So that ball changes direction only once
ball.bounce_paddle()
elif ball.xcor() > 420: # Ball crosses right boundary
ball.reset_position("left")
scoreboard.update_score_left()
elif ball.xcor() < -420: # Ball crosses left boundary
ball.reset_position("right")
scoreboard.update_score_right()
if scoreboard.score_left == 10 or scoreboard.score_right == 10:
scoreboard.final_result()
ball.hideturtle()
game_not_over = False
sleep(0.01)
screen.update()
# Screen does not close automatically
screen.exitonclick()
| {"/main.py": ["/ball.py", "/scoreboard.py"]} |
72,101 | HasratSingh/Pong | refs/heads/master | /ball.py | from turtle import Turtle
from random import randint, choice
class Ball(Turtle):
def __init__(self):
super().__init__()
self.reset_position()
self.seth(randint(0, 360)) # Initially ball can go towards any side.
def move(self):
self.fd(10)
def bounce_wall(self):
current_angle = self.heading()
self.seth(360-current_angle)
def bounce_paddle(self):
current_angle = self.heading()
if 90 < current_angle < 100: # Fixes bug in which case ball keeps bouncing between walls.
self.seth(0)
elif 80 < current_angle < 90: # Fixes bug in which case ball keeps bouncing between walls.
self.seth(180)
else:
self.seth(180-current_angle)
def reset_position(self, side="left"): # If no side is given ball goes towards left
self.penup()
self.shape("circle")
self.color("white")
self.goto(0, 0)
if side == "right":
right_side_range = list(range(0, 90))+list(range(270, 360)) # Angle values for throwing ball to right side
self.seth(choice(right_side_range))
else:
self.seth(randint(90, 270))
| {"/main.py": ["/ball.py", "/scoreboard.py"]} |
72,102 | TavaresFilipe/WallPaperChanger | refs/heads/main | /test/test_wallpaper.py | import unittest
from wallpaperChanger import wallpaper
class TestWallpaper(unittest.TestCase):
def test_get_wallpapers(self):
wallpapers = wallpaper.get_wallpaper_images('day', 'rain')
self.assertEqual(2, len(wallpapers))
wallpapers = wallpaper.get_wallpaper_images('night', 'clear')
self.assertEqual(12, len(wallpapers))
| {"/wallpaperChanger/wallpaper.py": ["/wallpaperChanger/exceptions.py"], "/wallpaperChanger/mainScript.py": ["/wallpaperChanger/settings.py"]} |
72,103 | TavaresFilipe/WallPaperChanger | refs/heads/main | /wallpaperChanger/settings.py | import os
from pathlib import Path
from dotenv import load_dotenv
BASE_DIR = Path(__file__).parent.parent
ASSETS_DIR = BASE_DIR / 'assets'
GENERATED_DIR = BASE_DIR / 'generated'
OK_WALLPAPER = GENERATED_DIR / 'wallpaper.jpeg'
ERROR_WALLPAPER = GENERATED_DIR / 'error.jpeg'
load_dotenv() # load environment variables.
API_KEY = os.getenv("API_KEY", '') # place openweather api key here <------ from https://openweathermap.org/api
CITY = os.getenv("city", '') # write your city name here in lowercase
| {"/wallpaperChanger/wallpaper.py": ["/wallpaperChanger/exceptions.py"], "/wallpaperChanger/mainScript.py": ["/wallpaperChanger/settings.py"]} |
72,104 | TavaresFilipe/WallPaperChanger | refs/heads/main | /wallpaperChanger/exceptions.py |
class PlatformNotSupportedException(Exception):
"""Raised when the platform the script is running in is not supported"""
| {"/wallpaperChanger/wallpaper.py": ["/wallpaperChanger/exceptions.py"], "/wallpaperChanger/mainScript.py": ["/wallpaperChanger/settings.py"]} |
72,105 | TavaresFilipe/WallPaperChanger | refs/heads/main | /wallpaperChanger/wallpaper.py | import platform
import random
import subprocess
from functools import wraps
from pathlib import Path
from typing import Callable, List
from wallpaperChanger import settings
from wallpaperChanger.exceptions import PlatformNotSupportedException
system = platform.system() # https://docs.python.org/3/library/platform.html#platform.system
# Used to identify is a system has support to change wallpaper
# alternative to calling a method and catching the exception
system_supported = True
def _ensure_exists(func: Callable[[Path], None]):
"""Decorator that ensures that the file in the argument exists"""
@wraps(func)
def wrapper(file: Path):
if not file.exists() or not file.is_file():
raise FileNotFoundError(f"'{file}' was not found.")
return func(file)
return wrapper
if system == 'Windows':
import ctypes
@_ensure_exists
def set_wallpaper(file: Path):
"""Change windows wallpaper to the provided file
:raises FileNotFoundError: if the provided file does not exist
"""
ctypes.windll.user32.SystemParametersInfoW(20, 0, str(file), 0)
elif system == 'Linux':
# TODO add support for kde desktops
@_ensure_exists
def set_wallpaper(file: Path):
"""Change linux wallpaper to the provided file
:raises FileNotFoundError: if the provided file does not exist
"""
subprocess.Popen(
f"gsettings set org.gnome.desktop.background picture-uri 'file://{file}'",
shell=True,
)
else:
system_supported = False
def set_wallpaper(file: Path):
"""Placeholder function that throws a PlatformNotSupportedException when called"""
raise PlatformNotSupportedException(f"'{system}' does not currently have support to change wallpaper.")
def get_wallpaper_images(time_of_day: str, weather_condition: str) -> List[Path]:
"""Returns paths of all wallpapers for the select conditions"""
return [
p for p in
settings.ASSETS_DIR.glob(f'./wallpapers/{time_of_day}/{weather_condition}/*')
if p.is_file()
]
def get_random_wallpaper_image(time_of_day: str, weather_condition: str) -> Path:
"""Return a path pointing to random wallpaper pertaining to the conditions"""
return random.choice(get_wallpaper_images(time_of_day, weather_condition))
| {"/wallpaperChanger/wallpaper.py": ["/wallpaperChanger/exceptions.py"], "/wallpaperChanger/mainScript.py": ["/wallpaperChanger/settings.py"]} |
72,106 | TavaresFilipe/WallPaperChanger | refs/heads/main | /wallpaperChanger/mainScript.py | """
daily wallpaper generator: by clarence yang 4/09/20
creates a wallpaper depending on the weather!
image url for weather: customise your own here:
https://www.theweather.com/
you'll need your own api key for openweather:
https://openweathermap.org/api
You can run this script using a batch file and run it periodically (e.g., every hour) through windows task scheduler.
Make sure you edit the run.bat file to include the file location of the batch script.
"""
# imports
import xml.etree.ElementTree as ET
from datetime import datetime
from urllib.request import urlopen, Request
import requests
from PIL import Image, ImageFont, ImageDraw
from wallpaperChanger import wallpaper
from wallpaperChanger.settings import ASSETS_DIR, GENERATED_DIR, OK_WALLPAPER, ERROR_WALLPAPER, API_KEY, CITY
from datetime import datetime
from dateutil import tz
# Step 1: get your custom weather widget from https://www.theweather.com/,
# change the syles to your likings, Recommened transparent background and white foreground
pic_url = "https://www.theweather.com/wimages/foto9a654be7aab09bde5e0fd21539da5f0e.png" # place custom weather url here
# Step 2: get your api key from openweather: https://openweathermap.org/api
CurrentUrl = f"http://api.openweathermap.org/data/2.5/weather?q={CITY}&mode=xml&units=metric&APPID={API_KEY}" # <--- change parameters from settings.py
# Step 3 (optional): choose your styles/themes (see README.md)
# widget location / date text location (x, y) / water mark show / load time show / load time location / font style (see fonts)
currentTheme = "default"
configurations = {
"default": [(3350, 200), ["center", "center"], True, True, ["right", "top"], "light"],
"middle-left": [(3350, 200), ["left", "center"], True, True, ["right", "top"], "light"],
"middle-right": [(3350, 200), ["right", "center"], True, True, ["right", "top"], "light"],
"custom": [(3350, 200), ["left", "bottom"], True, True, ["right", "top"], "Medium"], # change this one to your needs, or define more themes
}
date_text_anchors = { # anchor factors
"top": [6, 5.6], # y
"bottom": [1.4, 1.4], # y
"center": [2, 2], # x or y
"right": [1.07, 1.055], # x
"left": [12, 12], # x
}
# load fonts
font = ImageFont.truetype(str(ASSETS_DIR / "fonts/Montserrat/Montserrat-{}.ttf").format(configurations[currentTheme][5]), 120)
font2 = ImageFont.truetype(str(ASSETS_DIR / "fonts/Montserrat/Montserrat-{}.ttf").format(configurations[currentTheme][5]), 50)
font3 = ImageFont.truetype(str(ASSETS_DIR / "fonts/Montserrat/Montserrat-{}.ttf").format(configurations[currentTheme][5]), 70)
font4 = ImageFont.truetype(str(ASSETS_DIR / "fonts/Montserrat/Montserrat-{}.ttf").format(configurations[currentTheme][5]), 30)
# weather data: work on this <-- add temperature functions
City = ""
# temp = [] #current, min, max
# clouds = ""
# weather = ""
weather_ID = 0
# image brightness
brightness = 0.4
def main(): # main function
# get api: get wallpaper, edit texts
global brightness, weather_ID
try:
# getting our weather data
sunrise = 6
sunset = 18
response = requests.get(CurrentUrl) # first get current weather
with (GENERATED_DIR / 'feed.xml').open('wb') as file:
file.write(
response.content) # write weather data to feed.xml <-- this will be automatically created if it doesnt exist.
tree = ET.parse(GENERATED_DIR / 'feed.xml')
root = tree.getroot()
for child in root:
if child.tag == "weather":
weather_ID = child.attrib[
'number'] # weather ID, the weather condition is stored in a unique ID:
# https://openweathermap.org/weather-conditions
if child.tag == "city": # get sunrise and sunset times
for item in child:
if item.tag == "sun":
sunrise = datetime.strptime(item.attrib['rise'], '%Y-%m-%dT%H:%M:%S')
sunset = datetime.strptime(item.attrib['set'], '%Y-%m-%dT%H:%M:%S')
# getting time
hour = getHour()
# sunrise and sunset are in utc
from_zone = tz.tzutc()
to_zone = tz.tzlocal()
sunrise = sunrise.replace(tzinfo=from_zone)
sunset = sunset.replace(tzinfo=from_zone)
sunrise = sunrise.astimezone(to_zone)
sunset = sunset.astimezone(to_zone)
if hour < sunrise.hour or hour > sunset.hour: # change this to find a sun rise sun set api
# night
dayState = "night"
brightness = 0.4
print("is day: false: {}".format(sunrise))
else:
brightness = 0.7
dayState = "day"
print("is day: true")
weather_code = "" # current weather
# checking the type of weather: obviously you could go deeper and have more images,
# see: https://openweathermap.org/weather-conditions for modifications add other weather codes if you want.
print(weather_ID)
if 300 <= int(weather_ID) < 623:
# rain or snow, idk, just put it as rain
weather_code = "rain"
elif 700 < int(weather_ID) < 782:
# fog or atmosphere
weather_code = "mist"
elif int(weather_ID) >= 800:
weather_code = "clear"
# clear
elif 200 <= int(weather_ID) <= 232:
# thunder
weather_code = "thunder"
createWallpaper(dayState, weather_code) # create the wallpaper
except requests.ConnectionError:
# inform them of the specific error here (based off the error code)
getFailed()
except Exception as e:
print(e)
getFailed()
# failed, see which type of fail it is
def getFailed():
try:
img = Image.open(ERROR_WALLPAPER)
img = img.point(lambda p: p * brightness) # set brightness of the error wallpaper.
draw = ImageDraw.Draw(img)
now = datetime.now()
W, H = img.size
# positioning date time text
w, h = draw.textsize(now.strftime("%A"), font=font)
draw.text(((W - w) / 2, (H - h) / 2), now.strftime("%A"), (255, 255, 255),
font=font) # day text: what day it is
w, h = draw.textsize(now.strftime("%B") + " " + str(now.day) + " " + str(now.year), font=font2)
draw.text(((W - w) / 2, (H - h) / 2 + 100), now.strftime("%B") + " " + str(now.day) + " " + str(now.year),
(255, 255, 255), font=font2) # date text: the date
# Bottom right.
draw.text((3200, 2000), "Smart Wallpaper", (255, 255, 255), font=font3)
draw.text((3280, 2100), "by Clarence Yang", (255, 255, 255), font=font2)
img.save(ERROR_WALLPAPER)
except Exception as e: # the above code failed: perhaps the error.jpeg doesn't exist.
print(e) # debug
w, h = 3936, 2424
img = Image.new("RGB", (w, h))
now = datetime.now()
img1 = ImageDraw.Draw(img)
img1.rectangle([(0, 0), img.size], fill=(102, 102, 102)) # draw the background as a plain colour
W, H = img.size
# positioning date time text
w, h = img1.textsize(now.strftime("%A"), font=font)
img1.text(((W - w) / 2, (H - h) / 2), now.strftime("%A"), (255, 255, 255), font=font)
w, h = img1.textsize(now.strftime("%B") + " " + str(now.day) + " " + str(now.year), font=font2)
img1.text(((W - w) / 2, (H - h) / 2 + 100), now.strftime("%B") + " " + str(now.day) + " " + str(now.year),
(255, 255, 255), font=font2) # date text
# bottom right
img1.text((3200, 2000), "Smart Wallpaper", (255, 255, 255), font=font3)
img1.text((3280, 2100), "by Clarence Yang", (255, 255, 255), font=font2)
img.save(ERROR_WALLPAPER)
wallpaper.set_wallpaper(ERROR_WALLPAPER)
# returns current hour
def getHour():
return datetime.now().hour
def createWallpaper(daystate, WeatherCode): # creates wallpaper: clean code?
print(WeatherCode)
# if it is day
chosen_image = wallpaper.get_random_wallpaper_image(daystate, WeatherCode)
img = Image.open(chosen_image) # open image
img = img.point(lambda
p: p * brightness) # change image brightness, we don't want the brightness of the background
# to cancel out the white text.
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.3'}
im1 = Image.open(urlopen(Request(url=pic_url, headers=headers))) # get the weather widget
#select layout
# resizing and positioning the weather widget
baseheight = 600
hpercent = (baseheight / float(im1.size[1]))
wsize = int((float(im1.size[0]) * float(hpercent)))
im1 = im1.resize((wsize, baseheight))
img.paste(im1, (configurations[currentTheme][0]), im1) # widget location
# get current date and time.
draw = ImageDraw.Draw(img)
now = datetime.now()
# draw the day and date
W, H = img.size
w, h = draw.textsize(now.strftime("%A"), font=font)
draw.text(((W - w) / date_text_anchors[configurations[currentTheme][1][0]][0], (H - h) / date_text_anchors[configurations[currentTheme][1][1]][0]),
now.strftime("%A"), (255, 255, 255), font=font) # draw the day text
# draw the date: month day year
w, h = draw.textsize(now.strftime("%B") + " " + str(now.day) + " " + str(now.year), font=font2)
draw.text(((W - w) / date_text_anchors[configurations[currentTheme][1][0]][1], (H - h) / date_text_anchors[configurations[currentTheme][1][1]][1] + 100),
now.strftime("%B") + " " + str(now.day) + " " + str(now.year), (255, 255, 255), font=font2)
if (configurations[currentTheme][2]):
# bottom left add signature: you can change this if you want
draw.text((3300, 2000), "Smart Wallpaper", (255, 255, 255),font=font2)
draw.text((3300, 2060), "by Clarence Yang", (255, 255, 255), font=font4)
if (configurations[currentTheme][3]):
# the compile time text
w, h = draw.textsize("Updated: {}".format(now.strftime("%Y-%m-%d %H:%M:%S")), font=font4)
draw.text(((W - w) / date_text_anchors[configurations[currentTheme][4][0]][0] + 40, (H - h) / date_text_anchors[configurations[currentTheme][4][1]][0] + 450),
"Updated: {}".format(now.strftime("%Y-%m-%d %H:%M:%S")), (255, 255, 255), font=font4) # draw the day text
# save image and set it as the current wallpaper
img.save(OK_WALLPAPER)
wallpaper.set_wallpaper(OK_WALLPAPER)
if __name__ == '__main__':
# create required directories
GENERATED_DIR.mkdir(parents=True, exist_ok=True)
main()
| {"/wallpaperChanger/wallpaper.py": ["/wallpaperChanger/exceptions.py"], "/wallpaperChanger/mainScript.py": ["/wallpaperChanger/settings.py"]} |
72,108 | Skaty/orbital | refs/heads/develop | /miscellaneous/views.py | from django.contrib.auth.models import User
from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect
from django.views.generic import CreateView
from django.views.generic.base import TemplateView
from miscellaneous.forms import RegistrationForm
class HomepageView(TemplateView):
template_name = 'miscellaneous/index.html'
def get(self, request, *args, **kwargs):
if request.user.is_authenticated():
return redirect('projects:project-list')
return super(HomepageView, self).get(request, *args, **kwargs)
class RegistrationView(CreateView):
model = User
form_class = RegistrationForm
template_name = 'miscellaneous/registration_form.html'
success_url = reverse_lazy('projects:project-list')
def form_valid(self, form):
self.object = User.objects.create_user(form.instance.username, form.instance.email, form.instance.password,
first_name=form.instance.first_name, last_name=form.instance.last_name)
return HttpResponseRedirect(self.get_success_url()) | {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,109 | Skaty/orbital | refs/heads/develop | /miscellaneous/urls.py | from django.conf.urls import url, include
from miscellaneous.views import RegistrationView
urlpatterns = [
url(r'^register/$', RegistrationView.as_view(), name='register'),
]
| {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,110 | Skaty/orbital | refs/heads/develop | /miscellaneous/apps.py | from django.apps import AppConfig
class MiscellaneousConfig(AppConfig):
name = 'miscellaneous'
def ready(self):
import miscellaneous.signals | {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,111 | Skaty/orbital | refs/heads/develop | /projects/templatetags/addcss.py | from django import template
from django.forms import fields
register = template.Library()
@register.filter(name='addcss')
def addcss(field, css):
attributes = {'class': css}
if isinstance(field.field, fields.DateTimeField):
attributes['class'] += ' bs-datetime'
return field.as_widget(attrs=attributes) | {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,112 | Skaty/orbital | refs/heads/develop | /miscellaneous/templatetags/custom_filters.py | import bleach
from django import template
from django.conf import settings
from django.forms import fields
register = template.Library()
@register.filter()
def bleach_sanitize(value):
return bleach.clean(value, tags=settings.BLEACH_ALLOWED_TAGS, attributes=settings.BLEACH_ALLOWED_ATTRIBUTES) | {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,113 | Skaty/orbital | refs/heads/develop | /targets/views.py | import inspect
from django.contrib import messages
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.views.generic import View, CreateView, DeleteView, UpdateView
from projects.models import Project
from targets.models import Target, Goal, Milestone, AbstractTarget, TargetAssignment
@method_decorator(login_required, name='dispatch')
class CompleteAchievementView(View):
type = None
object = None
def post(self, request, *args, **kwargs):
if not inspect.isclass(self.type) or not issubclass(self.type, AbstractTarget):
print(kwargs)
return redirect('/')
try:
self.object = self.type.objects.get(pk=self.kwargs.get('pk', None))
except ObjectDoesNotExist:
messages.error(request, 'Sorry, we are unable to process your request at the moment!')
return redirect('/')
if hasattr(self.object, 'assigned_to'):
if request.user not in self.object.assigned_to.all():
messages.error(request, 'You are not authorised to perform this action!')
return redirect('/')
assignee_metadata = self.object.targetassignment_set.get(assignee=request.user)
assignee_metadata.marked_completed_on = timezone.now()
assignee_metadata.save()
else:
if not self.object.has_permission(request.user):
messages.error(request, 'You are not authorised to perform this action!')
return redirect('/')
self.object.completed_on = timezone.now()
self.object.save()
messages.info(request, 'You have marked {} as completed'.format(self.object))
return redirect('projects:project-detail', pk=self.kwargs.get('project_pk'))
class TargetGoalCreateView(CreateView):
template_name_suffix = '_group_create_form'
model = Target
fields = ['name', 'milestone', 'description', 'assigned_to', 'deadline']
success_url = reverse_lazy('projects:project-list')
def dispatch(self, request, *args, **kwargs):
self.project_pk = self.kwargs.get('project_pk')
try:
self.projectgroup = request.user.projectgroup_set.get(project__pk=self.project_pk)
except ObjectDoesNotExist:
return redirect('/')
self.success_url = reverse_lazy('projects:project-detail',kwargs={'pk': self.project_pk})
return super(TargetGoalCreateView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
"""
Adds projectgroup to template context
"""
kwargs['projectgroup'] = self.projectgroup
return super(TargetGoalCreateView, self).get_context_data(**kwargs)
def get_form(self, form_class=None):
form = super(TargetGoalCreateView, self).get_form(form_class)
form.fields['milestone'].queryset = Milestone.objects.filter(project__pk=self.project_pk)
form.fields['assigned_to'].queryset = self.projectgroup.members.all()
return form
def form_valid(self, form):
form.instance.group = self.projectgroup
form.instance.created_by = self.request.user
if 'assigned_to' in form.cleaned_data:
self.object = form.save(commit=False)
self.object.save()
for assigned_user in form.cleaned_data['assigned_to']:
relation, is_created = TargetAssignment.objects.get_or_create(
assignee=assigned_user,
target=self.object
)
del form.cleaned_data['assigned_to']
form.save_m2m()
return HttpResponseRedirect(self.get_success_url())
return super(TargetGoalCreateView, self).form_valid(form)
class BaseTargetCreateView(CreateView):
template_name_suffix = '_form'
fields = ['name', 'description', 'deadline']
success_url = ''
def dispatch(self, request, *args, **kwargs):
project_pk = self.kwargs.get('project_pk')
try:
self.project = Project.objects.get(id=project_pk)
if request.user not in self.project.facilitators.all():
messages.error(request, 'You are not authorised to perform this action!')
return redirect('/')
except ObjectDoesNotExist:
return redirect('/')
self.success_url = reverse_lazy('projects:project-detail', kwargs={'pk': self.project.pk})
return super(BaseTargetCreateView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
"""
Adds project instance to template context
"""
kwargs['project'] = self.project
return super(BaseTargetCreateView, self).get_context_data(**kwargs)
def form_valid(self, form):
form.instance.project = self.project
form.instance.created_by = self.request.user
return super(BaseTargetCreateView, self).form_valid(form)
@method_decorator(login_required, name='dispatch')
class GoalCreateView(BaseTargetCreateView):
model = Goal
class GoalUpdateView(UpdateView):
model = Goal
template_name_suffix = '_form'
fields = ['name', 'description', 'deadline']
def dispatch(self, request, *args, **kwargs):
project_pk = self.kwargs.get('project_pk')
try:
self.project = Project.objects.get(pk=project_pk)
if request.user not in self.project.facilitators.all():
messages.error(request, 'You are not authorised to perform this action!')
return redirect('/')
except ObjectDoesNotExist:
return redirect('/')
self.success_url = reverse_lazy('projects:project-detail', kwargs={'pk': self.project.pk})
return super(GoalUpdateView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
"""
Adds project instance to template context
"""
kwargs['project'] = self.project
return super(GoalUpdateView, self).get_context_data(**kwargs)
def form_valid(self, form):
form.instance.project = self.project
form.instance.created_by = self.request.user
messages.success(self.request, 'Goal for {project} has been successfuly modified!'.format(project=self.project))
return super(GoalUpdateView, self).form_valid(form)
class TargetDeleteView(DeleteView):
model = Target
success_url = ''
def dispatch(self, request, *args, **kwargs):
self.object = self.get_object()
self.success_url = reverse_lazy('projects:project-detail', kwargs={'pk': self.object.group.project.pk})
if self.object.created_by != request.user:
messages.error(request, 'You do not have permission to delete this target!')
return HttpResponseRedirect(self.success_url)
return super(TargetDeleteView, self).dispatch(request, *args, **kwargs)
@method_decorator(login_required, name='dispatch')
class MilestoneCreateView(BaseTargetCreateView):
model = Milestone
@method_decorator(login_required, name='dispatch')
class MilestoneUpdateView(UpdateView):
model = Milestone
template_name_suffix = '_form'
fields = ['name', 'description', 'deadline']
def dispatch(self, request, *args, **kwargs):
project_pk = self.kwargs.get('project_pk')
try:
self.project = Project.objects.get(pk=project_pk)
if self.project.facilitators.filter(pk=request.user.pk).count() <= 0:
messages.error(request, 'You are not authorised to perform this action!')
return redirect('/')
except ObjectDoesNotExist:
return redirect('/')
self.success_url = reverse_lazy('projects:project-detail', kwargs={'pk': self.project.pk})
return super(MilestoneUpdateView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
"""
Adds project instance to template context
"""
kwargs['project'] = self.project
return super(MilestoneUpdateView, self).get_context_data(**kwargs)
def form_valid(self, form):
form.instance.project = self.project
form.instance.created_by = self.request.user
messages.success(self.request, 'Milestone for {project} has been successfuly modified!'.format(project=self.project))
return super(MilestoneUpdateView, self).form_valid(form)
class MilestoneDeleteView(DeleteView):
model = Milestone
success_url = ''
def dispatch(self, request, *args, **kwargs):
self.object = self.get_object()
self.success_url = reverse_lazy('projects:project-detail', kwargs={'pk': self.object.project.pk})
if self.object.project.facilitators.filter(pk=request.user.pk).count() <= 0:
messages.error(request, 'You do not have permission to delete this target!')
return HttpResponseRedirect(self.success_url)
return super(MilestoneDeleteView, self).dispatch(request, *args, **kwargs) | {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,114 | Skaty/orbital | refs/heads/develop | /profiles/models.py | from django.db import models
from django.conf import settings
from pytz import common_timezones
# Create your models here.
class Preferences(models.Model):
TZ_CHOICES = [(x, x.replace('_', ' ')) for x in common_timezones]
user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key=True, on_delete=models.CASCADE)
timezone = models.CharField(
max_length=255,
choices=TZ_CHOICES,
default='UTC'
) | {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,115 | Skaty/orbital | refs/heads/develop | /projection/urls.py | """projection URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
from miscellaneous.views import HomepageView
urlpatterns = [
url(r'^$', HomepageView.as_view(), name='homepage'),
url(r'^sso/', include('social.apps.django_app.urls', namespace='sso')),
url(r'^admin/', admin.site.urls),
url(r'^projects/', include('projects.urls', namespace='projects')),
url(r'^achievements/', include('targets.urls', namespace='achievements')),
url(r'^auth/', include('django.contrib.auth.urls', namespace='authentication')),
url(r'^system/', include('miscellaneous.urls', namespace='system')),
url(r'^profiles/', include('profiles.urls', namespace='profiles')),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^api/', include([
url('^projects/', include('projects.api.urls', namespace='projects_api')),
url('^achievements/', include('targets.api.urls', namespace='achievements_api')),
])),
url(r'^messaging/', include('postman.urls', namespace='postman')),
]
| {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,116 | Skaty/orbital | refs/heads/develop | /projection/middleware.py | import pytz
from django.utils import timezone
class TimezoneMiddleware(object):
def process_request(self, request):
if request.user and hasattr(request.user, 'preferences'):
tzname = request.user.preferences.timezone
timezone.activate(pytz.timezone(tzname))
else:
timezone.deactivate() | {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,117 | Skaty/orbital | refs/heads/develop | /projects/api/serializers.py | from rest_framework import serializers
from projects.models import *
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = ('id', 'created_on', 'ends_on', 'projectgroup_set')
class ProjectGroupSerializer(serializers.ModelSerializer):
class Meta:
model = ProjectGroup
fields = ('name', 'members', 'project') | {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,118 | Skaty/orbital | refs/heads/develop | /projects/admin.py | from django.contrib import admin
from projects.models import Project, ProjectGroup
from targets.admin import TargetInlineAdmin, GoalInlineAdmin, MilestoneInlineAdmin
class ProjectGroupInlineAdmin(admin.TabularInline):
model = ProjectGroup
@admin.register(Project)
class ProjectModelAdmin(admin.ModelAdmin):
model = Project
inlines = [
GoalInlineAdmin,
MilestoneInlineAdmin,
ProjectGroupInlineAdmin
]
@admin.register(ProjectGroup)
class ProjectGroupModelAdmin(admin.ModelAdmin):
model = ProjectGroup
inlines = [
TargetInlineAdmin
]
| {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,119 | Skaty/orbital | refs/heads/develop | /projects/views.py | from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect
from django.utils.decorators import method_decorator
from django.views.generic import CreateView, ListView, DetailView, UpdateView, DeleteView
from projects.models import Project, ProjectGroup
from targets.models import Target, TargetAssignment
@method_decorator(login_required, name='dispatch')
class ProjectListView(ListView):
model = Project
@method_decorator(login_required, name='dispatch')
class ProjectCreateView(CreateView):
model = Project
fields = ['name', 'facilitators', 'ends_on']
success_url = reverse_lazy('projects:project-list')
def get_form(self, form_class=None):
form = super(ProjectCreateView, self).get_form(form_class)
form.initial['facilitators'] = [self.request.user]
return form
def form_valid(self, form):
self.object = form.save()
if self.object.facilitators.filter(pk=self.request.user.pk).count() <= 0:
self.object.facilitators.add(self.request.user)
return HttpResponseRedirect(reverse_lazy('projects:project-detail', kwargs={'pk': self.object.pk}))
@method_decorator(login_required, name='dispatch')
class ProjectDetailView(DetailView):
model = Project
def get(self, request, *args, **kwargs):
self.object = self.get_object()
context = self.get_context_data(object=self.object)
if not (context.get('is_facilitator') or context.get('is_member')):
messages.error(request, "You are not a member or facilitator of this project!")
return redirect('/')
return self.render_to_response(context)
def get_context_data(self, **kwargs):
kwargs['is_facilitator'] = self.request.user in self.object.facilitators.all()
kwargs['is_member'] = (self.request.user.projectgroup_set.filter(project=self.object).count() > 0)
milestones_list = self.object.milestone_set.filter(project=self.object)
kwargs['milestones'] = []
if kwargs['is_member']:
kwargs['projectgroup'] = self.request.user.projectgroup_set.get(project=self.object)
incomplete_tasks = TargetAssignment.objects.filter(assignee=self.request.user,
marked_completed_on__isnull=True,
target__group=kwargs['projectgroup'])
kwargs['incomplete_tasks'] = [x.target for x in incomplete_tasks]
for milestone in milestones_list:
completed_tasks = Target.objects.filter(group=kwargs['projectgroup'], completed_on__isnull=False,
milestone=milestone).count()
total_tasks = Target.objects.filter(group=kwargs['projectgroup'], milestone=milestone).count()
kwargs['milestones'] += [{'meta': milestone, 'tasks_completed': completed_tasks,
'total_tasks': total_tasks}]
elif kwargs['is_facilitator']:
kwargs['projectgroups'] = [{'meta': x} for x in self.object.projectgroup_set.all()]
for milestone in milestones_list:
group_completed = 0
group_total = len(kwargs['projectgroups'])
for idx, group in enumerate(kwargs['projectgroups']):
completed_tasks = Target.objects.filter(group_id=group['meta'], completed_on__isnull=False,
milestone=milestone).count()
total_tasks = Target.objects.filter(group_id=group['meta'], milestone=milestone).count()
milestone_obj = {'name': milestone.name, 'completed_tasks': completed_tasks, 'total': total_tasks}
if total_tasks != 0 and completed_tasks == total_tasks:
group_completed += 1
milestone_obj['is_completed'] = True
else:
milestone_obj['is_completed'] = False
kwargs['projectgroups'][idx].setdefault('milestones', []).append(milestone_obj)
kwargs['milestones'] += [{'meta': milestone, 'tasks_completed': group_completed,
'total_tasks': group_total}]
return super(ProjectDetailView, self).get_context_data(**kwargs)
@method_decorator(login_required, name='dispatch')
class ProjectGroupCreateView(CreateView):
model = ProjectGroup
fields = ['name', 'members']
def dispatch(self, request, *args, **kwargs):
project_pk = self.kwargs.get('project_pk')
try:
self.project = Project.objects.get(pk=project_pk)
if request.user not in self.project.facilitators.all():
messages.error(request, 'You are not authorised to perform this action!')
return redirect('/')
except ObjectDoesNotExist:
return redirect('/')
self.success_url = reverse_lazy('projects:project-detail', kwargs={'pk': self.project.pk})
return super(ProjectGroupCreateView, self).dispatch(request, *args, **kwargs)
def get_form(self, form_class=None):
form = super(ProjectGroupCreateView, self).get_form(form_class)
form.fields['members'].queryset = User.objects.exclude(project__pk=self.project.pk)
return form
def form_valid(self, form):
form.instance.project = self.project
return super(ProjectGroupCreateView, self).form_valid(form)
@method_decorator(login_required, name='dispatch')
class ProjectGroupUpdateView(UpdateView):
model = ProjectGroup
fields = ['name', 'members']
def dispatch(self, request, *args, **kwargs):
project_pk = self.kwargs.get('project_pk')
try:
self.project = Project.objects.get(pk=project_pk)
if self.project.facilitators.filter(pk=request.user.pk).count() <= 0:
messages.error(request, 'You are not authorised to perform this action!')
return redirect('/')
except ObjectDoesNotExist:
return redirect('/')
self.success_url = reverse_lazy('projects:project-detail', kwargs={'pk': self.project.pk})
return super(ProjectGroupUpdateView, self).dispatch(request, *args, **kwargs)
@method_decorator(login_required, name='dispatch')
class ProjectGroupDeleteView(DeleteView):
model = ProjectGroup
success_url = ''
def dispatch(self, request, *args, **kwargs):
self.object = self.get_object()
self.success_url = reverse_lazy('projects:project-detail', kwargs={'pk': self.object.project.pk})
if self.object.project.facilitators.filter(pk=request.user.pk).count() <= 0:
messages.error(request, 'You do not have permission to delete this target!')
return HttpResponseRedirect(self.success_url)
return super(ProjectGroupDeleteView, self).dispatch(request, *args, **kwargs)
| {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,120 | Skaty/orbital | refs/heads/develop | /projects/models.py | from django.conf import settings
from django.db import models
from django.utils import timezone
class Project(models.Model):
name = models.CharField(max_length=255)
facilitators = models.ManyToManyField(settings.AUTH_USER_MODEL)
created_on = models.DateTimeField(auto_now_add=True)
ends_on = models.DateTimeField(blank=True, null=True)
def __str__(self):
return self.name
def is_active(self):
"Checks if the project has ended"
return self.ends_on >= timezone.now() if self.ends_on else True
class ProjectGroup(models.Model):
name = models.CharField(max_length=255)
members = models.ManyToManyField(settings.AUTH_USER_MODEL)
project = models.ForeignKey(Project, on_delete=models.CASCADE)
def __str__(self):
return self.name
| {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,121 | Skaty/orbital | refs/heads/develop | /projects/urls.py | from django.conf.urls import url, include
from projects.views import *
urlpatterns = [
url(r'^$', ProjectListView.as_view(), name='project-list'),
url(r'^create/$', ProjectCreateView.as_view(), name='project-create'),
url(r'^(?P<pk>[0-9]+)/$', ProjectDetailView.as_view(), name='project-detail'),
url(r'^(?P<project_pk>[0-9]+)/', include('targets.urls', namespace='achievements')),
url(r'^(?P<project_pk>[0-9]+)/groups/add/$', ProjectGroupCreateView.as_view(), name='group-create'),
url(r'^(?P<project_pk>[0-9]+)/groups/(?P<pk>[0-9]+)/edit/$', ProjectGroupUpdateView.as_view(), name='group-edit'),
url(r'^(?P<project_pk>[0-9]+)/groups/(?P<pk>[0-9]+)/delete/$', ProjectGroupDeleteView.as_view(), name='group-delete')
] | {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,122 | Skaty/orbital | refs/heads/develop | /targets/admin.py | from django.contrib import admin
from targets.models import Goal, Target, Milestone
class GoalInlineAdmin(admin.TabularInline):
model = Goal
class MilestoneInlineAdmin(admin.TabularInline):
model = Milestone
class TargetInlineAdmin(admin.TabularInline):
model = Target | {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,123 | Skaty/orbital | refs/heads/develop | /miscellaneous/forms.py | from django.contrib.auth.models import User
from django import forms
class RegistrationForm(forms.ModelForm):
confirm_password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['first_name', 'last_name', 'username', 'email', 'password', 'confirm_password']
widgets = {
'password': forms.PasswordInput(),
}
def __init__(self, *args, **kwargs):
super(RegistrationForm, self).__init__(*args, **kwargs)
for key in self.fields:
self.fields[key].required = True
def clean(self):
cleaned_data = super(RegistrationForm, self).clean()
password = cleaned_data.get('password')
confirm = cleaned_data.get('confirm_password')
if password != confirm:
msg = "Passwords do not match!"
self.add_error('password', msg)
self.add_error('confirm_password', msg)
return cleaned_data | {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,124 | Skaty/orbital | refs/heads/develop | /projects/api/urls.py | from rest_framework import routers
from projects.api.views import *
router = routers.DefaultRouter()
router.register(r'projects', ProjectViewSet, base_name='projects')
router.register(r'groups', ProjectGroupViewSet, base_name='groups')
urlpatterns = router.urls | {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
72,125 | Skaty/orbital | refs/heads/develop | /targets/urls.py | from django.conf.urls import url, include
from targets.views import *
urlpatterns = [
url(r'^targets/add/$', TargetGoalCreateView.as_view(), name="add-group-target"),
url(r'^targets/(?P<pk>[0-9]+)/delete/$', TargetDeleteView.as_view(), name="delete-group-target"),
url(r'^targets/(?P<pk>[0-9]+)/complete/$', CompleteAchievementView.as_view(type=Target), name="complete-target"),
url(r'^goals/add/$', GoalCreateView.as_view(), name="add-goal"),
url(r'^goals/(?P<pk>[0-9]+)/$', GoalUpdateView.as_view(), name="update-goal"),
url(r'^milestones/add/$', MilestoneCreateView.as_view(), name="add-milestone"),
url(r'^milestones/(?P<pk>[0-9]+)/$', MilestoneUpdateView.as_view(), name="update-milestone"),
url(r'^milestones/(?P<pk>[0-9]+)/delete/$', MilestoneDeleteView.as_view(), name="delete-milestone"),
]
| {"/miscellaneous/views.py": ["/miscellaneous/forms.py"], "/miscellaneous/urls.py": ["/miscellaneous/views.py"], "/miscellaneous/apps.py": ["/miscellaneous/signals.py"], "/targets/views.py": ["/projects/models.py", "/targets/models.py"], "/projection/urls.py": ["/miscellaneous/views.py"], "/projects/api/serializers.py": ["/projects/models.py"], "/projects/admin.py": ["/projects/models.py", "/targets/admin.py"], "/projects/views.py": ["/projects/models.py", "/targets/models.py"], "/projects/urls.py": ["/projects/views.py"], "/targets/admin.py": ["/targets/models.py"], "/projects/api/urls.py": ["/projects/api/views.py"], "/targets/urls.py": ["/targets/views.py"], "/profiles/admin.py": ["/profiles/models.py"], "/projects/api/views.py": ["/projects/models.py", "/projects/api/serializers.py"], "/projects/tests/test_models.py": ["/projects/models.py"], "/projects/tests/__init__.py": ["/projects/tests/test_models.py"], "/miscellaneous/signals.py": ["/profiles/models.py"], "/targets/api/urls.py": ["/targets/api/views.py"], "/targets/signals.py": ["/targets/models.py"], "/targets/api/serializers.py": ["/targets/models.py"], "/profiles/views.py": ["/profiles/models.py"], "/targets/api/views.py": ["/targets/models.py", "/targets/api/serializers.py"], "/profiles/urls.py": ["/profiles/views.py"]} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.