Exemplo n.º 1
0
def upload_photo(photo_path: str, gallery_name: str=None):
    """
        Using Photo class from Photologue models upload photo to db
    """
    photo_date = get_photo_date(photo_path)
    upload_date = datetime.now(pytz.timezone("US/Central"))
    photo_file_name = photo_path.split("/")[-1]
    photo_title = photo_file_name.replace(".jpg", "")
    # new_photo_path = (
    #     f"public/photogallery/media/photologue/photos/{photo_file_name}"
    # )
    # photologue_path = f"photologue/photos/{photo_file_name}"
    # Move photo to photologue directory
    # shutil.copy(photo_path, new_photo_path)
    # os.rename(photo_path, new_photo_path)
    photo_model = Photo(
        image=photo_path, date_taken=photo_date, title=photo_title,
        slug=slugify(photo_title), caption='', date_added=upload_date,
        is_public=True
    )
    LOG.info(f"Saving photo {photo_title} to {photo_path}")
    photo_model.save()
    if gallery_name:
        LOG.info(f"Saving photo {photo_title} to Gallery: {gallery_name}")
        add_photo_to_gallery(photo_obj=photo_model, gallery_name=gallery_name)
Exemplo n.º 2
0
def _convert(track, fileext):
    filename =  track.title_slug
    input = track.original_track.file.name
    print 'Original: ' + input
    print call('ffmpeg -i %s -sameq %s.%s' % (input, filename, fileext), shell=True)
    #Open the file and put it in a friendly format for image save
    f = open('%s.%s' % (filename, fileext), 'r')
    filecontent = ContentFile(f.read())
    track.__getattribute__("track_" + fileext).save('%s.%s' % (filename, fileext), filecontent , save=True)
    f.close()
    if track.image:
        pass
    else:
        print call('ffmpeg -i %s.%s -vframes 1 -ss 30 -sameq %s%sd.png' % (filename, fileext, filename, '%'), shell=True)
        f = open('%s1.png' % filename, 'r')
        filecontent = ContentFile(f.read())
        image = Photo(title=filename, title_slug=filename)
        image.image.save('%s.png' % filename, filecontent , save=True)
        image.save()
        track.image = image
    #Clean the flv and png files left around
    #call("find . -maxdepth 1 -type f -name '*." + fileext + "' -o -name '*.png' | xargs rm", shell=True)
    call("rm *." + fileext + " *.png *.stt", shell=True)
    track.save()
    print 'Converted' + track.__getattribute__("track_" + fileext).file.name
Exemplo n.º 3
0
    def setUp(self):
        user = GamerUser.objects.create_user('urtzai', '*****@*****.**', 'urtzaipass')
        user.is_superuser = True
        user.save()
        photo = Photo(title='GETB atala irudia', slug='gtb-atala-irudia', is_public=True)
        photo.image.save('test_photologue_landscape.jpg', ContentFile(open(LANDSCAPE_IMAGE_PATH, 'rb').read()))
        photo.save()
        Atala.objects.create(izenburua='GETB atala', slug='getb-atala', desk='Lehen atala duzue honako hau.', argazkia=photo,  publikoa_da=True)

        plataforma = Plataforma.objects.create(izena='Play Station 4', slug='play-station-4')
        jokoa = Jokoa.objects.create(izena='Call of Duty', bertsioa='4', slug='call-of-duty-4', logoa=photo, publikoa_da=True)
        zailtasuna = Zailtasuna.objects.create(izena='Zaila', slug='zaila')
        kategoria = Kategoria.objects.create(izena='FPS', slug='fps', desk="First Person Shooter")
        gameplaya = GamePlaya(izenburua='Barrebusa 1', slug='barrebusa-1', desk="Espero dut gustuko izatea.", argazkia=photo, bideoa='c21XAuI3aMo',
                                 jokoa=jokoa, plataforma=plataforma, zailtasuna=zailtasuna, erabiltzailea=user, publikoa_da=True, status='1')
        gameplaya.save()
        gameplaya.kategoria.add(kategoria)
        gameplaya.save()

        gaia = Gaia.objects.create(izena='Berriak', slug='berriak')
        berria = Berria(izenburua='Switch argitaratu da', slug='switch-argitaratu-da', desk="Nintendoren kontsola berria argitaratu da.", erabiltzailea=user, argazkia=photo,
                              jokoa=jokoa, publikoa_da=True, status='1')
        berria.save()
        berria.gaia.add(gaia)
        berria.save()

        txapelketa = Txapelketa.objects.create(izena='LoL txapelketa', slug="lol-txapelketa", desk="LoLeko beste txapelketa bat.", jokoa=jokoa)
        txapelketa.adminak.add(user)
Exemplo n.º 4
0
 def save_model(self, request, obj, form, change):
     files = {}
     if 'zipfile' in request.FILES :
         photolist = load_zip_file(request.FILES['zipfile'])
         files = photolist
     obj.save()
     photos = []
     for photo_name in files:
         if not verify_image(files[photo_name]):
             continue
         title = self.get_title(obj, photo_name)
         slug = self.get_slug(obj, photo_name)
         tags = self.get_tags(photo_name)
         photo = Photo(title=title,
            title_slug=slug,
            caption=title,
            is_public=obj.is_public,
            tags=tags)
         photo.image.save(photo_name, ContentFile(files[photo_name]))
         photo.save()
         photos.append(photo)
     cleaned_data = self.form.clean(form)
     for photo in photos:
         cleaned_data['photos'].append(photo)
     return obj
Exemplo n.º 5
0
def profile_photos_add(request):
    if request.POST:
        title = uuid.uuid5(uuid.uuid1(), str(os.getpid())).hex[:32]
        photologue_photo = PhotologuePhoto(image=request.FILES["file"],
                                           title=title,
                                           slug=title,
                                           is_public=True)
        photologue_photo.save()

        primary = False
        if Photo.objects.filter(
                profile=request.user.matrimony_profile).count() == 0:
            primary = True

        photo = Photo(
            photo=photologue_photo,
            profile=request.user.matrimony_profile,
            primary=primary,
        )
        photo.save()
        return JsonResponse({
            "error": False,
            "data": {
                "image_url": photo.photo.get_display_url(),
                "thumbnail_url": photo.photo.get_thumbnail_url(),
                "id": photo.id,
                "title": photo.photo.title,
                "slug": photo.photo.slug,
            },
        })
Exemplo n.º 6
0
	def form_valid(self, form):

		f = self.request.FILES.get('file')
		file_type =  f.content_type.split('/')[0]
		self.object = form.save(commit=False)

		if file_type == 'image':
			self.object.type='image'
			p=Photo(image=f, title=f.name)
			p.save()
			self.object.photo=p
		elif file_type == 'audio':
			self.object.type='audio'
		elif file_type == 'video':
			self.object.type='video'
		else:
			self.object.type='other'
		
		self.object.slug=f.name
		# logger=getlogger()
		# logger.debug(file_type)	
		# logger.debug('-----------------------------------------------------------------------------------------------------------------')
		# logger.debug("type:" + form.fields['type'])	
		# logger.debug('-----------------------------------------------------------------------------------------------------------------')
		# logger.debug(file_type)
		
		self.object.realsave()
		# logger.debug()	

		data = [{'name': f.name, 'url': self.object.url, 'thumbnail_url': self.object.thumb_url, 'delete_url': reverse('upload-delete', args=[f.name]), 'delete_type': "DELETE"}]
		return JSONResponse(data)
Exemplo n.º 7
0
def handle_photo_file(f, title):
    """ """
    photo = Photo()
    photo.title = u'%s %s' % (time_slug_string(), title)
    photo.title_slug = time_slug_string()
    photo.image = f
    photo.save()
    return photo
Exemplo n.º 8
0
def handle_uploaded_file(f,title):
    """ """
    photo = Photo()
    photo.title = u'%s %s' % (time_slug_string(), title) 
    photo.slug = time_slug_string()
    photo.image = f
    photo.save()
    return photo    
Exemplo n.º 9
0
def markdown_uploader(request):
    """
    Markdown image upload to Image db object (using default storage)
    and represent as json for markdown editor.
    """
    if request.method == 'POST' and request.is_ajax():
        if 'markdown-image-upload' in request.FILES:
            image = request.FILES['markdown-image-upload']
            image_types = [
                'image/png', 'image/jpg', 'image/jpeg', 'image/pjpeg',
                'image/gif'
            ]
            if image.content_type not in image_types:
                data = json.dumps(
                    {
                        'status': 405,
                        'error': _('Bad image format.')
                    },
                    cls=LazyEncoder)
                return HttpResponse(data,
                                    content_type='application/json',
                                    status=405)

            if image.size > settings.MAX_IMAGE_UPLOAD_SIZE:
                to_MB = settings.MAX_IMAGE_UPLOAD_SIZE / (1024 * 1024)
                data = json.dumps(
                    {
                        'status': 405,
                        'error': _('Maximum image file is %(size) MB.') % {
                            'size': to_MB
                        }
                    },
                    cls=LazyEncoder)
                return HttpResponse(data,
                                    content_type='application/json',
                                    status=405)

            slug = "{0}-{1}".format(uuid.uuid4().hex[:10], slugify(image.name))
            photo_db = Photo(
                image=image,
                title=slug,
                slug=slug,
            )
            photo_db.save()

            image_url = reverse('utils:photo_SIZE_by_slug',
                                args=[photo_db.slug, 'medium'])

            data = json.dumps({
                'status': 200,
                'link': image_url,
                'name': photo_db.title
            })
            return HttpResponse(data, content_type='application/json')
        return HttpResponse(_('Invalid request!'))
    return HttpResponse(_('Invalid request!'))
Exemplo n.º 10
0
Arquivo: upload.py Projeto: wghub/DCRM
def handle_uploaded_screenshot(content):
    """
    :param content: Image info
    :type content: dict
    :return: Result Dict
    :rtype: dict
    """
    result_dict = {}
    try:
        image_dir = os.path.join(settings.MEDIA_ROOT, 'photologue', 'photos')
        if not os.path.isdir(image_dir):
            mkdir_p(image_dir)
        file_name = os.path.basename(content['path'])
        with transaction.atomic():
            content_id = content['id']
            content_slug = content['slug']
            gallery = Gallery.objects.filter(slug=content_slug).last()
            current_site = Site.objects.get(id=settings.SITE_ID)
            p_version = Version.objects.get(id=content_id)
            c_name = re.sub('[^A-Za-z0-9]', '', p_version.c_name)  # filter
            if gallery:
                pass
            else:
                # create a new gallery
                gallery = Gallery.objects.create(title=c_name,
                                                 slug=content_slug,
                                                 description=p_version.c_depiction if p_version.c_depiction else 'None',
                                                 is_public=1)
                gallery.sites.add(current_site)
            # save
            photo = Photo(title=c_name + '_' + str(uuid.uuid1()),
                          slug=c_name.lower() + '_' + str(uuid.uuid1()),
                          caption='',
                          is_public=1)
            data = open(content['path'], 'rb')
            content_file = ContentFile(data.read())
            photo.image.save(file_name, content_file)
            photo.save()
            photo.sites.add(current_site)
            gallery.photos.add(photo)
            data.close()
            if p_version.gallery is None:
                p_version.gallery = gallery
                p_version.save()
            result_dict.update({
                "success": True,
                "version": p_version.id
            })
    except Exception as e:
        # error handler
        result_dict.update({
            "success": False,
            "exception": str(e)
        })
    return result_dict
Exemplo n.º 11
0
def get_image_from_url(data):
    try:
        image = Photo.objects.get(slug=data['slug'])
    except Photo.DoesNotExist:
        url = data.pop('image', None)
        name, file = get_serialized_image(url)
        del data['sites']
        image = Photo(**data)
        image.image.save(name, file, save=True)
        image.save()
    return image
Exemplo n.º 12
0
def get_image_from_url(data):
    try:
        image = Photo.objects.get(slug=data['slug'])
    except Photo.DoesNotExist:
        url = data.pop('image', None)
        name, file = get_serialized_image(url)
        del data['sites']
        image = Photo(**data)
        image.image.save(name, file, save=True)
        image.save()
    return image
Exemplo n.º 13
0
def handle_uploaded_file(f, author):
    photo = Photo()
    extra = PhotoExtended()
    photo.title = u"%s %s" % (author, time_slug_string())
    photo.slug = u"%s-%s" % (author, slugify(time_slug_string()))
    photo.image = f
    photo.save()
    extra.photo = photo
    extra.author = author
    extra.save()
    return photo
Exemplo n.º 14
0
def uploadimagejson(request):
  p = Photo()
  if request.user.is_authenticated():
    if request.method == 'POST':
      pt = codegenerator()+codegenerator()
      p.image = request.FILES['file']
      p.title = pt
      p.title_slug = slugify(pt) #+codegenerator()
      p.save()
#  template = loader.get_template('redactorimageupload.html')
    params = { 'photo' : p }
#  context = RequestContext(request, params)  
  return render_to_response('redactorimageupload.html',params,context_instance = RequestContext(request))
Exemplo n.º 15
0
def handle_url_file(url, author):
    photo = Photo()
    extra = PhotoExtended()
    photo.title = u"%s %s" % (author, time_slug_string())
    photo.slug = u"%s-%s" % (slugify(author), slugify(time_slug_string()))

    img_name = photo.slug + url[url.rfind(".") :]
    photo.image.save(img_name, ContentFile(urllib2.urlopen(url).read()))
    photo.save()
    extra.photo = photo
    extra.author = author
    extra.save()
    return photo
Exemplo n.º 16
0
def uploadimagejson(request):
    p = Photo()
    if request.user.is_authenticated():
        if request.method == 'POST':
            pt = codegenerator() + codegenerator()
            p.image = request.FILES['file']
            p.title = pt
            p.title_slug = slugify(pt)  #+codegenerator()
            p.save()
#  template = loader.get_template('redactorimageupload.html')
        params = {'photo': p}
#  context = RequestContext(request, params)
    return render_to_response('redactorimageupload.html',
                              params,
                              context_instance=RequestContext(request))
Exemplo n.º 17
0
 def save(self):
   data = self.cleaned_data
   photo = Photo()
   photo.title = data.get('title')
   photo.slug = re.sub(' +', '_', photo.title)
   photo.caption = data.get('caption')
   if (data.get('image') is not None):
     img_file = data.get('image')
     photo.image.save('%s' % (img_file.name), img_file, save=True)
   photo.save()
   galleries = data.get('galleries')
   if galleries is not None:
     for gallery in galleries:
       gallery.photos.add(photo)
       gallery.save()
   return photo
Exemplo n.º 18
0
def loadUrlImage(url='', title='', tags='', format='jpg', slug=''):
    """ """
    if not url:
        url = 'http://irudiak.argazkiak.org/1d3023545b4051907e533648e66329f8_c.jpg'
        title = 'Kakalardoa'
        tags = 'test argazkiak'

    if not slug:
        slug = time_slug()

    if Photo.objects.filter(slug=slug):
        slug = time_slug_long()

    title = title[:99]
    if Photo.objects.filter(title=title):
        title = '%s %s' % (slug, title)[:90]
    
        
    image = _getUrlImage(url)

    if not image:
        return None

    photo = Photo()
    photo.title = title[:100]
    photo.tags = tags
    photo.slug = slug
    
    try:
        image_t = Image.open(ContentFile(image.read()))
        image_t = image_t.convert("RGB")
        f=StringIO()
        image_t.save(f,"JPEG")
        f.seek(0)    
    
        photo.image.save('%s.%s' % (slug,format), ContentFile(f.read()))

    except Exception:
        print('Errorea irudi honekin RGB', photo.slug)
        return photo      

    try:
        photo.save()
    except:
        print('Errorea irudi honekin', photo.slug)

    return photo
Exemplo n.º 19
0
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)
Exemplo n.º 20
0
 def clean_new_image(self):
     """Let's take the uploaded image, create a new photo and bind to 
     the image field in model"""
     rand_int = random.randint(1,99)
     if self.cleaned_data['image']:
         image = self.cleaned_data['image']
         if self.cleaned_data['new_image']:                
             image.image = self.cleaned_data['new_image']
             image.save()
         self.cleaned_data['image'] = image
     else:
         new_photo = Photo(image=self.cleaned_data['new_image'],
                       title= "%s %s %s" %(self.cleaned_data['title'], self.cleaned_data['seller'].user.username, rand_int),
                       title_slug = "%s_%s" %(self.cleaned_data['slug_url'], rand_int))
         new_photo.save()
         self.cleaned_data['image'] = new_photo
     return self.cleaned_data['image']
Exemplo n.º 21
0
 def clean_photo(self):
     cleaned_data = self.cleaned_data
     cleaned_data['id_photo'] = self.data['id_photo']
     photo = cleaned_data.get('photo')
     if isinstance(photo, long):
         try:
             cleaned_data['photo'] = Photo.objects.get(pk=photo)
         except Photo.DoesNotExist:
             raise forms.ValidationError(_('Photo does not exist'))
     elif isinstance(photo, InMemoryUploadedFile):
         new_photo = Photo(title=photo.name, image=photo, is_gallery_thumbnail=True)
         cleaned_data['photo'] = new_photo
         try:
             new_photo.save()
         except IntegrityError:
             new_photo.title = new_photo.get_avaliable_title()
             new_photo.save()
     return cleaned_data['photo']
Exemplo n.º 22
0
def question_add(request):
    form = QuestionForm()

    if request.method == 'POST':
        file_photo = request.FILES['photo']
        form = QuestionForm(request.POST, request.FILES)
        photo = Photo(image=handle_uploaded_file(file_photo),
                      title=file_photo.name,
                      title_slug=slugify(file_photo.name),)
        photo.save()
        form.photo = photo
        if form.is_valid():
            form.user = request.user
            question = form.save()
            return redirect(question)

    return render_to_response(
                'question_add.html',
                {'form': form},
                context_instance=RequestContext(request))
Exemplo n.º 23
0
def upload_data():

    with open(TEST_FILENAME) as f:
        data = json.loads(f.read())

    user = User.objects.all()[0]

    skipped = 0

    for i, point in enumerate(data):
        try:
            photo_file_url = point['photo_file_url']
            photo_title = point['photo_title'][:30]
            photo_location = Point(point['latitude'], point['longitude'])

            photo_filename = '{}.jpg'.format(slugify(photo_title))
            photo_file = URLopener().retrieve(photo_file_url,
                os.path.join('public/media', photo_filename))

            photo = Photo(image=File(open(photo_file[0])))
            unique_slugify(photo, photo_title)
            photo.title = photo.slug
            photo.save()

            poi = POI()
            poi.location = photo_location
            poi.name = photo_title
            poi.description = get_description(
                point['latitude'], point['longitude'], photo_title)
            poi.user = user
            poi.photo = photo
            poi.save()

            print i, photo_title, 'Saved.'
        except Exception:
            print traceback.format_exc()
            skipped += 1

    print skipped, 'POIs were skipped.'
Exemplo n.º 24
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()
Exemplo n.º 25
0
def loadUrlImage(url='', title='', tags='', format='jpg'):
    """ """
    if not url:
        url = 'http://ahotsak.com/files/Proiektuak/beasain.jpg'
        title = 'Beasain'
        tags = 'proiektua beasain'

    slug = slugify(title)[:50]

    image = _getUrlImage(url)

    if not image:
        return 0

    if Photo.objects.filter(title_slug=slug):
        for i in range(1,1000):
            new_slug = '%s-%d' % (slug,i)
            new_title = '%s (%d)' % (title,i)
            if not Photo.objects.filter(title_slug=new_slug):
                slug = new_slug
                title = new_title
                break
        
    photo = Photo()
    photo.title = title
    photo.tags = tags
    photo.title_slug = slug
    photo.image.save('%s.%s' % (slug,format), ContentFile(image.read()))
    try:
        photo.save()
    except:
        print 'Errorea irudi honekin', photo.title
        """
        photo.title_slug = photo.title_slug + '_2'         
        photo.save()
        """
    return photo
Exemplo n.º 26
0
def _create_new_photo(name, slug):
    pl = Photo(title=name, title_slug=slug)
    pl.image.save(os.path.basename(LANDSCAPE_IMAGE_PATH),
                  ContentFile(open(LANDSCAPE_IMAGE_PATH, 'rb').read()))
    pl.save()
    return pl
Exemplo n.º 27
0
def refresh_media():
    """
    Scan media upload folder and add any missing gallery items.
    """

    itemized = map(lambda o: o.file.path, MediaModel.objects.all())

    my_root = os.path.join(settings.MEDIA_ROOT, PHOTOLOGUE_DIR)
    for root, dirs, files in os.walk(my_root, followlinks=True):
        # First filter out cache and poster directories
        try:
            dirs.remove('cache')
            dirs.remove('poster')
        except:
            pass
        # Go througth files
        for fn in files:
            full = os.path.join(root, fn)
            if full in itemized:
                continue
            date_taken = datetime.fromtimestamp(os.path.getmtime(full))
            if not is_aware(date_taken):
                date_taken = make_aware(date_taken, get_current_timezone())

            # Next part is taken from process_zipfile
            filetype = False
            # Is it an image?
            try:
                trial_image = Image.open(full)
                trial_image.load()
                trial_image = Image.open(full)
                trial_image.verify()
                filetype = 'image'
            except Exception, e:
                pass
            # Is it a video?
            if not filetype:
                try:
                    sizes = video_info(full)
                    # Here comes a problem. If it is a jpeg image, it is
                    # detected as mjpeg movie...check if it least at least 1s long
                    if sizes[3] >= 1:
                        filetype = 'video'
                except Exception, e:
                    pass
            if not filetype:
                continue

            namebase, ext = os.path.splitext(fn)
            count = 0
            while 1:
                if count:
                    title = ''.join([namebase, '_'+str(count), ext])
                else:
                    title = fn
                slug = slugify(title)
                try:
                    p = GalleryItemBase.objects.get(title_slug=slug)
                except GalleryItemBase.DoesNotExist:
                    if filetype == 'image':
                        item = Photo(title=title,
                                  title_slug=slug)
                    elif filetype == 'video':
                        item = Video(title=title,
                                  title_slug=slug)
                    else:
                        raise Exception("Unknown file type")

                    # This will just update path in file entry 
                    move_file(item, full, full)
                    item.save()

                    if abs(item.date_taken - item.date_added) < timedelta(seconds=3):
                        item.date_taken = date_taken
                        item.save()
                    print "Added ", item.title, " - ", item.date_taken
                    break
                count = count + 1
Exemplo n.º 28
0
    def save(self, request=None, zip_file=None):
        print(self.cleaned_data['gallery_type'])

        if not zip_file:
            zip_file = self.cleaned_data['zip_file']
            encoded = zip_file._name.encode('utf-8').decode()
            zipname = encoded.split('.')[0]
            zip = zipfile.ZipFile(zip_file)
            count = 1
            current_site = Site.objects.get(id=settings.SITE_ID)
        if self.cleaned_data['gallery']:
            logger.debug('Using pre-existing gallery.')
            gallery = self.cleaned_data['gallery']
        else:
            logger.debug(
                force_text('Creating new gallery "{0}".').format(
                    self.cleaned_data['title']))
            gallery_type_cls = {
                'WEDDING': Wedding,
                'LOVESTORY': Lovestory,
                'FAMILY': Family,
                'PORTRAIT': Portrait,
                'TRAVEL': Travel,
            }
            gallery = gallery_type_cls[
                self.cleaned_data['gallery_type']].objects.create(
                    title=self.cleaned_data['title'],
                    slug=slugify(self.cleaned_data['title']),
                    description=self.cleaned_data['description'],
                    is_public=self.cleaned_data['is_public'])
            gallery.sites.add(current_site)

        for filename in sorted(zip.namelist()):
            logger.debug('Reading file "{0}".'.format(filename))

            if filename.startswith('__') or filename.startswith('.'):
                logger.debug('Ignoring file "{0}".'.format(filename))
                continue

            if os.path.dirname(filename):
                logger.warning('Ignoring file "{0}" as it is in a subfolder;\
                               all images should be in the top '
                               'folder of the zip.'.format(filename))
                if request:
                    messages.warning(request,
                                     _('Ignoring file "{filename}"\
                                       as it is in a subfolder;\
                                       all images should \
                                       be in the top folder of the zip.').
                                     format(filename=filename),
                                     fail_silently=True)
                continue

            data = zip.read(filename)

            if not len(data):
                logger.debug('File "{0}" is empty.'.format(filename))
                continue

            photo_title_root = self.cleaned_data['title'] if self.cleaned_data[
                'title'] else gallery.title

            # A photo might already exist with the same slug. So it's somewhat inefficient,
            # but we loop until we find a slug that's available.
            while True:
                photo_title = ' '.join([photo_title_root, str(count)])
                slug = slugify(photo_title)
                if Photo.objects.filter(slug=slug).exists():
                    count += 1
                    continue
                break

            photo = Photo(title=photo_title,
                          slug=slug,
                          caption=self.cleaned_data['caption'],
                          is_public=self.cleaned_data['is_public'])

            # Basic check that we have a valid image.
            try:
                file = BytesIO(data)
                opened = Image.open(file)
                opened.verify()
            except Exception:
                # Pillow (or PIL) doesn't recognize it as an image.
                # If a "bad" file is found we just skip it.
                # But we do flag this both in the logs and to the user.
                logger.error(
                    'Could not process file "{0}" in the .zip archive.'.format(
                        filename))
                if request:
                    messages.warning(
                        request,
                        _('Could not process file "{0}" in the .zip archive.'
                          ).format(filename),
                        fail_silently=True)
                continue

            contentfile = ContentFile(data)
            photo.image.save("%s/%s" % (zipname, filename), contentfile)
            photo.save()
            photo.sites.add(current_site)
            gallery.photos.add(photo)
            count += 1

        zip.close()

        if request:
            messages.success(
                request,
                _('The photos have been added to gallery "{0}".').format(
                    gallery.title),
                fail_silently=True)
Exemplo n.º 29
0
class PhotoTest(PhotologueBaseTest):
    def tearDown(self):
        """Delete any extra test files (if created)."""
        super(PhotoTest, self).tearDown()
        try:
            self.pl2.delete()
        except:
            pass

    def test_new_photo(self):
        self.assertEqual(Photo.objects.count(), 1)
        self.assertTrue(os.path.isfile(self.pl.image.path))
        self.assertEqual(os.path.getsize(self.pl.image.path),
                         os.path.getsize(LANDSCAPE_IMAGE_PATH))

    #def test_exif(self):
    #    self.assert_(len(self.pl.EXIF.keys()) > 0)

    def test_paths(self):
        self.assertEqual(
            os.path.normpath(str(self.pl.cache_path())).lower(),
            os.path.normpath(
                os.path.join(settings.MEDIA_ROOT, PHOTOLOGUE_DIR, 'photos',
                             'cache')).lower())
        self.assertEqual(self.pl.cache_url(),
                         settings.MEDIA_URL + PHOTOLOGUE_DIR + '/photos/cache')

    def test_count(self):
        for i in range(5):
            self.pl.get_testPhotoSize_url()
        self.assertEqual(self.pl.view_count, 0)
        self.s.increment_count = True
        self.s.save()
        for i in range(5):
            self.pl.get_testPhotoSize_url()
        self.assertEqual(self.pl.view_count, 5)

    def test_precache(self):
        # set the thumbnail photo size to pre-cache
        self.s.pre_cache = True
        self.s.save()
        # make sure it created the file
        self.assertTrue(os.path.isfile(self.pl.get_testPhotoSize_filename()))
        self.s.pre_cache = False
        self.s.save()
        # clear the cache and make sure the file's deleted
        self.pl.clear_cache()
        self.assertFalse(os.path.isfile(self.pl.get_testPhotoSize_filename()))

    def test_accessor_methods(self):
        self.assertEqual(self.pl.get_testPhotoSize_photosize(), self.s)
        self.assertEqual(self.pl.get_testPhotoSize_size(),
                         Image.open(self.pl.get_testPhotoSize_filename()).size)
        self.assertEqual(self.pl.get_testPhotoSize_url(),
                         self.pl.cache_url() + '/' + \
                         self.pl._get_filename_for_size(self.s))
        self.assertEqual(
            self.pl.get_testPhotoSize_filename(),
            os.path.join(self.pl.cache_path(),
                         self.pl._get_filename_for_size(self.s)))

    def test_quoted_url(self):
        """Test for issue #29 - filenames of photos are incorrectly quoted when
        building a URL."""

        # Check that a 'normal' path works ok.
        self.assertEqual(
            self.pl.get_testPhotoSize_url(),
            self.pl.cache_url() + '/test_landscape_testPhotoSize.jpg')

        # Now create a Photo with a name that needs quoting.
        self.pl2 = Photo(title='test', title_slug='test')
        self.pl2.image.save(os.path.basename(QUOTING_IMAGE_PATH),
                            ContentFile(open(QUOTING_IMAGE_PATH, 'rb').read()))
        self.pl2.save()
        self.assertEqual(
            self.pl2.get_testPhotoSize_url(),
            self.pl2.cache_url() + '/test_%26quoting_testPhotoSize.jpg')
Exemplo n.º 30
0
def edit_profil(request, template_name="accounts/edit_profil_form.html"):
    """
    Simple profile form.
    """
    user = request.user
    p = None
    try:
        p = user.get_profile()
    except Profil.DoesNotExist:
        p = Profil(user=user)
        p.save()

    if request.POST:
        is_valid = False
        new_user_form = UserModificationForm(request.POST, instance=user)
        new_profil_form = ProfilForm(request.POST, instance=p)
        new_avatar_form = AvatarForm(request.POST)
        new_password_form = CustomPasswordChangeForm(user=user, data=request.POST)

        is_valid = (
            new_user_form.is_valid()
            and new_profil_form.is_valid()
            and new_avatar_form.is_valid()
            and new_password_form.is_valid()
        )

        if is_valid:
            new_user = new_user_form.save(commit=False)
            new_user.save()

            new_profil = new_profil_form.save(commit=False)
            new_profil.save()

            new_profil.suivre_les_sorties_partype.clear()
            for activite in Activite.objects.filter(pk__in=request.POST.getlist("suivre_les_sorties_partype")):
                new_profil.suivre_les_sorties_partype.add(activite)

            if (
                request.POST.get("old_password")
                and request.POST.get("new_password1")
                and request.POST.get("new_password1")
            ):
                new_password_form.save()

            p.gravatarurl = new_avatar_form.cleaned_data["gravatarurl"]
            title = "Avatar for user %s" % user.username
            if request.FILES.get("avatar"):
                title_slug = "avatar-%s" % user.username
                filename = "avatars/%s" % str(request.FILES.get("avatar"))
                photos = Photo.objects.filter(image=filename)
                photo = None
                if photos.count() > 0:
                    photo = photos[0]
                if not photo:
                    Photo.objects.filter(title_slug=title_slug).delete()
                    photo = Photo(title=title, title_slug=title_slug, is_public=False, tags="avatar")
                    photo.image.save(filename, ContentFile(request.FILES.get("avatar").read()))
                    photo.save()
                p.avatar = photo
            p.save()
            return HttpResponseRedirect(reverse("editprofil"))
        else:
            userform = new_user_form
            profilform = new_profil_form
            avatarform = new_avatar_form
            passwordform = new_password_form
    else:
        userform = UserModificationForm(instance=user)
        profilform = ProfilForm(instance=p)
        avatarform = AvatarForm(initial={"gravatarurl": p.gravatarurl})
        passwordform = CustomPasswordChangeForm(user=user)

    context = RequestContext(
        request,
        {
            "p": p,
            "profilform": profilform,
            "userform": userform,
            "avatarform": avatarform,
            "passwordform": passwordform,
            "full": True,
        },
    )
    return render_to_response(template_name, context)
Exemplo n.º 31
0
class PhotoTest(PhotologueBaseTest):
    def tearDown(self):
        """Delete any extra test files (if created)."""
        super(PhotoTest, self).tearDown()
        try:
            self.pl2.delete()
        except:
            pass

    def test_new_photo(self):
        self.assertEqual(Photo.objects.count(), 1)
        self.assertTrue(os.path.isfile(self.pl.image.path))
        self.assertEqual(os.path.getsize(self.pl.image.path),
                         os.path.getsize(LANDSCAPE_IMAGE_PATH))

    #def test_exif(self):
    #    self.assert_(len(self.pl.EXIF.keys()) > 0)

    def test_paths(self):
        self.assertEqual(os.path.normpath(str(self.pl.cache_path())).lower(),
                         os.path.normpath(os.path.join(settings.MEDIA_ROOT,
                                      PHOTOLOGUE_DIR,
                                      'photos',
                                      'cache')).lower())
        self.assertEqual(self.pl.cache_url(),
                         settings.MEDIA_URL + PHOTOLOGUE_DIR + '/photos/cache')

    def test_count(self):
        for i in range(5):
            self.pl.get_testPhotoSize_url()
        self.assertEqual(self.pl.view_count, 0)
        self.s.increment_count = True
        self.s.save()
        for i in range(5):
            self.pl.get_testPhotoSize_url()
        self.assertEqual(self.pl.view_count, 5)

    def test_precache(self):
        # set the thumbnail photo size to pre-cache
        self.s.pre_cache = True
        self.s.save()
        # make sure it created the file
        self.assertTrue(os.path.isfile(self.pl.get_testPhotoSize_filename()))
        self.s.pre_cache = False
        self.s.save()
        # clear the cache and make sure the file's deleted
        self.pl.clear_cache()
        self.assertFalse(os.path.isfile(self.pl.get_testPhotoSize_filename()))

    def test_accessor_methods(self):
        self.assertEqual(self.pl.get_testPhotoSize_photosize(), self.s)
        self.assertEqual(self.pl.get_testPhotoSize_size(),
                         Image.open(self.pl.get_testPhotoSize_filename()).size)
        self.assertEqual(self.pl.get_testPhotoSize_url(),
                         self.pl.cache_url() + '/' + \
                         self.pl._get_filename_for_size(self.s))
        self.assertEqual(self.pl.get_testPhotoSize_filename(),
                         os.path.join(self.pl.cache_path(),
                         self.pl._get_filename_for_size(self.s)))

    def test_quoted_url(self):
        """Test for issue #29 - filenames of photos are incorrectly quoted when
        building a URL."""

        # Check that a 'normal' path works ok.
        self.assertEqual(self.pl.get_testPhotoSize_url(),
                         self.pl.cache_url() + '/test_landscape_testPhotoSize.jpg')

        # Now create a Photo with a name that needs quoting.
        self.pl2 = Photo(title='test', title_slug='test')
        self.pl2.image.save(os.path.basename(QUOTING_IMAGE_PATH),
                           ContentFile(open(QUOTING_IMAGE_PATH, 'rb').read()))
        self.pl2.save()
        self.assertEqual(self.pl2.get_testPhotoSize_url(),
                         self.pl2.cache_url() + '/test_%26quoting_testPhotoSize.jpg')
Exemplo n.º 32
0
class ImageResizeTest(PhotologueBaseTest):
    def setUp(self):
        super(ImageResizeTest, self).setUp()
        self.pp = Photo(title='portrait',
            title_slug='portrait'
        )
        self.pp.image.save(os.path.basename(PORTRAIT_IMAGE_PATH),
                           ContentFile(open(PORTRAIT_IMAGE_PATH, 'rb').read()))
        self.pp.save()
        self.ps = Photo(title='square',
            title_slug='square',
        )
        self.ps.image.save(os.path.basename(SQUARE_IMAGE_PATH),
                           ContentFile(open(SQUARE_IMAGE_PATH, 'rb').read()))
        self.ps.save()

    def tearDown(self):
        super(ImageResizeTest, self).tearDown()
        self.pp.delete()
        self.ps.delete()

    def test_resize_to_fit(self):
        self.assertEqual(self.pl.get_testPhotoSize_size(), (100, 75))
        self.assertEqual(self.pp.get_testPhotoSize_size(), (75, 100))
        self.assertEqual(self.ps.get_testPhotoSize_size(), (100, 100))

    def test_resize_to_fit_width(self):
        self.s.size = (100, 0)
        self.s.save()
        self.assertEqual(self.pl.get_testPhotoSize_size(), (100, 75))
        self.assertEqual(self.pp.get_testPhotoSize_size(), (100, 133))
        self.assertEqual(self.ps.get_testPhotoSize_size(), (100, 100))

    def test_resize_to_fit_width_enlarge(self):
        self.s.size = (400, 0)
        self.s.upscale = True
        self.s.save()
        self.assertEqual(self.pl.get_testPhotoSize_size(), (400, 300))
        self.assertEqual(self.pp.get_testPhotoSize_size(), (400, 533))
        self.assertEqual(self.ps.get_testPhotoSize_size(), (400, 400))

    def test_resize_to_fit_height(self):
        self.s.size = (0, 100)
        self.s.save()
        self.assertEqual(self.pl.get_testPhotoSize_size(), (133, 100))
        self.assertEqual(self.pp.get_testPhotoSize_size(), (75, 100))
        self.assertEqual(self.ps.get_testPhotoSize_size(), (100, 100))

    def test_resize_to_fit_height_enlarge(self):
        self.s.size = (0, 400)
        self.s.upscale = True
        self.s.save()
        self.assertEqual(self.pl.get_testPhotoSize_size(), (533, 400))
        self.assertEqual(self.pp.get_testPhotoSize_size(), (300, 400))
        self.assertEqual(self.ps.get_testPhotoSize_size(), (400, 400))

    def test_resize_and_crop(self):
        self.s.crop = True
        self.s.save()
        self.assertEqual(self.pl.get_testPhotoSize_size(), self.s.size)
        self.assertEqual(self.pp.get_testPhotoSize_size(), self.s.size)
        self.assertEqual(self.ps.get_testPhotoSize_size(), self.s.size)

    def test_resize_rounding_to_fit(self):
        self.s.size = (113, 113)
        self.s.save()
        self.assertEqual(self.pl.get_testPhotoSize_size(), (113, 85))
        self.assertEqual(self.pp.get_testPhotoSize_size(), (85, 113))
        self.assertEqual(self.ps.get_testPhotoSize_size(), (113, 113))

    def test_resize_rounding_cropped(self):
        self.s.size = (113, 113)
        self.s.crop = True
        self.s.save()
        self.assertEqual(self.pl.get_testPhotoSize_size(), self.s.size)
        self.assertEqual(self.pp.get_testPhotoSize_size(), self.s.size)
        self.assertEqual(self.ps.get_testPhotoSize_size(), self.s.size)

    def test_resize_one_dimension_width(self):
        self.s.size = (100, 150)
        self.s.save()
        self.assertEqual(self.pl.get_testPhotoSize_size(), (100, 75))

    def test_resize_one_dimension_height(self):
        self.s.size = (200, 75)
        self.s.save()
        self.assertEqual(self.pl.get_testPhotoSize_size(), (100, 75))

    def test_resize_no_upscale(self):
        self.s.size = (1000, 1000)
        self.s.save()
        self.assertEqual(self.pl.get_testPhotoSize_size(), (200, 150))

    def test_resize_no_upscale_mixed_height(self):
        self.s.size = (400, 75)
        self.s.save()
        self.assertEqual(self.pl.get_testPhotoSize_size(), (100, 75))

    def test_resize_no_upscale_mixed_width(self):
        self.s.size = (100, 300)
        self.s.save()
        self.assertEqual(self.pl.get_testPhotoSize_size(), (100, 75))

    def test_resize_no_upscale_crop(self):
        self.s.size = (1000, 1000)
        self.s.crop = True
        self.s.save()
        self.assertEqual(self.pl.get_testPhotoSize_size(), (1000, 1000))

    def test_resize_upscale(self):
        self.s.size = (1000, 1000)
        self.s.upscale = True
        self.s.save()
        self.assertEqual(self.pl.get_testPhotoSize_size(), (1000, 750))
        self.assertEqual(self.pp.get_testPhotoSize_size(), (750, 1000))
        self.assertEqual(self.ps.get_testPhotoSize_size(), (1000, 1000))
Exemplo n.º 33
0
            if caption:
                kwargs['caption'] = caption
            if is_public:
                kwargs['is_public'] = is_public

            if filetype == 'image':
                item = Photo(**kwargs)
            elif filetype == 'video':
                item = Video(**kwargs)
            else:
                raise Exception("Unknown file type")
            if type(content) == str:
                item.file.save(name, ContentFile(content), save=False)
            else:
                item.file.save(name, File(content), save=False)
            item.save()
            if tags:
                item.tags.add(*tags)
            # Assume that item is added to photologue at least 3 seconds after created
            if date_taken and abs(item.date_taken - item.date_added) < timedelta(seconds=3):
                item.date_taken = date_taken
                item.save()
            if gallery:
                gallery.items.add(item)
            if update_dar:
                try:
                    set_mpg_dar(item.file.path)
                except:
                    pass
            break
        count = count + 1
Exemplo n.º 34
0
def _create_new_photo(name, slug):
    pl = Photo(title=name, title_slug=slug)
    pl.image.save(os.path.basename(LANDSCAPE_IMAGE_PATH),
                       ContentFile(open(LANDSCAPE_IMAGE_PATH, 'rb').read()))
    pl.save()
    return pl
Exemplo n.º 35
0
    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)