def post(self):
        playerId = self.get_argument('playerId')
        logging.info('Handling avatar upload for playerId %s' % playerId)

        file1 = self.request.files['avatar'][0]
        original_fname = file1['filename']

        # TODO: read the binary directly into a PIL.Image
        output_file = open(playerId, 'wb')
        output_file.write(file1['body'])
        output_file.close()

        # Crop/Resize image to 100x100
        img = Image.open(playerId)
        (w, h) = img.size
        d = int(abs(w-h)/2)
        if w > h:
            box = (d, 0, w-d, h)
        else:
            box = (0, d, w, h-d)
        img = img.crop(box)
        img = img.resize((100, 100), Image.ANTIALIAS)
        img = img.convert('RGB')
        img.save('web/static/avatars/' + playerId + '.jpg', "JPEG",
                 quality=95)

        try:
            os.remove(playerId)
        except OSError as e:
            print("Error deleting temporary avatar file: %s - %s."
                  % (e.filename, e.strerror))

        db_manager.save_avatar_info(playerId, True)
        self.finish(json.dumps('file uploaded successfully'))
Esempio n. 2
0
    def post(self):
        playerId = self.get_argument('playerId')
        logging.info('Handling avatar upload for playerId %s' % playerId)

        file1 = self.request.files['avatar'][0]
        original_fname = file1['filename']

        # TODO: read the binary directly into a PIL.Image
        output_file = open(playerId, 'wb')
        output_file.write(file1['body'])
        output_file.close()

        # Crop/Resize image to 100x100
        img = Image.open(playerId)
        (w, h) = img.size
        d = int(abs(w-h)/2)
        if w > h:
            box = (d, 0, w-d, h)
        else:
            box = (0, d, w, h-d)
        img = img.crop(box)
        img = img.resize((100, 100), Image.ANTIALIAS)
        img = img.convert('RGB')
        img.save('web/static/avatars/' + playerId + '.jpg', "JPEG",
                 quality=95)

        try:
            os.remove(playerId)
        except OSError as e:
            print("Error deleting temporary avatar file: %s - %s."
                  % (e.filename, e.strerror))

        db_manager.save_avatar_info(playerId, True)
        self.finish(json.dumps('file uploaded successfully'))
Esempio n. 3
0
    def receiveFromClient(self, client, msgtype, msgid, message):
        logging.debug(msgtype, msgid, message)

        if msgtype == 'SUBMIT_BLACKLIST':
            db_manager.store_blacklist(client.playerId, message['blacklist'],
                                       message['merge'])

        elif msgtype == 'SUBMIT_PRO_RATING':
            time = datetime.datetime.now()
            db_manager.record_pro_rating(message['playerId'],
                                         message['mu'], message['sigma'],
                                         message['displayed'])

        elif msgtype == 'SUBMIT_PRO_RATINGS':
            time = datetime.datetime.now()
            for i in range(len(message['playerIds'])):
                playerId = message['playerIds'][i]
                mu = message['ratings'][i]['mu']
                sigma = message['ratings'][i]['sigma']
                displayed = message['ratings'][i]['displayed']
                db_manager.record_pro_rating(playerId, mu, sigma, displayed)

        elif msgtype == 'QUERY_EXTUSERS':
            out = []
            for c in self.clients:
                out.append({
                    'connId': id(c.conn),
                    'playerId': c.playerId,
                    'playerName': c.playerName,
                    'version': c.version
                })
            self.interface.respondToClient(client, msgtype, msgid,
                                           clientlist=out)

        elif msgtype == 'QUERY_BLACKLIST':
            blist = db_manager.fetch_blacklist(client.playerId)
            self.interface.respondToClient(client, msgtype, msgid,
                                           blacklist=blist)

        elif msgtype == 'QUERY_BLACKLIST_COMMON':
            cbl = db_manager.fetch_blacklist_common(message['percentile'])
            self.interface.respondToClient(client, msgtype, msgid,
                                           common_blacklist=cbl)

        # TODO: clean up this logic
        elif msgtype == 'QUERY_ISO_RATINGS':
            pids = message['playerIds']
            out = []
            for i in range(len(pids)):
                pid = pids[i]
                rating = db_manager.get_rating_by_id(pid)
                if rating is None:
                    # TODO: Ask client for player name, record it.  Either
                    # this person has played no games or we don't have their
                    # playerId-playerName mapped yet.
                    rating = isotropish.new_player_rating()
                    rating = (rating.mu, rating.sigma, 0)
                rating = {
                    'playerId': pid,
                    'mu': rating[0],
                    'sigma': rating[1],
                    'numgames': rating[2]
                }
                out.append(rating)
            self.interface.respondToClient(client, msgtype, msgid, ratings=out)

        elif msgtype == 'QUERY_ISOLEVEL':
            rating = db_manager.get_rating_by_id(message['playerId'])
            if rating is None:
                db_manager.record_player_id(message['playerId'],
                                            message['playerName'])
                rating = db_manager.get_rating(message['playerName'])
                logging.info('Recording new playerInfo: (%s, %s)' %
                             (message['playerId'], message['playerName']))
            if rating is None:
                isolevel = 0
            else:
                (mu, sigma, numgames) = rating
                isolevel = math.floor(mu - 3 * sigma)
            self.interface.respondToClient(client, msgtype, msgid,
                                           isolevel=isolevel)

        elif msgtype == 'QUERY_ISO_TABLE':
            self.interface.respondToClient(client, msgtype, msgid,
                                           isolevel=self.iso_table)

        elif msgtype == 'QUERY_AVATAR_TABLE':
            if self.avatar_table is None:
                self.avatar_table = db_manager.get_all_avatar_info()
            self.interface.respondToClient(client, msgtype, msgid,
                                           available=self.avatar_table)

        elif msgtype == 'QUERY_AVATAR':
            pid = message['playerId']
            if self.avatar_table is None:
                self.avatar_table = db_manager.get_all_avatar_info()
            if not pid in self.avatar_table:
                logging.info('Avatar info not found.  Looking up on '
                             + 'retrobox -- playerId: %s' % pid)
                url = "http://dom.retrobox.eu/avatars/%s.png"
                url = url % message['playerId']
                r = requests.get(url, stream=True)
                available = r.status_code != 404
                if available:
                    logging.info('Writing avatar to file: %s' % pid)

                    # As uploaded
                    with open(pid, 'wb') as f:
                        for chunk in r.iter_content(1024):
                            f.write(chunk)
                        f.flush()
                        f.close()

                    # As uploaded
                    img = Image.open(pid)
                    (w, h) = img.size
                    img = img.resize((100, 100), Image.ANTIALIAS)
                    img = img.convert('RGB')
                    img.save('web/static/avatars/' + pid + '.jpg', "JPEG",
                             quality=95)

                    # As uploaded
                    try:
                        os.remove(pid)
                    except OSError as e:
                        logging.error("Error: %s - %s."
                                      % (e.filename, e.strerror))

                    db_manager.save_avatar_info(pid, True)
                else:
                    db_manager.save_avatar_info(pid, False)
                self.interface.respondToClient(client, msgtype, msgid,
                                               available=available)
            else:
                logging.debug('Avatar info found for %s %s - %s'
                              % (pid, msgid, self.avatar_table[pid]))
                self.interface.respondToClient(
                    client, msgtype, msgid, playerid=pid,
                    available=self.avatar_table[pid])

        elif msgtype == 'QUERY_ASSESSMENT':
            if message['system'] == 'pro':
                r_me = Rating(message['myRating']['mu'],
                              message['myRating']['sigma'])
                r_opp = Rating(message['hisRating']['mu'],
                               message['hisRating']['sigma'])
                wld_delta = {
                    'win': {'score': 1, 'me': {}, 'opp': {}},
                    'draw': {'score': 0, 'me': {}, 'opp': {}},
                    'loss': {'score': -1, 'me': {}, 'opp': {}}
                }
                for key in wld_delta:
                    (x, y) = rate(r_me, r_opp, wld_delta[key]['score'],
                                  goko_env)
                    wld_delta[key]['me']['mu'] = x.mu - r_me.mu
                    wld_delta[key]['me']['sigma'] = x.sigma - r_me.sigma
                    wld_delta[key]['me']['displayed'] = \
                        (x.mu - 2 * x.sigma) - (r_me.mu - 2 * r_me.sigma)
                self.interface.respondToClient(client, msgtype, msgid,
                                               wld_delta=wld_delta)
            else:
                self.interface.respondToClient(client, msgtype, msgid,
                                               error='Unknown rating system')

        else:
            logging.warn("""Received unknown message type %s from client %s
                         """ % (msgtype, client))
            self.interface.respondToClient(client, msgtype, msgid,
                                           response="Unknown message type")
Esempio n. 4
0
    def receiveFromClient(self, client, msgtype, msgid, message):
        if msgtype == 'QUERY_CLIENTLIST':
            self.interface.respondToClient(client, msgtype, msgid,
                                           clientlist=self.clients)

        elif msgtype == 'SUBMIT_BLACKLIST':
            db_manager.store_blacklist(client.playerId, message['blacklist'],
                                       message['merge'])

        elif msgtype == 'QUERY_BLACKLIST':
            blist = db_manager.fetch_blacklist(client.playerId)
            self.interface.respondToClient(client, msgtype, msgid,
                                           blacklist=blist)

        elif msgtype == 'QUERY_BLACKLIST_COMMON':
            cbl = db_manager.fetch_blacklist_common(message['percentile'])
            self.interface.respondToClient(client, msgtype, msgid,
                                           common_blacklist=cbl)

        elif msgtype == 'QUERY_ISOLEVEL':
            rating = db_manager.get_rating_by_id(message['playerId'])
            if rating is None:
                db_manager.record_player_id(message['playerId'],
                                            message['playerName'])
                rating = db_manager.get_rating(message['playerName'])
                logging.info('Recording new playerInfo: (%s, %s)' %
                      (message['playerId'], message['playerName']))
            if rating is None:
                isolevel = 0
            else:
                (mu, sigma, numgames) = rating
                isolevel = math.floor(mu - 3 * sigma)
            self.interface.respondToClient(client, msgtype, msgid,
                                           isolevel=isolevel)

        elif msgtype == 'QUERY_ISO_TABLE':
            self.interface.respondToClient(client, msgtype, msgid,
                                           isolevel=self.iso_table)

        elif msgtype == 'QUERY_AVATAR_TABLE':
            if self.avatar_table is None:
                self.avatar_table = db_manager.get_all_avatar_info()
            self.interface.respondToClient(client, msgtype, msgid,
                                           available=self.avatar_table)

        elif msgtype == 'QUERY_AVATAR':
            pid = message['playerId']
            if self.avatar_table is None:
                self.avatar_table = db_manager.get_all_avatar_info()
            if not pid in self.avatar_table:
                logging.info('Avatar info not found.  Looking up on '
                             + 'retrobox -- playerId: %s' % pid)
                url = "http://dom.retrobox.eu/avatars/%s.png"
                url = url % message['playerId']
                r = requests.get(url, stream=True)
                available = r.status_code != 404
                if available:
                    logging.info('Writing avatar to file: %s' % pid)

                    # As uploaded
                    with open(pid, 'wb') as f:
                        for chunk in r.iter_content(1024):
                            f.write(chunk)
                        f.flush()
                        f.close()

                    # As uploaded
                    img = Image.open(pid)
                    (w, h) = img.size
                    img = img.resize((100, 100), Image.ANTIALIAS)
                    img = img.convert('RGB')
                    img.save('web/static/avatars/' + pid + '.jpg', "JPEG",
                             quality=95)

                    # As uploaded
                    try:
                        os.remove(pid)
                    except OSError as e:
                        print("Error: %s - %s." % (e.filename, e.strerror))

                    db_manager.save_avatar_info(pid, True)
                else:
                    db_manager.save_avatar_info(pid, False)
                self.interface.respondToClient(client, msgtype, msgid,
                                               available=available)
            else:
                logging.debug('Avatar info found for %s %s - %s'
                              % (pid, msgid, self.avatar_table[pid]))
                self.interface.respondToClient(client, msgtype, msgid,
                                               playerid=pid,
                                               available=self.avatar_table[pid])
        else:
            logging.warn("""Received unknown message type %s from client %s
                         """ % (msgtype, client))
            self.interface.respondToClient(client, msgtype, msgid,
                                           response="Unknown message type")
Esempio n. 5
0
    def receiveFromClient(self, client, msgtype, msgid, message):
        logging.debug(msgtype, msgid, message)

        if msgtype == 'SUBMIT_BLACKLIST':
            db_manager.store_blacklist(client.playerId, message['blacklist'],
                                       message['merge'])

        elif msgtype == 'SUBMIT_PRO_RATING':
            time = datetime.datetime.now()
            db_manager.record_pro_rating(message['playerId'], message['mu'],
                                         message['sigma'],
                                         message['displayed'])

        elif msgtype == 'SUBMIT_PRO_RATINGS':
            time = datetime.datetime.now()
            for i in range(len(message['playerIds'])):
                playerId = message['playerIds'][i]
                mu = message['ratings'][i]['mu']
                sigma = message['ratings'][i]['sigma']
                displayed = message['ratings'][i]['displayed']
                db_manager.record_pro_rating(playerId, mu, sigma, displayed)

        elif msgtype == 'QUERY_EXTUSERS':
            out = []
            for c in self.clients:
                out.append({
                    'connId': id(c.conn),
                    'playerId': c.playerId,
                    'playerName': c.playerName,
                    'version': c.version
                })
            self.interface.respondToClient(client,
                                           msgtype,
                                           msgid,
                                           clientlist=out)

        elif msgtype == 'QUERY_BLACKLIST':
            blist = db_manager.fetch_blacklist(client.playerId)
            self.interface.respondToClient(client,
                                           msgtype,
                                           msgid,
                                           blacklist=blist)

        elif msgtype == 'QUERY_BLACKLIST_COMMON':
            cbl = db_manager.fetch_blacklist_common(message['percentile'])
            self.interface.respondToClient(client,
                                           msgtype,
                                           msgid,
                                           common_blacklist=cbl)

        # TODO: clean up this logic
        elif msgtype == 'QUERY_ISO_RATINGS':
            pids = message['playerIds']
            out = []
            for i in range(len(pids)):
                pid = pids[i]
                rating = db_manager.get_rating_by_id(pid)
                if rating is None:
                    # TODO: Ask client for player name, record it.  Either
                    # this person has played no games or we don't have their
                    # playerId-playerName mapped yet.
                    rating = isotropish.new_player_rating()
                    rating = (rating.mu, rating.sigma, 0)
                rating = {
                    'playerId': pid,
                    'mu': rating[0],
                    'sigma': rating[1],
                    'numgames': rating[2]
                }
                out.append(rating)
            self.interface.respondToClient(client, msgtype, msgid, ratings=out)

        elif msgtype == 'QUERY_ISOLEVEL':
            rating = db_manager.get_rating_by_id(message['playerId'])
            if rating is None:
                db_manager.record_player_id(message['playerId'],
                                            message['playerName'])
                rating = db_manager.get_rating(message['playerName'])
                logging.info('Recording new playerInfo: (%s, %s)' %
                             (message['playerId'], message['playerName']))
            if rating is None:
                isolevel = 0
            else:
                (mu, sigma, numgames) = rating
                isolevel = math.floor(mu - 3 * sigma)
            self.interface.respondToClient(client,
                                           msgtype,
                                           msgid,
                                           isolevel=isolevel)

        elif msgtype == 'QUERY_ISO_TABLE':
            self.interface.respondToClient(client,
                                           msgtype,
                                           msgid,
                                           isolevel=self.iso_table)

        elif msgtype == 'QUERY_AVATAR_TABLE':
            if self.avatar_table is None:
                self.avatar_table = db_manager.get_all_avatar_info()
            self.interface.respondToClient(client,
                                           msgtype,
                                           msgid,
                                           available=self.avatar_table)

        elif msgtype == 'QUERY_AVATAR':
            pid = message['playerId']
            if self.avatar_table is None:
                self.avatar_table = db_manager.get_all_avatar_info()
            if not pid in self.avatar_table:
                logging.info('Avatar info not found.  Looking up on ' +
                             'retrobox -- playerId: %s' % pid)
                url = "http://dom.retrobox.eu/avatars/%s.png"
                url = url % message['playerId']
                r = requests.get(url, stream=True)
                available = r.status_code != 404
                if available:
                    logging.info('Writing avatar to file: %s' % pid)

                    # As uploaded
                    with open(pid, 'wb') as f:
                        for chunk in r.iter_content(1024):
                            f.write(chunk)
                        f.flush()
                        f.close()

                    # As uploaded
                    img = Image.open(pid)
                    (w, h) = img.size
                    img = img.resize((100, 100), Image.ANTIALIAS)
                    img = img.convert('RGB')
                    img.save('web/static/avatars/' + pid + '.jpg',
                             "JPEG",
                             quality=95)

                    # As uploaded
                    try:
                        os.remove(pid)
                    except OSError as e:
                        logging.error("Error: %s - %s." %
                                      (e.filename, e.strerror))

                    db_manager.save_avatar_info(pid, True)
                else:
                    db_manager.save_avatar_info(pid, False)
                self.interface.respondToClient(client,
                                               msgtype,
                                               msgid,
                                               available=available)
            else:
                logging.debug('Avatar info found for %s %s - %s' %
                              (pid, msgid, self.avatar_table[pid]))
                self.interface.respondToClient(
                    client,
                    msgtype,
                    msgid,
                    playerid=pid,
                    available=self.avatar_table[pid])

        elif msgtype == 'QUERY_ASSESSMENT':
            if message['system'] == 'pro':
                r_me = Rating(message['myRating']['mu'],
                              message['myRating']['sigma'])
                r_opp = Rating(message['hisRating']['mu'],
                               message['hisRating']['sigma'])
                wld_delta = {
                    'win': {
                        'score': 1,
                        'me': {},
                        'opp': {}
                    },
                    'draw': {
                        'score': 0,
                        'me': {},
                        'opp': {}
                    },
                    'loss': {
                        'score': -1,
                        'me': {},
                        'opp': {}
                    }
                }
                for key in wld_delta:
                    (x, y) = rate(r_me, r_opp, wld_delta[key]['score'],
                                  goko_env)
                    wld_delta[key]['me']['mu'] = x.mu - r_me.mu
                    wld_delta[key]['me']['sigma'] = x.sigma - r_me.sigma
                    wld_delta[key]['me']['displayed'] = \
                        (x.mu - 2 * x.sigma) - (r_me.mu - 2 * r_me.sigma)
                self.interface.respondToClient(client,
                                               msgtype,
                                               msgid,
                                               wld_delta=wld_delta)
            else:
                self.interface.respondToClient(client,
                                               msgtype,
                                               msgid,
                                               error='Unknown rating system')

        else:
            logging.warn("""Received unknown message type %s from client %s
                         """ % (msgtype, client))
            self.interface.respondToClient(client,
                                           msgtype,
                                           msgid,
                                           response="Unknown message type")