예제 #1
0
파일: chat.py 프로젝트: Zekka/webterm
 def cmd_rank(self, client, username=None, rank=None):
     """
     /rank [username] [newrank]
     Displays the rank of the user with the given username. If no username is given, displays your rank. If a new rank is given, assigns the new rank.
     """
     if username == None:
         username = self.chat.identify(client)
     if not rank:
         caller = self.chat.identify(client)
         acct_rank = Account.get_rank(username)
         return StatusMessage("%s has rank %s." % (username, acct_rank))
     new_rank = int(rank)
     acct = Account.find_user(username)
     client_rank = Account.get_rank(self.chat.identify(client))
     if not acct:
         return ErrorMessage(
             "No such account was found. As a security" +
             " precaution, rank cannot be assigned to accounts that have" +
             " not been created and given password")
     if acct.rank >= client_rank:
         return ErrorMessage(
             "That user's rank is currently greater than or" +
             " equal to yours. Ask somebody of greater rank to make the" +
             " change instead.")
     if new_rank >= client_rank:
         return ErrorMessage(
             "The rank you are attempting to give that user" +
             " is greater than your current rank. Ask somebody of greater" +
             " rank to make the change instead.")
     acct.rank = int(new_rank)
     return StatusMessage("Rank of user %s is now %s." %
                          (username, acct.rank))
예제 #2
0
파일: chat.py 프로젝트: Zekka/webterm
 def run(self, cmd, client, args):
     name = cmd.lower()
     try:
         cmdfunc = getattr(self, "cmd_%s" % name)
     except AttributeError:
         return ErrorMessage("No command %s exists." % cmd)
     try:
         return cmdfunc(client, *args)
     except TypeError, e:
         print "A TypeError occurred during command %s." % cmd
         traceback.print_exc()
         return ErrorMessage(
             "Incorrect arguments to command or internal error." +
             " have the maintainer check the logs if you're sure you" +
             " didn't screw up.")
예제 #3
0
파일: index.py 프로젝트: pako535/melvil
def add_like():
    wish_id = request.form['wish_id']
    user = User.query.filter_by(id=session['id']).first()
    if not Like.like_exists(wish_id, user):
        try:
            Like.like(wish_id, user)
        except exc.SQLAlchemyError:
            return ErrorMessage.message(error_body='Oops something went wrong')
    else:
        try:
            Like.unlike(wish_id, user)
        except exc.SQLAlchemyError:
            return ErrorMessage.message(error_body='Oops something went wrong')
    return json.dumps({
        'num_of_likes':
        len(WishListItem.query.filter_by(id=wish_id).first().likes)
    })
예제 #4
0
 def _end_session(self):
     """
     Ends the command session by sending an empty error message
     :return: None
     """
     end_command = ErrorMessage()
     self.networking.send_message(end_command)
     self._session_started = False
예제 #5
0
파일: chat.py 프로젝트: Zekka/webterm
 def _f(self, client, *args, **kwargs):
     client_rank = Account.get_rank(self.chat.identify(client))
     if client_rank < required_rank:
         return ErrorMessage("%s Your current rank is %s." % (
             fail_message,
             client_rank,
         ))
     return f(self, client, *args, **kwargs)
예제 #6
0
파일: chat.py 프로젝트: Zekka/webterm
 def cmd_register(self, client, username, password):
     """
     /register username password
     Registers the given username with the given password. While passwords are case-sensitive, usernames are not. After registration you should log in with /auth.
     """
     try:
         Account.create(username, password)
         return StatusMessage("Registration complete: you may now /auth.")
     except AccountError, e:
         return ErrorMessage("Registration failed: %s" % e.message)
예제 #7
0
파일: chat.py 프로젝트: Zekka/webterm
 def cmd_drop(self, client):
     """
     /drop
     Releases control of the console if you have it.
     """
     if self.chat.find_owner() != client:
         return ErrorMessage("You do not control the console.")
     self.chat.socket_manager.multicast(
         StatusMessage("%s has dropped control." %
                       (self.chat.identify(client))))
     self.chat.change_owner(None)
예제 #8
0
파일: chat.py 프로젝트: Zekka/webterm
    def cmd_free(self, client):
        """
        /free
        Releases control of the console from whoever has it. This is similar to
        a /grab followed by a /drop.
        """
        owner = self.chat.find_owner()
        if not owner:
            return ErrorMessage("The console is already free.")

        rank = Account.get_rank(self.chat.identify(client))
        rank_other = (Account.get_rank(self.chat.identify(owner))
                      if owner else 0)

        if rank < rank_other:
            return ErrorMessage("The current arbiter outranks you.")

        self.chat.socket_manager.multicast(
            StatusMessage("%s has freed the console." %
                          (self.chat.identify(client))))
        self.chat.change_owner(None)
예제 #9
0
파일: chat.py 프로젝트: Zekka/webterm
 def cmd_ask(self, client):
     """
     /ask
     The gentle alternative to /grab: for women and hippies.
     Takes control of the console only if nobody else has it. 
     You can use /take if you want webterm to automatically decide between /grabbing and /asking.
     """
     if self.chat.find_owner():
         return ErrorMessage("Someone is already the arbiter.")
     self.chat.socket_manager.multicast(
         StatusMessage("%s has requested control." %
                       (self.chat.identify(client))))
     self.chat.change_owner(client)
예제 #10
0
    def submit_new_note(self):
        conn = sqlite3.connect(self.current_file)
        conn.execute('PRAGMA foreign_keys = 1')
        cur = conn.cursor()

        new_note_text = self.note_input.text.get(1.0, 'end-1c')
        new_subtopic = self.subtopic_input.get()
        cur.execute(select_count_subtopic, (new_subtopic, ))
        count = cur.fetchone()[0]
        if count > 0:
            non_unique_subtopic = ErrorMessage(
                self, message="Each subtopic can be\nused once in a tree.")
            non_unique_subtopic.title('Non-unique Note Title Error')
            self.subtopic_input.focus_set()
            return

        if len(new_subtopic) == 0:
            blank_subtopic = ErrorMessage(self,
                                          message="Blank notes are OK\n"
                                          "but not blank note titles.")
            blank_subtopic.title('Blank Note Title Error')
            self.subtopic_input.focus_set()
            return
        cur.execute(insert_note, (new_note_text, new_subtopic))
        conn.commit()
        cur.execute("SELECT seq FROM SQLITE_SEQUENCE WHERE name = 'note'")
        new_note_id = cur.fetchone()[0]

        cur.execute(insert_findings_notes,
                    (self.finding_id, new_note_id, self.new_index))
        conn.commit()
        cur.close()
        conn.close()

        self.master.current_note_text = new_note_text
        self.refresh_notes_per_finding()
        self.toc.insert(self.new_index, new_subtopic)
        items = self.toc.listbox_content.winfo_children()
        for child in items:
            child.bind('<<ListboxSelected>>', self.switch_note)
        self.toc.resize_scrollbar()
        self.toc.selection_set(self.new_index)
        self.switch_note()
        self.pressed.config(text=' ... ')
        self.new_index = len(self.subtopics)
        self.close_subtopic_dialog()
        self.refresh()
예제 #11
0
파일: chat.py 프로젝트: Zekka/webterm
 def cmd_help(self, client, cmd=None):
     """
     /help [cmd]
     Displays help for a given command, or else lists all commands if none is specified.
     """
     if cmd == None:
         return self.cmd_list(client)
     cmd = cmd.lower()
     try:
         cmdfunc = getattr(self, "cmd_%s" % cmd)
     except AttributeError:
         return ErrorMessage("No command %s exists." % cmd)
     doc = textwrap.dedent(cmdfunc.__doc__.strip())
     for i in doc.split("\n"):
         client.status(i)
예제 #12
0
파일: index.py 프로젝트: pako535/melvil
def add_wish():
    form = WishlistForm()
    if form.validate_on_submit():
        try:
            new_wish_item = WishListItem(authors=form.authors.data,
                                         item_type=form.type.data,
                                         title=form.title.data,
                                         pub_year=datetime.strptime(
                                             form.pub_date.data, "%Y").date())

            db.session.add(new_wish_item)
            db.session.commit()
            return redirect(url_for('library.wishlist'))
        except exc.SQLAlchemyError:
            return ErrorMessage.message(error_body='Oops something went wrong')
    return render_template('wishlist_add.html', form=form, error=form.errors)
예제 #13
0
파일: chat.py 프로젝트: Zekka/webterm
 def cmd_grab(self, client):
     """
     /grab
     The forceful alternative to /take: for real men only.
     Attempts to forcefully grab control of the console from whoever currently has it. That person immediately loses control. Can only be used on others who are lower-ranking.
     You can use /take if you want webterm to automatically decide between /grabbing and /asking.
     """
     rank = Account.get_rank(self.chat.identify(client))
     rank_other = (Account.get_rank(
         self.chat.identify(self.chat.find_owner()))
                   if self.chat.find_owner() else 0)
     if rank < rank_other:
         return ErrorMessage("The current arbiter outranks you.")
     self.chat.socket_manager.multicast(
         StatusMessage("%s has grabbed control." %
                       (self.chat.identify(client))))
     self.chat.change_owner(client)
예제 #14
0
파일: app.py 프로젝트: Zekka/webterm
    def api_handle(self, client, message):
        handlers = {
            "?": self.handle_change_request,
            "%": self.handle_screen_request,
            "s": self.handle_settings_request,
            "h": self.handle_hello_request,
            "k": self.handle_keypress_request,
            "l": self.handle_leave_request,
            ":": self.handle_chat_request,
            "~": self.handle_owner_request,
        }

        if not self.session:
            self.start()
        self.session.process()
        tag, args = message[0], message[1:]
        try:
            hndlr = handlers[tag]
        except KeyError:
            return ErrorMessage("unrecognized request: %s" % tag)
        return hndlr(client, *args)
예제 #15
0
파일: chat.py 프로젝트: Zekka/webterm
class ChatCommands(object):
    def __init__(self, chat):
        self.chat = chat

    def run(self, cmd, client, args):
        name = cmd.lower()
        try:
            cmdfunc = getattr(self, "cmd_%s" % name)
        except AttributeError:
            return ErrorMessage("No command %s exists." % cmd)
        try:
            return cmdfunc(client, *args)
        except TypeError, e:
            print "A TypeError occurred during command %s." % cmd
            traceback.print_exc()
            return ErrorMessage(
                "Incorrect arguments to command or internal error." +
                " have the maintainer check the logs if you're sure you" +
                " didn't screw up.")
        except Exception, e:
            print "Some exception occurred during command %s." % cmd
            traceback.print_exc()
            return ErrorMessage("An exception occurred during command." +
                                " Bother the maintainer to fix it.")
예제 #16
0
                conn._send()

        log("== Network thread is gracefully ending")


### ---------------------------------------------------------------------------

# sublime.set_timeout_async(lambda: test())

mgr = ConnectionManager()
mgr.startup()

conn = mgr.connect("dart", 50000)
# mgr.connect("dart", 7)
# conn1 = mgr.connect("dart", 7)

conn.send(IntroductionMessage())
conn.send(MessageMessage("I am the arbitrary message text!"))
conn.send(ErrorMessage(77341926, "This is an arbitrary error message. Go us!"))
# conn1.close()
# conn1 = None

for x in range(100):
    msg = conn.receive()
    if msg is not None:
        log("==> Received {0}".format(msg))
    time.sleep(0.1)

# print(mgr.find_connection(host="localhost", port=50000))
mgr.shutdown()
print("Run complete")
예제 #17
0
파일: app.py 프로젝트: Zekka/webterm
 def handle_keypress_request(self, client, key):
     if client != self.owner:
         return ErrorMessage("You are not the current arbiter.")
     self.session.input_bytes(key)
     self.session.process()
     return OkMessage()
예제 #18
0
파일: app.py 프로젝트: Zekka/webterm
 def error(self, errormessage):
     self.msg(ErrorMessage(errormessage))
예제 #19
0
파일: chat.py 프로젝트: Zekka/webterm
        cmds = [i[len(prefix):] for i in dir(self) if i.startswith(prefix)]
        return StatusMessage("Currently availiable commands are %s" %
                             ", ".join(cmds))

    def cmd_register(self, client, username, password):
        """
        /register username password
        Registers the given username with the given password. While passwords are case-sensitive, usernames are not. After registration you should log in with /auth.
        """
        try:
            Account.create(username, password)
            return StatusMessage("Registration complete: you may now /auth.")
        except AccountError, e:
            return ErrorMessage("Registration failed: %s" % e.message)
        except ValueError, e:
            return ErrorMessage(e.message)

    def cmd_auth(self, client, username, password):
        """
        /auth username password
        Authenticates with the given username/password pair. While passwords are case-sensitive, usernames are not. Success will change your displayed username to the username passed, preserving case.
        """
        if Account.check_auth(username, password):
            self.chat.approve_auth(client, username)
        elif Account.exists(username):
            client.error("That is not the password for that account.")
        else:
            client.error("That is not a real account.")

    def cmd_rank(self, client, username=None, rank=None):
        """
예제 #20
0
파일: index.py 프로젝트: pako535/melvil
def delete_wish(wish_id):
    try:
        WishListItem.delete_wish(wish_id)
    except exc.SQLAlchemyError:
        return ErrorMessage.message(error_body='Oops something went wrong')
    return redirect(url_for('library.wishlist'))