File size: 6,332 Bytes
51e9b08
 
77251b2
51e9b08
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77251b2
 
 
 
 
 
 
51e9b08
77251b2
 
 
 
 
 
 
 
51e9b08
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77251b2
51e9b08
 
77251b2
51e9b08
77251b2
51e9b08
0e5d110
 
 
 
 
 
 
 
77251b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e5d110
 
 
77251b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51e9b08
0e5d110
77251b2
 
 
 
 
 
51e9b08
 
0e5d110
51e9b08
77251b2
51e9b08
0e5d110
51e9b08
 
 
 
0e5d110
 
 
51334da
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
import gradio as gr
import os
import shutil
import json
from pymongo.mongo_client import MongoClient
from pymongo.server_api import ServerApi
import urllib.parse
from bson.objectid import ObjectId

username = urllib.parse.quote_plus(os.getenv('MONGO_USERNAME'))
password = urllib.parse.quote_plus(os.getenv('MONGO_PASSWORD'))
restUri = os.getenv('REST_URI')
uri = f'mongodb+srv://{username}:{password}{restUri}'
client = MongoClient(uri, server_api=ServerApi('1'))
db = client['file_storage']
references_collection = db['references']

try:
    client.admin.command('ping')
    print("Pinged your deployment. You successfully connected to MongoDB!")
except Exception as e:
    print(e)

theme = gr.themes.Default(
    primary_hue="blue",
    secondary_hue="violet",
    neutral_hue="slate",
)

def upload(file, secret):
    if secret == os.environ.get('SECRET_KEY'):
        root_directory = '/tmp/gradio'
        folder_contents_dict = get_folder_contents_dict(root_directory)
        base_url = "https://abhicodes-file-sharing-system.hf.space/file=/tmp/gradio"
        urls = [f"{base_url}/{folder}/{file}" for folder, files in folder_contents_dict.items() for file in files]
        references_collection.update_one({"_id": ObjectId('66531a797cbaa19ba4e441c5')}, {"$set": {"urls": urls}})

        gr.Info("Uploaded Successfully")
    
    else:
        for ele in file:
            dir_to_remove = os.path.dirname(ele)
            shutil.rmtree(dir_to_remove)
        
        gr.Warning("Unauthorized to upload")

def get_folder_contents_dict(root_dir):
    folder_contents = {}
    for item in os.listdir(root_dir):
        item_path = os.path.join(root_dir, item)
        if os.path.isdir(item_path):
            contents = os.listdir(item_path)
            folder_contents[item] = contents
    
    return folder_contents

def generate_markdown(json_data):
    urls = json_data.get("urls", [])
    markdown_lines = []
    for url in urls:
        encoded_url = urllib.parse.quote(url, safe=':/')
        filename = url.split('/')[-1]
        encoded_filename = urllib.parse.quote(filename)
        markdown_lines.append(f'- <a style="text-decoration:none; font-size:18px" href={encoded_url} target="_blank">{encoded_filename}</a>')
    return "\n".join(markdown_lines)

def get_uploads(secret):
    if secret == os.environ.get('SECRET_KEY'):
        result = references_collection.find_one({"_id": ObjectId('66531a797cbaa19ba4e441c5')}, {"_id": 0})
        if result:
            markdown_output = generate_markdown(result)
            gr.Info("Recieved uploaded files")
            return markdown_output
        else:
            return '''<p style="color:red;font-size:20px;text-align:center;font-weight:bold;">No result found</p>'''
    else:
        return '''<p style="color:red;font-size:20px;text-align:center;font-weight:bold;">Invalid Secret Key</p>'''

js = '''
function test() {
    document.title = "File Sharing System";
    var link = document.createElement('link');
    link.type = 'image/x-icon';
    link.rel = 'shortcut icon';
    link.href = 'https://cdn3d.iconscout.com/3d/premium/thumb/cloud-storage-5402862-4521475.png';
    document.getElementsByTagName('head')[0].appendChild(link);

    function updateHeroContainerStyle() {
        if (window.innerWidth <= 600) {
            const ele = document.querySelector(".hero-container");
            if (ele) {
                ele.style.flexDirection = 'column';
                ele.style.padding = '5px';
                ele.style.margin = '0px';
                ele.style.gap = '0px';
            }
        }
        else {
            const ele = document.querySelector(".hero-container");
            if (ele) {
                ele.style.flexDirection = 'row';
                ele.style.padding = '5px';
                ele.style.margin = '0px 20px 0px 20px';
                ele.style.gap = '50px';
            }
        }
    }
    updateHeroContainerStyle();
    window.addEventListener('resize', updateHeroContainerStyle);
}
'''

css = '''
.hero-container {
    display: flex;
    flex-direction: row;
    gap:50px;
    justify-content: center;
    align-items: center;
    padding: 5px;
    border-radius: 10px;
    max-width: 100%;
    margin: 20px;
    margin-top: 0px;
    margin-bottom: 0px;
}
.logo {
    width: 80px;
}
.description {
    text-align: justify;
}
'''

with gr.Blocks(theme=theme, js=js, css=css) as demo:
    gr.Markdown('''<h1 style="text-align:center;">File Storing and Sharing System</h1>''')
    with gr.Column():
        gr.Markdown(''' <div class="hero-container">
                            <img src="https://cdn3d.iconscout.com/3d/premium/thumb/cloud-storage-5402862-4521475.png" alt="logo" class="logo">
                            <p class="description">This project is a file storing and sharing system built using Gradio for the front-end interface and MongoDB for the back-end database. The system allows users to upload files, which are then stored and managed within a specified directory. URLs for accessing these files are generated and stored in a MongoDB collection, making it easy to share and access the uploaded files.</p>
                        </div> ''')    
        
    secret_key = gr.Text(label="🔐 Secret Key", placeholder="Enter your secret key here...", type="password", autofocus=True)
    with gr.Row():
        with gr.Column():
            gr.Markdown('''<h1 style="text-align:center;display:flex;justify-content:center;align-items:center"><img src="https://i.ibb.co/FB6tMdT/upload.png" alt="upload" width="50">Uploader</h1>''')
            input = gr.File(label="Input", file_count="multiple")
            input.upload(fn=upload, inputs=[input, secret_key])
        with gr.Column():
            gr.Markdown('''<h1 style="text-align:center;display:flex;justify-content:center;align-items:center"><img src="https://i.ibb.co/K9Bq3j7/download.png" alt="download" width="50">Downloader</h1>''')
            uploads = gr.Markdown(label="Uploads")
            get_upload_button = gr.Button("Get Uploads", variant='primary')
            get_upload_button.click(fn=get_uploads, inputs=secret_key, outputs=uploads)

    gr.Markdown('''> To know more read the docs at: [Documentation](https://huggingface.co/spaces/abhicodes/file-sharing-system/blob/main/README.md)''')


demo.launch(debug=True)