Exemple #1
0
    def _send_basic_infos(self):
        '''
        Send the basic informations, friends, ...
        '''
        self._send_connected_friends()
        self._send_ship()

        # script
        script = DataBase.get_script(self.username)
        self._send_script(script)
        self.send(Message('sc', None), pickling=True)

        # script status
        script_status = DataBase.get_script_status(self.username)
        self.send(Message('scst', script_status), pickling=True)

        # friend demands
        dfrs = DataBase.get_friend_demands(self.username)

        for sender in dfrs:

            if sender == '':
                continue

            Interaction.send_demand_friend(self.username, sender)
Exemple #2
0
    def demand_friend(self, content):
        '''
        Manage the friend demand
        Content: target username
        '''
        is_error = False

        # check target is not user
        if content == self.username:
            is_error = True

        # check requested user exist
        if not DataBase.is_user(content):
            is_error = True

        # check not already friends
        if content in DataBase.get_friends(self.username):
            is_error = True

        if is_error:
            # send error in friend demand
            self.send(Message('rdfr', False), pickling=True)
            return

        DataBase.add_friend_demand(content, self.username)

        # check if requested user is connected
        if Interaction.is_user(content):
            Interaction.send_demand_friend(content, self.username)

        # send friend demand is ok
        self.send(Message('rdfr', True), pickling=True)
Exemple #3
0
    def set_script_status(self, content):
        '''
        Set the status of the user script.
        '''
        DataBase.set_script_status(self.username, content)

        # send status back to user
        self.send(Message('scst', content), pickling=True)
Exemple #4
0
    def save_script(self, status):
        '''
        Store the script
        '''
        script = self._script_cache
        DataBase.set_script(self.username, script)

        # empty cache
        self._script_cache = []
Exemple #5
0
    def ship_config(self, arr):
        '''
        Store the new ship config of the client,  
        Store the ship status, send it to the client
        '''
        DataBase.set_ship(self.username, arr)
        DataBase.set_ship_status(self.username, 1)

        self.send(Message('shst', 1), pickling=True)
Exemple #6
0
    def _send_ship(self):
        '''
        Send the ship grid and ship status
        '''
        # ship grid
        arr = DataBase.get_ship(self.username)
        self.send(Message('sh', arr), pickling=True)

        # ship status
        self.send(Message('shst', DataBase.get_ship_status(self.username)),
                  pickling=True)
Exemple #7
0
 def commit(self, db: DataBase):
     if db.find_obj(self) is None:
         self.__id = db.save_get_id(self)
     elif self.__is_changed:
         new_name = self.name if self.__new_name is None else self.__new_name
         new_country = self.country if self.__new_country is None else self.__new_country
         db.update(self, Recorder(new_name, new_country))
         self.name, self.country = new_name, new_country
         self.__is_changed = False
     else:
         self.__id = db.get_id_obj(self)
Exemple #8
0
 def commit(self, db: DataBase):
     if db.find_obj(self) is None:
         self.__id = db.save_get_id(self)
     elif self.__is_changed:
         new_name = self.name if self.__new_name is None else self.__new_name
         new_soloists = self.soloists if self.soloists == self.__new_soloists else self.__new_soloists
         db.update(self, Author(new_name, new_soloists))
         self.name, self.soloists = new_name, new_soloists
         self.__is_changed = False
     else:
         self.__id = db.get_id_obj(self)
     self.__new_soloists = []
 def commit(self, db: DataBase):
     if db.find_obj(self) is None:
         self.__id = db.save_get_id(self)
     elif self.__is_changed:
         new_name_song = self.__new_name_song if self.__new_name_song is not None else self.name_song
         new_author = self.__new_author if self.__new_author is not None else self.author
         db.update(self, Song(new_name_song, new_author))
         self.name_song = new_name_song
         self.author = new_author
         self.__is_changed = False
     else:
         self.__id = db.get_id_obj(self)
 def __dict__(self):
     return {
         "name":
         self.name,
         "year":
         self.year,
         "recorder":
         DBRef(collection=DataBase.get_type_collection(self.recorder),
               id=self.recorder.id),
         "types":
         self.types,
         "songs": [
             DBRef(collection=DataBase.get_type_collection(song),
                   id=song.id) for song in self.songs
         ]
     }
 def __dict__(self):
     return {
         "name_song":
         self.name_song,
         "author":
         DBRef(collection=DataBase.get_type_collection(self.author),
               id=self.author.id)
     }
Exemple #12
0
def register(model):
    conn_provider = DataBase.instance_output_db()
    try:
        model_register = ModelRegister(conn_provider, log)

        model_register.register(model)
    finally:
        conn_provider.close_all_holders()
Exemple #13
0
    def send_connection_state(cls, username, state):
        '''
        Send to every friend of user his state: if he's connected.
        '''
        # get friends
        friends = DataBase.get_friends(username)

        for friend in friends:
            if cls.is_user(friend):
                cls.send(friend, Message('frs', [[username, state]]))
Exemple #14
0
    def send_enter_game(self, opp_client, team):
        '''
        Send to client that he's entering in a game.  
        team specify the starting position of the ship.
        '''
        # send script
        script = DataBase.get_script(self.username)
        self._send_script(script)
        self.send(Message('sc', None), pickling=True)

        # send opp ship grid
        arr = DataBase.get_ship(opp_client.username)
        self.send(Message('igsh', arr), pickling=True)

        # send own ship grid
        arr = DataBase.get_ship(self.username)
        self.send(Message('sh', arr), pickling=True)

        # notify in game | opponent username, the position id of the ship
        self.send(Message('ign', [opp_client.username, team]), pickling=True)
 def commit(self, db: DataBase):
     if db.find_obj(self) is None:
         self.__id = db.save_get_id(self)
     elif self.__is_changed:
         new_name = self.__new_name if self.__new_name is not None else self.name
         new_year = self.__new_year if self.__new_year is not None else self.year
         new_recorder = self.__new_recorder if self.__new_recorder is not None else self.recorder
         new_songs = self.songs if self.songs == self.__new_songs else self.__new_songs
         new_types = self.types if self.types == self.__new_types else self.__new_types
         db.update(
             self,
             MediaProduct(new_name, new_types, new_recorder, new_year,
                          new_songs))
         self.name = new_name
         self.year = new_year
         self.recorder = new_recorder
         self.__types = new_types
         self.__songs = new_songs
         self.__is_changed = False
     else:
         self.__id = db.get_id_obj(self)
Exemple #16
0
    def _send_connected_friends(self):
        '''Send the status of each friend of client'''
        friends = []

        # get friends
        username_friends = DataBase.get_friends(self.username)

        for username in username_friends:

            friends.append([username, Interaction.is_user(username)])

        self.send(Message('frs', friends), pickling=True)
Exemple #17
0
    def login(self, content):
        '''
        Log the user in.  
        Content: username, password
        '''
        username, password = content

        # check that the username exists and that the password is correct
        if DataBase.is_user(username):

            if Interaction.is_user(username):
                # can't log in -> already connected
                self.send(Message('rlg', False), pickling=True)
                return

            if DataBase.get_password(username) == password:
                # log in
                self.send(Message('rlg', True), pickling=True)
                self._log_client(username)
                return

        # can't log in
        self.send(Message('rlg', False), pickling=True)
Exemple #18
0
    def response_demand_friend(self, content):
        '''
        Manage the response of a friend demand.
        Content: username, response
        '''
        username, response = content

        is_connected = False  # if sender is connected

        DataBase.remove_friend_demand(self.username, username)

        if response:
            DataBase.set_as_friends(self.username, username)

            # send to new friend that we are connected
            if Interaction.is_user(username):
                is_connected = True
                Interaction.send(username,
                                 Message('frs', [[self.username, True]]))

            # send to client if new friend is connected
            self.send(Message('frs', [[username, is_connected]]),
                      pickling=True)
Exemple #19
0
    def on_disconnect(self, content=None):
        '''
        Executed on disconnection, to have a clean disconnection
        '''
        self.logged = False
        self.print("Disconnected.")

        if self.username is None:
            return

        # inform friends
        Interaction.send_connection_state(self.username, False)

        # remove from Interaction
        Interaction.remove(self.username)

        # if in game -> inform opponent that is leaving
        if not self.game_tag is None:
            Interaction.send(self.opponent, Message('olg', True))

            # count game as a loss
            DataBase.increment_loss(self.username)

        self.username = None
Exemple #20
0
    def profil_demand(self, username):
        '''
        Get the stats of a user,  
        send stats to user
        '''
        wins = DataBase.get_wins(username)
        loss = DataBase.get_loss(username)
        ship = DataBase.get_ship(username)
        friends = DataBase.get_friends(username)
        grid = DataBase.get_ship(username)

        if self.username in friends:
            friends.remove(self.username)

        msg = Message(
            'rpd', {
                'username': username,
                'wins': wins,
                'loss': loss,
                'friends': friends,
                'grid': grid
            })

        self.send(msg, pickling=True)
Exemple #21
0
    def sign_up(self, content):
        '''
        Create a new account.  
        Content: username, password
        '''
        username, password = content

        # try to add the new user
        if DataBase.add_user(username, password):
            # sign up
            self.send(Message('rsg', True), pickling=True)

            self._log_client(username)
        else:
            # can't sign up
            self.send(Message('rsg', False), pickling=True)
Exemple #22
0
    def end_game(cls, tag):
        '''
        End a game, stop udp clients.  
        '''
        user1, user2 = cls.games[tag].keys()

        # update DataBase
        if cls.games[tag][user1] == 'win':
            DataBase.increment_wins(user1)
        else:
            DataBase.increment_loss(user1)

        if cls.games[tag][user2] == 'win':
            DataBase.increment_wins(user2)
        else:
            DataBase.increment_loss(user2)

        # update udp clients
        ip1 = cls.clients[user1].ip
        ip2 = cls.clients[user2].ip

        cls.queue.put(['unlink', ip1, ip2])

        cls.games.pop(tag)
Exemple #23
0
import sys
from multiprocessing import Queue, Process
from tcp.server import Server as TCPServer
from udp.server import Server as UDPServer
from db.db import DataBase
from spec import Spec

queue = Queue()

server_udp = UDPServer()
server_tcp = TCPServer(queue)

DataBase.load()

p = Process(target=server_udp.run, args=[queue])
p.start()


try:
    server_tcp.run()

except KeyboardInterrupt:
    print('\nStore database...\n')
    DataBase.store()
    p.terminate()
Exemple #24
0
 def remove(self, db: DataBase):
     db.remove(self)
Exemple #25
0
 def set_ship_status(self, content):
     '''
     Set the status of the user ship.
     '''
     DataBase.set_ship_status(self.username, content)
Exemple #26
0
import asyncio
from aiohttp import web
import json
from db.db import DataBase

db = DataBase()


async def send(message):
    reader, writer = await asyncio.open_connection('calculator', 8888)
    message_len = len(message)
    writer.write(f'{message_len}\n{message}'.encode())
    data = await reader.read()
    writer.close()
    return data


async def calc(request):
    data = await request.json()
    answer = await send(json.dumps(data))
    answer = answer.decode()
    if answer:
        if answer != 'False':
            expression_id = db.save_result(float(answer))
            return web.json_response({'expression_id': expression_id})
        raise web.HTTPBadRequest()
    raise web.HTTPInternalServerError()


async def result(request):
    data = await request.json()
 def __init__(self, *args, **kwargs):
     super(TestDB, self).__init__(*args, **kwargs)
     self.db = DataBase("test")
class TestDB(unittest.TestCase):
    def __init__(self, *args, **kwargs):
        super(TestDB, self).__init__(*args, **kwargs)
        self.db = DataBase("test")

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.db.db.dropDatabase()

    def test_recorder_new(self):
        atlantic = Recorder("Atlantic", "USA")
        atlantic.commit(self.db)
        self.assertEqual({
            "name": "Atlantic",
            "country": "USA"
        }, atlantic.__dict__())
        self.assertEqual({
            "name": "Atlantic",
            "country": "USA"
        },
                         self.db.db.recorder.find({"name": "Atlantic"},
                                                  {"_id": False})[0])

    def test_update(self):
        expected = Recorder("boss", "huge")
        expected.commit(self.db)
        self.db.update(Recorder("asa", "sos"), expected)
        actual = self.db.db.recorder.find_one({"name": "boss"}, {"_id": False})
        self.assertEqual(expected.__dict__(), actual)

    def test_author(self):
        itmoment = Author("in this moment", "maria brink", "eduard alal")
        itmoment.commit(self.db)
        expected = itmoment.__dict__()
        actual = self.db.db.author.find_one({"name": "in this moment"},
                                            {"_id": False})
        self.assertEqual(expected, actual)
        itmoment.add_soloist("f*g")
        actual = self.db.db.author.find_one({"name": "in this moment"},
                                            {"_id": False})
        expected = itmoment.__dict__()
        self.assertEqual(expected, actual)

    def test_get_id(self):
        a = Recorder("dfv", "dfgfd")
        a.commit(self.db)
        # print(self.db.get_id_obj(a)['_id'])

    def test_song(self):
        linda = Author("linda", "linda")
        linda.commit(self.db)
        vorona = Song("ya vorona", linda)
        vorona.commit(self.db)
        id = self.db.get_id_obj(vorona.author)
        actual = self.db.db.author.find_one({"_id": id})
        vorona.name_song = "i am vorona"
        vorona.commit(self.db)
        # print(actual['name'])

    def test_media(self):
        pass
Exemple #29
0
        else:
            start = self.threadID*distributeNum
            end = start + distributeNum
            logs.debug("start:%d,end:%d",start,end)
            self.startGrabInfo(start,end)

    def run(self):
        logs.debug(self.name + " is running")
        self.entrance()

if __name__ == "__main__":
    threads = []
    #多线程
    config = Config()
    sysConfig = config.GetSysConfigPara()
    logConfig = config.GetLogConfigPara()
    dbConfig = config.GetDBConfigPara()
    logs = LogHandler(logConfig['logname'],logConfig['level'],logConfig['isfile'])
    db = DataBase(dbConfig['db_host'],dbConfig['db_port'],dbConfig['db_user'],dbConfig['db_pass'],dbConfig['db_db'],dbConfig['db_charset'],dbConfig['db_maxoverflow'])
    threads_num = sysConfig['threads_num']
    db.connectDB()
    page = sysConfig['crwaling_page']
    distributeNum = int(page / threads_num)
    failPageCount=[]
    logs.debug("distributeNum:%d",distributeNum)

    interface = Interface()
    interface.gui_arrang()
    tk.mainloop()