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())
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()
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) )
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)
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)
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')
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