# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import os

from django.db import migrations

from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps

from zerver.lib.upload import attachment_url_re, attachment_url_to_path_id


def check_and_create_attachments(apps, schema_editor):
    # type: (StateApps, DatabaseSchemaEditor) -> None
    STREAM = 2
    Message = apps.get_model('zerver', 'Message')
    Attachment = apps.get_model('zerver', 'Attachment')
    Stream = apps.get_model('zerver', 'Stream')
    for message in Message.objects.filter(has_attachment=True, attachment=None):
        attachment_url_list = attachment_url_re.findall(message.content)
        for url in attachment_url_list:
            path_id = attachment_url_to_path_id(url)
            user_profile = message.sender
            is_message_realm_public = False
            if message.recipient.type == STREAM:
                stream = Stream.objects.get(id=message.recipient.type_id)
                is_message_realm_public = not stream.invite_only and stream.realm.domain != "mit.edu"

            if path_id is not None:
                attachment = Attachment.objects.create(
                    file_name=os.path.basename(path_id), path_id=path_id, owner=user_profile,
                    realm=user_profile.realm, is_realm_public=is_message_realm_public)
                attachment.messages.add(message)


class Migration(migrations.Migration):

    dependencies = [
        ('zerver', '0040_realm_authentication_methods'),
    ]

    operations = [
        migrations.RunPython(check_and_create_attachments)
    ]

Add migration to create attachments for old uploads.
Add migration to create attachments for old uploads.

This migration ensures that all historically uploaded files from
before we started tracking files in the Zulip database via the
Attachment model have Attachment objects.

This has been tested by tabbott against a production server to ensure
that it results in all old uploaded files having corresponding
attachment objects.

Merging this change is a key prerequisite for making our adding
attachment access controls in an enforcing fashion.
