Ejemplo n.º 1
0
    def delete(self):
        # Suppression du média physiquement
        # En réalité renommage
        if self.media.media_path:
            initial_path = self.media.media_path
            (inv_file_name, inv_file_path) = initial_path[::-1].split('/', 1)
            file_name = inv_file_name[::-1]
            file_path = inv_file_path[::-1]

            try:
                new_path = rename_file(
                    self.media.media_path, "{}/deleted_{}".format(
                        file_path, file_name
                    )
                )
                self.media.media_path = new_path
            except FileNotFoundError:
                raise Exception('Unable to delete file')

        # Suppression du média dans la base
        try:
            DB.session.delete(self.media)
            DB.session.commit()
        except Exception:
            new_path = rename_file(
                "{}/deleted_{}".format(file_path, file_name),
                initial_path
            )
Ejemplo n.º 2
0
    def delete(self):
        # Suppression du média physiquement
        # En réalité renommage
        if self.media.media_path:
            initial_path = self.media.media_path
            (inv_file_name, inv_file_path) = initial_path[::-1].split('/', 1)
            file_name = inv_file_name[::-1]
            file_path = inv_file_path[::-1]

            try:
                new_path = rename_file(
                    self.media.media_path, "{}/deleted_{}".format(
                        file_path, file_name
                    )
                )
                self.media.media_path = new_path
            except FileNotFoundError:
                raise Exception('Unable to delete file')

        # Suppression du média dans la base
        try:
            DB.session.delete(self.media)
            DB.session.commit()
        except Exception:
            new_path = rename_file(
                "{}/deleted_{}".format(file_path, file_name),
                initial_path
            )
Ejemplo n.º 3
0
    def delete(self):
        # Note si SQLALCHEMY_TRACK_MODIFICATIONS  = true alors suppression du fichier gérée automatiquement

        # Suppression du média physiquement
        # En réalité renommage
        initial_path = self.media.media_path

        if self.media.media_path and not current_app.config['SQLALCHEMY_TRACK_MODIFICATIONS']:

            try:
                self.media.__before_commit_delete__()

            except FileNotFoundError:
                raise Exception('Unable to delete file')

        # Suppression du média dans la base
        try:
            DB.session.delete(self.media)
            DB.session.commit()
        except Exception:
            if initial_path:
                new_path = rename_file(
                    self.media.media_path,
                    initial_path
                )
Ejemplo n.º 4
0
    def remove_file(self):
        if not self.media_path:
            return
        initial_path = self.media_path
        (inv_file_name, inv_file_path) = initial_path[::-1].split("/", 1)
        file_name = inv_file_name[::-1]
        file_path = inv_file_path[::-1]

        try:
            self.media_path = rename_file(
                self.media_path, "{}/deleted_{}".format(file_path, file_name))
        except FileNotFoundError:
            raise Exception("Unable to delete file {}".format(initial_path))
Ejemplo n.º 5
0
    def sync_medias():
        """
            Met à jour les médias
              - supprime les médias sans uuid_attached_row plus vieux que 24h
              - supprime les médias dont l'object attaché n'existe plus
        """

        # delete media temp > 24h
        res_medias_temp = (DB.session.query(TMedias.id_media).filter(
            and_(
                TMedias.meta_update_date <
                (datetime.datetime.now() - datetime.timedelta(hours=24)),
                TMedias.uuid_attached_row == None)).all())

        id_medias_temp = [res.id_media for res in res_medias_temp]

        if (id_medias_temp):
            print('sync media remove temp media with ids : ', id_medias_temp)

        for id_media in id_medias_temp:
            TMediaRepository(id_media=id_media).delete()

        # SYNCRONISATION media - fichiers

        # liste des id des medias fichiers
        liste_fichiers = []
        search_path = pathlib.Path(current_app.config["BASE_DIR"],
                                   current_app.config["UPLOAD_FOLDER"])
        for (repertoire, sous_repertoires, fichiers) in os.walk(search_path):
            for f in fichiers:
                id_media = f.split('_')[0]
                try:
                    id_media = int(id_media)
                    f_data = {
                        'id_media': id_media,
                        'path': pathlib.Path(repertoire, f)
                    }
                    liste_fichiers.append(f_data)
                except ValueError:
                    pass

        # liste des media fichier supprimés en base
        ids_media_file = [x['id_media'] for x in liste_fichiers]
        ids_media_file = list(dict.fromkeys(ids_media_file))

        # suppression des fichiers dont le media n'existe plpus en base
        ids_media_base = DB.session.query(TMedias.id_media).filter(
            TMedias.id_media.in_(ids_media_file)).all()
        ids_media_base = [x[0] for x in ids_media_base]

        ids_media_to_delete = [
            x for x in ids_media_file if x not in ids_media_base
        ]

        if (ids_media_to_delete):
            print('sync media remove unassociated medias with ids : ',
                  ids_media_to_delete)

        for f_data in liste_fichiers:
            if f_data['id_media'] not in ids_media_to_delete:
                continue
            if 'thumbnail' in str(f_data['path']):
                os.remove(f_data['path'])
            else:
                deleted_paths = str(f_data['path']).split('/')
                deleted_paths[-1] = 'deleted_' + deleted_paths[-1]
                rename_file(f_data['path'], "/".join(deleted_paths))