Example #1
0
    def get(self):
        session_id = self.get_argument("s", default="")
        if not session_id:
            msg = 'GET paramet "s"(session) is missing!'
            json_msg = Util.getSimpleJson("Error", msg)
            logger.info("Sent: " + json_msg.replace("\n", "\\n") + "\t" + session_id)
            self.write(json_msg)
            self.finish()
            return

        logger.info("GET /r/?s=" + session_id + "\t" + session_id + "\tFROM:" + self.request.remote_ip)

        cls = ClientPool
        if session_id not in cls.client_callbacks.keys():
            msg = "The session does not exist! (ID:{0})".format(session_id)
            json_msg = Util.getSimpleJson("Error", msg)
            logger.info("Sent: " + json_msg.replace("\n", "\\n"))
            self.write(json_msg)
            self.finish()
            return
        else:
            info = cls.session_info[session_id]  # a dict for storing session info
            file_url = info.get("file_url")
            rsp_obj = dict()
            rsp_obj["Ok"] = file_url
            json_msg = json.dumps(rsp_obj) + "\n"
            logger.info("Sent: " + json_msg.replace("\n", "\\n") + "\t" + session_id + "\tTO:" + self.request.remote_ip)
            self.write(json_msg)
            self.flush()
            self.finish()
Example #2
0
    def post(self):
        
        str_time_suffix = datetime.datetime.now().strftime("_%Y%m%d_%H%M%S")
        #'_20120420_140745'

        #make sure file exist
        if "file" not in self.request.files.keys():
            msg = 'The "file" attribute does not exists'
            json_msg = Util.getSimpleJson("Error", msg)
            logger.error(json_msg.replace("\n", "\\n"))
            self.write(json_msg)
            self.finish()
            return
                        
        photofile = self.request.files['file'][0]
        filename = photofile['filename']
        
        # .jpg?
        if not (filename.lower().endswith(".jpg") or 
                filename.lower().endswith(".pdf")):
            msg = 'The file may not be a jpg nor a pdf file.'
            json_msg = Util.getSimpleJson("Error", msg)
            logger.error(json_msg.replace("\n", "\\n"))
            self.write(json_msg)
            self.finish()
            return    
        
        if filename.lower().endswith(".pdf"):
            new_filename_pdf = filename[:-4] + str_time_suffix + ".pdf"
            output_file = open("./static/pdf/" + new_filename_pdf, 'w')
            output_file.write(photofile['body'])
            output_file.close()                        
        else:        
            new_filename = filename[:-4] + str_time_suffix + ".jpg"
                
            output_file = open("./static/jpg/" + new_filename, 'w')
            output_file.write(photofile['body'])
            output_file.close()
                
            #msg = 'File: {0} ==> Saved to {1}'.format(photofile['filename'], 
                                                  #photofile['filename']+str_time_suffix
                                                  #)
                    
            new_filename_pdf = filename[:-4] + str_time_suffix + ".pdf"
            cmd = "convert {0} -rotate 90 {1}".format(
                "./static/jpg/"+ new_filename, 
                "./static/pdf/"+ new_filename_pdf)
            msg_convert = os.system(cmd)
            logger.info("running convert..." + str(msg_convert))
        
        msg = SERVER_PREFIX + "static/pdf/" + new_filename_pdf
        json_msg = Util.getSimpleJson("Ok", msg)        
        logger.info(json_msg.replace("\n", "\\n"))
        self.write(json_msg)
        self.finish()
        
        
        """
Example #3
0
    def leave(self, callback):
        cls = ClientPool
        callback(messages="", close_resp=True)
        # Delete the lookup table
        session_id = cls.session_id_lookup_by_callback.get(callback, None)
        if session_id:
            del cls.session_id_lookup_by_callback[callback]
        conn_id = cls.connection_id_lookup_by_callback.get(callback, None)
        if conn_id:
            del cls.connection_id_lookup_by_callback[callback]

        # Remove call back and then update session info in cls.session_info
        if session_id in cls.client_callbacks.keys():
            cls.client_callbacks[session_id].remove(callback)
            # Owner
            cls.session_info[session_id]["clients"].remove(conn_id)
            if conn_id == cls.session_info.get("owner"):
                cls.session_info[session_id]["owner"] = cls.session_info[session_id].get("clients").pop()
                ls.session_info[session_id]["clients"].add(cls.session_info[session_id].get("owner"))
                # pop() will remove the client so you have to add it back
        else:
            logging.warning("Cannot find session_id in session_id_lookup_by_callback")
            for sid in cls.client_callbacks.keys():
                logging.warning("Try a global memory search .")
                if cb in cls.client_callbacks[sid]:
                    cls.client_callbacks[sid].remove(cb)
                    # TODO: deal with owner issue
                    break
        msg = "You (conection id: {1}) have leave session:{0}.".format(session_id, conn_id)
        json_msg = Util.getSimpleJson("Ok", msg)
        logger.info(json_msg.replace("\n", "\\n") + "\t" + session_id)
Example #4
0
    def join(self, callback, session_id, conn_id):
        cls = ClientPool
        # if session_id not in cls.client_callbacks.keys():
        # logging.error("The session does not exist! (ID:{0})".format(session_id),
        # exc_info=True)
        # else:

        if callback not in cls.client_callbacks:
            cls.client_callbacks[session_id].append(callback)
            cls.session_id_lookup_by_callback[callback] = session_id
            cls.connection_id_lookup_by_callback[callback] = conn_id
        else:
            msg = "The client is arealy in the session."
            json_msg = Util.getSimpleJson("Ok", msg)
            logger.error(json_msg.replace("\n", "\\n") + "\t" + session_id)
            return False
        return True
Example #5
0
    def get(self):
        session_id = self.get_argument("s", default="")
        connection_id = self.get_argument("c", default="")
        msg_all = self.get_argument("b", default="")

        if not session_id:
            msg = 'GET paramet "s"(session) is missing!'
            json_msg = Util.getSimpleJson("Error", msg)
            logger.info("Sent: " + json_msg.replace("\n", "\\n") + "\t" + session_id)
            self.write(json_msg)
            self.finish()
            return

        if not connection_id:
            msg = 'GET paramet "c"(connection_id) is missing!'
            json_msg = Util.getSimpleJson("Error", msg)
            logger.info("Sent: " + json_msg.replace("\n", "\\n") + "\t" + session_id)
            self.write(json_msg)
            self.finish()
            return
        if not msg_all:
            msg = 'GET paramet "b"(message for all) is missing!'
            json_msg = Util.getSimpleJson("Error", msg)
            logger.info("Sent: " + json_msg.replace("\n", "\\n") + "\t" + session_id)
            self.write(json_msg)
            self.finish()
            return

        logger.info(
            "GET /r/?s="
            + session_id
            + "&c="
            + connection_id
            + "&m="
            + msg_all
            + "\t"
            + session_id
            + "\tFROM:"
            + self.request.remote_ip
        )

        try:
            msg_obj = json.loads(msg_all)
        except ValueError:
            msg = "No broadcast because the message" + "is not a json format string: " + msg_all
            json_msg = Util.getSimpleJson("Error", msg)
            logger.error("Sent: " + json_msg.replace("\n", "\\n") + "\t" + session_id)
            self.write(json_msg)
            self.finish()
            return

        # TODO: Special case here
        if "Command" in msg_obj.keys():
            if msg_obj["Command"] == "CleanUp":
                self.shutdown_all_clients()
                return

        b_success = self.broadcast(msg_all, session_id, connection_id)
        if b_success:
            rsp_msg = "Broadcast complete: " + msg_all.replace("\n", "\\n").replace('"', '\\"')
            logger.info(rsp_msg + "\t" + session_id)
            json_rsp_msg = Util.getSimpleJson("Ok", rsp_msg)
            self.write(json_rsp_msg)
        else:
            rsp_msg = "Broadcast fail: the session id ({0}) does not exist!".format(session_id)
            logger.error(rsp_msg + "\t" + session_id)
            json_rsp_msg = Util.getSimpleJson("Error", rsp_msg)
            self.write(json_rsp_msg)
Example #6
0
    def get(self):
        session_id = self.get_argument("s", default="")
        username = self.get_argument("u", default="")

        if not session_id:
            msg = 'GET paramet "s"(session) is missing!'
            json_msg = Util.getSimpleJson("Error", msg)
            logger.info("Sent: " + json_msg.replace("\n", "\\n") + "\t" + session_id)
            self.write(json_msg)
            self.finish()
            return

        if not username:
            msg = 'GET paramet "u"(username) is missing!'
            json_msg = Util.getSimpleJson("Error", msg)
            logger.info("Sent: " + json_msg.replace("\n", "\\n") + "\t" + session_id)
            self.write(json_msg)
            self.finish()
            return

        logger.info(
            "GET /r/?s=" + session_id + "&u=" + username + "\t" + session_id + "\tFROM:" + self.request.remote_ip
        )

        cls = ClientPool
        if session_id not in cls.client_callbacks.keys():
            msg = "The session does not exist! (ID:{0})".format(session_id)
            json_msg = Util.getSimpleJson("Error", msg)
            logger.info("Sent: " + json_msg.replace("\n", "\\n"))
            self.write(json_msg)
            self.finish()
            return
        else:
            info = cls.session_info[session_id]  # a dict for storing session info
            conn_id = Util.tenCharRandom() if PRODUCTION_MODE else "a123456789"

            if "owner" not in info.keys():  # first participant
                info["owner"] = conn_id
                logger.info("Adding a owner [{0}] to session [{1}]".format(conn_id, session_id) + "\t" + session_id)
                info["clients"] = set()
                info["clients"].add(conn_id)
            else:
                while conn_id in info["clients"]:
                    conn_id = Util.tenCharRandom()
                info["clients"].add(conn_id)
            logger.info("Adding a client [{0}] to session [{1}]".format(conn_id, session_id) + "\t" + session_id)

            join_success = self.join(self.on_new_messages, session_id, conn_id)
            if not join_success:
                msg = "Joining failed!"
                json_msg = Util.getSimpleJson("Error", msg)
                logger.info(
                    "Sent: " + json_msg.replace("\n", "\\n") + "\t" + session_id + "\tTO:" + self.request.remote_ip
                )

            copy_of_info = dict()
            for k in info:
                copy_of_info[k] = str(info[k])

            logger.info("Session: " + json.dumps(copy_of_info[k]).replace("\n", "\\n") + "\t" + session_id)
            rsp_obj = dict()
            rsp_obj["connection_id"] = conn_id
            rsp_obj["file_url"] = info.get("file_url")
            ok_obj = dict()
            ok_obj["Ok"] = rsp_obj
            json_msg = json.dumps(ok_obj) + "\n"
            ten_json_msg = json_msg * 50

            logger.info(
                "Sent: "
                + json_msg.replace("\n", "\\n")
                + "* 50 times."
                + "\t"
                + session_id
                + "\tTO:"
                + self.request.remote_ip
            )
            self.write(ten_json_msg)
            self.flush()