Skip to content

Instantly share code, notes, and snippets.

@victorusachev
Created October 9, 2020 15:35
Show Gist options
  • Save victorusachev/631fcef2b8ca2f003c5c6f2aa1e98d08 to your computer and use it in GitHub Desktop.
Save victorusachev/631fcef2b8ca2f003c5c6f2aa1e98d08 to your computer and use it in GitHub Desktop.
import sys
import contextlib
from pathlib import Path
from typing import Any, ClassVar, Dict, Iterable, List, Optional
import requests
class GameApi:
base_url: ClassVar[str] = 'https://www.planitpoker.com/api/'
headers: ClassVar[Dict[str, Any]] = {
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
}
def __init__(self, game_id: int) -> None:
self.game_id = game_id
def __call__(self, endpoint: str, data: Dict[str, Any]) -> Dict[str, Any]:
url = self.base_url + endpoint
resp = requests.post(url, data, headers=self.headers)
assert resp.status_code == 200, resp.text
return resp.json()
def get_stories(self) -> List[Dict[str, Any]]:
endpoint = 'stories/get/'
data = {
'gameId': self.game_id,
'page': 2,
'perPage': 200,
'status': 1,
'sortingKey': 'votingStart',
}
resp = self(endpoint, data)
return resp['stories']
def get_story(self, story_id: int) -> Dict[str, Any]:
endpoint = 'stories/details/'
data = {'storyId': story_id, 'gameId': self.game_id}
return self(endpoint, data)
def vote_text_to_float(vote: str) -> float:
if vote.isdecimal():
return int(vote)
elif vote == '½':
return 0.5
if vote in ('?', 'Coffee'):
return 0.0
else:
raise ValueError(vote)
def calculate_avg_vote(story: Dict[str, Any]) -> float:
votes = [vote_text_to_float(v['valueText']) for v in story['votes']]
avg = round(sum(votes) / max(1, len(votes)), 2)
return avg
@contextlib.contextmanager
def nullcontext(enter_result: Any = None) -> Iterable[Any]:
yield enter_result
def main(game_id: int, path: Optional[Path]) -> None:
api = GameApi(game_id=game_id)
stories_ids: List[int] = [s['id'] for s in api.get_stories()]
if path:
cm = path.open('w')
else:
cm = nullcontext(sys.stdout)
with cm as fp:
for story_id in stories_ids:
story = api.get_story(story_id=story_id)
title = story['title']
avg = calculate_avg_vote(story=story)
fp.writelines(f'{title}; {avg:.2f}\n')
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('game', type=int, help='game id')
parser.add_argument('--path', type=Path, default=None, help='output file')
args = parser.parse_args()
main(game_id=args.game, path=args.path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment