예제 #1
0
파일: frontend.py 프로젝트: cpdef/pymux
    def main(stdscr):
        try:
            # init colors:
            curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_RED)

            # create terminal:
            win = curses.newwin(100, 100, 0, 0)
            master = TerminalContainer(stdscr)

            # bin signals:
            signal(SIGINT, master.signal_handler)
            #signal(SIGTSTP, term.signal_handler)

            # run terminal:
            master.run()
        except Exception as e:
            # close all terminals if there is an bug/error in this program
            try:
                Session.close_all()
            except:
                pass
            raise e

        # close all sessions:
        Session.close_all()
예제 #2
0
def startGame(user, gameid):
    userData = getUserData(user)
    if user:
        session = Session()
        game = session.query(GameModel) \
                .filter(GameModel.id==gameid).first()
        if ((user == game.owner) and (user in game.players)
                and game.status == "new"
                and (len(game.players) == game.nplayers)):
            players = []
            for player in game.players:
                players.append({'name': player.username, 'id': player.id})
                notes = Notes(player, game)
                session.add(notes)
            newgame = Game(players, game.advanced, game.id)
            activePlayer = newgame.getActivePlayer()
            active = session.query(User) \
                    .filter(User.id==activePlayer.id).first()
            game.active = active
            game.status = "running"
            game.game = jsonpickle.encode(newgame)
            session.commit()
            emails = [player.email for player in game.players]
            send_start_game_email(emails, gameid)
        session.close()
    return gameList(userData)
예제 #3
0
def executeAction(method, id, **kwargs):
    session = Session()
    game = session.query(GameModel) \
            .filter(GameModel.id==id).first()
    gm = jsonpickle.decode(game.game)
    error = execute(gm, method, **kwargs)
    if error:
        session.close()
        return error
    else:
        game.game = jsonpickle.encode(gm)
        if gm.status.endOfGame:
            game.status = "finished"
            game.active = None
            emails = [player.email for player in game.players]
            send_end_of_game_email(emails, id)
        else:
            activePlayer = gm.getActivePlayer()
            active = session.query(User) \
                    .filter(User.id==activePlayer.id).first()
            game.active = active
            # removed the condition if the active player is not changed
            # since apparently players do not notice it is still their turn
            # if (active.username != kwargs['name']):
            if True:
                send_notification(active, id)
        session.commit()
        session.close()
        return None
예제 #4
0
def confirm():
    session = Session()
    req = request.get_json()
    user = getUserByToken(req, salt='registration', onlyIfConfirmed=False)
    data = {}
    if user:
        user.confirmed = True
        session.commit()
        data['status'] = 'confirmed'
    else:
        data['status'] = 'not confirmed'
    json_data = json.dumps(data)
    return json_data
예제 #5
0
def changepassword():
    session = Session()
    req = request.get_json()
    user = getUserByToken(req, salt='reset', onlyIfConfirmed=False)
    data = {}
    if not user:
        data['status'] = 'failed'
    else:
        password = req['password']
        user.set_password(password)
        data['status'] = 'changed'
        session.commit()
    json_data = json.dumps(data)
    return json_data
예제 #6
0
def deleteGame(user, gameid):
    userData = getUserData(user)
    if user:
        session = Session()
        game = session.query(GameModel) \
                .filter(GameModel.id==gameid).first()
        if game.owner == user and game.status == "new":
            session.delete(game)
        session.commit()
        session.close()
    return gameList(userData)
예제 #7
0
def requestresetpassword():
    session = Session()
    req = request.get_json()
    email = req['email']
    #password = req['password']
    #username = req['username']
    url = req['url']
    data = {}
    user = Session.query(User).filter_by(email=email).first()
    if not user:
        data['status'] = 'failed'
    else:
        send_reset_email(user, url)
        data['status'] = 'success'
    json_data = json.dumps(data)
    return json_data
예제 #8
0
def createGame(user, nplayers, advanced):
    userData = getUserData(user)
    if user:
        session = Session()
        newgame = GameModel(advanced=advanced, nplayers=nplayers, owner=user)
        newgame.players = [user]
        session.add(newgame)
        session.commit()
        session.close()
    return gameList(userData)
예제 #9
0
def getUserByPassword(req, salt=None, onlyIfConfirmed=True):
    username = None
    if 'username' in req:
        username = req['username']
    password = None
    if 'password' in req:
        password = req['password']
    if username and password:
        session = Session()
        user = Session.query(User).filter_by(username=username).first()
        if (user and user.check_password(password)):
            if (onlyIfConfirmed and not user.confirmed):
                return None
            else:
                return user
        else:
            return None
    else:
        return None
예제 #10
0
def getUserByToken(req, salt=None, onlyIfConfirmed=True):
    token = None
    if 'token' in req:
        token = req['token']
    session = Session()
    user = User.verify_token(token, salt)
    if (onlyIfConfirmed and not (user and user.confirmed)):
        return None
    else:
        return user
예제 #11
0
def getUser(req):
    token = None
    if 'token' in req:
        token = req['token']
    session = Session()
    user = User.verify_token(token)
    if user and user.confirmed:
        return user
    else:
        return None
예제 #12
0
 def verify_token(token, salt=None):
     s = Serializer(current_app.config['SECRET_KEY'])
     """
     print("try: ")
     stoken = s.loads(token)
     user_id = stoken['user_id']
     """
     try:
         user_id = s.loads(token, salt=salt)['user_id']
     except:
         return None
     return Session.query(User).get(user_id)
예제 #13
0
def resetpassword():
    session = Session()
    req = request.get_json()
    user = getUserByToken(req, salt='reset', onlyIfConfirmed=False)
    data = {}
    if user:
        data['status'] = 'reset_password'
        data['token'] = req['token']
    else:
        data['status'] = 'failed'
    json_data = json.dumps(data)
    return json_data
예제 #14
0
파일: frontend.py 프로젝트: cpdef/pymux
    def __init__(self, parent_window, width=None, height=None, top=0, left=0):
        h, w = parent_window.getmaxyx()
        if not width:
            width = w
        if not height:
            height = h - 1
        win = curses.newwin(height, width, top, left)
        win.nodelay(1)

        # set w, h
        self.height, self.width = win.getmaxyx()
        self.width -= 1
        self.height -= 1
        #max is max-1
        self.session = Session(width=self.width, height=self.height)
        self.pid = self.session.pid
        self._window = win

        self.scrollback = 0
        self.last_scrollback = 0
        self.last_scroll_screen = None
예제 #15
0
def login():
    session = Session()
    req = request.get_json()
    user = getUserByPassword(req, salt=None)
    data = {}
    if (user):
        data['status'] = 'authenticated'
        data['idToken'] = user.get_token()
        data['username'] = user.username
    else:
        data['status'] = 'failed'
    json_data = json.dumps(data)
    return json_data
예제 #16
0
def account():
    print("NOW IN  /user/account")
    session = Session()
    req = request.get_json(force=True)
    user = getUserByToken(req, salt=None)
    data = {}
    if (user):
        data['email'] = user.email
        data['status'] = 'success'
    else:
        data['status'] = 'failed'
    json_data = json.dumps(data)
    return json_data
예제 #17
0
def leaveGame(user, gameid):
    userData = getUserData(user)
    if user:
        session = Session()
        game = session.query(GameModel) \
                .filter(GameModel.id==gameid).first()
        if (user != game.owner) and (user
                                     in game.players) and game.status == "new":
            game.players.remove(user)
        session.commit()
        session.close()
    return gameList(userData)
예제 #18
0
def listOfGames():
    session = Session()
    newgames = session.query(GameModel) \
            .filter(GameModel.status=="new").all()
    runninggames = session.query(GameModel) \
            .filter(GameModel.status=="running").all()
    finishedgames = session.query(GameModel) \
            .filter(GameModel.status=="finished").all()
    lst = {}
    lst['new'] = dbToDict(newgames)
    lst['running'] = dbToDict(runninggames)
    lst['finished'] = dbToDict(finishedgames)
    session.close()
    return lst
예제 #19
0
def joinGame(user, gameid):
    userData = getUserData(user)
    if user:
        session = Session()
        game = session.query(GameModel) \
                .filter(GameModel.id==gameid).first()
        if game.status == "new":
            if ((user not in game.players)
                    and (len(game.players) < game.nplayers)):
                game.players.append(user)
                session.commit()
            if len(game.players) == game.nplayers:
                send_ready_game_email(game.owner, gameid)
        session.close()
    return gameList(userData)
예제 #20
0
def getGame(userData=None, id=None):

    session = Session()
    game = session.query(GameModel) \
            .filter(GameModel.id==id).first()
    gm = jsonpickle.decode(game.game)
    chat = game.chat
    if userData is None:
        notesdict = None
    else:
        notes = session.query(Notes) \
            .filter(Notes.game_id==id,
                    Notes.player_id==userData["id"]).first()
        notesdict = notes.dict() if notes else None
    session.commit()
    session.close()
    gm.removeHiddenInfo(userData)
    gamejs_expand = jsonpickle.encode(gm, unpicklable=False)
    return gamejs_expand, chat, notesdict
예제 #21
0
def changeNotes(newnotes, name):
    data = {}
    session = Session()
    user_id = newnotes['player_id']
    player = session.query(User) \
            .filter(User.id==user_id).first()
    if (player is None) or (player.username != name):
        data['error'] = 'user error'
        return data
    id = newnotes['id']
    notes = session.query(Notes) \
            .filter(Notes.id==id).first()
    if notes is None:
        data['error'] = 'notes error'
        return data
    notes.notes = newnotes['notes']
    session.commit()
    session.close()
    return None
예제 #22
0
def addMainPost(post, name, timestamp=None):
    # add a new post to the main chat
    # if timestamp is not provided, save the current time
    # as UTC, and in iso format for easy handling on frontend
    session = Session()
    chatmodel = session.query(ChatModel).first()
    chat = jsonpickle.decode(chatmodel.chat)
    if (chat is None):
        chat = []
    if timestamp is None:
        now = datetime.datetime.now(tz=datetime.timezone.utc)
        timestamp = now.isoformat()
    fullPost = [name, post, timestamp]
    chat.append(fullPost)
    chatmodel.chat = jsonpickle.encode(chat)
    session.commit()
    session.close()
    return None
예제 #23
0
def signup():
    session = Session()
    req = request.get_json()
    email = req['email']
    password = req['password']
    username = req['username']
    url = req['url']
    data = {}
    if exists_email(email):
        data['status'] = 'email_exists'
    elif exists_username(username):
        data['status'] = 'username_exists'
    else:
        user = User(username=username, email=email, password=password)
        session.add(user)
        # now first commit before sending email, else the new user has no id
        # yet...
        session.commit()
        send_registration_email(user, url)
        data['status'] = 'success'
    json_data = json.dumps(data)
    return json_data
예제 #24
0
def exists_email(email):
    user = Session.query(User).filter_by(email=email).first()
    return user
예제 #25
0
파일: frontend.py 프로젝트: cpdef/pymux
class Terminal(object):
    keymap = {
        'SIGTSTP': b'\x1a',
        curses.KEY_BACKSPACE: b'\x08',
        curses.KEY_CANCEL: b'\x03',
        curses.KEY_CLEAR: b'\x0c',
        curses.KEY_DC: b'~4',
        curses.KEY_DOWN: b'~B',
        curses.KEY_END: b'~F',
        curses.KEY_F1: b'~a',
        curses.KEY_F2: b'~b',
        curses.KEY_F3: b'~c',
        curses.KEY_F4: b'~d',
        curses.KEY_F5: b'~e',
        curses.KEY_F6: b'~f',
        curses.KEY_F7: b'~g',
        curses.KEY_F8: b'~h',
        curses.KEY_F9: b'~i',
        curses.KEY_F10: b'~j',
        curses.KEY_F11: b'~k',
        curses.KEY_F12: b'~l',
        curses.KEY_HOME: b'~H',
        curses.KEY_IC: b'~3',
        curses.KEY_LEFT: b'~D',
        curses.KEY_NPAGE: b'~2',
        curses.KEY_PPAGE: b'~1',
        curses.KEY_RIGHT: b'~C',
        curses.KEY_UP: b'~A',
    }

    def __init__(self, parent_window, width=None, height=None, top=0, left=0):
        h, w = parent_window.getmaxyx()
        if not width:
            width = w
        if not height:
            height = h - 1
        win = curses.newwin(height, width, top, left)
        win.nodelay(1)

        # set w, h
        self.height, self.width = win.getmaxyx()
        self.width -= 1
        self.height -= 1
        #max is max-1
        self.session = Session(width=self.width, height=self.height)
        self.pid = self.session.pid
        self._window = win

        self.scrollback = 0
        self.last_scrollback = 0
        self.last_scroll_screen = None

    def get_input(self):
        inp = self._window.getch()
        return inp

    def send_key(self, key):
        if key == -1:
            return
        elif key in self.keymap:
            c_char = self.keymap[key]
        elif key == curses.KEY_SPREVIOUS:
            self.scrollback += 5
            return
        elif key == curses.KEY_SNEXT:
            self.scrollback -= 5
            if self.scrollback < 0:
                self.scrollback = 0
            return
        else:
            c_char = chr(key).encode('utf-8')

        self.session.write(c_char)

    def get_cursorscreen(self):
        if self.scrollback == 0:
            self.last_scrollback = 0
            return self.session.dump()
        else:
            if self.scrollback != self.last_scrollback:
                self.last_scroll_screen = self.session.dump_history(
                    self.scrollback)
                self.last_scrollback = self.scrollback
            return self.last_scroll_screen

    def refresh(self):
        (cx, cy), screen = self.get_cursorscreen()

        # write the current screen to the window
        self._window.erase()
        for line_nr, line in enumerate(screen):
            text = ''
            for element in line:
                if type(element) == str:
                    text += element
            self._window.addstr(line_nr, 0, text)

        # move to currents sessions cursor pos:
        if cy != None:
            self._window.move(cy, cx)

        self._window.refresh()

    def is_alive(self):
        return self.session.is_alive()

    def _write(self, d):
        self.session.write(d)

    def cancel(self):
        self._write(self.keymap[curses.KEY_CANCEL])

    def run(self):
        self.session.keepalive()
예제 #26
0
def exists_username(username):
    user = Session.query(User).filter_by(username=username).first()
    return user
예제 #27
0
from backend import Session

session = Session()
#print(dir(session))
session.start("/bin/bash")
session.write(b"HALLO\n")
lc = session.last_change()
print(session.dump(), lc)
예제 #28
0
def getMainChat():
    session = Session()
    chatmodel = session.query(ChatModel).first()
    chat = chatmodel.chat
    session.close()
    return chat