def insertIntoGallery(
    gallery_title,
    gallery_slug,
    screenshot,
    title,
    slug,
    gallery_description="",
    gallery_tags="",
    caption="",
    tags="",
    fab_dir='%s/.fabric-bolt' % (os.path.expanduser('~/'))
):
    # Add custom fabric-bolt settings directory
    sys.path.insert(0, fab_dir)
    # Utilize django within fabfile
    # Load custom fabric-bolt settings file
    django.settings_module('settings')
    # Loads the django Models
    get_wsgi_application()
    # Once loaded we can reference them
    from photologue.models import Photo
    from photologue.models import Gallery

    file = open(screenshot, 'rb')
    data = file.read()

    # First Generate or Retrieve the Photo Model and save or update it
    try:
        photo = Photo.objects.get(slug=slug)
        photo.date_added = datetime.now()
        photo.date_taken = datetime.now()
        print("~~~ FOUND existing Screenshot ~~~")
    except Photo.DoesNotExist:
        photo = Photo(title=title, slug=slug, caption=caption, is_public=True, tags=tags,)
        print("~~~ CREATED new Screenshot ~~~")

    try:
        photo.image.save(os.path.basename(screenshot), ContentFile(data))
    except FieldError:
        # For some reason a field, 'photo,' is being passed to model as a field.
        pass
    print("~~~ SAVED Screenshot ~~~")

    # Now Create or Retrieve the named Gallery and add the photo to it.
    gallery = None
    try:
        gallery = Gallery.objects.get(title=gallery_title)
        print("~~~ FOUND existing Screenshot Gallery ~~~")
    except Gallery.DoesNotExist:
        gallery = Gallery(title=gallery_title, slug=gallery_slug, description=gallery_description, is_public=True, tags=gallery_tags,)
        gallery.save()
        print("~~~ CREATED new Screenshot Gallery ~~~")

    if gallery:
        gallery.photos.add(photo)
        print("~~~ Added Screenshot to Gallery ~~~")
        print("<a target=\"_parent\" href=\"/photologue/gallery/%s\">View Screenshot Gallery %s</a>") % (gallery_title, gallery_title)

    # Reset the syspath
    sys.path.remove(fab_dir)
Esempio n. 2
0
 def save_model(self, request, obj, form, change):
     if not change:
         g = Gallery(title=obj.name+ " gallery",
                     title_slug=slugify(obj.nameid+"-gallery"),
                     is_public=True)
         g.save()
         obj.gallery=g
     obj.save()
Esempio n. 3
0
def upload_photo(request, narrative_id):
    narrative = get_object_or_404(Narrative, pk=narrative_id)
    if request.user == narrative.author:
        if narrative.gallery:
            gallery = narrative.gallery
        else:
            gallery = Gallery(title=narrative.title[:50], content_type=ContentType.objects.get_for_model(Narrative), object_pk=narrative.id, is_public=narrative.experience.is_public)
            gallery.save()
            gallery.explorers.add(request.user)
            narrative.gallery = gallery
            narrative.save()
        return redirect('/photologue/gallery/{0}/upload_photo/'.format(gallery.id))
    raise PermissionDenied
Esempio n. 4
0
    def handle(self, *args, **options):
        try:
            from photologue.models import Gallery, Photo, PhotoSize
        except:
            self.stderr.write('photologue is not installed. Install it fist.\n')
            return

        # check the thumnail size
        photo_size = PhotoSize.objects.filter(name__exact='thumbnail')
        if not photo_size:
            self.stderr.write('you have not defined the thumbnail size. run plinit and define it.\n')
            return

        # check the saladoplayer gallery
        hotspots = {'see': 'oeil_jaune_noir_rond.png',
                    'info':'info_bleu_blanc_triangle.png',
                    'goto': 'pas_orange_blanc_carre.png',
                    'link': 'fleche_bleu_blanc_rond.png',
                   }
        gallery = Gallery.objects.filter(title_slug__exact='saladoplayer')
        if gallery:
            self.stdout.write('saladoplayer gallery already exists\n')
            photos = Photo.objects.filter(galleries__exact=gallery)
            if len(photos) != len(hotspots):
                self.stderr.write('incorrect number of photos in the saladoplayer gallery\n')
            for photo in photos:
                if not photo.title_slug in hotspots.keys():
                    self.stderr.write('incorrect title of photo in the saladoplayer gallery\n')
                    self.stderr.write('invalid photo %s in saladoplayer gallery\n' % photo.title)
                    return
            return

        #create saladoplayer gallery
        creation_date = timezone.localtime(timezone.now())
        g = Gallery(title='saladoplayer', title_slug='saladoplayer',
                    description='for use by saladoplayer app',
                    date_added=creation_date)
        g.save()
        # create default hotspots and add them to the 'saladoplayer' gallery
        for k, v in hotspots.items():
            filename = os.path.join(os.path.dirname(saladoplayer.__file__),
                                    'static/hotspots/images/%s' % v)
            f = File(open(filename))
            p = Photo(title=k, title_slug=k,
                      date_added=creation_date, date_taken=creation_date)
            p.image.save('saladoplayer/%s' % (v,), f, save=True)
            f.close()
            g.photos.add(p)
        self.stdout.write('saladoplayer gallery successfuly added\n')
Esempio n. 5
0
def create(request):
    if request.method == 'POST' and 'initial' not in request.POST:
        explorer_form = RegistrationForm(request.POST)
        if explorer_form.is_valid():
            # The person correctly filled out the form. Register them
            explorer_form.save(commit=False)
            explorer_form.instance.set_password(explorer_form.cleaned_data['password1'])
            explorer = explorer_form.save()
            explorer = authenticate(
                username=explorer_form.cleaned_data['email'],
                password=explorer_form.cleaned_data['password1']
            )
            # Log new explorer in
            login(request, explorer)
            first_experience = None
            if request.POST.get('title'):
                # Save their experience
                first_experience = ExperienceForm(request.POST,
                        author=explorer).save()
                explorer.featured_experience = first_experience
                explorer.save()
            # Create a gallery for the new explorer
            gallery = Gallery(title=explorer.get_full_name(), title_slug=slugify(explorer.trailname), content_type=ContentType.objects.get_for_model(get_user_model()), object_pk=explorer.id)
            gallery.save()
            gallery.explorers.add(explorer)
            explorer.gallery = gallery
            explorer.save()
            # Welcome and send them on introductory tour
            messages.success(request, 'Welcome aboard, {0}!'.format(explorer.get_full_name()))
            notify.send(sender=explorer, recipient=get_user_model().objects.get(pk=1), verb='is now a fellow explorer')
            if first_experience:
                messages.success(request, '''You can get started by developing
                your experience a little and then making it public when ready, sharing it
                with others and feeling the power you can draw from support 
                along this journey.''')
                return redirect(reverse('experience', args=(first_experience.id,)))
            else:
                return redirect(reverse('journey', args=(explorer.id,)))
    else:
        explorer_form = RegistrationForm()
    return render(request, 'registration/register.html', {
            'form': explorer_form,
            'experience': request.POST.get('title'),
            'min_password_len': settings.MIN_PASSWORD_LEN,
        }
    )
Esempio n. 6
0
 def save(self):
   data = self.cleaned_data
   gallery = Gallery()
   gallery.title = data.get('title')
   gallery.slug = re.sub(' +', '_', gallery.title)
   gallery.description = data.get('description')
   gallery.save()
   return gallery
Esempio n. 7
0
def upload_image(request, upload_path=None):
    form = ImageForm(request.POST, request.FILES)
    if form.is_valid():
        image = form.cleaned_data['file']
        if image.content_type not in ['image/png', 'image/jpg', 'image/jpeg', 'image/pjpeg']:
            return HttpResponse('Bad image format')

        try:
          gallery = Gallery.objects.get(title_slug='pages_photos')
        except:
          gallery = Gallery(
                title = 'Site Pages Photos',
                title_slug = 'pages_photos',
                is_public = False,
                description = 'System album for holding images added directly to the pages',
              )
          gallery.save()


        image_name, extension = os.path.splitext(image.name)
        m = md5.new(smart_str(image_name))
        image_name = '{0}{1}'.format(m.hexdigest(), extension)

        try:
          photo = Photo(image=image, title=image_name, title_slug = slugify(image_name), caption='')
        except:
          photo = Photo(image=image_name, title_slug = slugify(image_name), caption='')

        photo.save()
        gallery.photos.add(photo)
        image_url = photo.get_display_url()

        # Original Code
        m = md5.new(smart_str(image_name))
        hashed_name = '{0}{1}'.format(m.hexdigest(), extension)
        image_path = default_storage.save(os.path.join(upload_path or UPLOAD_PATH, hashed_name), image)
       # image_url = default_storage.url(image_path)
        return HttpResponse(json.dumps({'filelink': image_url}))
    return HttpResponseForbidden()
def import_folder(request=None, gallery_name=None):
    count = 0
    current_site = Site.objects.get(id=settings.SITE_ID)
    if gallery_name:
        gallery = Gallery.objects.filter(slug=gallery_name)
        if not gallery:
            gallery = Gallery(title=gallery_name, slug=gallery_name)
            gallery.save()
    else:
        gallery = Gallery.objects.first()
        if not gallery:
            gallery = Gallery(title="MyFirstGallery", slug='MyFirstGallery')
            gallery.save()

    for filename in os.listdir(IMPORT_FOLDER):
        if not os.path.isfile(filename):
            if filename[-3:] in image_extensions:
                logger.debug('Reading file "{0}").'.format(filename))

                full_name = os.path.join(IMPORT_FOLDER, filename)

                if Photo.objects.filter(title=filename).exists():
                    logger.debug('file already exist in system: "{0}").'.format(filename))
                    dst_name = os.path.join(IMPORT_CONFLICT_FOLDER, filename)
                    shutil.move(full_name, dst_name)
                else:
                    storage_path = models.get_storage_path(None, filename)
                    dst_name = os.path.join(settings.MEDIA_ROOT, storage_path)
                    shutil.move(full_name, dst_name)

                    photo = Photo(title=filename,
                                  slug=slugify(filename),
                                  caption=filename,
                                  is_public=True)
                    photo.image = storage_path
                    photo.save()
                    photo.sites.add(current_site)
                    gallery.photos.add(photo)
                    count += 1

    if request:
        messages.success(request,
                         _('{0} photos have been added to gallery "{1}".').format(
                             count,
                             gallery.title),
                         fail_silently=True)
    def handle(self, *args, **options):
        if len(args) != 2:
            raise CommandError("This command takes exactly two arguments")
        galleries_filename, pictures_filename = args
        with open(galleries_filename, 'r') as gh:
            galleries = json.load(gh)


        galleries_result = {}
        paths = {} 

        for gallery in galleries:
            paths[gallery['gid']] = gallery['path']
            kwargs = {
                'title': gallery['title'],
                'title_slug': gallery['slug'],
                'description': gallery['galdesc'],
            }
            try:
                new_gallery = Gallery.objects.get(title_slug=gallery['slug'])
                for key, value in kwargs.items():
                    setattr(new_gallery, key, value)
            except Gallery.DoesNotExist:
                new_gallery = Gallery(**kwargs)
            new_gallery.save()
            galleries_result[gallery['gid']] = new_gallery

        with open(pictures_filename, 'r') as ph:
            pictures = json.load(ph)

        result = []
        for picture in pictures:
            path = paths[picture['galleryid']]
            kwargs = {
                'title': picture['alttext'],
                'title_slug': picture['image_slug'],
                'date_taken': datetime(*time.strptime(picture['imagedate'], "%Y-%m-%d %H:%M:%S")[0:6]),
                'image': os.path.join('/'.join(path.split('/')[1:]), picture['filename']),
                'caption': picture['description'],
                'is_public': not bool(picture['exclude']),
            }
            d = 0
            try:
                new_photo = Photo.objects.get(title_slug=picture['image_slug'])
                for key, value in kwargs.items():
                    setattr(new_gallery, key, value)
            except Photo.DoesNotExist:
                new_photo = Photo(**kwargs)
                while True:
                    try:
                        if d:
                            title = new_photo.title + (' %d' % d)
                        else:
                            title = new_photo.title
                        Photo.objects.get(title=title)
                        d+=1
                    except Photo.DoesNotExist:
                        new_photo.title = title
                        break
            gallery = galleries_result[picture['galleryid']]
            new_photo.save()
            gallery.photos.add(new_photo)
Esempio n. 10
0
def insertIntoGallery(gallery_title,
                      gallery_slug,
                      screenshot,
                      title,
                      slug,
                      gallery_description="",
                      gallery_tags="",
                      caption="",
                      tags="",
                      fab_dir='%s/.fabric-bolt' % (os.path.expanduser('~/'))):
    # Add custom fabric-bolt settings directory
    sys.path.insert(0, fab_dir)
    # Utilize django within fabfile
    # Load custom fabric-bolt settings file
    django.settings_module('settings')
    # Loads the django Models
    get_wsgi_application()
    # Once loaded we can reference them
    from photologue.models import Photo
    from photologue.models import Gallery

    file = open(screenshot, 'rb')
    data = file.read()

    # First Generate or Retrieve the Photo Model and save or update it
    try:
        photo = Photo.objects.get(slug=slug)
        photo.date_added = datetime.now()
        photo.date_taken = datetime.now()
        print("~~~ FOUND existing Screenshot ~~~")
    except Photo.DoesNotExist:
        photo = Photo(
            title=title,
            slug=slug,
            caption=caption,
            is_public=True,
            tags=tags,
        )
        print("~~~ CREATED new Screenshot ~~~")

    try:
        photo.image.save(os.path.basename(screenshot), ContentFile(data))
    except FieldError:
        # For some reason a field, 'photo,' is being passed to model as a field.
        pass
    print("~~~ SAVED Screenshot ~~~")

    # Now Create or Retrieve the named Gallery and add the photo to it.
    gallery = None
    try:
        gallery = Gallery.objects.get(title=gallery_title)
        print("~~~ FOUND existing Screenshot Gallery ~~~")
    except Gallery.DoesNotExist:
        gallery = Gallery(
            title=gallery_title,
            slug=gallery_slug,
            description=gallery_description,
            is_public=True,
            tags=gallery_tags,
        )
        gallery.save()
        print("~~~ CREATED new Screenshot Gallery ~~~")

    if gallery:
        gallery.photos.add(photo)
        print("~~~ Added Screenshot to Gallery ~~~")
        print(
            "<a target=\"_parent\" href=\"/photologue/gallery/%s\">View Screenshot Gallery %s</a>"
        ) % (gallery_title, gallery_title)

    # Reset the syspath
    sys.path.remove(fab_dir)