Ejemplo n.º 1
0
 def clean_file(self):
     try:
         json.loads(self.cleaned_data['file'].read())
         self.cleaned_data['file'].seek(0)
         return self.cleaned_data['file']
     except Exception, e:
         try:
             reader = csv.reader(self.cleaned_data['file'].readlines())
             self.cleaned_data['file'].seek(0)
             return self.cleaned_data['file']
         except Exception, e:
             raise forms.ValidationError(_(u"uploaded file must contain json or csv data"))
def decode(self, session_data):
    encoded_data = base64.decodestring(session_data)
    try:
        # could produce ValueError if there is no ':'
        hash, jsond = encoded_data.split(':', 1)
        expected_hash = self._hash(jsond)
        if not constant_time_compare(hash, expected_hash):
            raise SuspiciousOperation("Session data corrupted")
        else:
            try:
                return json.loads(jsond.decode('zlib'))
            except json.decoder.JSONDecodeError:
                raise ValueError
    except Exception:
        return {}
def view_newsletter_preview(request, nid, cid):
    newsletter = get_object_or_404(Newsletter, uuid=nid)

    base_url = "http://"+Site.objects.get_current().domain

    contact = newsletter.mailing_list.subscribers.filter(uuid=cid)
    if (contact.count() == 0):
        contact = newsletter.mailing_list.unsubscribers.filter(uuid=cid)
        if (contact.count() == 0):
            contact = newsletter.test_contacts.filter(uuid=cid)
            if (contact.count() == 0):
                raise Http404()

    unsubscribe = reverse('newsletter_newsletter_unsubscribe',kwargs={'nid':nid,'cid':cid})
    subscribe = reverse('newsletter_newsletter_subscribe',kwargs={'nid':nid,'cid':cid})
    preview = reverse('newsletter_newsletter_preview',kwargs={'nid':nid,'cid':cid})
    tracking = reverse('newsletter_newsletter_tracking',kwargs={'nid':nid,'cid':cid})

    d = {
        'contact':contact,
        'data':simplejson.loads(newsletter.dictionary),
        'preview_link': base_url+preview,
        'unsubscribe_link': base_url+unsubscribe,
        'subscribe_link': base_url+subscribe,
        'tracking_link': base_url+tracking
    }
    context = Context(d)

    try:
        subject = render_to_string(newsletter.template_subject, context).replace('\n','').replace('\t','').replace('\r','')
    except Exception as es:
        subject = "Missing or broken template %s (%s)" % (newsletter.template_subject, str(traceback.format_exc()))

    d['subject'] = subject
    context = Context(d)

    return render_to_response(newsletter.template_body, context)
Ejemplo n.º 4
0
    def _send_contact(self, base_url, contact):
        unsubscribe = reverse('newsletter_newsletter_unsubscribe',kwargs={'nid':self.uuid,'cid':contact.uuid})
        preview = reverse('newsletter_newsletter_preview',kwargs={'nid':self.uuid,'cid':contact.uuid})
        tracking = reverse('newsletter_newsletter_tracking',kwargs={'nid':self.uuid,'cid':contact.uuid})
        subscribe = reverse('newsletter_newsletter_subscribe',kwargs={'nid':self.uuid,'cid':contact.uuid})

        d = {
            'contact':contact,
            'data':simplejson.loads(self.dictionary),
            'preview_link': base_url+preview,
            'unsubscribe_link': base_url+unsubscribe,
            'tracking_link': base_url+tracking,
            'subscribe_link': base_url+subscribe
        }
        context = Context(d)

        try:
            subject = render_to_string(self.template_subject, context).replace('\n','').replace('\t','').replace('\r','')
        except Exception as es:
            subject = "Missing or broken template %s (%s)" % (self.template_subject, str(traceback.format_exc()))

        d['subject'] = subject
        context = Context(d)

        try:
            html_content = render_to_string(self.template_body, context)
        except Exception as es:
            html_content = "<h1>Missing or broken template %s</h1><br/>%s" % (self.template_body, str(traceback.format_exc()))
        text_content = html2text(html_content)

        text_content = force_unicode(text_content)
        subject = force_unicode(subject)

        msg = EmailMultiAlternatives(subject, text_content, self.header_sender, [contact.email])
        msg.attach_alternative(html_content, "text/html")
        msg.send()
Ejemplo n.º 5
0
 def create_json(cls, raw):
     data = simplejson.loads(raw)
     return cls.create(data)
Ejemplo n.º 6
0
def process_paypal_donation(sender, **kwargs):
    ipn_obj = sender
            
    if ipn_obj.payment_status == u'Completed':
        try:
            custom = simplejson.loads(ipn_obj.custom)
        except:
            custom = {}
       
        creator = None 
        if custom.has_key('creator'):
            try:
                supporter = Supporter.objects.get(id = custom['creator'])
                if supporter.user_profile:
                    creator = supporter.user_profile.user
            except Supporter.DoesNotExist:
                pass
        if not creator:
            creator = get_default_creator()
            
        # Lookup Supporter
        try:
            supporter = Supporter.objects.get(
                first_name = ipn_obj.first_name,
                last_name = ipn_obj.last_name,
                contact_profile__primary_address__address1 = ipn_obj.address_street,
                contact_profile__primary_address__zip = ipn_obj.address_zip,
            )
            contact_profile = supporter.contact_profile
            
        except Supporter.DoesNotExist:
            supporter = Supporter(
                first_name = ipn_obj.first_name,
                last_name = ipn_obj.last_name,
                creator = creator,
            )
            supporter.save()
            contact_profile = None

        if not contact_profile:
            contact_profile = ContactProfile()
            contact_profile.save()
            supporter.contact_profile = contact_profile
            supporter.save()

        if not contact_profile.primary_address or contact_profile.primary_address.address1 != ipn_obj.address_street or contact_profile.primary_address.zip != ipn_obj.address_zip:
            address_info = {
                'address1': ipn_obj.address_street,
                'city': ipn_obj.address_city,
                'state': ipn_obj.address_state,
                'zip': ipn_obj.address_zip,
            }
            address = get_or_create_address(address_info)
            if contact_profile.primary_address:
                contact_profile.other_addresses.add(contact_profile.primary_address)
            contact_profile.primary_address = address

        if not contact_profile.primary_email or contact_profile.primary_email.email != ipn_obj.payer_email:
            try:
                email = EmailAddress.objects.get(email = ipn_obj.payer_email)
            except EmailAddress.DoesNotExist:
                email = EmailAddress(
                    email = ipn_obj.payer_email,
                    type = get_default_email_type(),
                )
                email.save()
            if contact_profile.primary_email:
                contact_profile.other_emails.add(contact_profile.primary_email)
            contact_profile.primary_email = email
            
        contact_profile.save()

        campaign = None
        if custom.has_key('campaign'):
            try:
                campaign = Campaign.objects.get(id = custom['campaign'])
            except Campaign.DoesNotExist:
                pass

        donation = Donation(
            supporter = supporter,
            creator = creator,
            campaign = campaign,
            date_transaction = ipn_obj.payment_date,
            status = 'received',
            amount = ipn_obj.mc_gross,            
        )
        donation.save()
Ejemplo n.º 7
0
    def import_view(self, request, extra_context=None):
        """
        Import email addresses and salutation from a uploaded text file.
        """
        model = self.model
        opts = model._meta
        
        if not self.has_import_permission(request):
            raise PermissionDenied

        if request.method == 'POST':
            form = UploadForm(request.POST, request.FILES)
            if form.is_valid():
                num_import = 0

                try: # try json
                    data = json.loads(form.cleaned_data['file'].read())

                    for entry in data:
                        try:
                            Subscriber.objects.create(email=entry['email'], salutation=force_unicode(entry['name']))
                            num_import += 1
                        except Exception, e:
                            pass
                except: # may be csv data
                    try:
                        reader = csv.reader(form.cleaned_data['file'].readlines(), delimiter=',')
                        for entry in reader:
                            try:
                                Subscriber.objects.create(email=entry[0], salutation=force_unicode(entry[1]))
                                num_import += 1
                            except Exception, e:
                                pass
                    except:
                        raise
                                
                request.user.message_set.create(message=_(u'Successfully imported  %(num_import)s %(name)s.' %  {'name': force_unicode(opts.verbose_name_plural), 'num_import': num_import,}))
                return HttpResponseRedirect('../')
                        
        else:
            form = UploadForm()

        def form_media():
            from django.conf import settings
            css = ['css/forms.css',]
            return forms.Media(css={'screen': ['%s%s' % (settings.ADMIN_MEDIA_PREFIX, url) for url in css]})

        media = self.media + form_media()
        context = {
            'title': _('Import %s') % force_unicode(opts.verbose_name_plural),
            'is_popup': request.REQUEST.has_key('_popup'),
            'media': mark_safe(media),
            'root_path': self.admin_site.root_path,
            'app_label': opts.app_label,
            'opts': opts,
            'form': form,
        }

        context.update(extra_context or {})
        return render_to_response(self.import_template or
            ['admin/%s/%s/import.html' % (opts.app_label, opts.object_name.lower()),
            'admin/%s/import.html' % opts.app_label,
            'admin/import.html'], context, context_instance=template.RequestContext(request))
Ejemplo n.º 8
0
 def save(self, force_insert=False, force_update=False):
     try:
         simplejson.loads(self.dictionary)
     except:
         raise IntegrityError(_('Invalid json'))
     models.Model.save(self, force_insert, force_update)
 def decode_cache(self, session_data):
     try:
         return json.loads(session_data.decode('zlib'))
     except json.decoder.JSONDecodeError:
         raise ValueError