Пример #1
0
def revision_add_attachment(request, pk):
    """Add attachment, download if necessary
    """
    revision = get_object_or_404(PackageRevision, pk=pk)
    if request.user.pk != revision.author.pk:
        log_msg = ("[security] Attempt to add attachment to package (%s) by "
                   "non-owner (%s)" % (revision.package, request.user))
        log.warning(log_msg)
        return HttpResponseForbidden(
            'You are not the author of this %s' % escape(
                revision.package.get_type_name()))
    url = request.POST.get('url', None)
    filename = request.POST.get('filename', None)
    log.debug(filename)
    if not filename or filename == "":
        log.error('Trying to create an attachment without name')
        return HttpResponseForbidden('Path not found.')
    content = ''
    if url:
        # validate url
        field = URLField(verify_exists=True)
        try:
            url = field.clean(url)
        except ValidationError, err:
            log.debug('Invalid url provided (%s)\n%s' % (url,
                '\n'.join(err.messages)))
            return HttpResponseForbidden(("Loading attachment failed<br/>"
                "%s") % '<br/>'.join(err.messages))
        except Exception, err:
            return HttpResponseForbidden(str(err))
Пример #2
0
def revision_add_attachment(request, pk):
    """Add attachment, download if necessary
    """
    revision = get_object_or_404(PackageRevision, pk=pk)
    if request.user.pk != revision.author.pk:
        log_msg = ("[security] Attempt to add attachment to package (%s) by "
                   "non-owner (%s)" % (revision.package, request.user))
        log.warning(log_msg)
        return HttpResponseForbidden('You are not the author of this %s' %
                                     escape(revision.package.get_type_name()))
    url = request.POST.get('url', None)
    filename = request.POST.get('filename', None)
    if not filename or filename == "":
        log.error('Trying to create an attachment without name')
        return HttpResponseBadRequest('Path not found.')
    content = ''
    if url:
        log.info(('[%s] Preparing to download %s as an attachment of '
                  'PackageRevision %d') % (filename, url, revision.pk))
        # validate url
        field = URLField(verify_exists=True)
        encoding = request.POST.get('force_contenttype', False)
        try:
            url = field.clean(url)
        except ValidationError, err:
            log.warning('[%s] Invalid url provided\n%s' %
                        (url, '\n'.join(err.messages)))
            raise Http404()
        except Exception, err:
            log.warning('[%s] Exception raised\n%s' % (url, str(err)))
            raise Http404()
Пример #3
0
def revision_add_attachment(request, pk):
    """Add attachment, download if necessary
    """
    revision = get_object_or_404(PackageRevision, pk=pk)
    if request.user.pk != revision.author.pk:
        log_msg = ("[security] Attempt to add attachment to package (%s) by "
                   "non-owner (%s)" % (revision.package, request.user))
        log.warning(log_msg)
        return HttpResponseForbidden(
            'You are not the author of this %s' % escape(
                revision.package.get_type_name()))
    url = request.POST.get('url', None)
    filename = request.POST.get('filename', None)
    if not filename or filename == "":
        log.error('Trying to create an attachment without name')
        return HttpResponseBadRequest('Path not found.')
    content = ''
    if url:
        log.info(('[%s] Preparing to download %s as an attachment of '
            'PackageRevision %d') % (filename, url, revision.pk))
        # validate url
        field = URLField(verify_exists=True)
        encoding = request.POST.get('force_contenttype', False)
        try:
            url = field.clean(url)
        except ValidationError, err:
            log.warning('[%s] Invalid url provided\n%s' % (url,
                '\n'.join(err.messages)))
            return HttpResponseBadRequest(("Loading attachment failed\n"
                "%s") % parse_validation_messages(err))
        except Exception, err:
            log.warning('[%s] Exception raised\n%s' % (url, str(err)))
            return HttpResponseBadRequest(str(err))
Пример #4
0
class CompanyForm(ModelForm):
    site = URLField(max_length=100)

    class Meta:
        model = Company
        fields = (
            "name",
            "short_description",
            "long_description",
            "image",
            "site",
            "email_address",
            "phone_number",
        )

        exclude = ["old_image"]

        # Widget generator accepts a form widget, and a list of tuples between field name and an attribute dict
        widgets = widget_generator(
            SingleImageInput,
            [("image", {
                "id": "responsive-image-id",
                "preset": ImageFormat.COMPANY
            })],
        )
Пример #5
0
 def clean(self, value):
     # first sort out whether it's a doi
     parsed = value.split(":")
     if parsed[0] in ["DOI", "doi"]:
         # value='http://dx.doi.org/'+parsed[1]
         # we can't use URLfield because doi.org doens't return a 404 .
         return value
     else:
         return URLField.clean(self, value)
Пример #6
0
class CompanyForm(ModelForm):
    site = URLField(max_length=100)

    class Meta(object):
        model = Company
        fields = ('name', 'short_description', 'long_description', 'image', 'site', 'email_address', 'phone_number',)

        exclude = ['old_image']

        # Widget generator accepts a form widget, and a list of tuples between field name and an attribute dict
        widgets = widget_generator(SingleImageInput, [('image', {'id': 'responsive-image-id'})])
Пример #7
0
class PollAnswerForm(forms.Form):
    tag = CharField(max_length=30,
                    widget=TextInput(attrs={
                        "autocomplete": "off",
                    }),
                    required=False)
    description = CharField(
        max_length=400,
        widget=Textarea(attrs={"onkeyup": "return countChars();"}),
        required=False)
    link = URLField(max_length=250, required=False)
Пример #8
0
class SettingsAvatarForm(forms.Form):
    avatar_url = URLField(required=True)

    def clean(self):
        cleaned_data = super(SettingsAvatarForm, self).clean()
        avatar_url = str(cleaned_data.get('avatar_url', ""))
        if len(avatar_url) < 5 or avatar_url[-4:] != '.gif':
            self._errors['avatar_url'] = self.error_class(
                ["Avatar must be a valid image URL"])
            del cleaned_data['avatar_url']
        return cleaned_data

    def getAvatarURL(self):
        return self.cleaned_data['avatar_url']

    def clean_AvatarURL(self):
        return self.cleaned_data.get('avatar_url', "")
Пример #9
0
class UpdateProfileForm(ModelForm):
    input_field_class = 'bg-gray-700 bg-opacity-0 ml-2 pb-1 outline-none text-white placeholder-gray-600'

    profile_image = ImageField(label='',
                               widget=FileInput(attrs={
                                   'class': 'hidden',
                                   'accept': '.jpg,.png'
                               }))

    background_image = ImageField(widget=FileInput(attrs={
        'class': 'hidden',
        'accept': '.jpg,.png'
    }))

    bio = CharField(required=False,
                    widget=Textarea(
                        attrs={
                            'class': input_field_class + ' resize-none',
                            'placeholder': 'Add your bio',
                            'rows': 3
                        }))

    location = CharField(
        required=False,
        widget=TextInput(attrs={
            'class': input_field_class,
            'placeholder': 'Add your location'
        }))

    website = URLField(
        required=False,
        max_length=100,
        widget=URLInput(attrs={
            'class': input_field_class,
            'placeholder': 'Add your website'
        }))

    class Meta:
        model = Profile
        fields = [
            'profile_image', 'background_image', 'bio', 'location', 'website'
        ]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
Пример #10
0
 def __init__(self, to=None, *args, **kwargs):
     """
     Accepts EITHER a file or an URL.
     The `to` parameter accepts 3 values:
         None: default to_python, returns either url or file
         'file': if an url is submited, download it into an inmemory object
         'url': uploads the file to default storage and returns the URL
     The`upload_to` param must be set when to='url'
     if using AWS, set no_aws_qs to disable querystring auth
     """
     self.to = to
     self.no_aws_qs = kwargs.pop('no_aws_qs', False)
     if 'upload_to' in kwargs:
         self.upload_to = kwargs.pop('upload_to')
     elif self.to == 'url':
         raise RuntimeError('If normalizing to an URL `upload_to` '
                            'must be set')
     fields = (FileField(), URLField())
     super(FileOrURLField, self).__init__(fields, *args, **kwargs)
Пример #11
0
class UploadImage(Form):
    """Form for uploading image."""

    url_upload = URLField(required=False)
    file_upload = ImageField(required=False)

    def clean(self):
        if bool(self.data.get('url_upload')) == bool(
                self.files.get('file_upload')):
            raise ValidationError("Выберите что-то одно.")

        cleaned_data = super().clean()

        if url_upload := cleaned_data.get('url_upload'):
            try:
                response = request.urlopen(url_upload)

                content_type = response.getheader('Content-Type')
                if not content_type or not content_type.startswith('image'):
                    raise ValidationError("Ссылка не похожа на изображение.")

                content_length = int(response.getheader('Content-Length', 0))
                if content_length > settings.FILE_UPLOAD_MAX_SIZE:
                    raise ValidationError("Слишком большой файл.")

                image_bytes = BytesIO()
                while chunk := response.read(1024 * 1024):
                    image_bytes.write(chunk)
                    if image_bytes.tell() > settings.FILE_UPLOAD_MAX_SIZE:
                        raise ValidationError("Слишком большой файл.")

            except (HTTPError, URLError) as e:
                raise ValidationError("Ошибка скачивания файла.") from e

            image_name = parse.urlparse(response.url).path.split('/')[-1]
            if '.' not in image_name:
                image_name += '.' + content_type.removeprefix('image/')
            self.files['url_upload'] = ImageFile(image_bytes, name=image_name)

        return cleaned_data
Пример #12
0
class MobileSyncForm(CremeForm):
    url_examples = ChoiceField(
        label=_(u"Server URL examples"),
        required=False,
        help_text=_(u"Some common configurations"),
        choices=chain((("", ""), ), COMMONS_SERVER_URL_CFG),
        widget=Select(
            attrs={'onchange': 'this.form.url.value=$(this).val();'}))
    url = URLField(label=_(u"Server URL"), required=False)
    domain = CharField(label=_(u"Domain"), required=False)
    ssl = BooleanField(label=_(u"Is secure"), required=False)

    def __init__(self, *args, **kwargs):
        # get_sv = SettingValue.objects.get
        # self.server_url    = url    = get_sv(key_id=MAPI_SERVER_URL)
        # self.server_domain = domain = get_sv(key_id=MAPI_DOMAIN)
        # self.server_ssl    = ssl    = get_sv(key_id=MAPI_SERVER_SSL)
        svalues = get_default_server_setting_values()
        self.server_url = url = svalues['url']
        self.server_domain = domain = svalues['domain']
        self.server_ssl = ssl = svalues['ssl']

        initial = kwargs['initial'] or {}
        initial.update(url=url.value, domain=domain.value, ssl=ssl.value)
        kwargs['initial'] = initial

        super(MobileSyncForm, self).__init__(*args, **kwargs)

    def save(self):
        clean_get = self.cleaned_data.get

        def upgrade_svalue(svalue, value):
            if svalue.value != value:
                svalue.value = value
                svalue.save()

        upgrade_svalue(self.server_url, clean_get('url'))
        upgrade_svalue(self.server_domain, clean_get('domain'))
        upgrade_svalue(self.server_ssl, clean_get('ssl'))
Пример #13
0
    def clean_resource(self):
        indexes_to_remove = []

        print self.resources_title

        # if the whole field was not binded, just remove it from the data to validate
        for i in range(len(self.resources_url)):
            if self.resources_url[i].strip() == u'':
                if self.resources_title[i].strip() != u'':
                    raise ValidationError(
                        _('If the title is defined, the url must be defined as well'
                          ))
                else:
                    indexes_to_remove.append(i)

        for i in indexes_to_remove:
            del self.resources_title[i]
            del self.resources_url[i]

        # now, let's validate the urls
        final_urls = []
        for url in self.resources_url:
            #url = URLField(required=True,verify_exists=True).clean(url)
            final_urls.append(URLField().clean(url))

        # if a title was not provided, but its url was, populate it whit the same value as the url
        final_titles = []
        idx = 0
        for title in self.resources_title:
            final_titles.append(final_urls[idx] if title.strip() ==
                                u'' else title)
            idx = idx + 1

        self.resources = [(final_titles[i], final_urls[i])
                          for i in range(len(final_titles))]
        print self.resources

        return ''
Пример #14
0
class YoutubeFormMixin(EntangledModelFormMixin):
    ASPECT_RATIO_CHOICES = [
        ('embed-responsive-21by9', _("Responsive 21:9")),
        ('embed-responsive-16by9', _("Responsive 16:9")),
        ('embed-responsive-4by3', _("Responsive 4:3")),
        ('embed-responsive-1by1', _("Responsive 1:1")),
    ]

    videoid = EntangledField()

    url = URLField(
        label=_("YouTube URL"),
        widget=widgets.URLInput(attrs={'size': 50}),
    )

    aspect_ratio = ChoiceField(
        label=_("Aspect Ratio"),
        choices=ASPECT_RATIO_CHOICES,
        widget=widgets.RadioSelect,
        initial=ASPECT_RATIO_CHOICES[1][0],
    )

    allow_fullscreen = BooleanField(
        label=_("Allow Fullscreen"),
        required=False,
        initial=True,
    )

    autoplay = BooleanField(
        label=_("Autoplay"),
        required=False,
    )

    controls = BooleanField(
        label=_("Display Controls"),
        required=False,
    )

    loop = BooleanField(
        label=_("Enable Looping"),
        required=False,
    )

    rel = BooleanField(
        label=_("Show related"),
        required=False,
    )

    class Meta:
        untangled_fields = ['url']
        entangled_fields = {
            'glossary': [
                'videoid', 'aspect_ratio', 'allow_fullscreen', 'autoplay',
                'controls', 'loop', 'rel'
            ]
        }

    def __init__(self, *args, **kwargs):
        instance = kwargs.get('instance')
        if instance:
            videoid = instance.glossary.get('videoid')
            if videoid:
                parts = ParseResult('https', 'youtu.be', videoid, '', '', '')
                initial = {'url': urlunparse(parts)}
                kwargs.update(initial=initial)
        super().__init__(*args, **kwargs)

    def clean(self):
        cleaned_data = super().clean()
        url = cleaned_data.get('url')
        if url:
            parts = urlparse(url)
            match = re.search(r'^v=([^&]+)', parts.query)
            if match:
                cleaned_data['videoid'] = match.group(1)
                return cleaned_data
            match = re.search(r'([^/]+)$', parts.path)
            if match:
                cleaned_data['videoid'] = match.group(1)
                return cleaned_data
        raise ValidationError(_("Please enter a valid YouTube URL"))
Пример #15
0
 def quote_url(self):
     url = URLField()
     try:
         return url.clean(self.quote)
     except:
         return None
Пример #16
0
 def __init__(self, *args, **kwargs):
     fields = (
         FileField(),
         URLField(),
     )
     super(FileOrUrlField, self).__init__(fields, *args, **kwargs)
Пример #17
0
    def __init__(self, action, *args, **kwargs):

        # build the forms from the action attributes
        try:
            self.action_item = Action.objects.get(name=action)
        except ObjectDoesNotExist:
            self.action_item = Action(name=action, )

        attributes = self.action_item.attributes.all()

        from django.forms.models import fields_for_model
        model_fields = fields_for_model(Translation)

        model_fields = {}

        #for field in model_fields_list:
        #    print(field)
        #    model_fields[ field ] = model_fields_list[field]

        #for attr in attributes:
        #    if attr.datatype in model_fields:
        #        self.Meta.fields.append(attr.datatype)

        #if self.action_item.target_type:
        #    if not 'target' in self.Meta.fields:
        #        self.Meta.fields.append('target')

        super(BaseActionForm, self).__init__(*args, **kwargs)

        # build fields from attributes
        attributes = self.action_item.attributes.all()

        for attr in attributes:

            if attr.datatype == 'target':
                qs = Item.objects.filter(id__in=list(
                    get_targets(self.instance, self.action_item.target_type)))
                att_field = TargetModelChoiceField(queryset=qs, )

            elif attr.datatype == 'query':
                qs = Item.objects.filter(id__in=list(
                    get_targets(self.instance, self.action_item.target_type)))
                att_field = TargetQueryField(queryset=qs, initial=None)

            elif attr.datatype == 'string':
                att_field = CharField(max_length=1024)

            elif attr.datatype == 'markdown':
                att_field = CharField(max_length=25600, widget=Textarea)

            elif attr.datatype == 'description':
                att_field = CharField(max_length=25600000, widget=Textarea)

            elif attr.datatype == 'boolean':
                att_field = BooleanField()

            elif attr.datatype == 'integer':
                att_field = IntegerField()

            elif attr.datatype == 'number':
                att_field = FloatField()

            elif attr.datatype == 'email':
                att_field = EmailField()

            elif attr.datatype == 'slug':
                att_field = SlugField()

            elif attr.datatype == 'url':
                att_field = URLField()

            #elif attr.datatype in model_fields:
            #    att_field = model_fields[ attr.datatype ]

            elif attr.datatype == 'image':
                att_field = MediaUploadField()

            else:
                #continue
                att_field = CharField(max_length=1024)

            att_field.initial = attr.default
            att_field.required = attr.required
            att_field.label = attr.label
            att_field.help_text = attr.help

            self.fields[attr.name] = att_field

            if attr.hidden:
                self.fields[attr.name].widget = forms.HiddenInput()

            if attr.regexp:
                validator = RegexValidator(attr.regexp,
                                           message=attr.regexp_error)
                if not att_field.validators:
                    att_field.validators = []
                att_field.validators.append(validator)

        self.set_form_control_class()
Пример #18
0
class URLForm(forms.Form):
    url = URLField(widget=forms.TextInput(attrs={'title': 'URL',
                                                 'placeholder': 'http://www.example.com/'}),
                   required=True)
    force_new = BooleanField(required=False)
Пример #19
0
class SellerForm(ModelForm):
    # seller_user_id = IntegerField(required=False)
    seller_logo_image = ImageField(label='seller_logo_image',
                                   help_text='for Seller logo',
                                   required=False)
    seller_category_logo_image = ImageField(
        label='seller Category logo ',
        help_text='for Seller category logo',
        required=False)
    related_article_url = URLField(label='interview article address',
                                   help_text='FOR SELLER  interview article',
                                   required=False)

    def __init__(self, *args, **kwargs):
        super(SellerForm, self).__init__(*args, **kwargs)
        # self.fields['seller_user_id'].widget.attrs.update({'class':'user-id-input form-control'})
        self.fields['seller_name'].widget.attrs.update(
            {'class': 'form-control'})

        # self.fields['logo'].widget.attrs.update({'class':'form-control'})
        self.fields['seller_logo_image'].widget.attrs.update(
            {'class': 'form-control'})
        self.fields['seller_category_logo_image'].widget.attrs.update(
            {'class': 'form-control'})

        self.fields['shop_title'].widget.attrs.update(
            {'class': 'form-control'})
        self.fields['shop_link'].widget.attrs.update({'class': 'form-control'})
        self.fields['shop_desc'].widget.attrs.update({'class': 'form-control'})
        self.fields['status'].widget.attrs.update({'class': 'form-control'})
        self.fields['business_section'].widget.attrs.update(
            {'class': 'form-control'})
        self.fields['gk_stars'].widget.attrs.update({'class': 'form-control'})
        self.fields['related_article_url'].widget.attrs.update(
            {'class': 'form-control'})
        # self.fields['is2016store'].widget.attrs.update({'class':'form-control'})
        # self.fields['is2015store'].widget.attrs.update({'class':'form-control'})

    class Meta:
        model = Seller_Profile
        fields = [
                # 'seller_user_id',\
                  'seller_name','seller_logo_image','seller_category_logo_image',\
                  'shop_title','shop_link', 'shop_desc', 'status', 'business_section',\
                  'gk_stars', 'related_article_url', 'is2016store', 'is2015store'
                  ]

    def clean_related_article_url(self):
        url = self.cleaned_data.get('related_article_url')
        if not url:
            return None
        p = re.compile(r'articles/(\d+)')
        k = p.search(url)
        if k is None:
            raise ValidationError('can not find article id in URL')
            return None

        article_id = k.group(1)
        try:
            article = Article.objects.get(pk=article_id)
        except Article.DoesNotExist:
            raise ValidationError('can not find article object')
            return None

        return url

    def handle_related_article_url(self):

        url = self.cleaned_data.get('related_article_url')
        if not url:
            return

        p = re.compile(r'articles/(\d+)')
        k = p.search(url)
        article_id = k.group(1)
        article = Article.objects.get(pk=article_id)
        self.instance.related_article = article

    def handle_post_image_by_name(self, image_name):
        _image = HandleImage(image_file=self.cleaned_data.get(image_name))
        _image_path = _image.icon_save()
        return _image_path

    def handle_category_logo_image(self):
        image_name = 'seller_category_logo_image'
        if not self.cleaned_data.get(image_name):
            return

        _image_path = self.handle_post_image_by_name(image_name)

        self.instance.category_logo = _image_path

        return

    def handle_logo_image(self):
        image_name = 'seller_logo_image'

        if not self.cleaned_data.get(image_name):
            return

        _image_path = self.handle_post_image_by_name(image_name)
        self.instance.logo = _image_path

        return

    def save(self, commit=True, *args, **kwargs):
        self.handle_logo_image()
        self.handle_category_logo_image()
        self.handle_related_article_url()
        seller_profile = super(SellerForm, self).save(commit=True,
                                                      *args,
                                                      **kwargs)
Пример #20
0
class UserSettingsConfigForm(CremeForm):
    url = URLField(label=_(u'Server URL'), required=False)
    url_examples = ChoiceField(
        label=_(u'Server URL examples'),
        required=False,
        help_text=_(u'Some common configurations'),
        choices=chain((("", ""), ), COMMONS_SERVER_URL_CFG),
        widget=Select(
            attrs={'onchange': 'this.form.url.value=$(this).val();'}),
    )
    domain = CharField(label=_(u'Domain'), required=False)
    ssl = ChoiceField(
        label=_(u'Is secure'),
        required=False,
        choices=(('', _('Default')), (1, _('Yes')), (0, _('No'))),
    )
    login = CharField(label=_(u'Login'), required=False)
    password = CharField(label=_(u'Password'),
                         required=False,
                         widget=PasswordInput)
    sync_calendars = TypedChoiceField(
        label=_(u'Synchronize activities (calendars)'),
        help_text=_(u'Choose if either you want to synchronize '
                    u'your activities in both way or not.'),
        choices=_BOOL_CHOICES,
        coerce=_choice_2_bool,
    )
    sync_contacts = TypedChoiceField(
        label=_(u'Synchronize contacts'),
        help_text=_(u'Choose if either you want to synchronize '
                    u'your contacts in both way or not.'),
        choices=_BOOL_CHOICES,
        coerce=_choice_2_bool,
    )

    blocks = FieldBlockManager(
        ('mobile_sync', _(u'Mobile synchronization configuration'), '*'),
        ('what_sync', _(u'What to sync'), ('sync_calendars', 'sync_contacts')),
    )

    def __init__(self, *args, **kwargs):
        super(UserSettingsConfigForm, self).__init__(*args, **kwargs)
        # user = self.user

        # self._svalues_cache = svalues_cache = {}
        # sv_get = SettingValue.objects.get

        # def get_svalue(key_id):
        #     sv = svalues_cache[key_id] = sv_get(key_id=key_id, user=user)
        #     return sv

        fields = self.fields

        user_settings = self.user.settings
        # sv_doesnotexist = SettingValue.DoesNotExist

        def_svalues = get_default_server_setting_values()
        let_empty_msg = ugettext(
            u"Let empty to get the default configuration (currently '%s').")

        url_field = fields['url']
        # url_field.help_text = let_empty_msg % sv_get(key_id=MAPI_SERVER_URL).value
        url_field.help_text = let_empty_msg % (def_svalues['url'].value or '')
        # try:
        #     url_field.initial = get_svalue(USER_MOBILE_SYNC_SERVER_URL).value
        # except sv_doesnotexist:
        #     pass
        url_field.initial = self._old_url = user_settings.get(
            user_msync_server_url_key, '')

        domain_field = fields['domain']
        # domain_field.help_text = let_empty_msg % sv_get(key_id=MAPI_DOMAIN).value
        domain_field.help_text = let_empty_msg % (def_svalues['domain'].value
                                                  or '')
        # try:
        #     domain_field.initial = get_svalue(USER_MOBILE_SYNC_SERVER_DOMAIN).value
        # except sv_doesnotexist:
        #     pass
        domain_field.initial = user_settings.get(user_msync_server_domain_key,
                                                 '')

        ssl_field = fields['ssl']
        ssl_field.help_text = ugettext(
            u"Let 'Default' to get the default configuration (currently '%s')."
        ) % (
            # ugettext('Yes') if sv_get(key_id=MAPI_SERVER_SSL).value else ugettext('No')
            ugettext('Yes') if def_svalues['ssl'].value else ugettext('No'))
        # try:
        #     ssl_field.initial = int(get_svalue(USER_MOBILE_SYNC_SERVER_SSL).value)
        # except sv_doesnotexist:
        #     pass
        ssl_field.initial = int(
            user_settings.get(user_msync_server_ssl_key, False))

        # ----------------------------------
        # try:
        #     fields['login'].initial = get_svalue(USER_MOBILE_SYNC_SERVER_LOGIN).value
        # except sv_doesnotexist:
        #     pass
        fields['login'].initial = self._old_login = user_settings.get(
            user_msync_server_login_key, '')

        pwd_field = fields['password']
        # try:
        #     pwd_field.initial = Cipher.decrypt_from_db(get_svalue(USER_MOBILE_SYNC_SERVER_PWD).value)
        #     pwd_field.widget.render_value = True
        # except sv_doesnotexist:
        #     pass
        try:
            pwd_field.initial = Cipher.decrypt_from_db(
                user_settings[user_msync_server_pwd_key])
        except KeyError:
            pass
        else:
            pwd_field.widget.render_value = True

        # try:
        #     fields['sync_calendars'].initial = int(get_svalue(USER_MOBILE_SYNC_ACTIVITIES).value)
        # except sv_doesnotexist:
        #     pass
        fields['sync_calendars'].initial = int(
            user_settings.get(user_msync_activities_key, False))

        # try:
        #     fields['sync_contacts'].initial = int(get_svalue(USER_MOBILE_SYNC_CONTACTS).value)
        # except sv_doesnotexist:
        #     pass
        fields['sync_contacts'].initial = int(
            user_settings.get(user_msync_contacts_key, False))

    def clean_ssl(self):
        try:
            return _choice_2_bool(self.cleaned_data['ssl'])
        except ValueError:
            pass

    def save(self):
        user = self.user
        clean_get = self.cleaned_data.get

        # url_is_created   = False
        # login_is_created = False

        # def upgrade_svalue(key_id, value):
        #     svalue = self._svalues_cache.get(key_id)
        #     created = False
        #
        #     if svalue is None:
        #         svalue = self._svalues_cache[key_id] \
        #                = SettingValue.objects.create(key_id=key_id, user=user, value=value)
        #         created = True
        #     elif svalue.value != value:
        #         svalue.value = value
        #         svalue.save()
        #
        #     return created
        #
        # def delete_svalue(key_id):
        #     svalue = self._svalues_cache.pop(key_id, None)
        #
        #     if svalue is not None:
        #         svalue.delete()

        url = clean_get('url')
        # if url:
        #     url_is_created = upgrade_svalue(USER_MOBILE_SYNC_SERVER_URL, url)
        # else:
        #     delete_svalue(USER_MOBILE_SYNC_SERVER_URL)

        domain = clean_get('domain')
        # if domain:
        #     upgrade_svalue(USER_MOBILE_SYNC_SERVER_DOMAIN, domain)
        # else:
        #     delete_svalue(USER_MOBILE_SYNC_SERVER_DOMAIN)

        ssl = clean_get('ssl')
        # if ssl is not None:
        #     upgrade_svalue(USER_MOBILE_SYNC_SERVER_SSL, ssl)
        # else:
        #     delete_svalue(USER_MOBILE_SYNC_SERVER_SSL)

        login = clean_get('login')
        # if login:
        #     login_is_created = upgrade_svalue(USER_MOBILE_SYNC_SERVER_LOGIN, login)
        # else:
        #     delete_svalue(USER_MOBILE_SYNC_SERVER_LOGIN)

        # upgrade_svalue(USER_MOBILE_SYNC_ACTIVITIES, clean_get('sync_calendars'))
        # upgrade_svalue(USER_MOBILE_SYNC_CONTACTS,   clean_get('sync_contacts'))

        password = clean_get('password')
        # if password:
        #     upgrade_svalue(USER_MOBILE_SYNC_SERVER_PWD, Cipher.encrypt_for_db(password))
        # else:
        #     delete_svalue(USER_MOBILE_SYNC_SERVER_PWD)

        with self.user.settings as user_settings:
            # TODO: factorise
            if url:
                user_settings[user_msync_server_url_key] = url
            else:
                user_settings.pop(user_msync_server_url_key, None)

            if domain:
                user_settings[user_msync_server_domain_key] = domain
            else:
                user_settings.pop(user_msync_server_domain_key, None)

            if ssl is not None:
                user_settings[user_msync_server_ssl_key] = ssl
            else:
                user_settings.pop(user_msync_server_ssl_key, None)

            if login:
                user_settings[user_msync_server_login_key] = login
            else:
                user_settings.pop(user_msync_server_login_key, None)

            user_settings[user_msync_activities_key] = clean_get(
                'sync_calendars')
            user_settings[user_msync_contacts_key] = clean_get('sync_contacts')

            if password:
                user_settings[
                    user_msync_server_pwd_key] = Cipher.encrypt_for_db(
                        password)
            else:
                user_settings.pop(user_msync_server_pwd_key, None)

        # TODO: test
        # TODO: add a true button to purge (ex: we could want to purge if the url is changed, or not)
        # if url_is_created or login_is_created:
        if self._old_url != url or self._old_login != login:
            try:
                as_client = CremeClient.objects.get(user=user)
            except CremeClient.DoesNotExist:
                pass
            else:
                as_client.purge(
                )  # NB: If server_url or login have changed, we reset all mapping & clientdef
Пример #21
0
class ScreenslopForm(Form):
    url = URLField()
    viewports = MultipleChoiceField(choices=AVAILABLE_RESOLUTIONS,
                                    widget=CheckboxSelectMultiple)