# Path: api/serializers/model_serializers.py
# class ProfileSerializer(serializers.Serializer):
#     id = serializers.IntegerField()
#     username = serializers.ReadOnlyField(source='id_user.username')
#     email = serializers.ReadOnlyField(source='id_user.email')
#     user_photo = serializers.SerializerMethodField('get_user_photo_url')
# 
#     def get_user_photo_url(self, obj):
#         return obj.user_photo.url if obj.user_photo else static('/app/images/user.png')
# 
# Path: api/serializers/request_serializers.py
# class ProfileRequest(TokenSerializer):
#     pass
# 
# class ChangePasswordRequest(TokenSerializer):
#     prev_password = serializers.CharField(min_length=6,
#                                           max_length=16)
#     new_password = serializers.CharField(min_length=6,
#                                          max_length=16)
# 
# class UploadAvatarRequest(TokenSerializer):
#     pass
# 
# Path: api/utils.py
# def invalid_data_response(request_serializer):
#     """
#     Returns the error message depending on missing/invalid data in serializer.
#     """
#     return Response({'detail': request_serializer.errors,
#                      'data': {}}, status=status.HTTP_400_BAD_REQUEST)
# 
# def validate_api_secret_key(secret_key):
#     """
#     Checks if request received from known origin Application. If not returns 404 (not found) status
#     """
#     if secret_key != settings.API_SECRET_KEY:
#         logger.info('Incorrect API key: "{}"'.format(secret_key))
#         raise Http404('The API key isn\t correct!')
# 
# Path: app/constants.py
# class Queues:
#     default = 'default'
#     high_priority = 'high_priority'
# 
# Path: app/models.py
# class TheUser(models.Model):
#     """
#     Class for user objects in database.
#     """
#     REMINDER_TEMPLATE = json.dumps({
#         "common": {
#             "fb_page": True,
#             "fb_group": True,
#             "twitter": True,
#             "vk": True,
#             "disabled_all": False
#         },
#         "api": {
#             "app_rate": True
#         },
#         "web": {
#             "app_download": True,
#         },
#     })
# 
#     id_user = models.OneToOneField(User)
#     user_photo = models.ImageField(blank=True, upload_to='user', storage=OverwriteStorage())
#     auth_token = models.CharField(max_length=50, null=True, blank=True)
#     subscription = models.BooleanField(default=True)
#     reminder = models.CharField(max_length=256, null=False, default=REMINDER_TEMPLATE)
# 
#     # ------------------------------------------------------------------------------------------------------------------
#     def __str__(self):
#         return str(self.id_user)
# 
#     # ------------------------------------------------------------------------------------------------------------------
#     def get_api_reminders(self):
#         """
#         Returns the reminders only necessary for API endpoints.
#         """
#         data = json.loads(self.reminder)
# 
#         mobile_data = dict(data['common'])
#         mobile_data.update(data['api'])
# 
#         return mobile_data
# 
#     # ------------------------------------------------------------------------------------------------------------------
#     def get_web_reminders(self):
#         """
#         Returns the reminders only necessary for web part.
#         """
#         data = json.loads(self.reminder)
#         
#         web_data = dict(data['common'])
#         web_data.update(data['web'])
# 
#         return web_data
# 
#     # ------------------------------------------------------------------------------------------------------------------
#     def update_reminder(self, field, value):
#         """
#         Updates the reminder status.
#         """
#         data = json.loads(self.reminder)
# 
#         for key in data:
#             if field in data[key]:
#                 data[key][field] = value
# 
#         self.reminder = json.dumps(data)
#         self.save()
# 
# Path: app/tasks.py
# @shared_task
# def changed_password(username, recipient):
#     """
#     Celery task for sending mail, to notify user about password changed.
# 
#     :param str username:   The restored username.
#     :param str recipient:  The mail recipient.
#     """
#     html_content = render_to_string(
#         'mails/password_changed.html',
#         {'username': username, 'email_host_user': settings.EMAIL_HOST_USER}
#     )
#     text_content = strip_tags(html_content)
#     subject = 'Изменение пароля аккаунта - plamber.com.ua'
# 
#     email = EmailMultiAlternatives(subject, text_content, to=[recipient])
#     email.attach_alternative(html_content, 'text/html')
#     email.send()
# 
#     logger.info("Sent changed password message to '{}'.".format(recipient))
# 
# Path: app/utils.py
# def resize_image(path, width):
#     """
#     Resizes the image.
# 
#     :param str path:  The path to the image file.
#     :param int width: The width of the output image.
#     """
#     try:
#         img = Image.open(path)
# 
#         ratio = width / float(img.width)
#         height = int(float(img.height) * float(ratio))
# 
#         new_img = img.resize((width, height), Image.ANTIALIAS)
#         new_img.save(path)
# 
#     except IOError:
#         pass


import logging
import random
from django.db import transaction
from django.core.exceptions import ValidationError
from django.shortcuts import get_object_or_404
from rest_framework import status
from rest_framework.decorators import api_view, parser_classes
from rest_framework.parsers import MultiPartParser
from rest_framework.response import Response
from ..serializers.model_serializers import ProfileSerializer
from ..serializers.request_serializers import ProfileRequest, ChangePasswordRequest, UploadAvatarRequest
from ..utils import invalid_data_response, validate_api_secret_key
from app.constants import Queues
from app.models import TheUser
from app.tasks import changed_password
from app.utils import resize_image
# -*- coding: utf-8 -*-






AVATAR_WIDTH = 250

logger = logging.getLogger('changes')


# ----------------------------------------------------------------------------------------------------------------------
@api_view(['POST'])
def my_profile(request):
    """
    Generates the user profile data.
    """

# Path: api/serializers/model_serializers.py
# class ProfileSerializer(serializers.Serializer):
#     id = serializers.IntegerField()
#     username = serializers.ReadOnlyField(source='id_user.username')
#     email = serializers.ReadOnlyField(source='id_user.email')
#     user_photo = serializers.SerializerMethodField('get_user_photo_url')
# 
#     def get_user_photo_url(self, obj):
#         return obj.user_photo.url if obj.user_photo else static('/app/images/user.png')
# 
# Path: api/serializers/request_serializers.py
# class ProfileRequest(TokenSerializer):
#     pass
# 
# class ChangePasswordRequest(TokenSerializer):
#     prev_password = serializers.CharField(min_length=6,
#                                           max_length=16)
#     new_password = serializers.CharField(min_length=6,
#                                          max_length=16)
# 
# class UploadAvatarRequest(TokenSerializer):
#     pass
# 
# Path: api/utils.py
# def invalid_data_response(request_serializer):
#     """
#     Returns the error message depending on missing/invalid data in serializer.
#     """
#     return Response({'detail': request_serializer.errors,
#                      'data': {}}, status=status.HTTP_400_BAD_REQUEST)
# 
# def validate_api_secret_key(secret_key):
#     """
#     Checks if request received from known origin Application. If not returns 404 (not found) status
#     """
#     if secret_key != settings.API_SECRET_KEY:
#         logger.info('Incorrect API key: "{}"'.format(secret_key))
#         raise Http404('The API key isn\t correct!')
# 
# Path: app/constants.py
# class Queues:
#     default = 'default'
#     high_priority = 'high_priority'
# 
# Path: app/models.py
# class TheUser(models.Model):
#     """
#     Class for user objects in database.
#     """
#     REMINDER_TEMPLATE = json.dumps({
#         "common": {
#             "fb_page": True,
#             "fb_group": True,
#             "twitter": True,
#             "vk": True,
#             "disabled_all": False
#         },
#         "api": {
#             "app_rate": True
#         },
#         "web": {
#             "app_download": True,
#         },
#     })
# 
#     id_user = models.OneToOneField(User)
#     user_photo = models.ImageField(blank=True, upload_to='user', storage=OverwriteStorage())
#     auth_token = models.CharField(max_length=50, null=True, blank=True)
#     subscription = models.BooleanField(default=True)
#     reminder = models.CharField(max_length=256, null=False, default=REMINDER_TEMPLATE)
# 
#     # ------------------------------------------------------------------------------------------------------------------
#     def __str__(self):
#         return str(self.id_user)
# 
#     # ------------------------------------------------------------------------------------------------------------------
#     def get_api_reminders(self):
#         """
#         Returns the reminders only necessary for API endpoints.
#         """
#         data = json.loads(self.reminder)
# 
#         mobile_data = dict(data['common'])
#         mobile_data.update(data['api'])
# 
#         return mobile_data
# 
#     # ------------------------------------------------------------------------------------------------------------------
#     def get_web_reminders(self):
#         """
#         Returns the reminders only necessary for web part.
#         """
#         data = json.loads(self.reminder)
#         
#         web_data = dict(data['common'])
#         web_data.update(data['web'])
# 
#         return web_data
# 
#     # ------------------------------------------------------------------------------------------------------------------
#     def update_reminder(self, field, value):
#         """
#         Updates the reminder status.
#         """
#         data = json.loads(self.reminder)
# 
#         for key in data:
#             if field in data[key]:
#                 data[key][field] = value
# 
#         self.reminder = json.dumps(data)
#         self.save()
# 
# Path: app/tasks.py
# @shared_task
# def changed_password(username, recipient):
#     """
#     Celery task for sending mail, to notify user about password changed.
# 
#     :param str username:   The restored username.
#     :param str recipient:  The mail recipient.
#     """
#     html_content = render_to_string(
#         'mails/password_changed.html',
#         {'username': username, 'email_host_user': settings.EMAIL_HOST_USER}
#     )
#     text_content = strip_tags(html_content)
#     subject = 'Изменение пароля аккаунта - plamber.com.ua'
# 
#     email = EmailMultiAlternatives(subject, text_content, to=[recipient])
#     email.attach_alternative(html_content, 'text/html')
#     email.send()
# 
#     logger.info("Sent changed password message to '{}'.".format(recipient))
# 
# Path: app/utils.py
# def resize_image(path, width):
#     """
#     Resizes the image.
# 
#     :param str path:  The path to the image file.
#     :param int width: The width of the output image.
#     """
#     try:
#         img = Image.open(path)
# 
#         ratio = width / float(img.width)
#         height = int(float(img.height) * float(ratio))
# 
#         new_img = img.resize((width, height), Image.ANTIALIAS)
#         new_img.save(path)
# 
#     except IOError:
#         pass


# Path: api/views/profile_views.py
import logging
import random
from django.db import transaction
from django.core.exceptions import ValidationError
from django.shortcuts import get_object_or_404
from rest_framework import status
from rest_framework.decorators import api_view, parser_classes
from rest_framework.parsers import MultiPartParser
from rest_framework.response import Response
from ..serializers.model_serializers import ProfileSerializer
from ..serializers.request_serializers import ProfileRequest, ChangePasswordRequest, UploadAvatarRequest
from ..utils import invalid_data_response, validate_api_secret_key
from app.constants import Queues
from app.models import TheUser
from app.tasks import changed_password
from app.utils import resize_image

# -*- coding: utf-8 -*-






AVATAR_WIDTH = 250

logger = logging.getLogger('changes')


# ----------------------------------------------------------------------------------------------------------------------
@api_view(['POST'])
def my_profile(request):
    """
    Generates the user profile data.
    """

    validate_api_secret_key(request.data.get('app_key'))