class MoveRename(QWidget):

    logginn = pyqtSignal(str, str, int)

    def __init__(self):
        super(MoveRename, self).__init__()
        self.loggin = Logger('MoveRenameGui', self.logginn)
        self.cl = QVBoxLayout()

        tt = QHBoxLayout()
        self.pathbar = QLineEdit()
        folder = qta.icon(
            'fa5s.folder-open',
            color='orange',
            color_active='red')
        self.pathbtn = QPushButton(folder, '')
        tt.addWidget(self.pathbar)
        tt.addWidget(self.pathbtn)
        self.cl.addLayout(tt)

        tt = QHBoxLayout()
        selall = qta.icon(
            'mdi.select-all',
            color='blue',
            color_active='red')
        self.all = QPushButton(selall, '')
        selinv = qta.icon(
            'mdi.select-inverse',
            color='blue',
            color_active='red')
        self.invert = QPushButton(selinv, "")
        self.move = QButtonGroup()
        tt1 = QRadioButton("Mover")
        tt1.setChecked(True)
        tt2 = QRadioButton("Renombrar")
        tt3 = QRadioButton("Renombrar a #")
        self.move.addButton(tt1, 1)
        self.move.addButton(tt2, 2)
        self.move.addButton(tt3, 3)
        self.move.setExclusive(True)
        tt.addWidget(self.all)
        tt.addWidget(self.invert)
        tt.addStretch()
        tt.addWidget(tt1)
        tt.addWidget(tt2)
        tt.addWidget(tt3)
        self.cl.addLayout(tt)

        self.li = QListWidget()
        self.cl.addWidget(self.li)
        self.li.itemDoubleClicked.connect(self.edititem)

        tt = QHBoxLayout()
        procc = qta.icon(
            'mdi.play',
            color='green',
            color_active='red')
        self.proc = QPushButton(procc, "")
        tt.addWidget(self.proc)
        tt.addStretch()
        self.cl.addLayout(tt)

        self.setLayout(self.cl)

        self.pathbtn.clicked.connect(self.set_path)
        self.li.itemClicked.connect(self.check_item)
        self.all.clicked.connect(self.allf)
        self.invert.clicked.connect(self.invertf)
        self.move.buttonClicked.connect(self.gen_list)
        self.proc.clicked.connect(self.procces)
        self.movethread = None

    def gen_list(self, id):
        if self.pathbar.text() == '':
            return
        self.build_ui_caps()
        self.allf()

    @pyqtSlot()
    def allf(self):
        li = self.li
        if li.count() == 0:
            return
        cpsm = self.capsmap
        for i in range(li.count()):
            item = li.item(i)
            if item.checkState() == Qt.Unchecked:
                item.setCheckState(Qt.Checked)
                txt = item.text().split("\t")
                cpsm[txt[1]]['state'] = True

    @pyqtSlot()
    def invertf(self):
        li = self.li
        if li.count() == 0:
            return
        cpsm = self.capsmap
        for i in range(li.count()):
            item = li.item(i)
            if item.checkState() == Qt.Unchecked:
                item.setCheckState(Qt.Checked)
                txt = item.text().split("\t")
                cpsm[txt[1]]['state'] = True
            else:
                item.setCheckState(Qt.Unchecked)
                txt = item.text().split("\t")
                cpsm[txt[1]]['state'] = False

    def check_item(self, item):
        cpsm = self.capsmap
        if item.checkState() == Qt.Unchecked:
            item.setCheckState(Qt.Checked)
            txt = item.text().split("\t")
            cpsm[txt[1]]['state'] = True
        else:
            item.setCheckState(Qt.Unchecked)
            txt = item.text().split("\t")
            cpsm[txt[1]]['state'] = False

    def edititem(self, item):
        cpsm = self.capsmap
        txt = item.text().split("\t")
        text, ok = QInputDialog.getText(None, "Editar",
                                        "Nombre:", QLineEdit.Normal,
                                        txt[0])
        if ok and text != '' and not(text is None):
            if text == txt[0]:
                return
            pth = cpsm[txt[1]]['vpath']
            pth2 = join(split(pth)[0], text)
            try:
                self.vfs.move(pth, pth2)
            except fs.errors.DestinationExists:
                self.loggin.emit(
                    'Ya existe otro fichero que tiene este posible nombre', ERROR)
                return
            cpsm[txt[1]]['vpath'] = pth2
            cpsm[txt[1]]['fixname'] = text
            item.setText(text + '\t' + txt[1])
            item.setCheckState(Qt.Checked)
            cpsm[txt[1]]['state'] = True

    def get_path(self):
        txt = self.pathbar.text()
        if txt is None or txt == "":
            txt = ""
        dirr = QFileDialog.getExistingDirectory(self, "Selecionar Directorio",
                                                txt,
                                                QFileDialog.ShowDirsOnly
                                                | QFileDialog.DontResolveSymlinks)
        # print(dirr)
        return dirr

    @pyqtSlot()
    def set_path(self):
        if self.movethread:
            if self.movethread.isAlive():
                self.loggin.emit(
                    'Hay un proceso en este momento, espere.', WARNING)
                return
        dirr = self.get_path()
        if dirr is None or dirr == '':
            return
        self.dirr = dirr
        self.pathbar.setText(dirr)
        self.build_ui_caps()
        self.allf()

    def build_ui_caps(self):
        dirr = self.dirr
        with OSFS(dirr) as f:
            data = make_temp_fs(f)
        self.vfs = data
        capsmap = {}
        vfs = self.vfs
        # vfs.tree()
        for path, _, files in vfs.walk():
            for i in files:
                dd = {}
                nn = i.name
                pp = rename(nn)
                dd['fixname'] = nn
                dd['cap'] = pp.episode
                dd['season'] = pp.season
                opth = vfs.gettext(join(path, nn))
                oon = split(opth)[1]
                dd['original'] = oon
                dd['ext'] = pp.ext.lower()
                dd['vpath'] = join(path, nn)
                dd['state'] = True
                dd['fold'] = split(path)[1]
                capsmap[oon] = dd
        self.capsmap = capsmap
        nonly = self.move.checkedId() == 3
        li = self.li
        lic = li.count()
        cps = list(capsmap.values())
        cpl = len(cps)
        if cpl <= lic:
            for n, i in enumerate(cps):
                name = i['fixname']
                if nonly:
                    name = i['cap'] + i['ext']
                ll = li.item(n)
                ll.setText(name + "\t" + i['original'])
            for i in range(lic - cpl):
                ll = li.takeItem(0)
                del ll
        else:
            for i in range(lic):
                name = cps[i]['fixname']
                if nonly:
                    name = i['cap'] + i['ext']
                ll = li.item(i)
                ll.setText(name + "\t" + cps[i]['original'])
            for i in range(cpl - lic):
                name = cps[lic + i]['fixname']
                if nonly:
                    name = i['cap'] + i['ext']
                li.addItem(name + "\t" + cps[lic + i]['original'])

    @pyqtSlot()
    def procces(self):
        if self.pathbar.text() == '':
            return
        if self.move.checkedId() == 1:
            self.movef(self.pathbar.text())
        else:
            self.renamef(self.pathbar.text())

    def movef(self, path):
        if self.movethread:
            if self.movethread.isAlive():
                self.loggin.emit(
                    'Hay un proceso en este momento, espere.', WARNING)
                return
        self.movethread = Thread(target=self._movef, args=(path,))
        self.movethread.start()

    def renamef(self, path):
        if self.movethread:
            if self.movethread.isAlive():
                self.loggin.emit(
                    'Hay un proceso en este momento, espere.', WARNING)
                return
        self.movethread = Thread(target=self._renamef, args=(path,))
        self.movethread.start()

    def _movef(self, path):
        # ram = self.vfs
        with OSFS(path) as ff:
            for data in self.capsmap.values():
                if not data['state']:
                    continue
                fold = data['fold']
                path = join('/', fold)
                if not(ff.exists(path)):
                    ff.makedir(path)
                path2 = join(path, data['fixname'])
                opth = join('/', data['original'])
                self.loggin.emit("Moviendo y renombrando: " + data['original'] + ' para ' + join(
                    data['fold'], data['fixname']), INFORMATION)
                try:
                    ff.move(opth, path2, True)
                except Exception as e:
                    self.loggin.emit("Error en archivo: " +
                                     data['original'] + '<br>' + str(e), ERROR)
        self.loggin.emit("Mover finalizado.", DEBUG)
        self.build_ui_caps()
        self.allf()

    def _renamef(self, path):
        with OSFS(path) as ff:
            for data in self.capsmap.values():
                if not data['state']:
                    continue
                if data['fixname'] == data['original']:
                    continue
                path = '/'
                path2 = join(path, data['fixname'])
                opth = join(path, data['original'])
                self.loggin.emit(
                    "Renombrando: " + data['original'] + ' a ' + data['fixname'], INFORMATION)
                try:
                    ff.move(opth, path2, overwrite=True)
                except Exception as e:
                    self.loggin.emit("Error en archivo: " +
                                     split(opth)[1] + '<br>' + str(e), ERROR)
        self.loggin.emit("Renombrar finalizado.", DEBUG)
        self.build_ui_caps()
        self.allf()
class FTPGui(QWidget):

    logginn = pyqtSignal(str, str, int)

    def __init__(self):
        super(FTPGui, self).__init__()
        self.cl = QVBoxLayout()
        self.loggin = Logger('FTPGui', self.logginn)

        tt = QHBoxLayout()
        self.local = QLabel('Local: ', self)
        self.pathbar = QLineEdit(self)
        folder = qta.icon('fa5s.folder-open',
                          color='orange',
                          color_active='red')
        self.pathbtn = QPushButton(folder, "", self)
        tt.addWidget(self.local)
        tt.addWidget(self.pathbar)
        tt.addWidget(self.pathbtn)
        self.cl.addLayout(tt)

        tt = QHBoxLayout()
        self.iplable = QLabel('ip: ')
        self.ip = QLineEdit(self)
        self.ip.setValidator(
            QRegExpValidator(
                QRegExp('[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'),
                self.ip))
        self.portlable = QLabel('puerto: ')
        self.port = QLineEdit(self)
        self.port.setValidator(QIntValidator(self.port))
        self.port.setText('21')
        conn = qta.icon('mdi.lan-connect', color='orange', color_active='red')
        self.ftpcon = QPushButton(conn, "", self)
        tt.addWidget(self.iplable)
        tt.addWidget(self.ip)
        tt.addSpacing(10)
        tt.addWidget(self.portlable)
        tt.addWidget(self.port)
        tt.addSpacing(10)
        tt.addWidget(self.ftpcon)
        self.cl.addLayout(tt)

        tt = QHBoxLayout()
        self.userlable = QLabel('usuario: ', self)
        self.user = QLineEdit(self)
        self.passwtlable = QLabel('contraseña: ', self)
        self.passw = QLineEdit(self)
        self.passw.setEchoMode(QLineEdit.Password)
        tt.addWidget(self.userlable)
        tt.addWidget(self.user)
        tt.addSpacing(10)
        tt.addWidget(self.passwtlable)
        tt.addWidget(self.passw)
        tt.addSpacing(10)
        self.cl.addLayout(tt)

        tt = QHBoxLayout()
        self.local = QLabel('FTP: ')
        self.pathbarftp = QLineEdit(self)
        self.pathbarftp.setReadOnly(True)
        tt.addWidget(self.local)
        tt.addWidget(self.pathbarftp)
        self.cl.addLayout(tt)

        self.li = QListWidget(self)
        self.cl.addWidget(self.li)
        self.li.itemDoubleClicked.connect(self.ftp_move_to)

        tt = QHBoxLayout()
        find = qta.icon('fa5s.search', color='orange', color_active='red')
        self.proc = QPushButton(find, "", self)
        tt.addWidget(self.proc)
        tt.addStretch()
        #self.configs = QToolButton(self)
        # self.configs.setPopupMode(QToolButton.InstantPopup)
        #self.confmenu = QMenu(self.configs)
        # tt.addWidget(self.configs)
        self.cl.addLayout(tt)

        tt = QVBoxLayout()
        tt3 = QHBoxLayout()
        self.namelabel = QLabel(self)
        tt3.addWidget(self.namelabel)
        tt2 = QHBoxLayout()
        self.progresslabel = QLabel(self)
        self.speedlabel = QLabel(self)
        tt2.addWidget(self.progresslabel)
        tt2.addWidget(self.speedlabel)
        self.progress = QProgressBar(self)
        self.progress.setMinimum(0)
        self.progress.setMaximum(100)
        tt.addLayout(tt3)
        tt.addLayout(tt2)
        tt.addWidget(self.progress)
        self.cl.addLayout(tt)

        self.setLayout(self.cl)
        self.pathbtn.clicked.connect(self.set_path)
        self.proc.clicked.connect(self.procces)
        self.ftpcon.clicked.connect(self.connectar)
        self.ftpm = None
        self.in_progress = False

    @pyqtSlot()
    def connectar(self):
        try:
            port = int(self.port.text())
        except:
            self.loggin.emit('Puerto incorrect', ERROR)
            return
        ip = self.ip.text()
        if len(ip.split('.')) != 4:
            self.loggin.emit('ip incorrect', ERROR)
            return
        try:
            if self.ftpm:
                self.ftpm.close()
                reconnect(self.ftpm.copier.worker.names)
                reconnect(self.ftpm.copier.worker.progress)
                reconnect(self.ftpm.copier.worker.finish)
                reconnect(self.ftpm.copier.finish)
            self.ftpm = FTPManager(ip, self.user.text(), self.passw.text(),
                                   port, self.loggin)
            reconnect(self.ftpm.copier.worker.names, self.change_names)
            reconnect(self.ftpm.copier.worker.progress, self.update)
            reconnect(self.ftpm.copier.worker.finish, self.copy_finish2)
            reconnect(self.ftpm.copier.finish, self.copy_finish)
            self.pathbarftp.setText('/')
        except Exception as e:
            self.loggin.emit(str(e), ERROR)
            return
        self.li.clear()
        for i in self.ftpm.list_dir('/'):
            item = QListWidgetItem(
                qta.icon('fa5s.folder-open', color='orange'), i, self.li)
            self.li.addItem(item)

    def ftp_move_to(self, item):
        txt = item.text()
        txt2 = normpath(join(self.pathbarftp.text(), txt))
        self.li.clear()
        if txt2 != '/':
            normpath(join(txt2, '..'))
            item = QListWidgetItem(
                qta.icon('fa5s.folder-open', color='orange'), '..', self.li)
            self.li.addItem(item)
        for i in self.ftpm.list_dir(txt2):
            item = QListWidgetItem(
                qta.icon('fa5s.folder-open', color='orange'), i, self.li)
            self.li.addItem(item)
        self.pathbarftp.setText(txt2)

    def get_path(self):
        txt = self.pathbar.text()
        if txt is None or txt == "":
            txt = ""
        dirr = QFileDialog.getExistingDirectory(
            self, "Selecionar Directorio", txt, QFileDialog.ShowDirsOnly
            | QFileDialog.DontResolveSymlinks)
        # print(dirr)
        return dirr

    @pyqtSlot()
    def set_path(self):
        dirr = self.get_path()
        if dirr is None or dirr == '':
            return
        self.pathbar.setText(dirr)

    def download(self):
        base = self.pathbar.text()
        if base == '':
            self.in_progress = False
            return
        if not self.ftpm:
            self.in_progress = False
            return
        self.in_progress = True
        self.ftpm.last(base)
        self.loggin.emit('Buscando capítulos', INFORMATION)
        self.ftpm.find_nexts(self.pathbarftp.text())
        r = self.ftpm.results
        for i in r:
            # ftpp = join(i[2],i[1])
            self.ftpm.download(i[2], i[1], base, i[3])

    @pyqtSlot(str, str)
    def change_names(self, src, dst):
        self.namelabel.setText(src + '    ' + dst)
        self.loggin.emit('Descargando ' + src + '  para  ' + dst, INFORMATION)

    @pyqtSlot(int, int, float)
    def update(self, total, count, speed):
        val = int(count / max(total, 1e-12) * 100)
        self.progress.setValue(val)
        self.speedlabel.setText(str(speed / (1024)) + ' Kb/s')

    @pyqtSlot()
    def copy_finish2(self):
        self.progress.setValue(100)
        self.loggin.emit('Descarga de archivo finalizada', INFORMATION)

    @pyqtSlot()
    def copy_finish(self):
        self.progress.setValue(0)
        self.speedlabel.clear()
        self.namelabel.clear()
        self.loggin.emit('Descarga finalizada', INFORMATION)
        self.in_progress = False

    @pyqtSlot()
    def procces(self):
        if self.in_progress:
            self.loggin.emit('Hay un proceso en este momento, espere.',
                             WARNING)
            return
        self.download()
Example #3
0
class FileGui(QWidget):

    logginn = pyqtSignal(str, str, int)

    def __init__(self):
        super(FileGui, self).__init__()
        self.cl = QVBoxLayout()
        self.loggin = Logger('FileGui', self.logginn)

        tt = QHBoxLayout()
        self.local = QLabel('Local: ', self)
        self.pathbar = QLineEdit(self)
        folder = qta.icon('fa5s.folder-open',
                          color='orange',
                          color_active='red')
        self.pathbtn = QPushButton(folder, "", self)
        tt.addWidget(self.local)
        tt.addWidget(self.pathbar)
        tt.addWidget(self.pathbtn)
        self.cl.addLayout(tt)

        tt = QHBoxLayout()
        self.other = QLabel('Otro: ', self)
        self.pathbar2 = QLineEdit(self)
        folder = qta.icon('fa5s.folder-open',
                          color='orange',
                          color_active='red')
        self.pathbtn2 = QPushButton(folder, "", self)
        tt.addWidget(self.other)
        tt.addWidget(self.pathbar2)
        tt.addWidget(self.pathbtn2)
        self.cl.addLayout(tt)

        tt = QHBoxLayout()
        self.local = QLabel('Folders: ')
        self.pathbarftp = QLineEdit(self)
        self.pathbarftp.setReadOnly(True)
        tt.addWidget(self.local)
        tt.addWidget(self.pathbarftp)
        self.cl.addLayout(tt)

        self.li = QListWidget(self)
        self.cl.addWidget(self.li)
        self.li.itemDoubleClicked.connect(self.ftp_move_to)

        tt = QHBoxLayout()
        find = qta.icon('fa5s.search', color='orange', color_active='red')
        self.proc = QPushButton(find, "", self)
        tt.addWidget(self.proc)
        tt.addStretch()
        self.move = QButtonGroup()
        tt1 = QRadioButton("Todos")
        tt2 = QRadioButton("Último")
        tt2.setChecked(True)
        self.move.addButton(tt1, 2)
        self.move.addButton(tt2, 1)
        self.move.setExclusive(True)
        tt.addWidget(tt1)
        tt.addWidget(tt2)
        self.cl.addLayout(tt)

        tt = QVBoxLayout()
        tt3 = QHBoxLayout()
        self.namelabel = QLabel(self)
        tt3.addWidget(self.namelabel)
        tt2 = QHBoxLayout()
        self.progresslabel = QLabel(self)
        self.speedlabel = QLabel(self)
        tt2.addWidget(self.progresslabel)
        tt2.addWidget(self.speedlabel)
        self.progress = QProgressBar(self)
        self.progress.setMinimum(0)
        self.progress.setMaximum(100)
        tt.addLayout(tt3)
        tt.addLayout(tt2)
        tt.addWidget(self.progress)
        self.cl.addLayout(tt)

        self.setLayout(self.cl)
        self.pathbtn.clicked.connect(self.set_path)
        self.proc.clicked.connect(self.procces)
        self.pathbtn2.clicked.connect(self.set_path2)
        self.ftpm = None
        self.in_progress = False

    @pyqtSlot()
    def set_path2(self):
        dirr = self.get_path()
        if dirr is None or dirr == '':
            return
        self.pathbar2.setText(dirr)
        if self.ftpm:
            self.ftpm.close()
            reconnect(self.ftpm.copier.worker.names)
            reconnect(self.ftpm.copier.worker.progress)
            reconnect(self.ftpm.copier.worker.finish)
            reconnect(self.ftpm.copier.finish)
        try:
            self.ftpm = FileManager(dirr, self.loggin)
            reconnect(self.ftpm.copier.worker.names, self.change_names)
            reconnect(self.ftpm.copier.worker.progress, self.update)
            reconnect(self.ftpm.copier.worker.finish, self.copy_finish2)
            reconnect(self.ftpm.copier.finish, self.copy_finish)
            self.pathbarftp.setText('/')
        except Exception as e:
            self.loggin.emit(str(e), ERROR)
            return
        self.li.clear()
        for i in self.ftpm.list_dir('/'):
            item = QListWidgetItem(
                qta.icon('fa5s.folder-open', color='orange'), i, self.li)
            self.li.addItem(item)

    @pyqtSlot()
    def ftp_move_to(self, item):
        txt = item.text()
        txt2 = normpath(join(self.pathbarftp.text(), txt))
        self.li.clear()
        if txt2 != '/':
            normpath(join(txt2, '..'))
            item = QListWidgetItem(
                qta.icon('fa5s.folder-open', color='orange'), '..', self.li)
            self.li.addItem(item)
        for i in self.ftpm.list_dir(txt2):
            item = QListWidgetItem(
                qta.icon('fa5s.folder-open', color='orange'), i, self.li)
            self.li.addItem(item)
        self.pathbarftp.setText(txt2)

    def get_path(self):
        txt = self.pathbar.text()
        if txt is None or txt == "":
            txt = ""
        dirr = QFileDialog.getExistingDirectory(
            self, "Selecionar Directorio", txt, QFileDialog.ShowDirsOnly
            | QFileDialog.DontResolveSymlinks)
        # print(dirr)
        return dirr

    @pyqtSlot()
    def set_path(self):
        dirr = self.get_path()
        if dirr is None or dirr == '':
            return
        self.pathbar.setText(dirr)

    def download(self):
        base = self.pathbar.text()
        if base == '':
            self.in_progress = False
            return
        if not self.ftpm:
            self.in_progress = False
            return
        if self.move.checkedId() == 1:
            self.ftpm.last(base)
        else:
            self.ftpm.last2(base)
        self.loggin.emit('Buscando capítulos', INFORMATION)
        if self.move.checkedId() == 1:
            self.ftpm.find_nexts(self.pathbarftp.text())
        else:
            self.ftpm.find_nexts2(self.pathbarftp.text())
        r = self.ftpm.results
        for i in r:
            # ftpp = join(i[2],i[1])
            self.ftpm.download(i[2], i[1], base, i[3])

    @pyqtSlot(str, str)
    def change_names(self, src, dst):
        self.namelabel.setText(src + '    ' + dst)
        self.loggin.emit('Descargando ' + src + '  para  ' + dst, INFORMATION)

    @pyqtSlot(int, int, float)
    def update(self, total, count, speed):
        val = int(count / max(total, 1e-12) * 100)
        self.progress.setValue(val)
        self.speedlabel.setText(str(speed / (1024)) + ' Kb/s')

    @pyqtSlot()
    def copy_finish2(self):
        self.progress.setValue(100)
        self.loggin.emit('Descarga de archivo finalizada', INFORMATION)

    @pyqtSlot()
    def copy_finish(self):
        self.progress.setValue(0)
        self.speedlabel.clear()
        self.namelabel.clear()
        self.loggin.emit('Descarga finalizada', INFORMATION)
        self.in_progress = False

    @pyqtSlot()
    def procces(self):
        if self.in_progress:
            self.loggin.emit('Hay un proceso en este momento, espere.',
                             WARNING)
            return
        self.download()