Exemple #1
0
def change_avatar(request,
                  target_obj,
                  target_type,
                  from_name,
                  extra_context={},
                  next_override=None,
                  current_app='plus_groups',
                  namespace='groups',
                  **kwargs):

    # XXX some of this should probably be refactored into the model layer
    target = target_obj.get_ref()
    avatars = Avatar.objects.filter(target=target).order_by('-primary')
    if avatars.count() > 0:
        avatar = avatars[0]
        kwargs = {'initial': {'choice': avatar.id}}
    else:
        avatar = None
        kwargs = {}

    primary_avatar_form = PrimaryAvatarForm(request.POST or None,
                                            target=target,
                                            **kwargs)
    if request.method == "POST":
        if 'avatar' in request.FILES:
            path = avatar_file_path(target=target,
                                    filename=request.FILES['avatar'].name)
            avatar = Avatar(
                target=target,
                primary=True,
                avatar=path,
            )
            new_file = avatar.avatar.storage.save(path,
                                                  request.FILES['avatar'])
            avatar.save()
            request.user.message_set.create(
                message=_("Successfully uploaded a new avatar."))
        if 'choice' in request.POST and primary_avatar_form.is_valid():
            avatar = Avatar.objects.get(
                id=primary_avatar_form.cleaned_data['choice'])
            avatar.primary = True
            avatar.save()

            request.user.message_set.create(
                message=_("Successfully updated your avatar."))
        return HttpResponseRedirect(next_override or _get_next(request))

    return render_to_response(
        'avatar/change.html',
        extra_context,
        context_instance=RequestContext(
            request, {
                'avatar': avatar,
                'avatars': avatars,
                'primary_avatar_form': primary_avatar_form,
                'next': next_override or _get_next(request),
                'target': target_obj,
                'target_type': target_type,
                'from_name': from_name,
            }))
Exemple #2
0
    def handle(self, *args, **options):
        from tendenci.core.files.models import File as tFile

        ct_user = ContentType.objects.get_for_model(User)
        tfiles = tFile.objects.filter(content_type=ct_user,
                                      object_id__isnull=False,
                                      status=True,
                                      status_detail='active')
        for tfile in tfiles:
            if default_storage.exists(tfile.file.name):
                is_image = mimetypes.guess_type(
                    tfile.file.name)[0].startswith('image')
                if is_image:
                    [user
                     ] = User.objects.filter(id=tfile.object_id)[:1] or [None]
                    if user:
                        [
                            user_avatar
                        ] = user.avatar_set.filter(primary=True)[:1] or [None]
                        if not user_avatar:
                            avatar_path = avatar_file_path(
                                user=user,
                                filename=(tfile.file.name.split('/'))[-1])
                            # copy the file to the avatar directory
                            default_storage.save(
                                avatar_path,
                                ContentFile(
                                    default_storage.open(
                                        tfile.file.name).read()))
                            # create an avatar object for the user
                            Avatar.objects.create(user=user,
                                                  primary=True,
                                                  avatar=avatar_path)
                            print 'Avatar created for ', user
        print 'Done'
    def handle(self, *args, **options):
        from tendenci.apps.files.models import File as tFile

        ct_user = ContentType.objects.get_for_model(User)
        tfiles = tFile.objects.filter(content_type=ct_user,
                                      object_id__isnull=False,
                                      status=True,
                                      status_detail='active')
        for tfile in tfiles:
            if default_storage.exists(tfile.file.name):
                is_image = mimetypes.guess_type(tfile.file.name)[0].startswith('image')
                if is_image:
                    [user] = User.objects.filter(id=tfile.object_id)[:1] or [None]
                    if user:
                        [user_avatar] = user.avatar_set.filter(
                                                primary=True)[:1] or [None]
                        if not user_avatar:
                            avatar_path = avatar_file_path(
                                                    user=user,
                                                    filename=(tfile.file.name.split('/'))[-1])
                            # copy the file to the avatar directory
                            default_storage.save(avatar_path,
                                                  ContentFile(
                                                   default_storage.open(
                                                    tfile.file.name).read()))
                            # create an avatar object for the user
                            Avatar.objects.create(
                                user=user,
                                primary=True,
                                avatar=avatar_path
                                    )
                            print 'Avatar created for ', user
        print 'Done'
Exemple #4
0
def change(request, extra_context={}, next_override=None):
    avatars = Avatar.objects.filter(user=request.user).order_by('-primary')
    if avatars.count() > 0:
        avatar = avatars[0]
        kwargs = {'initial': {'choice': avatar.id}}
    else:
        avatar = None
        kwargs = {}
    primary_avatar_form = PrimaryAvatarForm(request.POST or None,
                                            user=request.user,
                                            **kwargs)
    if request.method == "POST":
        updated = False
        if 'avatar' in request.FILES:
            path = avatar_file_path(user=request.user,
                                    filename=request.FILES['avatar'].name)
            avatar = Avatar(
                user=request.user,
                primary=True,
                avatar=path,
            )
            new_file = avatar.avatar.storage.save(path,
                                                  request.FILES['avatar'])
            avatar.save()
            updated = True
            request.user.message_set.create(
                message=_("Successfully uploaded a new avatar."))
        if 'choice' in request.POST and primary_avatar_form.is_valid():
            avatar = Avatar.objects.get(
                id=primary_avatar_form.cleaned_data['choice'])
            avatar.primary = True
            avatar.save()
            updated = True
            request.user.message_set.create(
                message=_("Successfully updated your avatar."))
        if updated and notification:
            notification.send([request.user], "avatar_updated", {
                "user": request.user,
                "avatar": avatar
            })
            if friends:
                notification.send(
                    (x['friend']
                     for x in Friendship.objects.friends_for_user(request.user)
                     ), "avatar_friend_updated", {
                         "user": request.user,
                         "avatar": avatar
                     })
        return HttpResponseRedirect(next_override or _get_next(request))
    return render_to_response(
        'avatar/change.html',
        extra_context,
        context_instance=RequestContext(
            request, {
                'avatar': avatar,
                'avatars': avatars,
                'primary_avatar_form': primary_avatar_form,
                'next': next_override or _get_next(request),
            }))
Exemple #5
0
def change_avatar(request, id, extra_context={}, next_override=None):
    user_edit = get_object_or_404(User, pk=id)
    try:
        profile = Profile.objects.get(user=user_edit)
    except Profile.DoesNotExist:
        profile = Profile.objects.create_profile(user=user_edit)
        
    #if not has_perm(request.user,'profiles.change_profile',profile): raise Http403
    if not profile.allow_edit_by(request.user): raise Http403
    
    avatars = Avatar.objects.filter(user=user_edit).order_by('-primary')
    if avatars.count() > 0:
        avatar = avatars[0]
        kwargs = {'initial': {'choice': avatar.id}}
    else:
        avatar = None
        kwargs = {}
    primary_avatar_form = PrimaryAvatarForm(request.POST or None, user=user_edit, **kwargs)
    if request.method == "POST":
        updated = False
        if 'avatar' in request.FILES:
            path = avatar_file_path(user=user_edit, 
                filename=request.FILES['avatar'].name)
            avatar = Avatar(
                user = user_edit,
                primary = True,
                avatar = path,
            )
            new_file = avatar.avatar.storage.save(path, request.FILES['avatar'])
            avatar.save()
            updated = True
            request.user.message_set.create(
                message=_("Successfully uploaded a new avatar."))
        if 'choice' in request.POST and primary_avatar_form.is_valid():
            avatar = Avatar.objects.get(id=
                primary_avatar_form.cleaned_data['choice'])
            avatar.primary = True
            avatar.save()
            updated = True
            request.user.message_set.create(
                message=_("Successfully updated your avatar."))
        if updated and notification:
            notification.send([request.user], "avatar_updated", {"user": user_edit, "avatar": avatar})
            #if friends:
            #    notification.send((x['friend'] for x in Friendship.objects.friends_for_user(user_edit)), "avatar_friend_updated", {"user": user_edit, "avatar": avatar})
        return HttpResponseRedirect(reverse('profile', args=[user_edit.username]))
        #return HttpResponseRedirect(next_override or _get_next(request))
    return render_to_response(
        'profiles/change_avatar.html',
        extra_context,
        context_instance = RequestContext(
            request,
            {'user_this': user_edit,
              'avatar': avatar, 
              'avatars': avatars,
              'primary_avatar_form': primary_avatar_form,
              'next': next_override or _get_next(request), }
        )
    )
def make_avatar(old_user):
    if old_user["profileicon"]:
        icon = path_to_profileimages+old_user["profileicon"]
        user = User.objects.get(pk=get_new_id("user", old_user["user_id"]))
        path = avatar_file_path(user=user, filename=old_user["profileicon"])
        avatar = Avatar(
            user = user,
            primary = True,
            avatar = path,
        )
        new_file = avatar.avatar.storage.save(path, ContentFile(open(icon, "r").read()))
        avatar.save()
Exemple #7
0
def change_avatar(request, target_obj, target_type, from_name, extra_context={}, 
                  next_override=None, current_app='plus_groups',namespace='groups',**kwargs):

    # XXX some of this should probably be refactored into the model layer 
    target = target_obj.get_ref()
    avatars = Avatar.objects.filter(target=target).order_by('-primary')
    if avatars.count() > 0:
        avatar = avatars[0]
        kwargs = {'initial': {'choice': avatar.id}}
    else:
        avatar = None
        kwargs = {}

    primary_avatar_form = PrimaryAvatarForm(request.POST or None, target=target, **kwargs)
    if request.method == "POST":
        if 'avatar' in request.FILES:
            path = avatar_file_path(target=target, 
                filename=request.FILES['avatar'].name)
            avatar = Avatar(
                target = target,
                primary = True,
                avatar = path,
            )
            new_file = avatar.avatar.storage.save(path, request.FILES['avatar'])
            avatar.save()
            request.user.message_set.create(
                message=_("Successfully uploaded a new avatar."))
        if 'choice' in request.POST and primary_avatar_form.is_valid():
            avatar = Avatar.objects.get(id=
                primary_avatar_form.cleaned_data['choice'])
            avatar.primary = True 
            avatar.save()
            
            request.user.message_set.create(
                message=_("Successfully updated your avatar."))
        return HttpResponseRedirect(next_override or _get_next(request))

    return render_to_response(
        'avatar/change.html',
        extra_context,
        context_instance = RequestContext(
            request,
            { 'avatar': avatar, 
              'avatars': avatars,
              'primary_avatar_form': primary_avatar_form,
              'next': next_override or _get_next(request),
              'target' : target_obj,
              'target_type' : target_type,
              'from_name' : from_name,
              }
        )
    )
Exemple #8
0
def change(request, extra_context={}, next_override=None):
    avatars = Avatar.objects.filter(user=request.user).order_by('-primary')
    if avatars.count() > 0:
        avatar = avatars[0]
        kwargs = {'initial': {'choice': avatar.id}}
    else:
        avatar = None
        kwargs = {}
    primary_avatar_form = PrimaryAvatarForm(
        request.POST or None, user=request.user, **kwargs)
    if request.method == "POST":
        updated = False
        if 'avatar' in request.FILES:
            path = avatar_file_path(user=request.user,
                                    filename=request.FILES['avatar'].name)
            avatar = Avatar(
                user=request.user,
                primary=True,
                avatar=path,
            )
            new_file = avatar.avatar.storage.save(
                path, request.FILES['avatar'])
            avatar.save()
            updated = True
            messages.info(request,
                _("Successfully uploaded a new avatar."))
        if 'choice' in request.POST and primary_avatar_form.is_valid():
            avatar = Avatar.objects.get(id=
                                        primary_avatar_form.cleaned_data['choice'])
            avatar.primary = True
            avatar.save()
            updated = True
            messages.info(request,
                _("Successfully updated your avatar."))
        if updated and notification:
            notification.send([request.user], "avatar_updated", {
                              "user": request.user, "avatar": avatar})
            if friends:
                notification.send((x['friend'] for x in Friendship.objects.friends_for_user(
                    request.user)), "avatar_friend_updated", {"user": request.user, "avatar": avatar})
        return HttpResponseRedirect(next_override or _get_next(request))
    return render_to_response(
        'avatar/change.html',
        extra_context,
        context_instance=RequestContext(
            request,
            {'avatar': avatar,
             'avatars': avatars,
             'primary_avatar_form': primary_avatar_form,
             'next': next_override or _get_next(request), }
        )
    )
Exemple #9
0
    def change_avatar(self, request):
        avatars = Avatar.objects.filter(user=request.user).order_by('-primary')
        if avatars.count() > 0:
            avatar = avatars[0]

        if 'avatar_file' in request.FILES:
            path = avatar_file_path(user=request.user,filename=request.FILES['avatar_file'].name)
            avatar = Avatar(
                user = request.user,
                primary = True,
                avatar = path,
            )
            new_file = avatar.avatar.storage.save(path, request.FILES['avatar_file'])
            avatar.save()
Exemple #10
0
def change(request, extra_context={}, next_override=None):
    avatars = Avatar.objects.filter(user=request.user).order_by("-primary")
    if avatars.count() > 0:
        avatar = avatars[0]
        kwargs = {"initial": {"choice": avatar.id}}
    else:
        avatar = None
        kwargs = {}
    primary_avatar_form = PrimaryAvatarForm(request.POST or None, user=request.user, **kwargs)
    if request.method == "POST":
        updated = False
        if "avatar" in request.FILES:
            path = avatar_file_path(user=request.user, filename=request.FILES["avatar"].name)
            avatar = Avatar(user=request.user, primary=True, avatar=path)
            new_file = avatar.avatar.storage.save(path, request.FILES["avatar"])
            avatar.save()
            updated = True
            # request.user.message_set.create(
            #    message=_("Successfully uploaded a new avatar."))
        if "choice" in request.POST and primary_avatar_form.is_valid():
            avatar = Avatar.objects.get(id=primary_avatar_form.cleaned_data["choice"])
            avatar.primary = True
            avatar.save()
            updated = True
            # request.user.message_set.create(
            #    message=_("Successfully updated your avatar."))
        if updated and notification:
            notification.send([request.user], "avatar_updated", {"user": request.user, "avatar": avatar})
            if friends:
                notification.send(
                    (x["friend"] for x in Friendship.objects.friends_for_user(request.user)),
                    "avatar_friend_updated",
                    {"user": request.user, "avatar": avatar},
                )
        return HttpResponseRedirect(next_override or _get_next(request))
    return render_to_response(
        "avatar/change.html",
        extra_context,
        context_instance=RequestContext(
            request,
            {
                "avatar": avatar,
                "avatars": avatars,
                "primary_avatar_form": primary_avatar_form,
                "next": next_override or _get_next(request),
            },
        ),
    )
Exemple #11
0
def add_avatar(group, image_dir, image_file_name) :
    if image_file_name == '' : 
        return

    f = ImageFile(open('mhpss_export/%s/%s'%(image_dir,image_file_name)),'rb')
    if f.size == 1357 :
        return   # image is plone default ... we don't want it
          
    path = avatar_file_path(target=group, filename=image_file_name)

    avatar = Avatar(
        target = group.get_ref(),
        primary = True,
        avatar = path,
        )

    avatar.save()
    new_file = avatar.avatar.storage.save(path, f)
    avatar.save()
Exemple #12
0
def change(request, extra_context={}, next_override=None):
    avatars = Avatar.objects.filter(user=request.user).order_by('-primary')
    if avatars.count() > 0:
        avatar = avatars[0]
        kwargs = {'initial': {'choice': avatar.id}}
    else:
        avatar = None
        kwargs = {}
    primary_avatar_form = PrimaryAvatarForm(request.POST or None, user=request.user, **kwargs)
    if request.method == "POST":
        if 'avatar' in request.FILES:
            path = avatar_file_path(user=request.user, 
                filename=request.FILES['avatar'].name)
            avatar = Avatar(
                user = request.user,
                primary = True,
                avatar = path,
            )
            new_file = avatar.avatar.storage.save(path, request.FILES['avatar'])
            avatar.save()
            request.user.message_set.create(
                message=_("Successfully uploaded a new avatar."))
        if 'choice' in request.POST and primary_avatar_form.is_valid():
            avatar = Avatar.objects.get(id=
                primary_avatar_form.cleaned_data['choice'])
            avatar.primary = True
            avatar.save()
            request.user.message_set.create(
                message=_("Successfully updated your avatar."))
        return HttpResponseRedirect(next_override or _get_next(request))
    return render_to_response(
        'avatar/change.html',
        extra_context,
        context_instance = RequestContext(
            request,
            { 'avatar': avatar, 
              'avatars': avatars,
              'primary_avatar_form': primary_avatar_form,
              'next': next_override or _get_next(request), }
        )
    )
Exemple #13
0
def change(request, extra_context={}, next_override=None):
    avatars = Avatar.objects.filter(user=request.user).order_by('-primary')
    if avatars.count() > 0:
        avatar = avatars[0]
        kwargs = {'initial': {'choice': avatar.id}}
    else:
        avatar = None
        kwargs = {}
    primary_avatar_form = PrimaryAvatarForm(request.POST or None, user=request.user, **kwargs)
    if request.method == "POST":
        if 'avatar' in request.FILES:
            path = avatar_file_path(user=request.user, 
                filename=request.FILES['avatar'].name)
            try:
                os.makedirs(os.path.join(
                    settings.MEDIA_ROOT, "/".join(path.split('/')[:-1])))
            except OSError, e:
                pass # The dirs already exist.
            new_file = default_storage.open(path, 'wb')
            for i, chunk in enumerate(request.FILES['avatar'].chunks()):
                if i * 16 == MAX_MEGABYTES:
                    raise Http404 # TODO: Is this the right thing to do?
                                  # Validation error maybe, instead?
                new_file.write(chunk)
            avatar = Avatar(
                user = request.user,
                primary = True,
                avatar = path,
            )
            avatar.save()
            new_file.close()
            request.user.message_set.create(
                message=_("Successfully uploaded a new avatar."))
        if 'choice' in request.POST and primary_avatar_form.is_valid():
            avatar = Avatar.objects.get(id=
                primary_avatar_form.cleaned_data['choice'])
            avatar.primary = True
            avatar.save()
            request.user.message_set.create(
                message=_("Successfully updated your avatar."))
        return HttpResponseRedirect(next_override or _get_next(request))
    def handle_noargs(self, **options):
        # define path to avatar folders
        avatar_path = os.path.join(settings.MEDIA_URL,
                                   settings.AVATAR_STORAGE_DIR)

        have_change = False
        for avatar in Avatar.objects.all():
            # get actuel path of avatar
            new_path = os.path.join(settings.MEDIA_URL,
                                    avatar_file_path(avatar))
            original_path = avatar.avatar.url
            if new_path != original_path:
                print("Move Avatar id=%s from %s to %s." % (avatar.id,
                                                            original_path,
                                                            new_path))

                # if different path: we copy + generate new thumbnails + clean
                media_path = original_path.replace(settings.MEDIA_URL, "")
                media_path = os.path.join(settings.MEDIA_ROOT, media_path)
                # copy original avatar into new folder
                avatar.avatar.save(os.path.basename(new_path),
                                   File(open(media_path)))
                avatar.save()

                # delete old folder and thumbnails
                i = original_path.find('/', len(avatar_path) + 1)
                folder = original_path[0:i]
                if folder[0:1] == "/":
                    folder = folder[1:]
                folder = os.path.join(settings.BASE_DIR, folder)
                print("Delete useless folder %s" % folder)
                shutil.rmtree(folder)
                have_change = True

        # generate all default thumbnails in new folder
        if have_change:
            call_command('rebuild_avatars')
        else:
            print("No change ;)")
Exemple #15
0
    def handle_noargs(self, **options):
        # define path to avatar folders
        avatar_path = os.path.join(settings.MEDIA_URL,
                                   settings.AVATAR_STORAGE_DIR)

        have_change = False
        for avatar in Avatar.objects.all():
            # get actuel path of avatar
            new_path = os.path.join(settings.MEDIA_URL,
                                    avatar_file_path(avatar))
            original_path = avatar.avatar.url
            if new_path != original_path:
                print("Move Avatar id=%s from %s to %s." %
                      (avatar.id, original_path, new_path))

                # if different path: we copy + generate new thumbnails + clean
                media_path = original_path.replace(settings.MEDIA_URL, "")
                media_path = os.path.join(settings.MEDIA_ROOT, media_path)
                # copy original avatar into new folder
                avatar.avatar.save(os.path.basename(new_path),
                                   File(open(media_path)))
                avatar.save()

                # delete old folder and thumbnails
                i = original_path.find('/', len(avatar_path) + 1)
                folder = original_path[0:i]
                if folder[0:1] == "/":
                    folder = folder[1:]
                folder = os.path.join(settings.BASE_DIR, folder)
                print("Delete useless folder %s" % folder)
                shutil.rmtree(folder)
                have_change = True

        # generate all default thumbnails in new folder
        if have_change:
            call_command('rebuild_avatars')
        else:
            print("No change ;)")
Exemple #16
0
def change(request):
    avatars = Avatar.objects.filter(user=request.user).order_by('-primary')
    if avatars.count() > 0:
        avatar = avatars[0]
    else:
        avatar = None

    if request.method == "POST":
        updated = False
        if 'avatar' in request.FILES:
            path = avatar_file_path(user=request.user,
                filename=request.FILES['avatar'].name)
            avatar = Avatar(
                user=request.user,
                primary=True,
                avatar=path,
            )
            new_file = avatar.avatar.storage.save(path, request.FILES['avatar'])
            avatar.save()
            updated = True
            request.user.message_set.create(
                message=_("Successfully uploaded a new avatar."))
        if updated and notification:
            notification.send([request.user], "avatar_updated", {"user": request.user, "avatar": avatar})

    return render_to_response(
        'avatar/change.html',
        {},
        context_instance=RequestContext(
            request,
                {
                'avatar': avatar,
                'avatars': avatars
            }
        )
    )
Exemple #17
0
    except Exception, exc:
        _log.warn("Exception %r on vCard BINVAL decoding." % exc)
        _log.debug(traceback.format_exc())
        return
    from django.core.files.base import ContentFile
    contentf = ContentFile(pdata)
    _log.debug("... creating avatar...")
    #contentf.name = 'xf-vcard-auto-avatar'
    autobasename = 'xf-vcard-auto-avatar.%s'
    contentf.name = autobasename % extension
    autoav = Avatar(user=user, avatar=contentf)
    # Check if auto-avatar is already presemt, replace if it is.
    # ! It's user's problem if user uploads an avatar with such a special
    #  name :)
    old_autoav_qs = Avatar.objects.filter(user=user,
      avatar__startswith=avatar_file_path(autoav, autobasename % ''))[:1]
    if old_autoav_qs:  # Already have some. Replace it.
        # ! XXX: non-parallel-safe here.
        old_autoav = old_autoav_qs[0]
        autoav.primary = old_autoav.primary  # XXX: Not very nice.
        old_autoav.delete()
    else:  # save the new one,
        autoav.save()
    _log.debug("... av done.")


def processcmd(indata):
    """ Processes XMPP-originating data such as statuses, text commands,
    etc.  """
    src = indata.get('src')
    srcbarejid = src.split("/")[0]  # Strip the resource if any.
Exemple #18
0
from django.core.files.images import ImageFile
from apps.plus_groups.models import Location

for u in User.objects.all():

    f_name = 'hubplus_avatars/binaries/user-%s' % u.id
    try:
        f = ImageFile(open(f_name), 'rb')
    except Exception:
        print "no file for %s, %s, %s" % (u.username, u.id, f_name)
        continue

    print "found one %s" % u.username

    path = avatar_file_path(target=u, filename=u.username)

    new_avatar = Avatar(
        target=u.get_ref(),
        primary=True,
        avatar=path,
    )

    avatars = Avatar.objects.filter(target=u).order_by('-primary')

    if avatars:
        old_avatar = avatars[0]
        #if old_avatar.avatar.size == new_avatar.avatar.size :
        #    print "exists"
        #    continue
Exemple #19
0
def import_user(u):
    print u['uid'], u['username']
    username = u['username']
    description = u['description']
    roles = u['roles']
    fullname = u['fullname'].strip()
    biography = u['biography']
    email = u['email']
    portrait = u['portraitfile'].split('/')[-1]
    psn_id = u['uid']
    location = u['location']

    if not user_exists(username, email):
        user = create_user(username, email_address=email, password='******')
    else:
        user = User.objects.get(username=username)

    user.set_password('password')
    if description:
        user.description = description
    elif biography:
        user.description = biography

    if not user.homeplace:
        if location:
            p, flag = Location.objects.get_or_create(name=location)
            user.homeplace = p
        else:
            user.homeplace = get_or_create_root_location()

    if " " in fullname:
        first, last = fullname.rsplit(' ', 1)
    elif "." in fullname:
        first, last = fullname.rsplit('.', 1)
    else:
        first = fullname
        last = ''

    user.first_name = first[:30]
    user.last_name = last[:30]
    user.psn_id = psn_id
    c = 1
    email2 = email
    while (email_exists(email2)):
        print email2
        email2 = '%s%s' % (c, email)
        c = c + 1
    user.email = email2
    user.save()

    f = ImageFile(open('mhpss_export/user_images/%s' % portrait), 'rb')
    if f.size == 1357:
        return  # image is plone default ... we don't want it

    path = avatar_file_path(target=user, filename=portrait)

    avatar = Avatar(
        target=user.get_ref(),
        primary=True,
        avatar=path,
    )

    avatar.save()
    new_file = avatar.avatar.storage.save(path, f)
    avatar.save()
Exemple #20
0
from django.core.files.images import ImageFile
from apps.plus_groups.models import Location

for u in User.objects.all() :

    f_name = 'hubplus_avatars/binaries/user-%s'%u.id
    try:
        f = ImageFile(open(f_name),'rb')
    except Exception :
        print "no file for %s, %s, %s" % (u.username,u.id,f_name)
        continue

    print "found one %s" % u.username

    path = avatar_file_path(target=u, filename=u.username)
 
    new_avatar = Avatar(
        target = u.get_ref(),
        primary = True,
        avatar = path,
        )

    avatars = Avatar.objects.filter(target=u).order_by('-primary')
 
    if avatars :    
        old_avatar = avatars[0]
        #if old_avatar.avatar.size == new_avatar.avatar.size :
        #    print "exists"
        #    continue
Exemple #21
0
def import_user(u):
    print u['uid'], u['username']
    username = u['username']
    description = u['description']
    roles = u['roles']
    fullname = u['fullname'].strip() 
    biography = u['biography']
    email = u['email']
    portrait = u['portraitfile'].split('/')[-1]
    psn_id = u['uid']
    location = u['location']
    
    if not user_exists(username, email):
        user = create_user(username, email_address=email, password='******')
    else:
        user = User.objects.get(username=username)
    
    user.set_password('password')
    if description : 
        user.description = description
    elif biography :
        user.description = biography

    if not user.homeplace :
        if location :
            p,flag = Location.objects.get_or_create(name=location)
            user.homeplace = p
        else :
            user.homeplace = get_or_create_root_location()
    
    if " " in fullname :
        first, last = fullname.rsplit(' ',1)
    elif "." in fullname :
        first, last = fullname.rsplit('.',1)
    else :
        first = fullname
        last = ''        

    user.first_name = first[:30]
    user.last_name = last[:30]
    user.psn_id = psn_id
    c = 1
    email2 = email
    while (email_exists(email2)) :
        print email2
        email2 = '%s%s'%(c,email)
        c=c+1
    user.email = email2
    user.save()

    f = ImageFile(open('mhpss_export/user_images/%s'%portrait),'rb')
    if f.size == 1357 :
        return # image is plone default ... we don't want it

    path = avatar_file_path(target=user, filename=portrait)
 
    avatar = Avatar(
        target = user.get_ref(),
        primary = True,
        avatar = path,
        )

    avatar.save()
    new_file = avatar.avatar.storage.save(path, f)
    avatar.save()
Exemple #22
0
def change_avatar(request, id, extra_context={}, next_override=None):
    user_edit = get_object_or_404(User, pk=id)
    try:
        profile = Profile.objects.get(user=user_edit)
    except Profile.DoesNotExist:
        profile = Profile.objects.create_profile(user=user_edit)

    #if not has_perm(request.user,'profiles.change_profile',profile): raise Http403
    if not profile.allow_edit_by(request.user): raise Http403

    avatars = Avatar.objects.filter(user=user_edit).order_by('-primary')
    if avatars.count() > 0:
        avatar = avatars[0]
        kwargs = {'initial': {'choice': avatar.id}}
    else:
        avatar = None
        kwargs = {}
    primary_avatar_form = PrimaryAvatarForm(request.POST or None,
                                            user=user_edit,
                                            **kwargs)
    if request.method == "POST":
        updated = False
        if 'avatar' in request.FILES:
            path = avatar_file_path(user=user_edit,
                                    filename=request.FILES['avatar'].name)
            avatar = Avatar(
                user=user_edit,
                primary=True,
                avatar=path,
            )
            new_file = avatar.avatar.storage.save(path,
                                                  request.FILES['avatar'])
            avatar.save()
            updated = True

            messages.add_message(request, messages.SUCCESS,
                                 _("Successfully uploaded a new avatar."))

        if 'choice' in request.POST and primary_avatar_form.is_valid():
            avatar = Avatar.objects.get(
                id=primary_avatar_form.cleaned_data['choice'])
            avatar.primary = True
            avatar.save()
            updated = True

            messages.add_message(request, messages.SUCCESS,
                                 _("Successfully updated your avatar."))

        if updated and notification:
            notification.send([request.user], "avatar_updated", {
                "user": user_edit,
                "avatar": avatar
            })
            #if friends:
            #    notification.send((x['friend'] for x in Friendship.objects.friends_for_user(user_edit)), "avatar_friend_updated", {"user": user_edit, "avatar": avatar})
        return HttpResponseRedirect(
            reverse('profile', args=[user_edit.username]))
        #return HttpResponseRedirect(next_override or _get_next(request))
    return render_to_response(
        'profiles/change_avatar.html',
        extra_context,
        context_instance=RequestContext(
            request, {
                'user_this': user_edit,
                'avatar': avatar,
                'avatars': avatars,
                'primary_avatar_form': primary_avatar_form,
                'next': next_override or _get_next(request),
            }))
Exemple #23
0
        first, last = fullname.rsplit('.',1)
    else :
        first = fullname
        last = ''        

    user.first_name = first[:30]
    user.last_name = last[:30]
    user.psn_id = psn_id

    user.save()

    f = ImageFile(open('mhpss_export/user_images/%s'%portrait),'rb')
    if f.size == 1357 :
        continue

    path = avatar_file_path(user=user, filename=portrait)
 
    avatar = Avatar(
        user = user,
        primary = True,
        avatar = path,
        )


    avatar.save()

    new_file = avatar.avatar.storage.save(path, f)
    avatar.save()