<commit_before>#!/usr/bin/env python2
# -*- coding: utf8
# This file is part of Archivematica.
#
# Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com>
#
# Archivematica is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Archivematica is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Archivematica.  If not, see <http://www.gnu.org/licenses/>.

# @package Archivematica
# @subpackage archivematicaClientScript
# @author <NAME> <<EMAIL>>
import os
import unicodedata

import django
import six

django.setup()
from django.db import transaction

# dashboard
from main.models import Event, File, Directory, Transfer, SIP

# archivematicaCommon
from custom_handlers import get_script_logger
import sanitize_names

logger = get_script_logger("archivematica.mcp.client.sanitizeObjectNames")


class NameSanitizer(object):
    """
    Class to track batch sanitizations of files and directories, both in the
    filesystem and in the database.
    """

    BATCH_SIZE = 2000
    EVENT_DETAIL = (
        'prohibited characters removed: program="sanitize_names"; version="'
        + sanitize_names.VERSION
        + '"'
    )

    def __init__(
        self, job, objects_directory, sip_uuid, date, group_type, group_sql, sip_path
    ):
        if group_type not in ("%SIPDirectory%", "%transferDirectory%"):
            raise ValueError("Unexpected group type: {}".format(group_type))

        if isinstance(objects_directory, six.binary_type):
            objects_directory = objects_directory.decode("utf-8")

        if isinstance(sip_path, six.binary_type):
            sip_path = sip_path.decode("utf-8")

        if group_sql == "transfer_id":
            self.transfer = Transfer.objects.get(uuid=sip_uuid)
            self.sip = None
        elif group_sql == "sip_id":
            self.transfer = None
            self.sip = SIP.objects.get(uuid=sip_uuid)
        else:
            raise ValueError("Unexpected group sql: {}".format(group_sql))

        self.job = job
        self.objects_directory = objects_directory
        self.date = date
        self.group_type = group_type
        self.sip_path = sip_path

        self.files_index = {}  # old_path: new_path
        self.dirs_index = {}  # old_path: new_path

    @property
    def directory_queryset(self):
        """
        Base queryset for Directory objects related to the SIP/Transfer.
        """
        if self.transfer is not None and self.transfer.diruuids:
            return Directory.objects.filter(transfer=self.transfer)
        elif self.sip is not None and self.sip.diruuids:
            return Directory.objects.filter(sip=self.sip)

        return None

    @property
    def file_queryset(self):
        """
        Base queryset for File objects related to the SIP/Transfer.
        """
        file_qs = File.objects.filter(removedtime__isnull=True)
        if self.sip is not None:
            return file_qs.filter(sip=self.sip)
        else:
            return file_qs.filter(transfer=self.transfer)

    def normalize_path_for_db(self, path):
        """
        Returns a unicode normalized, relative paths (e.g.
        %transferDirectory%objects/example.txt)
        """
        return unicodedata.normalize("NFC", path).replace(
            self.sip_path, self.group_type, 1
        )

    def apply_file_updates(self):
        """
        Run a single batch of File updates.
        """
        if self.sip:
            event_agents = self.sip.agents
        else:
            event_agents = self.transfer.agents

        events = []

        # We pass through _all_ objects here, as they may not be normalized in
        # the db :(
        for file_obj in self.file_queryset.iterator():
            old_location = unicodedata.normalize("NFC", file_obj.currentlocation)
            try:
                sanitized_location = self.files_index[old_location]
            except KeyError:
                continue

            file_obj.currentlocation = sanitized_location
            file_obj.save()

            sanitize_event = Event(
                file_uuid=file_obj,
                event_type="name cleanup",
                event_datetime=self.date,
                event_detail=self.EVENT_DETAIL,
            )
            events.append(sanitize_event)

        Event.objects.bulk_create(events)
<commit_msg>Restore eventOutcomeDetail in name cleanup<commit_after>#!/usr/bin/env python2
# -*- coding: utf8
# This file is part of Archivematica.
#
# Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com>
#
# Archivematica is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Archivematica is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Archivematica.  If not, see <http://www.gnu.org/licenses/>.

# @package Archivematica
# @subpackage archivematicaClientScript
# @author <NAME> <<EMAIL>>
import os
import unicodedata

import django
import six

django.setup()
from django.db import transaction

# dashboard
from main.models import Event, File, Directory, Transfer, SIP

# archivematicaCommon
from custom_handlers import get_script_logger
import sanitize_names

logger = get_script_logger("archivematica.mcp.client.sanitizeObjectNames")


class NameSanitizer(object):
    """
    Class to track batch sanitizations of files and directories, both in the
    filesystem and in the database.
    """

    BATCH_SIZE = 2000
    EVENT_DETAIL = (
        'prohibited characters removed: program="sanitize_names"; version="'
        + sanitize_names.VERSION
        + '"'
    )
    EVENT_OUTCOME_DETAIL = u'Original name="{}"; cleaned up name="{}"'

    def __init__(
        self, job, objects_directory, sip_uuid, date, group_type, group_sql, sip_path
    ):
        if group_type not in ("%SIPDirectory%", "%transferDirectory%"):
            raise ValueError("Unexpected group type: {}".format(group_type))

        if isinstance(objects_directory, six.binary_type):
            objects_directory = objects_directory.decode("utf-8")

        if isinstance(sip_path, six.binary_type):
            sip_path = sip_path.decode("utf-8")

        if group_sql == "transfer_id":
            self.transfer = Transfer.objects.get(uuid=sip_uuid)
            self.sip = None
        elif group_sql == "sip_id":
            self.transfer = None
            self.sip = SIP.objects.get(uuid=sip_uuid)
        else:
            raise ValueError("Unexpected group sql: {}".format(group_sql))

        self.job = job
        self.objects_directory = objects_directory
        self.date = date
        self.group_type = group_type
        self.sip_path = sip_path

        self.files_index = {}  # old_path: new_path
        self.dirs_index = {}  # old_path: new_path

    @property
    def directory_queryset(self):
        """
        Base queryset for Directory objects related to the SIP/Transfer.
        """
        if self.transfer is not None and self.transfer.diruuids:
            return Directory.objects.filter(transfer=self.transfer)
        elif self.sip is not None and self.sip.diruuids:
            return Directory.objects.filter(sip=self.sip)

        return None

    @property
    def file_queryset(self):
        """
        Base queryset for File objects related to the SIP/Transfer.
        """
        file_qs = File.objects.filter(removedtime__isnull=True)
        if self.sip is not None:
            return file_qs.filter(sip=self.sip)
        else:
            return file_qs.filter(transfer=self.transfer)

    def normalize_path_for_db(self, path):
        """
        Returns a unicode normalized, relative paths (e.g.
        %transferDirectory%objects/example.txt)
        """
        return unicodedata.normalize("NFC", path).replace(
            self.sip_path, self.group_type, 1
        )

    def apply_file_updates(self):
        """
        Run a single batch of File updates.
        """
        if self.sip:
            event_agents = self.sip.agents
        else:
            event_agents = self.transfer.agents

        events = []

        # We pass through _all_ objects here, as they may not be normalized in
        # the db :(
        for file_obj in self.file_queryset.iterator():
            old_location = unicodedata.normalize("NFC", file_obj.currentlocation)
            try:
                sanitized_location = self.files_index[old_location]
            except KeyError:
                continue

            file_obj.currentlocation = sanitized_location
            file_obj.save()

            sanitize_event = Event(
                file_uuid=file_obj,
                event_type="name cleanup",
                event_datetime=self.date,
                event_detail=self.EVENT_DETAIL,
                event_outcome_detail=self.EVENT_OUTCOME_DETAIL.format(
                    old_location, sanitized_location
                ),
            )
            events.append(sanitize_event)

        Event.objects.bulk_create(events)

{'fraction_non_alphanumeric': 0.08516063233044364, 'fraction_numerical': 0.003671596124426313, 'mean_word_length': 2.4723796033994336, 'pattern_counts': {'":': 4, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2765293', 'n_tokens_mistral': 2833, 'n_tokens_neox': 2717, 'n_words': 765}