예제 #1
0
파일: views.py 프로젝트: franciskung/myewb2
def resume(request):
    registration = get_object_or_none(ConferenceRegistration, user=request.user, submitted=True, cancelled=False)

    if not registration:
        request.user.message_set.create("You aren't registered for conference...")
        return HttpResponseRedirect(reverse('confreg'))
    
    if request.method == 'POST':
        form = ConferenceResumeForm(request.POST, request.FILES)
        if form.is_valid():
            resume = Attachment()
            resume.creator = request.user
            resume.content_type = ContentType.objects.get_for_model(registration)
            resume.object_id = registration.id
            resume.attachment_file = form.cleaned_data['resume']
            resume.save()
            
            request.user.message_set.create(message="Thank you!")
            return HttpResponseRedirect(reverse('confreg'))
    else:
        form = ConferenceResumeForm()
                
    return render_to_response('conference/resume.html',
                              {'registration': registration,
                               'form': form,
                               'user': request.user,
                              },
                              context_instance=RequestContext(request)
                             )
예제 #2
0
    def test_evidence_attachments(self):
        task = Task.objects.create(name='Test task',
                                   creator=self.user)
        self.assertEquals(Task.objects.filter(name='Test task').count(), 1)

        evidence = Evidence.objects.create(task=task)
        self.assertEquals(Evidence.objects.filter(task=task).count(), 1)

        att = Attachment()
        att.creator = self.user

        file_mock = mock.MagicMock(spec=File, name='FileMock')
        file_mock.name = 'test1.jpg'
        storage_mock = mock.MagicMock(spec=Storage, name='StorageMock')
        storage_mock.url = mock.MagicMock(name='url')
        storage_mock.url.return_value = '/tmp/test1.jpg'

        ct = ContentType.objects.get(app_label=evidence._meta.app_label,
                                     model=evidence._meta.model_name)
        att.content_type = ct
        att.object_id = evidence.id
        att.attachment_file = file_mock
        
        with mock.patch('django.core.files.storage.default_storage._wrapped', storage_mock):
            att.save()
        self.assertEquals(Attachment.objects.count(), 1)
        self.assertEquals(att, evidence.attachments.first())
예제 #3
0
파일: views.py 프로젝트: franciskung/myewb2
def registration_preview(request):
    username = request.user.username
    
    f = ConferenceRegistrationForm(request.POST, request.FILES)
    f.user = request.user
    if f.is_valid():
        if f.cleaned_data.get('resume', None):
            resume = Attachment()
            resume.creator = request.user
            resume.content_type = ContentType.objects.get_for_model(request.user)
            resume.object_id = request.user.id
            resume.attachment_file = f.cleaned_data['resume']
            resume.save()
            
    return ConferenceRegistrationFormPreview(ConferenceRegistrationForm)(request, username=username)
예제 #4
0
def attach_as_file(handle_id, name, content, user, overwrite=False):
    """
        Attach a file to a handle_id.
        - handle_id the id of the node to attach a file to.
        - name the name of the file
        - content the content of the file (e.g. a string)
        - user the user doing the attach
        - overwrite should the file be overwritten if it exists. (Default: False)

        All files are stored in {root}/niweb/media/attachments, and the metadata is attached in the django db.
    """
    nh = NodeHandle.objects.get(pk=handle_id)
    _file = SimpleUploadedFile(name,
                               content.encode('utf-8'),
                               content_type="text/plain")
    if overwrite:
        attachment = Attachment.objects.filter(
            object_id=handle_id, attachment_file__endswith=name).first()
        if attachment:
            attachment.attachment_file.delete()
    if not attachment:
        attachment = Attachment()
    attachment.content_type = ContentType.objects.get_for_model(nh)
    attachment.object_id = handle_id
    attachment.creator = user
    attachment.attachment_file = _file
    return attachment.save()
예제 #5
0
def upload_file(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            description = form.cleaned_data['description']
            attachment = Attachment(file=request.FILES['file'], description=description, uploader=request.user)
            attachment.save()
            return HttpResponseRedirect('/attachments/')
    if request.method == 'DELETE':
        aid = request.GET.get('id',None)
        if aid:
            attachment = Attachment.objects.get(id=aid)
            if attachment:
                attachment.delete()
        return HttpResponseRedirect('/attachments/')
    return HttpResponseRedirect('/attachments/')
예제 #6
0
def registration_preview(request):
    #def pay_membership_preview(request, username):
    username = request.user.username

    f = ConferenceRegistrationForm(request.POST, request.FILES)
    f.user = request.user
    if f.is_valid():
        if f.cleaned_data.get('resume', None):
            resume = Attachment()
            resume.creator = request.user
            resume.content_type = ContentType.objects.get_for_model(
                request.user)
            resume.object_id = request.user.id
            resume.attachment_file = f.cleaned_data['resume']
            resume.save()

    return ConferenceRegistrationFormPreview(ConferenceRegistrationForm)(
        request, username=username)
예제 #7
0
def articletobinder(article):
    bb = re.match(r'(?P<name>[^(]*)\(*(?P<location>[^)]*)', article.title)
    location_parts = bb.group('location').split(',')
    if len(location_parts) == 2 :
        (city, state) = location_parts
    else:
        city = bb.group('location').strip()
        state = ''
        
#   loc = re.match(r'(?P<city>\w*)\W*(?P<state>\w*).*$',  bb.group('location'))
#     if article.alias:
#         trimslug = re.match(r'[^\w]*([\w-]+)$', article.alias)
#         josslug = trimslug.group(1)
#     else:
#         josslug = slugify(bb.group('name').strip() + ' ' + bb.group('location').strip())
    
    jos_combined_text = article.introtext + article.fulltext
    entry = Entry.objects.create(
        name = bb.group('name').strip(),
        city = city.strip(),
        state = state.strip(),
        # location = bb.group('location').strip(),
        creator = import_user,
        )
    soup = BeautifulSoup.BeautifulSoup(jos_combined_text)
    for img in soup.findAll('img', src=True):
        absolutepath = os.path.join(JOOMLA_IMG_ROOT, unquote(img['src']))
        os.chdir(os.path.dirname(absolutepath))
        try:
            pict = File(open(os.path.basename(absolutepath), 'r'))
            a = Attachment()
            a.creator = import_user
            a.content_object = entry
            a.attachment_file = pict
            a.save()
            pict.close()
            img['src'] = urlparse(a.attachment_file.url)[2] # python 2.4 version 
                                                            # of urlparse
        except IOError:
            print 'cannot open ' , absolutepath
    
    entry.content = html2text(unicode(soup))
    entry.save()
    Tag.objects.add_tag(entry, 'joomlacontent')
예제 #8
0
    def _add_attachment(self, code, name='audit'):
        with tempfile.NamedTemporaryFile(
                mode='w+b', delete=False, suffix=".trash",
                dir=settings.MEDIA_ROOT) as temporary_file:
            try:
                temporary_file.write(b'\x04\x02')
                temporary_file.seek(0)
                file_type, created = FileType.objects.get_or_create(
                    name=name, label='audit', code='audit')

                attachment = Attachment(content_object=self.engagement,
                                        code=code,
                                        file_type=file_type)

                attachment.file.save(temporary_file.name, File(temporary_file))
                attachment.save()

            finally:
                if os.path.exists(temporary_file.name):
                    os.remove(temporary_file.name)
예제 #9
0
    def handle(self, *args, **options):

        if len(args) != 1:
            print "Usage: import_attachments", self.args
            return
        try:
            user = args[0]
            user = User.objects.get(username=user)
        except:
            print "unknown user", user
            return

        dirname = os.path.join(settings.MEDIA_ROOT,
                               settings.ATTACHMENT_LOCATION)
        for f in os.listdir(dirname):
            if not os.path.isdir(f):
                path = os.path.join(settings.ATTACHMENT_LOCATION, f)
                existing = Attachment.objects.filter(file=path)
                if len(existing) == 0:
                    a = Attachment(file=path, uploader=user, description=f)
                    a.save()
                    print "storing ", path
                else:
                    print "not storing ", path
예제 #10
0
def ticket_from_message(message):
    # 'message' must be an RFC822 formatted message.
    
    #BUG: We need to check for messages address to multiple tickets
    #BUG: Don't break with multiple 'to' addresses
    #BUG: What if a ticket is CC'd?
    
    message = email.message_from_string(message)
    subject = message.get('subject', 'No Subject')
    subject = subject.replace('Re:', '')
    subject = subject.replace('RE:', '')
    subject = subject.replace('re:', '')
    subject = subject.replace('FW:', '')
    subject = subject.replace('Fw:', '')
    subject = subject.replace('fw:', '')
    subject = subject.strip()

    sender = message.get('from', None)
    sender_email = parseaddr(sender)[1]

    recipients = getaddresses(message.get_all('to', []) + message.get_all('cc', []))
    #TODO: Check if all recipients are associated with the ticket(s), add if not
    
    tickets = []
    for recipient in recipients:
        name_part, user_part, plus_part, domain_part = get_address_parts(recipient)
        if user_part + '@' + domain_part == settings.IT_MAILSUCK_ADDRESS:
            #This recipient is a ticket address
            print 'Message destined for ticket system'
            if plus_part:
                #Message is destined for a specific ticket
                print 'Message allegedly for ticket: %s' %(plus_part)
                try:
                    t = Ticket.objects.get(pk=plus_part)
                    print 'Ticket found %s' %(plus_part)
                    if not t in tickets:
                        tickets.append(t)
                except Ticket.ObjectNotFound:
                    print 'Unable to locate ticket %s' %(plus_part)
                    continue
                    #BUG: This should be logged (in fact, all incoming messages should be logged...)
            else:
                t = Ticket()
                if not t in tickets:
                    tickets.append(t)
        else:
            print 'Not destined for ticket system, skipping' %(recipient)
            continue

#BUG: Don't blindly accept mail/attachments for existing tickets.  Allow only from people involved with the ticket.
#BUG: Don't blindly create new tickets, check account status

    body_plain, body_html = '', ''
    counter = 0
    files = []
    for part in message.walk():
        if part.get_content_maintype() == 'multipart':
            continue
        
        print 'Part params: '
        print part.get_params()
        name = part.get_param('name')

        if part.get_content_maintype() == 'text' and name == None:
            if part.get_content_subtype() == 'plain':
                body_plain = decodeUnknown(part.get_charset(), part.get_payload(decode=True))
            else:
                body_html = part.get_payload(decode=True)
        else:
            if not name:
                name = part.get_filename()
            
            files.append({
                'filename': name,
                'content': part.get_payload(decode=True),
                'type': part.get_content_type()},
                )
        counter += 1

    if body_plain:
        body = body_plain
    else:
        body = 'No plain-text email body available. Please see HTML attachment.'

    if body_html:
        files.append({
            'filename': 'email_html_body.html',
            'content': body_html,
            'type': 'text/html',
        })
    now = datetime.now()

    for ticket in tickets:
        if ticket.pk:
            #TODO: Existing tickets need a comment created
            pass
        else:
            #TODO: Lookup contact by e-mail, find associated company
            ticket.company = Company.objects.get(pk=1) #BUG: Hardcoded
            ticket.contact = User.objects.get(pk=1) #BUG: Hardcoded
            #TODO: Need to have finish 'team' setup and have a default tech for each account
            ticket.assignedto = User.objects.get(pk=1)
            ticket.source = TicketSource.objects.get(pk='E-Mail')
            ticket.summary =  subject
            ticket.description = body

        important_types = ('high', 'important', '1', 'urgent')
        if message.get('priority', '') in important_types or message.get('importance', '') in important_types:
            ticket.priority = TicketPriority.objects.get(name='Emergency')
        else:
            ticket.priority = TicketPriority.objects.get(name='Normal')

        #TODO: Check ticket status, change appropriately
        #TODO: Make sure everyone in 'to' or 'cc' get included in the ticket notification list

        #Save the ticket before attaching files...
        print ticket
        ticket.save()
    
    for file in files:
        print "Scanning through attachments"
        if file['content']:
            print 'Attaching file: %s' %(file['filename'])
            filename = file['filename'].encode('ascii', 'replace').replace(' ', '_')
            filename = re.sub('[^a-zA-Z0-9._-]+', '', filename)

            print 'Almost there: %s' %(filename)
            fh, fpath = mkstemp(prefix='itmailattach-', suffix='-%s' %(filename), text=True)
            f = open(fpath, 'w+')
            print 'Writing attachment to %s' %(fpath)
            f.write(file['content'])
            f.flush()
            fa = File(open(fpath, 'r'))

            for ticket in tickets:
                a = Attachment()
                a.content_object = ticket
                a.creator = User.objects.get(pk=1) #BUG: We need a way to specify a 'system' user or something
                a.attachment_file = fa
                a.save()

            fa.close()
            f.close()
            os.remove(fpath)

    return True
def create(request):
    form = MessageForm(request.POST)
    if form.is_valid():
        session = boto3.session.Session()
        s3_client = session.client(
            service_name='s3',
            endpoint_url='http://hb.bizmrg.com',
            aws_access_key_id='6Da62vVLUi6AKbFnnRoeA3',
            aws_secret_access_key=
            'gDYg4Bu15yUpNYGKmmpiVNGvLRWhUAJ3m1GGRvg8KTbU',
        )
        user = User.objects.get(username=request.POST['username'])
        chats = Member.objects.filter(user=user)
        for chat in chats:
            op = Member.objects.filter(chat=chat.chat).exclude(user=user).get()
            if op.user.username == request.POST['opponent']:
                result = chat.chat
                break
        message = Message(content=request.POST['content'],
                          chat=result,
                          user=user,
                          added_at=request.POST['date'])
        message.save()
        response = [message.id]
        result.last_message = '(' + request.POST['attach_type'] + ') ' +\
            request.POST['content'] if request.POST['attach_type'] != 'none' else request.POST['content']
        result.save()
        chat.last_read_message = Message.objects.filter(chat=result).filter(
            user=op.user).last()
        chat.save()
        attachs = {}
        attachs['type'] = request.POST['attach_type']
        if request.POST['attach_type'] == 'geolocation':
            attachment = Attachment(
                chat=result,
                user=user,
                message=message,
                attach_type='geolocation',
                url=request.POST['content'],
            )
            attachment.save()
            attachs['url'] = attachment.url
            response.append(attachment.id)
        else:
            attachs['url'] = []

        for file in request.FILES:
            key = 'attachments/' + request.POST[
                'attach_type'] + result.topic + '/' + str(hash(file))
            s3_client.put_object(
                Bucket='tsyrkov_messanger_bucket',
                Key=key,
                Body=request.FILES[file],
            )
            attachment = Attachment(
                chat=result,
                user=user,
                message=message,
                attach_type=request.POST['attach_type'],
                url=key,
            )
            attachment.save()
            attachs['url'].append(
                s3_client.generate_presigned_url(
                    'get_object',
                    Params={
                        'Bucket': 'tsyrkov_messanger_bucket',
                        'Key': attachment.url,
                    },
                    ExpiresIn=3600))
            response.append(attachment.id)

        # send message to client
        if attachs['type'] == 'audio':
            attachs['url'] = attachs['url'][0]
        avatar = s3_client.generate_presigned_url(
            'get_object',
            Params={
                'Bucket': 'tsyrkov_messanger_bucket',
                'Key': message.user.avatar,
            },
            ExpiresIn=3600)
        command_1 = {
            'method': 'publish',
            'params': {
                'channel': op.user.username + '_with_' + user.username,
                'data': {
                    'avatar': avatar,
                    'opponent': message.user.username,
                    'topic': result.topic,
                    'author': message.user.username,
                    'last_message': result.last_message,
                    'read': False,
                    'date': 'T'.join(message.added_at.split(' ')),
                    'message': message.content,
                    'attachments': attachs,
                }
            }
        }
        command_2 = {
            'method': 'publish',
            'params': {
                'channel': op.user.username,
                'data': {
                    'avatar': avatar,
                    'opponent': message.user.username,
                    'topic': result.topic,
                    'author': message.user.username,
                    'last_message': result.last_message,
                    'read': False,
                    'date': 'T'.join(message.added_at.split(' ')),
                    'message': message.content,
                    'attachments': attachs,
                }
            }
        }
        headers = {
            'Content-Type': 'application/json',
            'Authorization': 'apikey ' + API_KEY,
        }
        requests.post(url='http://localhost:9000/api',
                      data=json.dumps(command_1),
                      headers=headers)
        requests.post(url='http://localhost:9000/api',
                      data=json.dumps(command_2),
                      headers=headers)
        return JsonResponse({'success': response})
    return JsonResponse({'errors': form.errors}, status=400)
예제 #12
0
def upload(request, app_model, id, field=None, form=FileForm, filename_prefix=None):
    """
    Main Multiuploader module.
    Parses data from jQuery plugin and makes database changes.
    """
    att = False
    if request.method == 'POST':
        if "application/json" in request.META['HTTP_ACCEPT_ENCODING']:
            mimetype = 'application/json'
        else:
            mimetype = 'text/plain'

        log.info('received POST to main multiuploader view')
        if request.FILES == None:
            return HttpResponseBadRequest('Must have files attached!')

        #getting file data for farther manipulations
        file = request.FILES[u'files[]']
        wrapped_file = UploadedFile(file)
        filename = wrapped_file.name
        file_size = wrapped_file.file.size
        log.info ('Got file: "%s"' % str(filename))
        log.info('Content type: "$s" % file.content_type')

        """ Use a form to validate the upload """
        instance = form({ 'filename': filename, 'id': id })
        if not instance.is_valid():
            return HttpResponse(simplejson.dumps([{
                                        'error': instance.errors['__all__'],
                                        'name': filename,
                                        'size': file_size,
                                        }]), mimetype=mimetype)

        in_app, in_model = app_model.split('.')
        model = get_model(in_app, in_model)

        if field:
            field_info = model._meta.get_field_by_name(field)
        else:
            field_info = [False]

        obj = get_object_or_404(model, pk=id)
        if not isinstance(field_info[0], FileField) or not isinstance(field_info[0], ImageField):
            """ if the field we are uploading to is not a FileField or
                ImageField it is a generic attachment """
            if Attachment:
                """ attach the file """
                att = Attachment()
                att.content_object = obj
                att.client = obj.client
                att.file.save(filename, file, save=False)
                att.added_by = request.user
                att.save()
                if field:
                    """ if we pass in an optional field name then the sending
                    object tracks the attachement too.  So we set the attachment
                    ID in the foreign object """
                    setattr(obj, field, att)
            else:
                raise "Cannot attach file"
        else:
            """ this does not use the Attachment model and instead tracks the
            upload independantly.  Just upload the file and save it to the
            foreign model """
            if not field:
                raise "Field is mandatory when not a generic attachement"
            setattr(obj, field, file)

        obj.save()
        log.info('File saving done')

        upload_done.send(sender=create_string_wrapper('uploadit'),
                        app=app_model.split('.')[0],
                        model=app_model.split('.')[1],
                        field=field, instance=obj,
                        filename=filename, attachment_object=att)

        #generating json response array
        result = []
        result.append({"name":filename,
                       "size":file_size,
                       "delete_type":"POST",})

        response_data = simplejson.dumps(result)

        return HttpResponse(response_data, mimetype=mimetype)

    else: #GET
        return HttpResponseBadRequest()