Ejemplo n.º 1
0
def main():
    global sync
    print(sys.argv)
    url = "index.html"
    if len(sys.argv) > 1:
        url = sys.argv[1]
    print("main thread id:", threading.get_ident())

    data_dir = appdirs.user_data_dir(APPNAME)
    if not os.path.exists(data_dir):
        os.mkdir(data_dir)

    setting = read_setting_db()
    if not setting:
        setting = {
            "workspace": os.path.join(Path.home(), "gitCloud"),
            "interval": config.SYNC_INTERVAL
        }
    print("setting:", setting)
    excludesFile = os.path.join(appdirs.user_data_dir(APPNAME), ".gitignore")
    createExcludesFile(excludesFile)
    print("excludesFile:", excludesFile)

    workspace = setting["workspace"]
    if not os.path.exists(workspace):
        os.mkdir(workspace)

    if os.path.isabs(config.GIT):
        path = os.path.dirname(config.GIT)
        env_path = os.getenv("PATH")
        if env_path:
            env_path = env_path + ":" + path
        else:
            env_path = path
        set_env_path(env_path)

    api = Api(setting)
    repos = [repo.copy() for repo in api.repos]
    sync = Sync(repos, event_q, setting["interval"], excludesFile)

    window = webview.create_window('gitCloud',
                                   url,
                                   width=400,
                                   height=680,
                                   js_api=api)
    api.window = window

    api.start()
    sync.start(sync_q, workspace)

    webview.start(debug=config.DEBUG)
Ejemplo n.º 2
0
class SyncFrame(Frame):
    def __init__(self,master=None,controller=None,conn=None):
        Frame.__init__(self,master)

        self.controller = controller
        self.conn = self.controller.get_conn()
        self.logo = self.controller.get_logo()

        self.remotePgmTotal = 0
        self.remoteTrackTotal = 0

    def onShow(self):

        print(self.controller.get_srvAddr())
        self.sync = Sync(srvAddr=self.controller.get_srvAddr(),conn=self.conn,session=self.controller.get_session())

        if self.sync is not None:
            self.sync.dosync()
            self.remotePgmTotal = self.sync.getRemoteProgramTotalCount()
            self.remoteTrackTotal = self.sync.getRemoteTrackTotalCount()

        banner = Frame(self)
        banner.grid(row=0,column=0,sticky="WE")
        self.label = Label(banner,image=self.logo)
        self.label.image = self.logo
        self.label.pack()

        body = Frame(self)
        body.grid(row=1,column=0,sticky="NSWE")

        Label(body,text="歌曲同步中...",padding=(10, 5, 10, 5)).grid(row=1,column=0,sticky="WE")
        self.pgb_media = Progressbar(body, orient="horizontal", length=200, mode="determinate")
        self.pgb_media.grid(row=1,column=1,sticky="WE")
        self.pgb_media["value"]=0
        self.pgb_media["maximum"]=self.remoteTrackTotal

        self.sync.start()
        self.checkstatus()

    def checkstatus(self):
        self.pgb_media["value"] = 0 if self.sync is None else self.sync.getTrackIdx()
        if self.pgb_media["value"] >= self.remoteTrackTotal:
            self.gotoMain()
        else:
            self.after(200,self.checkstatus)

    def gotoMain(self):
        print('going to main....')
        self.controller.show_frame(EnvoMaster)
Ejemplo n.º 3
0
class SyncDevice(Device, metaclass=DeviceMeta):
    """
    Tango Sync device class.

    Parameters
    ----------
    None

    Examples
    --------

    >>> from PyTango.server import server_run
    >>> server_run((SyncDevice,))

    """

    time = attribute()  # read only is default

    error_handler = attribute(
        dtype=str,
        access=AttrWriteType.READ_WRITE,
    )

    device = attribute(
        dtype=str,
        access=AttrWriteType.READ_WRITE,
    )

    counter_input = attribute(
        dtype=str,
        access=AttrWriteType.READ_WRITE,
    )

    counter_output = attribute(
        dtype=str,
        access=AttrWriteType.READ_WRITE,
    )

    pulse_freq = attribute(
        dtype=float,
        access=AttrWriteType.READ_WRITE,
    )

    output_path = attribute(
        dtype=str,
        access=AttrWriteType.READ_WRITE,
    )

    line_labels = attribute(
        dtype=str,
        access=AttrWriteType.READ_WRITE,
    )

    # ------------------------------------------------------------------------------
    # INIT
    # ------------------------------------------------------------------------------

    def init_device(self):
        """
        Device constructor.  Automatically run by Tango upon device export.
        """
        self.set_state(DevState.ON)
        self.set_status("READY")
        self.attr_error_handler = ""
        self.attr_device = 'Dev1'
        self.attr_counter_input = 'ctr0'
        self.attr_counter_output = 'ctr2'
        self.attr_counter_bits = 64
        self.attr_event_bits = 24
        self.attr_pulse_freq = 10000000.0
        self.attr_output_path = "C:/sync/output/test.h5"
        self.attr_line_labels = "[]"
        print("Device initialized...")

    # ------------------------------------------------------------------------------
    # Attribute R/W
    # ------------------------------------------------------------------------------

    def read_time(self):
        return time.time()

    def read_error_handler(self):
        return self.attr_error_handler

    def write_error_handler(self, data):
        self.attr_error_handler = data

    def read_device(self):
        return self.attr_device

    def write_device(self, data):
        self.attr_device = data

    def read_counter_input(self):
        return self.attr_counter_input

    def write_counter_input(self, data):
        self.attr_counter_input = data

    def read_counter_output(self):
        return self.attr_counter_output

    def write_counter_output(self, data):
        self.attr_counter_output = data

    def read_pulse_freq(self):
        return self.attr_pulse_freq

    def write_pulse_freq(self, data):
        self.attr_pulse_freq = data

    def read_output_path(self):
        return self.attr_output_path

    def write_output_path(self, data):
        self.attr_output_path = data

    def read_line_labels(self):
        return self.attr_line_labels

    def write_line_labels(self, data):
        self.attr_line_labels = data

    # ------------------------------------------------------------------------------
    # Commands
    # ------------------------------------------------------------------------------

    @command(dtype_in=str, dtype_out=str)
    def echo(self, data):
        """
        For testing. Just echos whatever string you send.
        """
        return data

    @command(dtype_in=str, dtype_out=None)
    def throw(self, msg):
        print(("Raising exception:", msg))
        # Send to error handler or sequencing engine

    @command(dtype_in=None, dtype_out=None)
    def start(self):
        """
        Starts an experiment.
        """
        print("Starting experiment...")

        self.sync = Sync(
            device=self.attr_device,
            counter_input=self.attr_counter_input,
            counter_output=self.attr_counter_output,
            counter_bits=self.attr_counter_bits,
            event_bits=self.attr_event_bits,
            output_path=self.attr_output_path,
            freq=self.attr_pulse_freq,
            verbose=True,
            force_sync_callback=False,
        )

        lines = eval(self.attr_line_labels)
        for index, line in enumerate(lines):
            self.sync.add_label(index, line)

        self.sync.start()

    @command(dtype_in=None, dtype_out=None)
    def stop(self):
        """
        Stops an experiment and clears the NIDAQ tasks.
        """
        print("Stopping experiment...")
        try:
            self.sync.stop()
        except Exception as e:
            print(e)

        self.sync.clear(self.attr_output_path)
        self.sync = None
        del self.sync

    @command(dtype_in=str, dtype_out=None)
    def load_config(self, path):
        """
        Loads a configuration from a .pkl file.
        """
        print(("Loading configuration: %s" % path))

        with open(path, 'rb') as f:
            config = pickle.load(f)

        self.attr_device = config['device']
        self.attr_counter_input = config['counter']
        self.attr_counter_output = config['pulse']
        self.attr_counter_bits = int(config['counter_bits'])
        self.attr_event_bits = int(config['event_bits'])
        self.attr_pulse_freq = float(config['freq'])
        self.attr_output_path = config['output_dir']
        self.attr_line_labels = str(config['labels'])

    @command(dtype_in=str, dtype_out=None)
    def save_config(self, path):
        """
        Saves a configuration to a .pkl file.
        """
        print(("Saving configuration: %s" % path))

        config = {
            'device': self.attr_device,
            'counter': self.attr_counter_input,
            'pulse': self.attr_counter_output,
            'freq': self.attr_pulse_freq,
            'output_dir': self.attr_output_path,
            'labels': eval(self.attr_line_labels),
            'counter_bits': self.attr_counter_bits,
            'event_bits': self.attr_event_bits,
        }

        with open(path, 'wb') as f:
            pickle.dump(config, f)

    @command(dtype_in=str, dtype_out=None)
    def copy_dataset(self, folder):
        """
        Copies last dataset to specified folder.
        """
        source = self.attr_output_path
        dest = os.path.join(folder, os.path.basename(source))

        copyfile(source, dest)
Ejemplo n.º 4
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()