Как я могу использовать Kivy Filechooser для отображения файлов сервера (удаленный компьютер)? - PullRequest
1 голос
/ 31 марта 2020

Я создаю клиент-серверную программу с идеей облака общих файлов. Я хочу добавить экран, который отображает файлы на стороне сервера (чтобы создать на сервере указанную папку c, которая является «облаком», и отобразить ее на стороне клиента, клиент должен иметь возможность редактировать файлы, добавлять файлы и открываем файлы).

Вот что у меня сейчас (работает только сторона пользователя).

--- Клиент ---

import kivy
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.popup import Popup
from kivy.lang import Builder
import os
import socket
import sys


s = socket.socket()
PORT = 9898
s.connect(('127.0.0.1', PORT))


class P(FloatLayout):
    pass


def show_popup():
    show = P()
    popupWindow = Popup(title="", content=show, size_hint=(None, None), size=(400, 400))
    popupWindow.open()


class UserFileManager(BoxLayout):
    def open(self, path, filename):
        try:
            os.startfile(filename[0])
        except:
            show_popup()


    def selected(self, filename):
        try:
            print ("selected: %s" % filename[0])
        except:
            pass


    def send(self, filename):
        s.send('SEND'.encode('utf-8'))
        with open(filename, 'rb') as f:
            file_name_without_path = filename.split('\\')
            file_name_without_path = file_name_without_path[len(file_name_without_path)-1]
            s.send(file_name_without_path.encode('utf-8')) #send name
            filesize = os.path.getsize(filename)
            s.send(str(filesize).encode('utf-8'))  # send size
            bytesToSend = f.read(1024)
            s.send(bytesToSend)
            bytes_sent = 0
            while len(bytesToSend) != 0:
                bytesToSend = f.read(1024)
                bytes_sent += len(bytesToSend)
                s.send(bytesToSend)


class MyApp(App):
    def build(self):
        return UserFileManager()

if __name__ == '__main__':
    MyApp().run()
    # Close the connection from client side
    s.close()

- --- файл my.kv ----

<RoundedButton@Button>:
    background_color : (0,0,0,0)
    background_normal: ''
    back_color : (1,0,1,1)
    border_radius: [18]
    canvas.before:
        Color:
            rgba: self.back_color
        RoundedRectangle:
            size: self.size
            pos: self.pos
            radius: self.border_radius



<UserFileManager>:
    id: my_widget
    GridLayout:
        rows: 3
        GridLayout:
            rows: 1
            size_hint: 1, 0.1
            Label:
                text: "Welcome To RonDrive"
        GridLayout:
            rows: 1
            size: root.width, root.height - 100
            FileChooserListView:
                id: filechooser
                on_selection: my_widget.selected(filechooser.selection)
        FloatLayout:
            size_hint: 1, 0.2

            RoundedButton
                text: "open file"
                pos_hint: {"x":0.01, "top":1}
                back_color : (41/255, 21/255, 228/255, 1)
                size_hint: 0.1, 0.45
                on_release: my_widget.open(filechooser.path, filechooser.selection)
            RoundedButton
                text: " Upload File"
                pos_hint: {"x":0.115, "top":1}
                size_hint: 0.1, 0.45
                back_color : (41/255, 21/255, 228/255, 1)
                on_release: my_widget.send(filechooser.selection[0])

            RoundedButton
                text: "Nothing"
                size_hint: 0.1, 0.45
                pos_hint: {"x":0.01, "top":0.5}
                back_color : (41/255, 21/255, 228/255, 1)

<P>:
    Label:
        text: "You Haven't Chose Any File"
        size_hint: 0.6, 0.2
        pos_hint: {"x":0.2, "top": 1}

    Button:
        text: "OK, Got It"
        size_hint: 0.8, 0.2
        pos_hint: {"x":0.1, "y": 0.1}

--- сервер ---

import socket
import threading
import os


def UploadFile(client):
    filename = client.recv(1024).decode('utf-8')
    filesize = client.recv(1024).decode('utf-8')
    filesize = int(filesize)
    new_file_path = 'C:\\Users\\רון\\PycharmProjects\\untitled1\\RonDrive\\' + filename
    f = open(new_file_path, 'wb')
    data = client.recv(1024)
    totalRecv = len(data)
    f.write(data)
    while totalRecv < filesize:
        data = client.recv(1024)
        totalRecv += len(data)
        print(str((totalRecv / filesize) * 100) + "%")
        f.write(data)
    f.close()


def ReciveClientRequest(client):
    request = client.recv(1024).decode("utf-8")

    if request == "SEND":
        print ('UPLOAD')
        UploadFile(client)


def Main():
    host = '0.0.0.0'
    port = 9898

    s = socket.socket()
    s.bind((host, port))
    s.listen(1)
    client, addr = s.accept()
    while True:
       ReciveClientRequest(client)

    s.close()


if __name__ == '__main__':
    Main()
...