Beispiel #1
0
async def ws():
    global users
    g_user = ""
    try:
        while True:
            data = await websocket.receive()

            try:
                message_json = json.loads(data)
            except Exception as e:
                print(e)

            database = db.Database()

            # switch
            if message_json.get("type") == None:
                await websocket.send("Invalid")
            else:
                if message_json["type"] == "init":
                    g_user = message_json["username"]
                    users[g_user] = websocket._get_current_object()

                if message_json["type"] == "chat":
                    if users.get(message_json['receiver']) != None:
                        receiver_websocket = users[message_json['receiver']]
                        await receiver_websocket.send(data)

                    database.add_message(message_json['sender'],
                                         message_json['receiver'],
                                         message_json['content'])
            database.update_websocket_id(data,
                                         id(websocket._get_current_object()))

    except asyncio.CancelledError:
        del users[g_user]
Beispiel #2
0
async def list_user():
    data = await request.get_json()

    try:
        database = db.Database()
    except Exception as e:
        print(e)

    result = database.list_user()

    return {"data": result}
Beispiel #3
0
async def signup():
    data = await request.get_json()

    username = data['username']
    passwd = data['password']

    database = db.Database()

    result = database.create_user(username, passwd)

    if result == "Success":
        return json.dumps({"status": "success"})
    else:
        return Response(json.dumps({"error": result}), 404)
Beispiel #4
0
async def get_conversation():
    data = await request.get_json()

    receiver = request.args.get('username')
    username = request.headers['Authorization'].split("&")[0]

    try:
        database = db.Database()
    except Exception as e:
        print(e)

    result = database.show_conversation(username, receiver)

    return json.dumps({"data": result})
Beispiel #5
0
	def GetSettings(self):
		#Creating object
		DatabaseObj = db.Database()

		#Getting API Keys
		self.UserAPIKeys = DatabaseObj.GetAPIKeys()

		#Importing config file
		config = ConfigParser.ConfigParser()
		config.read('app/config/config.ini')

		#Getting webserver settings
		self.WebServerPort = int(config.get("WebServer", "PORT"))
		self.WebServerDebug = bool(config.getboolean("WebServer", "DEBUG_ENABLED"))
Beispiel #6
0
    async def wrapper(*args, **kwargs):
        if request.headers.get('Authorization') == None:
            return Response(json.dumps({"error": "Bad request"}), 400)

        cred = request.headers['Authorization']

        if cred == None or len(cred.split("&")) != 2:
            return Response(json.dumps({"error": "Forbidden"}), 403)

        database = db.Database()

        username, password = cred.split("&")
        isValidUser = database.check_valid_cred(username, password)

        if isValidUser != "Success":
            return Response(json.dumps({"error": "Forbidden"}), 403)
Beispiel #7
0
async def login():
    data = await request.get_json()
    username = data['username']
    passwd = data['password']

    try:
        database = db.Database()
    except Exception as e:
        print(e)

    result = database.check_valid_cred(username, passwd)

    if result == "Success":
        return json.dumps({"status": "success"})
    else:
        return Response(json.dumps({"error": result}), 404)
Beispiel #8
0
async def send_message():
    data = await request.get_json()

    username = request.headers['Authorization'].split("&")[0]
    receiver = data['receiver']
    content = data['content']

    try:
        database = db.Database()
    except Exception as e:
        print(e)

    result = database.add_message(username, receiver, content)

    if result == "Success":
        return json.dumps({"status": "success"})

    return Response(json.dumps({"error": result}), 500)
Beispiel #9
0
	def GetModules(self):
		#Creating object
		DatabaseObj = db.Database()

		#Getting modules
		self.modules = DatabaseObj.GetEnabledModules()

		#Modules array values
        #0 - module_id
        #1 - module_name
        #2 - module_type
        #3 - module_filename
        #4 - module_priority
        #5 - module_enabled

		#Looping and including modules
		for module in self.modules:
			#DEBUGGING print("Including: app.modules_"+module[2]+"."+module[3])
			__import__("app.modules_"+str(module[2])+"."+str(module[3]))

		print self.modules

		#Returning modules
		return self.modules
Beispiel #10
0
import pymysql
from flask import abort, Flask, jsonify, render_template, request, redirect, url_for
from flask import Response

# from flask_cors import CORS
from db import db
from s3 import s3_api

# project_folder = os.path.expanduser('~/Project1')  # adjust as appropriate
# load_dotenv(os.path.join(".", '.env'))

logger = logging.getLogger(__name__)
logger.setLevel("DEBUG")

app = Flask(__name__, template_folder='static')
db = db.Database()
username = None


@app.route('/homepage')
def homepage():
    global username
    username = request.args.get("user")
    # accToken = jwt.decode(token, algorithms=['RS256'])
    print(username)

    resp, status = db.read(id=None, username=username)
    # if status != 200:
    #     return jsonify({"status": "get all failed", "error": resp}), status
    print(resp, status)
    file_list = []
Beispiel #11
0
async def on_message(msg):
    if msg.author.bot:
        return
    if msg.content.startswith(config["prefix"]):
        db_guild = msg.guild
        msg_id = msg.author.id
        msg.content = msg.content[len(config["prefix"]):].split(" ")
        cmd = msg.content[0]
        if cmd == "init" and auth(msg_id, db_guild):
            for category in db_guild.categories:
                if category.name == "discord.fs":
                    for part in (await
                                 serverData.fs_location(db_guild,
                                                        msg.channel)):
                        await part.delete()
            await serverData.init_fs(db_guild)
            await msg.channel.send(embed=embeds.embed_make(
                "FS created!", "The file structure is ready.", msg.author))
        elif cmd == "remove" and auth(msg_id, db_guild):
            for part in await serverData.fs_location(db_guild, msg.channel):
                await part.delete()
            await msg.channel.send(embed=embeds.embed_make(
                "FS removed!", "The file structure was removed.", msg.author))
        elif cmd == "upload":
            db_channel = await serverData.get_db(db_guild)
            if db_channel is None:
                not_init(msg.channel)
                return
            db_wrapper = db.Database(db_channel, aes)
            await msg.channel.send(embed=embeds.embed_make(
                "Uploading...", "Please wait.", msg.author))
            attachments = []
            for attachment in msg.attachments:
                await db_wrapper.write_file(
                    attachment.filename, await
                    compression.compress(attachment), msg_id)
                attachments.append(attachment.filename)
            message = await msg.channel.send(
                embed=embeds.embed_make("File Uploaded!",
                                        "The file has uploaded.",
                                        msg.author,
                                        fields=[(attachment, "Completed.")
                                                for attachment in attachments])
            )
            await message.add_reaction("❌")
        elif cmd == "download":
            file_name = msg.content[1]
            db_channel = await serverData.get_db(db_guild)
            if db_channel is None:
                not_init(msg.channel)
                return
            db_wrapper = db.Database(db_channel, aes)
            file = await db_wrapper.get_file(file_name, msg_id)
            if not file:
                await msg.channel.send(
                    "You don't own this file or it doesn't exist!")
                return
            attachment = discord.File(io.BytesIO(compression.uncompress(file)),
                                      filename=file_name)
            message = await msg.channel.send(msg.author.mention,
                                             file=attachment)
            await message.add_reaction("❌")
        elif cmd == "help":
            prefix = config["prefix"]
            commands = [
                ("init",
                 "Creates the structure that allows discord.fs to function. (requires server owner or admin perms.)"
                 ), ("list", "List all files you own in the database."),
                ("download <file_name>",
                 "Download a uploaded file you own from the database."),
                ("delete <file_name>",
                 "Delete a file you own from the database."),
                ("remove",
                 "Clears the database. (requires server owner or admin perms.)"
                 ), ("upload", "Upload an attachment to the database.")
            ]
            await msg.channel.send(embed=embeds.embed_make(
                "Information.",
                "discord.fs is a bot that emulates a filesystem on a discord channel. This allows for what is essentially free storage, without the privacy concerns. Using AES encryption, Discord cannot look at your files, even if they wanted to.",
                msg.author,
                fields=commands))
        elif cmd == "delete":
            file_name = msg.content[1]
            db_channel = await serverData.get_db(db_guild)
            if db_channel is None:
                not_init(msg.channel)
                return
            db_wrapper = db.Database(db_channel, aes)
            await db_wrapper.delete_file(file_name, msg.author.id)

        elif cmd == "list":
            db_channel = await serverData.get_db(db_guild)
            if db_channel is None:
                not_init(msg.channel)
                return
            db_wrapper = db.Database(db_channel, aes)
            message = await msg.channel.send(embed=embeds.embed_make(
                "File List.", "Here are your files in the database.",
                msg.author, [
                    file
                    for file in await db_wrapper.get_file_names(msg.author.id)
                ]))
            await message.add_reaction("❌")