# Path: UniShared_python/website/tasks.py
# @task
# @only_one
# def email_task(subject, context, template, to, bcc=None, connection_label=None):
#     if not to and not bcc:
#         logger.debug('No recipients, adding managers')
#         to = [a[1] for a in settings.MANAGERS]
#         connection_label = 'gmail'
# 
#     logger.debug('Starting email task (subject: %s, template: %s, context: %s to: %s, bcc: %s, connection_label: %s',
#         subject, template, context, to, bcc, connection_label)
# 
#     def filter_emails(emails):
#         filtered_emails = []
# 
#         if emails:
#             for email in emails:
#                 try:
#                     user_profile = User.objects.get(email=email).get_profile()
# 
#                     if user_profile.is_email_verified is True and user_profile.enable_notifications is True:
#                         filtered_emails.append(email)
#                 except User.DoesNotExist:
#                     filtered_emails.append(email)
#         return filtered_emails
# 
#     filtered_to = filter_emails(to)
#     filtered_bcc = filter_emails(bcc)
# 
#     logger.debug('To length after filtering: %s', len(filtered_to))
#     logger.debug('Bcc length after filtering: %s', len(filtered_bcc))
# 
#     if len(filtered_to) or len(filtered_bcc):
#         if connection_label is None:
#             connection_label = getattr(settings, 'EMAIL_CONNECTION_DEFAULT', None)
# 
#         try:
#             connections = getattr(settings, 'EMAIL_CONNECTIONS')
#             real_options = connections[connection_label]
#             admin_options = connections['gmail']
#         except KeyError, AttributeError:
#             raise MissingConnectionException(
#                 'Settings for connection "%s" were not found' % connection_label)
# 
#         context.update({'BASE_URL': settings.BASE_URL,
#                         'link_underlined': 'border-bottom: 1px dashed #848484;text-decoration: none;',
#                         'link_style_share': 'color: #3CBDEE;border-bottom: 1px dashed #3CBDEE;text-decoration: none;',
#                         'link_style_participate': 'color: #F18C1B;text-decoration: none;border-bottom: 1px dashed #F18C1B;'})
#         text_message = get_template('mails/{0}.txt'.format(template)).render(context)
# 
#         real_connection = get_connection(**real_options)
#         real_connection.open()
# 
#         admin_connection = get_connection(**admin_options)
#         admin_connection.open()
# 
#         from_email = u'"Clément from UniShared" <clement@unishared.com>'
#         real_email = EmailMultiAlternatives(subject, text_message, from_email,
#             filtered_to, filtered_bcc, real_connection)
#         admin_email = EmailMultiAlternatives(subject, text_message, from_email,
#             [a[1] for a in settings.ADMINS], None, admin_connection)
#         try:
#             html_message = get_template('mails/{0}.html'.format(template)).render(context)
#             real_email.attach_alternative(html_message, 'text/html')
#             admin_email.attach_alternative(html_message, 'text/html')
#         except TemplateDoesNotExist:
#             pass
# 
#         real_email.send(fail_silently=False)
#         admin_email.send(fail_silently=False)
# 
#         real_connection.close()
#         admin_connection.close()
# 
# @task
# @only_one
# def google_apps_add_group_task(group_id, member_id):
#     logger.debug('Starting Google Apps add to group task')
#     try:
#         logger.debug('Get GroupsProvisioningClient')
#         clientInstance = GroupsProvisioningClient('unishared.com',
#             OAuthHmacToken('unishared.com', '',
#                 '', '', ACCESS_TOKEN))
#         clientInstance.ssl = True
#         logger.debug('Add {0} to {1}'.format(member_id, group_id))
#         clientInstance.AddMemberToGroup(group_id, member_id)
#         return True
#     except RequestError:
#         LoggingHelper.getErrorLogger().debug("Request error while adding user to Google group", exc_info=1)
#         return False
#     except Exception:
#         LoggingHelper.getErrorLogger().error("Error while adding user to Google group", exc_info=1)
#         return False


from datetime import datetime, timedelta
from urllib2 import urlopen
from django.core.files.base import ContentFile
from django.template.context import Context
from django.template.defaultfilters import slugify
from social_auth.backends import USERNAME
from social_auth.backends.facebook import FacebookBackend
from UniShared_python.settings import GAPPS_GROUP_NAME
from UniShared_python.website.tasks import email_task, google_apps_add_group_task
import hashlib
        url = "http://graph.facebook.com/%s/picture?type=large" % response['id']
    
    if url:
        profile = user.get_profile()
        if profile.image == '':
            avatar = urlopen(url)       

            content = avatar.read()
            md5 = hashlib.md5()
            md5.update(content)
            name = '{0}-{1}.jpg'.format(slugify(user.username + " social"), md5.hexdigest()[:12])
            profile.image.save(name, ContentFile(content))
            profile.save()

def add_user_to_group(backend, details, response, user, is_new=False, *args, **kwargs):   
    """ 
    Add current user to the UniShared's Google Group
    """
    
    if is_new:
        google_apps_add_group_task.apply_async([GAPPS_GROUP_NAME, user.email])

def send_welcome_mail(backend, details, response, user, is_new=False, *args, **kwargs):
    """
    Send a welcome mail
    """

    if is_new:
        context = Context({'user': user, 'ga_campaign_params' : 'utm_source=unishared&utm_content=v1&utm_medium=e-mail&utm_campaign=welcome_mail'})


# Path: UniShared_python/website/tasks.py
# @task
# @only_one
# def email_task(subject, context, template, to, bcc=None, connection_label=None):
#     if not to and not bcc:
#         logger.debug('No recipients, adding managers')
#         to = [a[1] for a in settings.MANAGERS]
#         connection_label = 'gmail'
# 
#     logger.debug('Starting email task (subject: %s, template: %s, context: %s to: %s, bcc: %s, connection_label: %s',
#         subject, template, context, to, bcc, connection_label)
# 
#     def filter_emails(emails):
#         filtered_emails = []
# 
#         if emails:
#             for email in emails:
#                 try:
#                     user_profile = User.objects.get(email=email).get_profile()
# 
#                     if user_profile.is_email_verified is True and user_profile.enable_notifications is True:
#                         filtered_emails.append(email)
#                 except User.DoesNotExist:
#                     filtered_emails.append(email)
#         return filtered_emails
# 
#     filtered_to = filter_emails(to)
#     filtered_bcc = filter_emails(bcc)
# 
#     logger.debug('To length after filtering: %s', len(filtered_to))
#     logger.debug('Bcc length after filtering: %s', len(filtered_bcc))
# 
#     if len(filtered_to) or len(filtered_bcc):
#         if connection_label is None:
#             connection_label = getattr(settings, 'EMAIL_CONNECTION_DEFAULT', None)
# 
#         try:
#             connections = getattr(settings, 'EMAIL_CONNECTIONS')
#             real_options = connections[connection_label]
#             admin_options = connections['gmail']
#         except KeyError, AttributeError:
#             raise MissingConnectionException(
#                 'Settings for connection "%s" were not found' % connection_label)
# 
#         context.update({'BASE_URL': settings.BASE_URL,
#                         'link_underlined': 'border-bottom: 1px dashed #848484;text-decoration: none;',
#                         'link_style_share': 'color: #3CBDEE;border-bottom: 1px dashed #3CBDEE;text-decoration: none;',
#                         'link_style_participate': 'color: #F18C1B;text-decoration: none;border-bottom: 1px dashed #F18C1B;'})
#         text_message = get_template('mails/{0}.txt'.format(template)).render(context)
# 
#         real_connection = get_connection(**real_options)
#         real_connection.open()
# 
#         admin_connection = get_connection(**admin_options)
#         admin_connection.open()
# 
#         from_email = u'"Clément from UniShared" <clement@unishared.com>'
#         real_email = EmailMultiAlternatives(subject, text_message, from_email,
#             filtered_to, filtered_bcc, real_connection)
#         admin_email = EmailMultiAlternatives(subject, text_message, from_email,
#             [a[1] for a in settings.ADMINS], None, admin_connection)
#         try:
#             html_message = get_template('mails/{0}.html'.format(template)).render(context)
#             real_email.attach_alternative(html_message, 'text/html')
#             admin_email.attach_alternative(html_message, 'text/html')
#         except TemplateDoesNotExist:
#             pass
# 
#         real_email.send(fail_silently=False)
#         admin_email.send(fail_silently=False)
# 
#         real_connection.close()
#         admin_connection.close()
# 
# @task
# @only_one
# def google_apps_add_group_task(group_id, member_id):
#     logger.debug('Starting Google Apps add to group task')
#     try:
#         logger.debug('Get GroupsProvisioningClient')
#         clientInstance = GroupsProvisioningClient('unishared.com',
#             OAuthHmacToken('unishared.com', '',
#                 '', '', ACCESS_TOKEN))
#         clientInstance.ssl = True
#         logger.debug('Add {0} to {1}'.format(member_id, group_id))
#         clientInstance.AddMemberToGroup(group_id, member_id)
#         return True
#     except RequestError:
#         LoggingHelper.getErrorLogger().debug("Request error while adding user to Google group", exc_info=1)
#         return False
#     except Exception:
#         LoggingHelper.getErrorLogger().error("Error while adding user to Google group", exc_info=1)
#         return False


# Path: UniShared_python/website/pipelines/user.py
from datetime import datetime, timedelta
from urllib2 import urlopen
from django.core.files.base import ContentFile
from django.template.context import Context
from django.template.defaultfilters import slugify
from social_auth.backends import USERNAME
from social_auth.backends.facebook import FacebookBackend
from UniShared_python.settings import GAPPS_GROUP_NAME
from UniShared_python.website.tasks import email_task, google_apps_add_group_task
import hashlib

        url = "http://graph.facebook.com/%s/picture?type=large" % response['id']
    
    if url:
        profile = user.get_profile()
        if profile.image == '':
            avatar = urlopen(url)       

            content = avatar.read()
            md5 = hashlib.md5()
            md5.update(content)
            name = '{0}-{1}.jpg'.format(slugify(user.username + " social"), md5.hexdigest()[:12])
            profile.image.save(name, ContentFile(content))
            profile.save()

def add_user_to_group(backend, details, response, user, is_new=False, *args, **kwargs):   
    """ 
    Add current user to the UniShared's Google Group
    """
    
    if is_new:
        google_apps_add_group_task.apply_async([GAPPS_GROUP_NAME, user.email])

def send_welcome_mail(backend, details, response, user, is_new=False, *args, **kwargs):
    """
    Send a welcome mail
    """

    if is_new:
        context = Context({'user': user, 'ga_campaign_params' : 'utm_source=unishared&utm_content=v1&utm_medium=e-mail&utm_campaign=welcome_mail'})


        email_task.apply_async([u'Welcome on UniShared!', context, 'welcome_mail', [user.email]], eta= datetime.utcnow() + timedelta(hours=1))