Пример #1
0
    def buildFile(self, fromPath, label="", catg=""):
        count = self.getCountParts(fromPath)
        Sys.pwlog([(" Get Hash... ", Const.CLZ_7, True)])
        sha256 = hash_sha256_file(fromPath)
        Sys.pwlog([(" hash : ", Const.CLZ_0), (sha256, Const.CLZ_2, True), (" Build File...", Const.CLZ_0, True)])

        kg = KeyGen(128)
        size = Sys.getsize(fromPath)
        row = self.idxu.index.get(sha256)
        if row is None:
            if label == "":
                label, ext = Sys.getFileExt(Sys.basename(fromPath))
            else:
                label, ext = Sys.getFileExt(label)
            if catg == "":
                catg = self.idxu.index.getAutoCatg(ext)
            size = Sys.getsize(fromPath)

            Sys.pwlog(
                [
                    (" Splitting ", Const.CLZ_1),
                    (label, Const.CLZ_7),
                    (ext, Const.CLZ_7),
                    (" (", Const.CLZ_0),
                    (Sys.readableBytes(size), Const.CLZ_3),
                    (")", Const.CLZ_0, True),
                ]
            )
            Sys.cli_emit_progress(0)
            Sys.sleep(0.2)
            km = Kirmah(kg.key)
            km.DIR_OUTBOX = self.outbox
            # hlst genetate with sha256
            hlst = km.ck.getHashList(sha256, int(count), True)
            usr = self.idxu.conf.get("name", "infos")
            ownerHash = self.idxu.mb.getHashName(usr)
            km.split(fromPath, hlst)
            Sys.pwlog([(" done ", Const.CLZ_2, True)])
            row = [kg.key, label, ext, count, catg, hlst, usr, ownerHash, sha256, size]
            self.backupAddMap(row)

        else:

            Sys.pwlog(
                [
                    (" File Already exist ! ", Const.CLZ_1, True),
                    (" id : ".rjust(10, " "), Const.CLZ_0),
                    (str(row[ImpraIndex.UID]), Const.CLZ_1, True),
                    (" label : ".rjust(10, " "), Const.CLZ_0),
                    (row[ImpraIndex.LABEL], Const.CLZ_3, True),
                ]
            )

            row = None
        return row
Пример #2
0
    def __init__(self, appname, debug, gui, color, loglvl, ppid, event, id, wp, delay, task, *args, **kwargs):
        def mptask(id, *args, **kwargs):
            Sys.sendMainProcMsg(Manager.MSG_INIT, None)
            otask = task(id=id, event=event, *args, **kwargs)
            Sys.sendMainProcMsg(Manager.MSG_END, None)
            return otask

        init(appname, debug, ppid, color, loglvl)
        Sys.g.WPIPE   = wp
        Sys.g.CPID    = id
        Sys.g.GUI     = gui
        # initialize child process event with parent process event
        Sys.g.MPEVENT = event
        if delay : Sys.sleep(delay)
        mptask(id, *args, **kwargs)
Пример #3
0
 def update_progress(self, progress, lvl=20, thname=None):
     #~ print('update_progress : '+str(thname))
     if True :
         pbar = self.widgetByThread[thname]['pbar']
         if progress > 0 :                
             pbar.set_text(str(progress))
             lp   = pbar.get_fraction()
             diff = (progress/100.0 - lp)
             if diff > 0 :
                 for i in range(lvl):
                     nf = lp+(i*diff/lvl)
                     if nf < progress/100.0 :
                         pbar.set_fraction(nf)
                         Sys.sleep(0.015)
             pbar.set_fraction(progress/100.0)
         else :
             pbar.set_fraction(pbar.get_fraction()+0.01)
Пример #4
0
    def getFileParts(self, row, ids):
        """"""
        done = False
        if len(ids) >= row[self.idxu.index.PARTS]:
            for i, uid in enumerate(ids):
                d = Sys.datetime.now()
                self.idxu.ih.getAttachment(uid, self.inbox, True)

                Sys.pwlog(
                    [
                        (" part ", Const.CLZ_0),
                        (str(i + 1).rjust(2, " "), Const.CLZ_2),
                        (" / ", Const.CLZ_0),
                        (str(len(ids)), Const.CLZ_3),
                        (" downloaded in ", Const.CLZ_0),
                        (Sys.getDelta(d), Const.CLZ_4, True),
                    ]
                )

                Sys.cli_emit_progress(int((i + 1) * 100 / len(ids)))
                Sys.sleep(0.5)

            Sys.mkdir_p(self.deploy + row[self.idxu.index.CATG])
            Sys.cli_emit_progress(100)
Пример #5
0
    def run(self):
        """"""
        self.cancelled = False
        self.evtStop.clear()
        Sys.g.THREAD_CLI       = self
        Sys.g.GUI              = True
        Sys.g.GUI_PRINT_STDOUT = True
        done                   = False
        self.can_retry         = True
        init(conf.PRG_NAME, Sys.g.DEBUG, loglvl=Const.LOG_APP)        
        try :
            if self.impst is None :
                
                label = ' [[ INIT IMPRASTORAGE ]] '
                label = ' '+'~'*((Const.LINE_SEP_LEN-len(label))//2-1)+label+'~'*((Const.LINE_SEP_LEN-len(label))//2-1)+' '
                Sys.pwlog([(Const.LINE_SEP_CHAR*Const.LINE_SEP_LEN , Const.CLZ_0     , True),
                           (label.ljust(Const.LINE_SEP_LEN, ' ')   , Const.CLZ_INIT  , True),
                           (Const.LINE_SEP_CHAR*Const.LINE_SEP_LEN , Const.CLZ_0     , True)])
                
                self.impst = ImpraStorage(self.conf, wkdir='.'+Sys.sep+'wk'+Sys.sep)

            done = True
        except Exception as e :
            self.emit('needconfig')
            raise e
        self.emit('indexrefreshed', done)
        if done :        
            while not self.evtStop.is_set() or not self.cancelled:
                with self.condition :
                    self.condition.wait_for(lambda : not self.taskQueue.empty(), 2)
                    
                    if self.can_retry and self.impst.hasBackupAddMap():
                        self.emit('hasaddretry')
                        self.can_retry = False
                    
                    if not self.taskQueue.empty():
                        task, params, idtask = self.taskQueue.get_nowait()
                        label = ' [[ TASK '+str(idtask)+' : '+self.TASK_LABEL[task].upper()+' ]] '
                        label = ' '+'>'*((Const.LINE_SEP_LEN-len(label))//2-1)+label+'<'*((Const.LINE_SEP_LEN-len(label))//2-1)+' '
                        Sys.pwlog([(Const.LINE_SEP_CHAR*Const.LINE_SEP_LEN , Const.CLZ_0     , True),
                                   (label.ljust(Const.LINE_SEP_LEN, ' ')   , Const.CLZ_ACTION, True),
                                   (Const.LINE_SEP_CHAR*Const.LINE_SEP_LEN , Const.CLZ_0     , True)])
                        
                        try:
                            if task is self.TASK_WAIT :
                                print('wait')
                                Sys.sleep(params)
                            elif task is self.TASK_GET:
                                #~ mg        = Manager(self.taskGet, 1, None, Sys.g.MPEVENT, uid=params)
                                #~ mg.run()
                                #~ self.emit('fileget', True, '')
                                #~ Thread(target=self.taskGet, name='impra-1', kwargs={'uid':params}).start()
                                print(params)
                                self.taskGet(params)
                            elif task is self.TASK_ADD:
                                self.taskAdd(params)
                            elif task is self.TASK_ADD_RETRY:
                                self.taskAddRetry(params)
                            elif task is self.TASK_REFRESH:
                                self.taskRefresh(params)
                            elif task is self.TASK_INFOS:
                                self.taskInfos(params)
                            elif task is self.TASK_REMOVE:
                                self.taskRemove(params)
                            elif task is self.TASK_EDIT:
                                self.taskEdit(params)
                            self.taskQueue.task_done()

                        except self.impst.SocketError() as e :
                            Sys.pwarn((('ImpraThread.run : ',(str(e),Sys.CLZ_WARN_PARAM), ' !'),))
                            self.impst.reconnect()

                        except Exception as e:
                            print(type(e))
                            Sys.pwarn((('ImpraThread.run : ',(str(e),Sys.CLZ_WARN_PARAM), ' !'),))                            
                    else :
                        """"""
                Sys.sleep(0.5)
        self.emit('completed')
Пример #6
0
 def wait(self):
     """"""
     while self.readers:
         self.wait_childs()
         if self.checktime is not None : Sys.sleep(self.checktime)
Пример #7
0
    def getFile(self, uid):
        """"""
        # ~ Sys.pwlog([(Const.LINE_SEP_CHAR*Const.LINE_SEP_LEN , Const.CLZ_0, True)])
        done = False
        key = self.idxu.index.getById(uid)
        row = self.idxu.index.get(key)
        filePath = None
        try:
            if row is not None:
                account = self.idxu.switchFileAccount(row[self.idxu.index.ACCOUNT])
                km = Kirmah(row[self.idxu.index.KEY])
                hlst = km.ck.getHashList(key, row[self.idxu.index.PARTS], True)
                ids = self.idxu.ih.searchBySubject(hlst["head"][2], True)
                Sys.cli_emit_progress(0)
                Sys.sleep(0.2)
                Sys.pwlog(
                    [
                        (" Downloading : ", Const.CLZ_7),
                        (row[self.idxu.index.LABEL] + row[self.idxu.index.EXT], Const.CLZ_2),
                        (" (", Const.CLZ_0),
                        (Sys.readableBytes(row[self.idxu.index.SIZE]), Const.CLZ_3),
                        (")", Const.CLZ_0),
                        (" please wait...", Const.CLZ_7, True),
                    ]
                )

                if len(ids) >= row[self.idxu.index.PARTS]:
                    self.getFileParts(row, ids)

                    Sys.pwlog([(" Merging parts...", Const.CLZ_7, True)])
                    Sys.cli_emit_progress(0)
                    Sys.sleep(0.2)
                    filePath = km.merge(
                        hlst,
                        self.deploy + row[self.idxu.index.CATG] + Sys.sep + row[self.idxu.index.LABEL],
                        ext=row[self.idxu.index.EXT],
                        uid=row[self.idxu.index.UID],
                        dirs=self.inbox,
                    )

                    Sys.pwlog(
                        [
                            (" Deployed as ", Const.CLZ_7),
                            (filePath, Const.CLZ_2),
                            (" (", Const.CLZ_0),
                            (Sys.readableBytes(Sys.getsize(filePath)), Const.CLZ_3),
                            (") ", Const.CLZ_0, True),
                            (" Checking integrity...", Const.CLZ_7, True),
                        ]
                    )
                    Sys.sleep(0.2)
                    sha256 = hash_sha256_file(filePath)
                    done = sha256 == row[ImpraIndex.HASH]
                    done = True

                else:
                    print("incomplete")

        except Exception as e:
            print(e)
        Sys.pwlog([(" done" if done else "ko", Const.CLZ_2 if done else Const.CLZ_1, True)])
        return done, filePath
Пример #8
0
    def sendFile(self, data, retry=False):
        """"""
        done = None
        key = None
        if data is not None:
            key, label, ext, count, catg, hlst, usr, ownerHash, sha256, size = data
            self.idxu.index.addUser(usr, ownerHash)
            account = self.idxu.switchFileAccount()
            sendIds = []
            cancel = False
            d = None

            Sys.cli_emit_progress(0)
            Sys.sleep(0.2)
            if not retry:
                Sys.pwlog(
                    [
                        (" Sending... ", Const.CLZ_7),
                        (" (", Const.CLZ_0),
                        (
                            " ~" + Sys.readableBytes(Sys.getsize(self.outbox + hlst["data"][0][1] + Kirmah.EXT)),
                            Const.CLZ_3,
                        ),
                        (" per msg ) ", Const.CLZ_0, True),
                    ]
                )
            else:
                Sys.pwlog(
                    [
                        (" Retry sending last file... ", Const.CLZ_0),
                        (label + ext, Const.CLZ_7),
                        (" (" + catg + ")", Const.CLZ_3, True),
                    ]
                )

            ignore = False

            for i, row in enumerate(hlst["data"]):
                """"""
                if retry:
                    if not Io.file_exists(self.outbox + row[1] + Kirmah.EXT):
                        continue
                    elif not ignore:
                        Sys.pwlog([(" Ignoring file 1 to " + str(i), Const.CLZ_1, True)])
                        ignore = True

                d = Sys.datetime.now()
                msg = self.idxu.mb.build(usr, "all", hlst["head"][2], self.outbox + row[1] + Kirmah.EXT)
                try:
                    mid = self.idxu.ih.send(msg.as_string(), self.rootBox)
                except Exception as e:
                    Sys.pwarn((("addFile : ", (str(e), Sys.CLZ_WARN_PARAM), " !"),))
                    Sys.echo("waiting 5 s and retry")
                    Sys.sleep(5)
                    # force reconnect
                    self.impst.idxu.switchFileAccount(account, True)
                    # retry
                    mid = self.idxu.ih.send(msg.as_string(), self.rootBox)
                finally:
                    if not mid is None:
                        status, resp = self.idxu.ih.fetch(mid[1], "(UID BODYSTRUCTURE)", True)
                        if status == self.idxu.ih.OK:
                            sendIds.append((mid[1], row))
                            Sys.pwlog(
                                [
                                    (" part ", Const.CLZ_0),
                                    (str(row[0]).rjust(2, "0"), Const.CLZ_2),
                                    (" sent as msg ", Const.CLZ_0),
                                    (str(mid[1]).rjust(5, "0"), Const.CLZ_1),
                                    (" (", Const.CLZ_7),
                                    (str(int(row[4]) + 1).rjust(2, "0"), Const.CLZ_2),
                                    ("/", Const.CLZ_7),
                                    (str(count), Const.CLZ_3),
                                    (") in ", Const.CLZ_7),
                                    (Sys.getDelta(d), Const.CLZ_4, True),
                                ]
                            )

                            Sys.cli_emit_progress(int((i + 1) * 100 / len(hlst["data"])))

                            Sys.removeFile(self.outbox + row[1] + Kirmah.EXT)
                        else:
                            Sys.pwarn((("error occured when sending part ", (row[0], Sys.Clz.fgb3), " !"),))

            diff = self.checkSendIds(sendIds, hlst["head"][2])
            if len(sendIds) == count or retry:
                self.idxu.get(True)
                self.idxu.index.add(key, label, hlst["head"][1], ext, ownerHash, catg, sha256, size, account)
                done = self.idxu.update()
                Io.removeFile(self.addmapPath + Kirmah.EXT)

            # resending missing parts
            else:
                Sys.pwarn((("TODO => must resending ", ("missing", Sys.CLZ_WARN_PARAM), " parts"),))
                print(diff)

            # clean
            for mid, row in sendIds:
                if Io.file_exists(self.outbox + row[1] + Kirmah.EXT):
                    Sys.removeFile(self.outbox + row[1] + Kirmah.EXT)
            if cancel:
                delids = [mid for mid, row in senids]
                print(delids)
                self.idxu.ih.delete(delids, True)
        return done, key