Esempio n. 1
0
    def edit_image(self):
        from forms import UploadImageForm
        from uliweb.utils.generic import EditView
        import os
        import Image

        def pre_save(obj, data):
            if 'image' in data and data['image']:
                data['image'].filename = _get_portrait_image_filename(
                    request.user.id)

        image = _get_portrait_image_filename(request.user.id)
        f = functions.get_filename(image)
        if os.path.exists(f):
            url = functions.get_href(image)
            img = Image.open(f)
            template_data = {'image_url': url, 'size': img.size}
        else:
            url = None
            template_data = {'image_url': url, 'size': (0, 0)}

        view = EditView('user',
                        condition=request.user.id,
                        ok_url=url_for(UserView.edit_image),
                        pre_save=pre_save,
                        fields=['image'],
                        template_data=template_data,
                        file_convert=False)

        return view.run()
Esempio n. 2
0
 def view(self, id):
     from uliweb.utils.generic import DetailView
     from uliweb import orm
     from uliweb.contrib.upload import get_filename, get_url
     import os
     
     User = orm.get_model('user')
     
     def boolean_convert(b, obj):
         if b:
             return '<div class="ui-icon ui-icon-check"></div>'
         else:
             return '<div class="ui-icon ui-icon-closethick"></div>'
     
     user = User.get(int(id))
     if not user:
         error(_('User is not exists!'))
         
     image = functions.get_filename(_get_portrait_image_thumbnail(user.id))
     if os.path.exists(image):
         image_url = functions.get_href(_get_portrait_image_thumbnail(user.id))
     else:
         image_url = user.get_image_url()
     can_modify = user.id == request.user.id
     template_data = {'image_url':image_url, 'can_modify':can_modify}
     view = DetailView('user', obj=user, template_data=template_data, table_class_attr='table table-bordered')
     view.types_convert_map = {orm.BooleanProperty:boolean_convert}
     return view.run()
Esempio n. 3
0
    def _clear_files(self, slug, text):
        import re
        import itertools
        from uliweb.utils.image import fix_filename
        File = get_model('forumattachment')

        r_links = re.compile(
            r'<a.*?href=\"([^"\?]+)(?:\"|\?)|<img.*?src=\"([^"]+)\"|<embed.*?src=\"([^"]+)\"',
            re.DOTALL)
        files = filter(None, itertools.chain(*re.findall(r_links, text)))
        for row in File.filter(File.c.slug == slug):
            _f = functions.get_filename(row.file_name)
            url = functions.get_href(row.file_name)
            if url in files:
                row.enabled = True
                row.save()
            else:
                if os.path.exists(_f):
                    os.unlink(_f)
                thumbnail = fix_filename(_f, '.thumbnail')
                if os.path.exists(thumbnail):
                    os.unlink(thumbnail)

        File.filter(File.c.slug == slug).filter(
            File.c.enabled == False).remove()
Esempio n. 4
0
    def view(self, id):
        from uliweb.utils.generic import DetailView
        from uliweb import orm
        from uliweb.contrib.upload import get_filename, get_url
        import os

        User = orm.get_model('user')

        def boolean_convert(b, obj):
            if b:
                return '<div class="ui-icon ui-icon-check"></div>'
            else:
                return '<div class="ui-icon ui-icon-closethick"></div>'

        user = User.get(int(id))
        if not user:
            error(_('User is not exists!'))

        image = functions.get_filename(_get_portrait_image_thumbnail(user.id))
        if os.path.exists(image):
            image_url = functions.get_href(
                _get_portrait_image_thumbnail(user.id))
        else:
            image_url = user.get_image_url()
        can_modify = user.id == request.user.id
        template_data = {'image_url': image_url, 'can_modify': can_modify}
        view = DetailView('user',
                          obj=user,
                          template_data=template_data,
                          table_class_attr='table table-bordered')
        view.types_convert_map = {orm.BooleanProperty: boolean_convert}
        return view.run()
Esempio n. 5
0
 def uploadimage(self, tid):
     """
     上传图片
     :param tid: 论坛id
     """
     import Image
     from uliweb.utils.image import thumbnail_image, fix_filename
     from uliweb import json_dumps
     from uliweb.form import Form, ImageField
     
     File = get_model('tutorials_albums')
     obj = self.model.get_or_notfound(int(tid))
     
     class UploadForm(Form):
         filename = ImageField()
     
     form = UploadForm()
     flag = form.validate(request.values, request.files)
     if flag:
         filename = functions.save_file(os.path.join('tutorials', str(obj.id), form.filename.data.filename), form.filename.data.file)
         #process thumbnail
         rfilename, thumbnail = thumbnail_image(functions.get_filename(filename, filesystem=True), filename, settings.get_var('TUTORIALS/IMAGE_THUMBNAIL_SIZE'))
         thumbnail_url = functions.get_href(thumbnail)
         url = functions.get_href(filename)
         f = File(filename=filename, tutorial=int(tid))
         f.save()
         return json({'success':True, 'filename':form.filename.data.filename, 'url':url, 'thumbnail_url':thumbnail_url, 'id':f.id}, content_type="text/html;charset=utf-8")
     else:
         #如果校验失败,则再次返回Form,将带有错误信息
         return json({'success':False}, content_type="text/html;charset=utf-8")
Esempio n. 6
0
    def postimage(self, tid):
        """
        处理HTML5文件上传
        :param tid:教程id
        """
        import base64
        from StringIO import StringIO
        from uliweb.utils.image import thumbnail_image, fix_filename

        File = get_model('tutorials_albums')

        if request.method == 'POST':
            _filename = os.path.join('tutorial/%s' % tid,
                                     request.values.get('filename'))
            fobj = StringIO(base64.b64decode(request.params.get('data')))
            filename = functions.save_file(_filename, fobj)
            #process thumbnail
            rfilename, thumbnail = thumbnail_image(
                functions.get_filename(filename, filesystem=True), filename,
                settings.get_var('TUTORIALS/IMAGE_THUMBNAIL_SIZE'))
            thumbnail_url = functions.get_href(thumbnail)
            url = functions.get_href(filename)
            f = File(filename=filename, tutorial=int(tid))
            f.save()
            return json({
                'success': True,
                'data': {
                    'filename': request.values.get('filename'),
                    'url': url,
                    'thumbnail_url': thumbnail_url,
                    'id': f.id
                }
            })
Esempio n. 7
0
    def _clear_files(self, slug, text):
        import re
        import itertools
        from uliweb.utils.image import fix_filename

        File = get_model("forumattachment")

        r_links = re.compile(
            r'<a.*?href=\"([^"\?]+)(?:\"|\?)|<img.*?src=\"([^"]+)\"|<embed.*?src=\"([^"]+)\"', re.DOTALL
        )
        files = filter(None, itertools.chain(*re.findall(r_links, text)))
        for row in File.filter(File.c.slug == slug):
            _f = functions.get_filename(row.file_name)
            url = functions.get_href(row.file_name)
            if url in files:
                row.enabled = True
                row.save()
            else:
                if os.path.exists(_f):
                    os.unlink(_f)
                thumbnail = fix_filename(_f, ".thumbnail")
                if os.path.exists(thumbnail):
                    os.unlink(thumbnail)

        File.filter(File.c.slug == slug).filter(File.c.enabled == False).remove()
Esempio n. 8
0
    def _upload_file(self, image=False, show_filename=True):
        import os
        import Image
        if image:
            from forms import ImageUploadForm as Form
        else:
            from forms import FileUploadForm as Form
        from uliweb.utils.image import thumbnail_image, fix_filename
        from uliweb import json_dumps

        File = get_model('forumattachment')

        forum_id = request.GET.get('forum_id')
        slug = request.GET.get('slug')
        form = Form()
        suffix = date.now().strftime('_%Y_%m_%d')
        if request.method == 'GET':
            form.bind({'is_thumbnail': True})
            return {'form': form}
        else:
            flag = form.validate(request.values, request.files)
            if flag:
                f = form.data['filedata']
                _f = os.path.basename(f['filename'])
                #文件格式为forum/<forum_id>/<filename_yyyy_mm_dd>
                filename = fix_filename('forum/%s/%s' % (forum_id, _f), suffix)
                if image:
                    filename = functions.save_file(filename, f['file'])
                    if form.data['is_thumbnail']:
                        #process thumbnail
                        rfilename, thumbnail = thumbnail_image(
                            functions.get_filename(filename, filesystem=True),
                            filename,
                            settings.get_var('PARA/FORUM_THUMBNAIL_SIZE'))
                        _file = functions.get_href(thumbnail)
                    else:
                        _file = functions.get_href(filename)
                    name = functions.get_href(filename)
                else:
                    filename = functions.save_file(filename, f['file'])
                    name = form.data['title']
                    if not name:
                        name = _f
                    _file = functions.get_href(filename, alt=name)
                ff = File(slug=slug, file_name=filename, name=name)
                ff.save()
                name = json_dumps(name, unicode=True)
                if show_filename:
                    fargs = '||%s' % name[1:-1]
                else:
                    fargs = ''
                return '''<script type="text/javascript">
var url='%s%s';
setTimeout(function(){callback(url);},100);
</script>
''' % (_file, fargs)
            else:
                return {'form': form}
Esempio n. 9
0
    def _upload_file(self, image=False, show_filename=True):
        import os
        import Image
        if image:
            from forms import ImageUploadForm as Form
        else:
            from forms import FileUploadForm as Form
        from uliweb.utils.image import thumbnail_image, fix_filename
        from uliweb import json_dumps
        
        File = get_model('forumattachment')
        
        forum_id = request.GET.get('forum_id')
        slug = request.GET.get('slug')
        form = Form()
        suffix = date.now().strftime('_%Y_%m_%d')
        if request.method == 'GET':
            form.bind({'is_thumbnail':True})
            return {'form':form}
        else:
            flag = form.validate(request.values, request.files)
            if flag:
                f = form.data['filedata']
                _f = os.path.basename(f['filename'])
                #文件格式为<forum_id>/<filename_yyyy_mm_dd>
                filename = fix_filename('%s/%s' % (forum_id, _f), suffix)
                if image:
                    filename = functions.save_file(filename, f['file'])
                    if form.data['is_thumbnail']:
                        #process thumbnail
                        rfilename, thumbnail = thumbnail_image(functions.get_filename(filename, filesystem=True), filename, settings.get_var('PARA/FORUM_THUMBNAIL_SIZE'))
                        _file = functions.get_href(thumbnail)
                    else:
                        _file = functions.get_href(filename)
                    name = functions.get_href(filename)
                else:
                    filename = functions.save_file(filename, f['file'])
                    name = form.data['title']
                    if not name:
                        name = _f
                    _file = functions.get_href(filename, alt=name)
                ff = File(slug=slug, file_name=filename, name=name)
                ff.save()
                name = json_dumps(name, unicode=True)
                if show_filename:
                    fargs = '||%s' % name[1:-1]
                else:
                    fargs = ''
                return '''<script type="text/javascript">
var url='%s%s';
setTimeout(function(){callback(url);},100);
</script>
''' % (_file, fargs)
            else:
                return {'form':form}
Esempio n. 10
0
def get_user_image(user, size=50):
    from uliweb.contrib.staticfiles import url_for_static
    from uliweb import functions
    import os
    
    if user:
        image = functions.get_filename(_get_portrait_image_thumbnail(user.id, size))
        if os.path.exists(image):
            image_url = functions.get_href(_get_portrait_image_thumbnail(user.id, size))
            return image_url

    return functions.url_for_static('images/user%dx%d.jpg' % (size, size))
Esempio n. 11
0
def uploadfile():
    from uliweb.form import Form, FileField
    from uliweb.utils.image import test_image, thumbnail_image
    
    fileserving = AttachmentsFileServing()
    
    Attachment = functions.get_model('generic_attachment')
    
    class UploadForm(Form):
        fileupload = FileField()
        
        def form_validate(self, data):
            error = {}
            return error
    
    form = UploadForm()
    table = request.GET.get('table')
    id = request.GET.get('id')
    slug = request.GET.get('slug')
    if form.validate(request.values, request.files):
        dir = settings.Generic_Attachment_Save_Dirs.get(table)
        if not dir:
            raise Exception("Saving directory of table %s is not defined in Generic_Attachment_Save_Dirs" % table)
        
        if id:
            path = os.path.join(dir, id)
        else:
            path = dir
        filename = fileserving.save_file(os.path.join(path, form.fileupload.data.filename), form.fileupload.data.file)
        is_image = test_image(filename)
        if is_image and settings.get_var('Generic_Attachment_FileServing/THUMBNAIL_PROCESS'):
            thumbnail_path, thumbnail = thumbnail_image(functions.get_filename(filename, filesystem=True), filename, settings.get_var('Generic_Attachment_FileServing/IMAGE_THUMBNAIL_SIZE'))
            thumbnail_url = functions.get_href(thumbnail)
        else:
            thumbnail = ''
            thumbnail_url = ''
        f = Attachment(filepath=filename, filename=form.fileupload.data.filename, 
            submitter=request.user.id, is_image=is_image, thumbnail_path=thumbnail)
        if slug:
            f.slug = slug
        else:
            f.content_object = (table, id)
        f.save()
        url = fileserving.get_url(filename, title=f.filename, query_para={'alt':f.filename}, _class='filedown')
        href = fileserving.get_href(filename, alt=f.filename)
        return json({'success':True, 'filename':f.filename, 
            'url':url, 'href':href, 'id':f.id, 'submitter':unicode(request.user),
            'is_image':is_image, 'thumbnail_url':thumbnail_url,
            'created_date':str(f.created_date)}, content_type="text/html;charset=utf-8")
    else:
        #如果校验失败,则再次返回Form,将带有错误信息
        return json({'success':False}, content_type="text/html;charset=utf-8")
Esempio n. 12
0
def get_user_image(user, size=50):
    from uliweb.contrib.staticfiles import url_for_static
    from uliweb import functions
    import os

    if user:
        image = functions.get_filename(
            _get_portrait_image_thumbnail(user.id, size))
        if os.path.exists(image):
            image_url = functions.get_href(
                _get_portrait_image_thumbnail(user.id, size))
            return image_url

    return functions.url_for_static('images/user%dx%d.jpg' % (size, size))
Esempio n. 13
0
def postimage():
    """
    处理HTML5文件上传
    """
    import base64
    from StringIO import StringIO
    from uliweb.utils.image import thumbnail_image, fix_filename
    from uliweb.form import Form, FileField
    
    fileserving = AttachmentsFileServing()
    
    Attachment = functions.get_model('generic_attachment')
    table = request.values.get('table')
    id = request.values.get('id')
    slug = request.values.get('slug')
    if request.method == 'POST':
        
        dir = settings.Generic_Attachment_Save_Dirs.get(table)
        if not dir:
            raise Exception("Saving directory of table %s is not defined in Generic_Attachment_Save_Dirs" % table)
        
        if id:
            path = os.path.join(dir, id, request.values.get('filename'))
        else:
            path = os.path.join(dir, request.values.get('filename'))
            
        fobj = StringIO(base64.b64decode(request.params.get('data')))
        filename = functions.save_file(path, fobj)
        if settings.get_var('Generic_Attachment_FileServing/THUMBNAIL_PROCESS'):
            thumbnail_path, thumbnail = thumbnail_image(functions.get_filename(filename, filesystem=True), filename, settings.get_var('Generic_Attachment_FileServing/IMAGE_THUMBNAIL_SIZE'))
            thumbnail_url = functions.get_href(thumbnail)
        else:
            thumbnail = ''
            thumbnail_url = ''
        fname = os.path.splitext(os.path.basename(filename))[0].split(',')[-1][:8]
        f = Attachment(filepath=filename, filename=fname, is_image=True,
            submitter=request.user.id, thumbnail_path=thumbnail)
        if slug:
            f.slug = slug
        else:
            f.content_object = (table, id)
        f.save()
        url = fileserving.get_url(filename, title=f.filename, alt=f.filename, _class='filedown')
        href = fileserving.get_href(filename, title=f.filename, query_para={'alt':f.filename})
        return json({'success':True, 'filename':f.filename, 'submitter':unicode(request.user),
            'url':url, 'href':href, 'is_image':f.is_image,
            'id':f.id, 'created_date':str(f.created_date), 'thumbnail_url':thumbnail_url,
            })
Esempio n. 14
0
    def uploadimage(self, tid):
        """
        上传图片
        :param tid: 论坛id
        """
        import Image
        from uliweb.utils.image import thumbnail_image, fix_filename
        from uliweb import json_dumps
        from uliweb.form import Form, ImageField

        File = get_model('tutorials_albums')
        obj = self.model.get_or_notfound(int(tid))

        class UploadForm(Form):
            filename = ImageField()

        form = UploadForm()
        flag = form.validate(request.values, request.files)
        if flag:
            filename = functions.save_file(
                os.path.join('tutorials', str(obj.id),
                             form.filename.data.filename),
                form.filename.data.file)
            #process thumbnail
            rfilename, thumbnail = thumbnail_image(
                functions.get_filename(filename, filesystem=True), filename,
                settings.get_var('TUTORIALS/IMAGE_THUMBNAIL_SIZE'))
            thumbnail_url = functions.get_href(thumbnail)
            url = functions.get_href(filename)
            f = File(filename=filename, tutorial=int(tid))
            f.save()
            return json(
                {
                    'success': True,
                    'filename': form.filename.data.filename,
                    'url': url,
                    'thumbnail_url': thumbnail_url,
                    'id': f.id
                },
                content_type="text/html;charset=utf-8")
        else:
            #如果校验失败,则再次返回Form,将带有错误信息
            return json({'success': False},
                        content_type="text/html;charset=utf-8")
Esempio n. 15
0
 def postimage(self, tid):
     """
     处理HTML5文件上传
     :param tid:教程id
     """
     import base64
     from StringIO import StringIO
     from uliweb.utils.image import thumbnail_image, fix_filename
 
     File = get_model('tutorials_albums')
     
     if request.method == 'POST':
         _filename = os.path.join('tutorial/%s' % tid, request.values.get('filename'))
         fobj = StringIO(base64.b64decode(request.params.get('data')))
         filename = functions.save_file(_filename, fobj)
         #process thumbnail
         rfilename, thumbnail = thumbnail_image(functions.get_filename(filename, filesystem=True), filename, settings.get_var('TUTORIALS/IMAGE_THUMBNAIL_SIZE'))
         thumbnail_url = functions.get_href(thumbnail)
         url = functions.get_href(filename)
         f = File(filename=filename, tutorial=int(tid))
         f.save()
         return json({'success':True, 'data':{'filename':request.values.get('filename'), 'url':url, 'thumbnail_url':thumbnail_url, 'id':f.id}})
Esempio n. 16
0
    def view(self):
        user_id = request.values.get("id", 0).strip()
        User = functions.get_model("user")
        if user_id:
            user = User.get(int(user_id))
            ldapuser = functions.ldap_get_user(username=user.username)
            image = functions.get_filename(
                _get_portrait_image_thumbnail(user.id))
            if os.path.exists(image):
                image_url = functions.get_href(
                    _get_portrait_image_thumbnail(user.id))
            else:
                image_url = user.get_image_url()
            can_modify = user.id == request.user.id
        else:
            error(_('error: para userid does not exist!'))

        return {
            "can_modify": can_modify,
            "image_url": image_url,
            "user": user.to_dict(),
            "ldapuser": ldapuser
        }
Esempio n. 17
0
    def edit_image(self):
        from .forms import UploadImageForm
        import os
        from PIL import Image

        file_image = request.files.get('image')
        if file_image:
            filename = _get_portrait_image_filename(request.user.id)
            functions.save_file(filename,
                                file_image,
                                replace=True,
                                convert=False)

        image = _get_portrait_image_filename(request.user.id)
        f = functions.get_filename(image)
        if os.path.exists(f):
            url = functions.get_href(image)
            img = Image.open(f)
            template_data = {'image_url': url, 'size': img.size}
        else:
            url = None
            template_data = {'image_url': url, 'size': (0, 0)}

        return template_data
Esempio n. 18
0
 def edit_image(self):
     from forms import UploadImageForm
     from uliweb.utils.generic import EditView
     import os
     from PIL import Image
     
     def pre_save(obj, data):
         if 'image' in data and data['image']:
             data['image'].filename = _get_portrait_image_filename(request.user.id)
             
     image = _get_portrait_image_filename(request.user.id)
     f = functions.get_filename(image)
     if os.path.exists(f):
         url = functions.get_href(image)
         img = Image.open(f)
         template_data = {'image_url':url, 'size':img.size}
     else:
         url = None
         template_data = {'image_url':url, 'size':(0, 0)}
         
     view = EditView('user', condition=request.user.id, ok_url=url_for(UserView.edit_image),
         pre_save=pre_save, fields=['image'], template_data=template_data, file_convert=False)
     
     return view.run()
Esempio n. 19
0
    def _upload_file(self, image=False, show_filename=True):
        import os
        import Image

        if image:
            from forms import ImageUploadForm as Form
        else:
            from forms import FileUploadForm as Form
        from uliweb.utils.image import thumbnail_image, fix_filename
        from uliweb import json_dumps

        File = get_model("forumattachment")

        forum_id = request.GET.get("forum_id")
        slug = request.GET.get("slug")
        form = Form()
        suffix = date.now().strftime("_%Y_%m_%d")
        if request.method == "GET":
            form.bind({"is_thumbnail": True})
            return {"form": form}
        else:
            flag = form.validate(request.values, request.files)
            if flag:
                f = form.data["filedata"]
                _f = os.path.basename(f["filename"])
                # 文件格式为forum/<forum_id>/<filename_yyyy_mm_dd>
                filename = fix_filename("forum/%s/%s" % (forum_id, _f), suffix)
                if image:
                    filename = functions.save_file(filename, f["file"])
                    if form.data["is_thumbnail"]:
                        # process thumbnail
                        rfilename, thumbnail = thumbnail_image(
                            functions.get_filename(filename, filesystem=True),
                            filename,
                            settings.get_var("PARA/FORUM_THUMBNAIL_SIZE"),
                        )
                        _file = functions.get_href(thumbnail)
                    else:
                        _file = functions.get_href(filename)
                    name = functions.get_href(filename)
                else:
                    filename = functions.save_file(filename, f["file"])
                    name = form.data["title"]
                    if not name:
                        name = _f
                    _file = functions.get_href(filename, alt=name)
                ff = File(slug=slug, file_name=filename, name=name)
                ff.save()
                name = json_dumps(name, unicode=True)
                if show_filename:
                    fargs = "||%s" % name[1:-1]
                else:
                    fargs = ""
                return """<script type="text/javascript">
var url='%s%s';
setTimeout(function(){callback(url);},100);
</script>
""" % (
                    _file,
                    fargs,
                )
            else:
                return {"form": form}