Exemple #1
0
    def get(self):
        verification_code = self.request.get("code")
        args = dict(client_id=Constants.FACEBOOK_APP_ID, redirect_uri=self.request.path_url)
        if self.request.get("code"):
            args["client_secret"] = Constants.FACEBOOK_APP_SECRET
            args["code"] = self.request.get("code")
            response = cgi.parse_qs(urllib.urlopen(
                "https://graph.facebook.com/oauth/access_token?" +
                urllib.urlencode(args)).read())
            access_token = response["access_token"][-1]

            # Download the user profile and cache a local instance of the
            # basic profile info
            profile = json.load(urllib.urlopen(
                "https://graph.facebook.com/me?" +
                urllib.urlencode(dict(access_token=access_token))))
            user = User(key_name=str(profile["id"]), id=str(profile["id"]),
                        name=profile["name"], access_token=access_token,
                        profile_url=profile["link"])
            user.put()
            functions.set_cookie(self.response, "fb_user", str(profile["id"]),
                       expires=time.time() + 30 * 86400)
            self.redirect("/")
        else:
            self.redirect(
                "https://graph.facebook.com/oauth/authorize?" +
                urllib.urlencode(args))
    def home(self, env, params={}):
        if (self.session_id is None):
            return self.redirect_to(env, to='/', params=params)
        print('home')
        # print(self.cookie)
        try:
            user = get_user(name=None, id=self.user_id)
            error = self.sessions[self.session_id].get('error', None)
            if (error is None):
                error_tag = ''
            else:
                font_color = self.sessions[self.session_id].get(
                    'font_color', None)
                self.sessions[self.session_id] = {}
                error_tag = "<font color='{font_color}'>{error}</font>".format(
                    font_color=font_color, error=error)
            with open('../template/home.html', 'r', encoding='utf-8') as fp:
                html = fp.read()
                html = html.replace('{error_tag}', error_tag)
                html = html.replace('{name}', user['name'])
                html = html.replace('{id}', str(user['id']))
                html = html.replace('{points}', str(user['points']))
                html = html.replace('{fee}', str(GAME_CONFIG['fee']))
            body = [html.encode('utf-8')]
        except Exception as e:
            # print(str(e))
            # logging.error(str(e))
            raise (e)
            return self.internal_server_error(env, params)

        status = '200 OK'
        headers = [('Content-Type', 'text/html; charset=utf-8')]
        headers = set_cookie(headers, self.cookie)

        return status, headers, body
    def index(self, env, params={}):
        print('index')
        # print(self.cookie)
        try:
            error = self.sessions[self.session_id].get('error', None)
            if (error is None):
                error_tag = ''
            else:
                font_color = self.sessions[self.session_id].get(
                    'font_color', None)
                self.sessions[self.session_id] = {}

                error_tag = "<font color='{font_color}'>{error}</font>".format(
                    font_color=font_color, error=error)
            with open('../template/index.html', 'r', encoding='utf-8') as fp:
                html = fp.read()
                html = html.replace('{error_tag}', error_tag)
            body = [html.encode('utf-8')]

        except Exception as e:
            # print(str(e))
            # logging.error(str(e))
            raise (e)
            return self.internal_server_error(env, params)

        status = '200 OK'
        headers = [('Content-Type', 'text/html; charset=utf-8')]
        headers = set_cookie(headers, self.cookie)

        return status, headers, body
    def redirect_to(self, env, to, params={}):
        home_url = util.application_uri(env)[:-1]
        redirect_url = home_url + to
        status = '303 See Other'
        headers = [('Content-type', 'text/html'), ('Location', redirect_url)]
        headers = set_cookie(headers, self.cookie)
        body = ["<p>リダイレクト中</p>".encode('utf-8')]

        return status, headers, body
    def signup(self, env, params={}):
        home_url = util.application_uri(env)
        try:
            name = params.get('name', 'guest')
            pwd = params.get('password', 'guest')
            params = {}
            # print("name: {}, pure_pwd: {}".format(name, pwd))

            res = get_user(name=name)
            print('signup_user: '******'error': 'user already exiets',
                    'font_color': 'red'
                }
                redirect_url = home_url

            else:
                if (set_user(name, pwd)):
                    print("ユーザーの作成に成功")
                    error_dict = {
                        'error': 'signup success',
                        'font_color': 'green'
                    }
                    redirect_url = home_url

                else:
                    print("ユーザーの作成に失敗")
                    error_dict = {
                        'error': 'signup failed',
                        'font_color': 'red'
                    }
                    redirect_url = home_url

        except Exception as e:
            # print(str(e))
            # logging.error(str(e))
            raise (e)
            return self.internal_server_error(env, params)

        self.sessions[self.session_id] = error_dict
        status = '303 See Other'
        headers = [('Content-type', 'text/html'), ('Location', redirect_url)]
        headers = set_cookie(headers, self.cookie)
        body = ["<p>リダイレクト中</p>".encode('utf-8')]

        return status, headers, body
    def game(self, env, params={}):
        if (self.session_id is None):
            return self.redirect_to(env, to='/', params=params)
        print('game')
        # print(self.cookie)
        # print(self.user_id)

        user = get_user(name=None, id=self.user_id)

        try:
            game_list = self.sessions[self.session_id].get('game', None)
            game = None if game_list is None else copy.deepcopy(game_list[-1])
            print(game)

            if (game is None):
                if (user['points'] < GAME_CONFIG['fee']):
                    with open('../template/game-result.html', 'r') as fp:
                        html = fp.read()
                        html = html.replace(
                            '{message}', '持ち点がゲーム参加に必要な{}ポイントに足りていません。'.format(
                                GAME_CONFIG['fee']))
                    body = [html.encode('utf-8')]
                    status = '200 OK'
                    headers = [('Content-Type', 'text/html; charset=utf-8')]
                    headers = set_cookie(headers, self.cookie)

                    return status, headers, body

                print('game init')
                update_user_points(user['id'],
                                   user['points'] - GAME_CONFIG['fee'])

                self.sessions[self.session_id]['game'] = []
                game = {
                    'turn': 0,
                    'MAX': random.randint(15, 30),
                    'TURN_MAX': random.randint(3, 6),
                    'count': 0,
                    'turn_count': 0,
                    'my_count': 0,
                    'is_finished': 0
                }

                status = '200 OK'
                headers = [('Content-Type', 'text/html; charset=utf-8')]
                headers = set_cookie(headers, self.cookie)

            elif (game['is_finished'] != 0):
                print('finish')
                my_count = game['my_count']
                if (game['is_finished'] == 1):
                    point = my_count * GAME_CONFIG['mag']
                    message = 'YOU WIN!!\n{}ポイント獲得!!'.format(point)
                    update_user_points(self.user_id, user['points'] + point)
                    user_status = '現在の所有ポイントは{}ポイントです。'.format(
                        str(user['points'] + point))

                elif (game['is_finished'] == -1):
                    message = 'YOU LOSE...'
                    user_status = '現在の所有ポイントは{}ポイントです。'.format(
                        str(user['points']))

                with open('../template/game-result.html', 'r') as fp:
                    html = fp.read()
                    html = html.replace('{message}', message)
                    html = html.replace('{user_status}', user_status)
                body = [html.encode('utf-8')]

                status = '200 OK'
                headers = [('Content-Type', 'text/html; charset=utf-8')]
                headers = set_cookie(headers, self.cookie)

                self.sessions[self.session_id]['game'] = None
                return status, headers, body

            else:
                MAX = game['MAX']
                TURN_MAX = game['TURN_MAX']

                if ('plus' in params.keys()):
                    print('plus')
                    if (game['turn_count'] >= TURN_MAX):
                        return self.redirect_to(env,
                                                to='/home/game',
                                                params=params)

                    game['turn_count'] += 1
                    game['count'] += 1
                    game['my_count'] += 1

                    if (game['count'] >= MAX):
                        game['is_finished'] = -1

                        self.sessions[self.session_id]['game'] += [
                            dict(game.items())
                        ]
                        gamelog = game_log(self.sessions[self.session_id].get(
                            'game', None))

                        return self.redirect_to(env,
                                                to='/home/game',
                                                params=params)

                    else:
                        pass

                elif ('submit' in params.keys()):
                    print('npc')
                    game["turn"] = 1
                    game['turn_count'] = 0

                    if (game['count'] == MAX - 1):
                        game['count'] += 1
                        game['is_finished'] = 1
                        self.sessions[self.session_id]['game'] += [
                            dict(game.items())
                        ]
                        gamelog = game_log(self.sessions[self.session_id].get(
                            'game', None))

                        return self.redirect_to(env,
                                                to='/home/game',
                                                params=params)

                    if (MAX - 1 - game['count'] <= TURN_MAX):
                        while game["count"] < MAX - 1:
                            game['count'] += 1
                            self.sessions[self.session_id]['game'] += [
                                dict(game.items())
                            ]

                    else:
                        add = random.randint(1, TURN_MAX)
                        for _ in range(add - 1):
                            game['count'] += 1
                            self.sessions[self.session_id]['game'] += [
                                dict(game.items())
                            ]
                        game['count'] += 1
                        self.sessions[self.session_id]['game'] += [
                            dict(game.items())
                        ]

                    game['turn'] = -1
                    self.sessions[self.session_id]['game'] += [
                        dict(game.items())
                    ]

                    game["turn"] = 0

                else:
                    print('else')

            print('end: ', end='')

            self.sessions[self.session_id]['game'] += [dict(game.items())]
            gamelog = game_log(self.sessions[self.session_id].get(
                'game', None))

            message = '{}に到達したら負け。<br>1ターンで{}回カウンターを増やせます。'.format(
                game['MAX'], game['TURN_MAX'])
            if (game['turn_count'] == 0):
                input_tag = \
                        """
                        <div class="form_contents">
                        <form method="POST" action='/home/game'>
                            <input class="send_btn" type="submit" id="plus" name="plus" value="+"/>
                        </form>
                        </div>
                        """
            elif (game['turn_count'] >= TURN_MAX):
                input_tag = \
                    """
                    <div class="form_contents">
                    <form method="POST" action='/home/game'>
                        <input class="send_btn" type="submit" id="submit" name="submit" value='ターン終了'/>
                    </form>
                    </div>
                    """
                game['turn_count'] = 0
                game['turn'] = -1
            else:
                input_tag = \
                        """
                        <div class="form_contents" style="width: 50%;">
                        <form method="POST" action='/home/game'>
                            <input class="send_btn" type="submit" id="submit" name="submit" value='ターン終了'/>
                        </form>
                        </div>
                        <div class="form_contents" style="width: 50%;">
                        <form method="POST" action='/home/game'>
                            <input class="send_btn" type="submit" id="plus" name="plus" value="+"/>
                        </form>
                        </div>
                        """

            # print(message)

            with open('../template/game.html', 'r', encoding='utf-8') as fp:
                html = fp.read()
                html = html.replace('{message}', message)
                # html = html.replace('{count}', str(game['count']))
                html = html.replace('{MAX}', str(game['MAX']))
                html = html.replace('{TURN_MAX}', str(game['TURN_MAX']))
                html = html.replace('{input_tag}', input_tag)
                html = html.replace('{log}', str(gamelog))
            body = [html.encode('utf-8')]

            status = '200 OK'
            headers = [('Content-Type', 'text/html; charset=utf-8')]
            headers = set_cookie(headers, self.cookie)

            return status, headers, body

        except Exception as e:
            # print(str(e))
            # logging.error(str(e))
            raise (e)
            return self.internal_server_error(env, params)

        status = '200 OK'
        headers = [('Content-Type', 'text/html; charset=utf-8')]
        headers = set_cookie(headers, self.cookie)

        return status, headers, body
Exemple #7
0
 def get(self):
     functions.set_cookie(self.response, "fb_user", "", expires=time.time() - 86400)
     self.redirect("/")