Пример #1
0
def publish(temp, humidity):
    print("Publising to firebase!")
    
    firebase = Firebase(config)
    db=firebase.database()
    data={"temperature":temp, "humidity":humidity}
    db.child("dht").push(data)
    
    count=len(db.child("dht").get().val())
    
    for x in db.child("dht").get().val():
        if(count<=30):
            break
        
        db.child("dht").child(str(x)).remove()
        count -= 1
        
    setTime()

    

    

    
    
Пример #2
0
class itfdb():

    # Connect to firebase dataset
    def __init__(self):
        self.config = {
            "apiKey": keys['firebase_api_key'],
            "authDomain": keys['firebase_auth_domain'],
            "databaseURL": keys['firebase_address'],
            "storageBucket": keys['firebase_storage_bucket']
        }
        self.firebase = Firebase(self.config)
        self.conn = self.firebase.database()

    # Returns a list of keys from the database
    def get_nodes(self, path):
        return list(self.conn.child(path).get().val().keys())

    # Returns a dict() structure from the database
    def get_data(self, path):
        return self.conn.child(path).get().val()

    # Add an item to the firebase dataset
    def create_node(self, path, data):
        self.conn.child(path).set(data)

    # Delete an item from the firebase dataset
    def destroy_node(self, path):
        self.conn.child(path).remove()
Пример #3
0
def questionBank():
    """
    Authenticated user will request for question from the question bank.
    Retrieve the questions and return it as a json to the client.
    # """

    firebase_apikey = os.environ.get("firebase_apiKey")
    firebase_authDomain = os.environ.get("firebase_authDomain")
    firebase_databaseURL = os.environ.get("firebase_databaseURL")
    firebase_storageBucket = os.environ.get("firebase_storageBucket")
    firebase_appId = os.environ.get("firebase_appId")
    firebase_storageBucket = os.environ.get("firebase_storageBucket")

    config = {
        "apiKey": firebase_apikey,
        "authDomain": firebase_authDomain,
        "databaseURL": firebase_databaseURL,
        "storageBucket": firebase_storageBucket
    }

    try:

        firebase = Firebase(config)
        db = firebase.database()
        firebase_result = db.child("question").get()
        result = {}
        for data in firebase_result.each():
            result[data.key()] = data.val()
        return json.dumps(result), 200
    except Exception as e:
        print(f"Error: {e}")
        return "An error has occurred", 400
Пример #4
0
def _init_database():
    global user
    global db
    global firebase

    print("Initializing database...")

    project_id = "fir-test-for-atb-default-rtdb"
    config = {
        "apiKey": token_loader.FIREBASE,
        "authDomain": f"{project_id}.firebaseapp.com",
        "databaseURL": f"https://{project_id}.firebaseio.com",
        "storageBucket": f"pro{project_id}jectId.appspot.com"
    }

    firebase = Firebase(config)

    # Get a reference to the auth service
    auth = firebase.auth()

    # Log the user in
    load_dotenv()
    username = os.getenv('FIREBASE_USERNAME')
    password = os.getenv('FIREBASE_PASSWORD')
    user = auth.sign_in_with_email_and_password(username, password)
    set_next_token_refresh_time()

    # Get a reference to the database service
    db = firebase.database()
Пример #5
0
    def Retrieve():

        config = {
            "apiKey": "AIzaSyDJIZK3ZCPPu3KNK0-1TuPULfbFGUn0aqI",
            "authDomain": "raspberry-pi-571ec.firebaseapp.com",
            "databaseURL": "https://raspberry-pi-571ec.firebaseio.com/",
            "storageBucket": "raspberry-pi-571ec.appspot.com"
        }

        firebase = Firebase(config)
        db = firebase.database()
        storage = firebase.storage()

        #new = db.child("Angelica's Inbox").child("New").get()
        new = db.child("Kris' Inbox").child("New").get()
        print(new.val())
        if (new.val() == '1'):
            try:
                storage.child("Kris' Inbox").child("Image").download(
                    "Image.jpg")
                print("image found")
                newImg = True
                return newImg

            except:
                print("No image")
        else:
            return False
Пример #6
0
def aboutus(request):
    firebase = Firebase(config)
    db = firebase.database()
    x = db.child("About Us").get()
    output = {
        'value': x,
    }
    return render(request, "about-us.html", output)
Пример #7
0
def updateOnCloud():
    if checkNetwork():
        try:
            firebase = Firebase(config)
            db = firebase.database()
            db.update(data)
            print("Data Pushed")
        except:
            print("Firebase Error")
 def __init__(self):
     with open('firebase_config.json', 'r') as file:
         config = json.loads(file.read())
     firebase = Firebase(config)
     auth = firebase.auth()
     user = auth.sign_in_with_email_and_password(
         os.environ['FIREBASE_EMAIL'], os.environ['FIREBASE_PWD'])
     self.auth_token = user['idToken']
     self.db = firebase.database()
     self._tags = None
Пример #9
0
    def Reset():

        config = {
            "apiKey": "AIzaSyDJIZK3ZCPPu3KNK0-1TuPULfbFGUn0aqI",
            "authDomain": "raspberry-pi-571ec.firebaseapp.com",
            "databaseURL": "https://raspberry-pi-571ec.firebaseio.com/",
            "storageBucket": "raspberry-pi-571ec.appspot.com"
        }

        firebase = Firebase(config)
        db = firebase.database()

        db.child("Kris' Inbox").child("New").set("0")
Пример #10
0
def mainCode():

    # Chrome Initialization
    op = webdriver.ChromeOptions()
    op.binary_location = os.environ.get("GOOGLE_CHROME_BIN")
    op.add_argument('headless')
    op.add_argument("--no-sandbox")
    op.add_argument("--disable-dev-sh-usage")

    driver = webdriver.Chrome(
        executable_path=os.environ.get("CHROMEDRIVER_PATH"), chrome_options=op)

    # Ovex.io
    driver.get('https://www.ovex.io/products/arbitrage')
    ovex = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, "//*[@id='live_premium']")))
    ovex = ovex.get_attribute("innerHTML")
    ovex = ovex.split()
    ovex = ovex[-1][:-1]
    print(ovex)

    # Arbatunity.com
    driver.get('https://www.arbatunity.com/wwwajax.php')
    arbatunity = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, "//body/b")))
    arbatunity = arbatunity.get_attribute("innerHTML")
    arbatunity = arbatunity[:-1]
    print(arbatunity)

    # DataBase Appending
    config = {}

    firebase = Firebase(config)
    db = firebase.database()

    key = db.generate_key()
    key = str(key)

    UTC = pytz.timezone('Africa/Blantyre')
    africa_utc = datetime.now(UTC)
    current_time = africa_utc.strftime("%H:%M:%S")

    data = {
        "arbatunity": arbatunity,
        "ovex": ovex,
        "current_time": current_time
    }

    results = db.child("Crypto Values/" + key).set(data)

    print(results)
Пример #11
0
def firebase_config():
    config = {
        # "apiKey": "apiKey",
        # "authDomain": "projectId.firebaseapp.com",
        # "databaseURL": "https://databaseName.firebaseio.com",
        # "storageBucket": "projectId.appspot.com",
        # "serviceAccount": "path/to/serviceAccountCredentials.json"  # (optional)
        "apiKey": "AIzaSyCOt619fNqEuIgFpzf20h2cmC6tFeQYuTE",
        "authDomain": "corona-charts-33e8a.firebaseapp.com",
        "databaseURL":
        "https://corona-charts-33e8a-default-rtdb.firebaseio.com/",
        "storageBucket": "corona-charts-33e8a.appspot.com"
    }

    firebase = Firebase(config)

    Constants.db = firebase.database()
Пример #12
0
def updateaboutus(request):
    if (request.method == 'POST'):
        Introduction = request.POST.get("Introductio")
        Definition = request.POST.get("Definitio")
        Information = request.POST.get("Informatio")
        WelcomeSugandh = request.POST.get("WelcomeSugandh")
        ContactSugandh = request.POST.get("ContactSugandh")
        firebase = Firebase(config)
        db = firebase.database()
        x = db.child("About Us").update({
            'Introduction': Introduction,
            'Definition': Definition,
            'Information': Information,
            'WelcomeSugandh': WelcomeSugandh,
            'ContactSugandh': ContactSugandh
        })
    return redirect("/About-Us")
Пример #13
0
    def Post():
        config = {
            "apiKey": "AIzaSyDJIZK3ZCPPu3KNK0-1TuPULfbFGUn0aqI",
            "authDomain": "raspberry-pi-571ec.firebaseapp.com",
            "databaseURL": "https://raspberry-pi-571ec.firebaseio.com/",
            "storageBucket": "raspberry-pi-571ec.appspot.com"
        }

        firebase = Firebase(config)
        db = firebase.database()
        storage = firebase.storage()

        try:
            storage.child("Kris' Inbox").child("Image").put(
                "C:/Users/khern/Desktop/Python/Practice.jpg")
            print("Image in storage")
            db.child("Kris' Inbox").child("New").set("1")

        except:
            print("Unable to upload image")
 def update_scores_with_firebase(self):
     self.pb.value = 0
     config = {
         "apiKey": "AIzaSyAdo9hLvVbA-KI7kwFlx2vOILV_o5K-dBE",
         "authDomain": "pa-project-1-graphs.firebaseapp.com",
         "databaseURL": "https://pa-project-1-graphs.firebaseio.com",
         "storageBucket": ""
     }
     self.simulate_loading(10)
     firebase = Firebase(config)
     self.simulate_loading(20)
     db = firebase.database()
     self.simulate_loading(70)
     player_list = db.child("players").get()
     player_info_list = [
         player_list.val()[player_key] for player_key in player_list.val()
     ]
     self.simulate_loading(100)
     self.update(player_info_list)
     self.scores = player_info_list
Пример #15
0
def syncWithCloud():
    if checkNetwork():
        try:
            firebase = Firebase(config)
            db = firebase.database()
            poles = db.child("poles").child("pole1").child("switchStatus").get()
            #print(poles.val())

            #for pole in poles.each():
                #print(pole.key())
               # print(pole.val())
            #print("Data Pulled")
            return poles.val()
        except:
            print("Firebase Error")
            return False



#updateOnCloud()
#syncWithCloud()
Пример #16
0
    return y_pred2[0]


from firebase import Firebase

config = {
    "apiKey": "AIzaSyBGv_05cA2Qm1QEuKUZ4U-hFCiyxc1e_8A",
    "authDomain": "car-price-bbaa2.firebaseapp.com",
    "databaseURL": "https://car-price-bbaa2.firebaseio.com",
    "storageBucket": "car-price-bbaa2.appspot.com",
    "serviceAccount": "car-price-bbaa2-firebase-adminsdk-hk1k5-7dd02ad457.json"
}

firebase = Firebase(config)
db = firebase.database()


def set_events():
    all_events = db.child("events").get()
    e = []
    for i in all_events.each():
        e.append(i.key())
    return set(e)


result = set_events()
while True:
    add = set_events() - result
    if len(add) > 0:
        print('add :', add)
import os
API_BINANCE_KEY = os.getenv("API_BINANCE_KEY")
API_BINANCE_SECRET = os.getenv("API_BINANCE_SECRET")

from firebase import Firebase

firebaseConfig = {
    "apiKey": os.getenv("FIREBASE_API_KEY"),
    "authDomain": "pybot-bottrade.firebaseapp.com",
    "projectId": "pybot-bottrade",
    "storageBucket": "pybot-bottrade.appspot.com",
    "messagingSenderId": "966280251835",
    "appId": "1:966280251835:web:a9ceef709f806fee8cdc9e",
    "measurementId": "G-KN2EG9DBH4",
    "databaseURL": os.getenv("FirebaseDatabaseURL"),
    "serviceAccount":
    "pybot-bottrade-firebase-adminsdk-9em5u-123a2cfc0e.json"  # นำไฟล์ของท่านมาใส่เองด้วย
}

firebaseCleint = Firebase(firebaseConfig)
auth = firebaseCleint.auth()
# ใช้ Service account .json ในการ authenticate as admin ได้เลย
# สามารถดูตามวิดิโอในกลุ่มนะคับ
# user = auth.sign_in_with_email_and_password(os.getenv("FIREBASE_EMAIL_AUTH"), os.getenv("FIREBASE_PASSWORD"))

#ทดสอบ
if __name__ == '__main__':
    db = firebaseCleint.database()
    data = {"name": "TEST"}
    user = auth.refresh(user['refreshToken'])
    results = db.child("users").push(data, user['idToken'])
Пример #18
0
def setTime():
    
    firebase = Firebase(config)
    db=firebase.database()
    db.child("time").set(int(time.time()))
Пример #19
0
class FirebaseConnection:
    def __init__(self):
        self.config = {
        'apiKey': "AIzaSyD3mdx4IJ4y5l9t16UAXiLsMyQEEDkpSPE",
        'authDomain': "pyrocoinip.firebaseapp.com",
        'databaseURL': "https://pyrocoinip.firebaseio.com",
        'storageBucket': "pyrocoinip.appspot.com",
        }
        self.firebase = Firebase(self.config)
        self.dataBase = self.firebase.database()

        self.nodeHostName = socket.gethostname()
        self.IPAddress = socket.gethostbyname(self.nodeHostName)
        self.currentNode = {'IP': self.IPAddress, 'PORT': 5050}
    
    def ReadStorage(self):
        self.ListOfNodeIPs = []
        with open('Endpoints.txt', 'r+') as EndpointsData:
            for line in EndpointsData:
                line = line.strip()
                self.ListOfNodeIPs.append(line)

    def ConvertToDict(self):
        self.NodesSockets = self.ListOfNodeIPs.copy()
        self.Nodes = []
        for string in self.NodesSockets:
            try:
                dictionary = eval(string)
                self.Nodes.append(dictionary)
            
            except:
                self.ListOfNodeIPs.remove(string)
        self.ListOfNodeIPs = self.Nodes.copy()
        
        

            

    def findSockets(self):
        if os.stat('Endpoints.txt').st_size == 0:
            self.dataBase.child('users').push(self.currentNode)

            users = self.dataBase.child('users').get()
            userDictionaries = users.val().values()
            self.userIPList = []
            EndpointsData = open('Endpoints.txt', 'w+')

            for data in userDictionaries:
                self.userIPList.append(data)
                EndpointsData.write("%s\n" % data)
            EndpointsData.close()
        else:
            EndpointsData = open('Endpoints.txt', 'r+')
            EndpointsData.truncate(0)
            users = self.dataBase.child('users').get()
            try:
                userDictionaries = users.val().values()
            except:
                userDictionaries = [self.currentNode]
            self.userIPList = []
            with open('Endpoints.txt', 'w') as f:
                for item in userDictionaries:
                    self.userIPList.append(item)
                    f.write("%s\n" % item)
            EndpointsData.close()
            

        self.ReadStorage()
        self.ConvertToDict()
Пример #20
0
from django.http import JsonResponse
from django.shortcuts import render
from django.views.generic import ListView
from firebase import Firebase, firebase
from django.contrib.auth.models import User
# Create your views here.

Config = {
    "apiKey": "AIzaSyBSIAwxO5geJSslxclj68G33dZ-yumOEMI",
    "authDomain": "mapstec-81290.firebaseapp.com",
    "databaseURL": "https://mapstec-81290.firebaseio.com",
    "storageBucket": "mapstec-81290.appspot.com",
    "measurementId": "G-85RHV43HWV"
}
_firebase = Firebase(Config)
db = _firebase.database()


class crear_evento(ListView):
    template_name = 'crear_evento.html'
    context_object_name = 'data'
    model = User


class informacion(ListView):
    template_name = 'information.html'
    context_object_name = 'data'
    model = User


class tablas(ListView):
def match_captured_image_with_thumbnails(file_path):
    config = {
        "apiKey": "AIzaSyDwu5UlB1jj-rQI05L1VEKJovXYShgWRbk",
        "authDomain": "koobookandroidapp.firebaseapp.com",
        "databaseURL": "https://koobookandroidapp.firebaseio.com",
        "storageBucket": "koobookandroidapp.appspot.com"
    }

    firebase = Firebase(config)
    db = firebase.database()
    storage = firebase.storage()

    # Load photo that was captured from android device
    url = "Photos/" + file_path
    recently_captured_photo_url = storage.child(url).get_url(None)
    req = urllib.request.urlopen(recently_captured_photo_url)
    arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
    img = cv2.imdecode(arr, 0)
    height, width = img.shape[:2]
    img = cv2.resize(img, (round(width / 10), round(height / 10)),
                     interpolation=cv2.INTER_AREA)
    # Get all thumbnail urls from firebase database
    allUrls = db.child("Book_thumbnail_urls").get()
    for i in allUrls.each():
        urls = i.item[1]

    # For each url retrieved from the database, use it to create an image via Cv2 and use it to run the brute force matching
    # Then get the top 5 matches distinace values, average it and store that along with the url in a dictionary
    top_matches_thumbnail_urls = {}

    for url in urls:
        if type(url) is str:
            req = urllib.request.urlopen(url)
            arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
            img2 = cv2.imdecode(arr, 0)
            img2 = cv2.resize(img2, (round(width / 10), round(height / 10)),
                              interpolation=cv2.INTER_AREA)

            # Credit to Pysource for the code https://www.youtube.com/watch?v=Fe-KWKPk9Zc
            # Define detector of similarities
            orb = cv2.ORB_create()

            keypoint1, descriptor1 = orb.detectAndCompute(img, None)
            keypoint2, descriptor2 = orb.detectAndCompute(img2, None)

            # Brute Force Matching
            bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=False)

            # Find matches and sort based on accuracy/confidence
            # The smaller the match distance, the better the match

            if (descriptor1 is None or descriptor2 is None) is False:
                matches = bf.match(descriptor1, descriptor2)
                matches = sorted(matches, key=lambda x: x.distance)
                top_matches = matches[:3]
                sum = 0
                for top_match in top_matches:
                    sum += top_match.distance

                avg = sum / 3
                top_matches_thumbnail_urls[url] = avg
    top_matches_thumbnail_urls = sorted(top_matches_thumbnail_urls.items(),
                                        key=lambda x: x[1])
    top_matches_thumbnail_urls = top_matches_thumbnail_urls[:6]
    top_matches_thumbnail_urls = dict(top_matches_thumbnail_urls)
    top_thumbnail_urls = list(top_matches_thumbnail_urls.keys())

    top_thumbnail_urls_concatanated = "#".join(top_thumbnail_urls)

    return top_thumbnail_urls_concatanated
Пример #22
0
def main():
    config = {
        "apiKey": "AIzaSyBkQ5z8Rs5IRP4lHoiWyXV9XVQHjAh-sEI",
        "authDomain": "a-eye-for-the-blind.firebaseapp.com",
        "storageBucket": "a-eye-for-the-blind.appspot.com",
        "databaseURL":
        "https://a-eye-for-the-blind-default-rtdb.firebaseio.com/",
    }
    uid = "^^^^^^^^^^^"  # unique user ID, must set before running
    email = '*****@*****.**'
    password = '******'
    firebase = Firebase(config)
    db = firebase.database()
    auth = firebase.auth()
    storage = firebase.storage()

    user = auth.sign_in_with_email_and_password(email, password)
    user = auth.refresh(user['refreshToken'])

    if uid == "" or email == "" or password == "":
        print("Please set user UID, email, or password in the lines above!")
        sys.exit()

    engine = pyttsx3.init()
    BATCH_SIZE = 1
    eval_num_threads = 2
    opt = TrainOptions().parse(
    )  # set CUDA_VISIBLE_DEVICES before import torch
    model = pix2pix_model.Pix2PixModel(opt)
    torch.backends.cudnn.enabled = True
    torch.backends.cudnn.benchmark = True
    best_epoch = 0
    global_step = 0
    model.switch_to_eval()
    video_list = 'D:/A-Eye For The Blind/2dtodepth/infile1/'
    save_path = 'D:/A-Eye For The Blind/2dtodepth/outfile/'
    uid = 'yQowLXfAMddiITuMFASMoKlSGyh1'
    # initialize the camera
    cam = cv2.VideoCapture(cv2.CAP_DSHOW)  # 0 -> index of camera
    x = 0
    while True:
        s, img = cam.read()
        cv2.imwrite("D:/A-Eye For The Blind/2dtodepth/infile1/filename.jpg",
                    img)  # save image
        # filename = uid + ' ' + time()
        storage.child(f"images/i{str(x)}.jpg").put(
            "D:/A-Eye For The Blind/2dtodepth/infile1/filename.jpg",
            user['idToken'])
        url = storage.child(f"images/i{str(x)}.jpg").get_url(user['idToken'])
        data = {f"i{str(x)}": f"{url}"}
        db.child(f"users/{uid}").child("images").update(data)
        video_data_loader = aligned_data_loader.DAVISDataLoader(
            video_list, BATCH_SIZE)
        video_dataset = video_data_loader.load_data()
        for i, data in enumerate(video_dataset):
            stacked_img = data[0]
            targets = data[1]
            output = model.run_and_save_DAVIS(stacked_img, targets, save_path)
            height, width, _ = output.shape
            width_cutoff = width // 2
            half1 = output[:, :width_cutoff]
            half2 = output[:, width_cutoff:]
            width_cutoff = width // 4
            s1 = half1[:, :width_cutoff]
            s2 = half1[:, width_cutoff:]
            s3 = half2[:, :width_cutoff]
            s4 = half2[:, width_cutoff:]
            commands = finalcommand(s1, s2, s3, s4)
            print(commands)
            if commands[1] == 0:
                if commands[0] == 0 and commands[2] == 0:
                    engine.say("STOP!")
                elif commands[0] == 0:
                    engine.say("Move right.")
                elif commands[2] == 2:
                    engine.say("Move left.")
                else:
                    engine.say("Move left.")
            engine.runAndWait()
        os.remove("D:/A-Eye For The Blind/2dtodepth/infile1/filename.jpg")
        x += 1
        if cv2.waitKey(33) == ord('a'):
            break
    cam.release()
Пример #23
0
Config = {
    'apiKey': "AIzaSyCN8RfCVP2gT-MW2ryZTUEAjXVFsw_qqjg",
    'authDomain': "authn-2dd06.firebaseapp.com",
    'databaseURL': "https://authn-2dd06.firebaseio.com",
    'projectId': "authn-2dd06",
    'storageBucket': "authn-2dd06.appspot.com",
    'messagingSenderId': "1078584542869",
    'appId': "1:1078584542869:web:ba520da0ed056ff47d3d9c",
    'measurementId': "G-58S94BH5NE"
}

default_app = Firebase(Config)

authi = default_app.auth()
databse = default_app.database()


def signin(request):
    return render(request, template_name="signIn.html")


def postsign(request):
    email = request.POST.get('email')
    passw = request.POST.get('password')
    try:
        user = authi.sign_in_with_email_and_password(email, passw)
    except:
        message = "invalid credentials"
        return render(request, "signIn.html", {'messa': message})
    session_id = user['idToken']
Пример #24
0
class IPFSDrive(Tk):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.geometry("300x350")
        self.title("IPFS-Drive")

        mainframe = Frame(self)
        mainframe.pack(side="top", fill="both", expand=True)
        mainframe.grid_rowconfigure(0, weight=1)
        mainframe.grid_columnconfigure(0, weight=1)

        self.frames = {}

        for F in (Start, Main, Authentication, Registration):
            frame = F(parent=mainframe, controller=self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        self.frames[Registration].next = Authentication
        self.frames[Start].next = Main
        self.frames[Main].prev = Start

        self.current_frame = None

        self.protocol("WM_DELETE_WINDOW", self.exit)

        self._working_dir_path = None
        self.init_working_dir()

        config = json.load(open("firebase.cfg"))
        self._firebase = Firebase(config)
        self._auth = self._firebase.auth()
        self._db = None
        self._ipfs = None
        self._root_dir_path = None
        self._encryption_password = None
        self._content = None
        self._event_observer = None
        self._sync = None

        self._logger = logging.getLogger()

        self._cipher = AESCipher()
        self._ipfs_client = IPFSClient(self._cipher, self._working_dir_path)
        self._ipfs_cluster = IPFSCluster()

        self.show_frame(Authentication)

    def show_frame(self, frame):
        self.current_frame = self.frames[frame]
        self.current_frame.tkraise()
        if isinstance(self.current_frame, Main):
            self.current_frame.on_raised()

    def get_frame(self, frame):
        return self.frames[frame]

    def get_auth(self):
        return self._firebase.auth()

    def get_content(self):
        return self._content

    def set_root_dir_path(self, root_dir_path):
        self._root_dir_path = root_dir_path.replace(os.sep, '/')

    def init_working_dir(self):
        self._working_dir_path = os.path.join(os.getcwd(), "working_dir")
        if not os.path.exists(self._working_dir_path):
            os.mkdir(self._working_dir_path)
            ctypes.windll.kernel32.SetFileAttributesW(self._working_dir_path, 2)

    def init_db(self, uid, token):
        self._db = Db(self._firebase.database(), uid, token)

    def init_content(self):
        self._content = Content(self._root_dir_path, self._db)

    def init_cipher_key(self, encryption_password):
        self._cipher.create_key(encryption_password)

    def init_ipfs(self):
        self._ipfs = IPFS()
        while not self._ipfs.is_ready():
            time.sleep(0.5)

    def init_sync(self):
        self._sync = Sync(self._root_dir_path, self._working_dir_path, self._content, self._db, self._ipfs_client,
                          self._cipher)

    def init_event_monitoring(self):
        event_handler = EventHandler(self._ipfs_client, self._ipfs_cluster, self._content, self._root_dir_path)
        self._event_observer = Observer()
        self._event_observer.schedule(event_handler, self._root_dir_path, recursive=True)
        self._event_observer.start()

    def synchronize(self):
        self._sync.start()

    def start_listening_for_changes(self):
        self._sync.start_listening()

    def add_root_dir(self, start_time):
        for path in os.listdir(self._root_dir_path):
            full_path = os.path.join(self._root_dir_path, path).replace(os.sep, '/')
            if os.path.getctime(full_path) >= start_time:
                continue
            if os.path.isfile(full_path):
                file = File(full_path)
                hash = self._ipfs_client.add_file(file)
                self._content.add(file.path, hash)
            elif os.path.isdir(full_path):
                content_list = self._ipfs_client.add_dir(Directory(full_path))
                self._content.add_list(content_list)
            self._ipfs_cluster.pin(self._content[full_path])

    def get_content_tree(self):
        db_content = self._db.get_content()

        root_dir = IPFSDirectory('.', None)

        if db_content is None:
            return root_dir

        for k, v in db_content.items():
            name = base64.b64decode(k).decode()
            if '.' in name:
                file = IPFSFile(name, v, root_dir)
                root_dir.add_file(file)
            else:
                dir = IPFSDirectory(name, v, root_dir)
                walk(dir)
                root_dir.add_dir(dir)

        return root_dir

    def attach(self, obj):
        self._content.attach(obj)
        self._logger.debug("Attached to content")
        if self._sync:
            self._sync.attach(obj)
            self._logger.debug("Attached to sync")

    def run(self):
        self.mainloop()

    def exit(self):
        if self.current_frame.close():
            if self._event_observer:
                self._event_observer.stop()
                self._event_observer.join()
            shutil.rmtree(self._working_dir_path)
            self.destroy()
Пример #25
0
def setup_db(player):
    global db
    firebase = Firebase(config)
    db = firebase.database()
    results = db.child("players").child(player.nombre).set("started")