Search in sources :

Example 1 with CalendarItemInfo

use of com.zimbra.cs.mailbox.Message.CalendarItemInfo in project zm-mailbox by Zimbra.

the class ArchiveFormatter method saveItem.

private ArchiveOutputStream saveItem(UserServletContext context, MailItem mi, Map<Integer, String> fldrs, Map<Integer, Integer> cnts, boolean version, ArchiveOutputStream aos, CharsetEncoder charsetEncoder, Set<String> names) throws ServiceException {
    String ext = null, name = null;
    String extra = null;
    Integer fid = mi.getFolderId();
    String fldr;
    InputStream is = null;
    String metaParam = context.params.get(UserServlet.QP_META);
    boolean meta = metaParam == null ? getDefaultMeta() : !metaParam.equals("0");
    if (!version && mi.isTagged(Flag.FlagInfo.VERSIONED)) {
        for (MailItem rev : context.targetMailbox.getAllRevisions(context.opContext, mi.getId(), mi.getType())) {
            if (mi.getVersion() != rev.getVersion())
                aos = saveItem(context, rev, fldrs, cnts, true, aos, charsetEncoder, names);
        }
    }
    switch(mi.getType()) {
        case APPOINTMENT:
            Appointment appt = (Appointment) mi;
            if (!appt.isPublic() && !appt.allowPrivateAccess(context.getAuthAccount(), context.isUsingAdminPrivileges())) {
                return aos;
            }
            if (meta) {
                name = appt.getSubject();
                ext = "appt";
            } else {
                ext = "ics";
            }
            break;
        case CHAT:
            ext = "chat";
            break;
        case CONTACT:
            Contact ct = (Contact) mi;
            name = ct.getFileAsString();
            if (!meta) {
                ext = "vcf";
            }
            break;
        case FLAG:
            return aos;
        case FOLDER:
        case MOUNTPOINT:
        case SEARCHFOLDER:
            if (mi.getId() == Mailbox.ID_FOLDER_ROOT) {
                name = "ROOT";
            } else if (mi.getId() == Mailbox.ID_FOLDER_USER_ROOT) {
                name = "USER_ROOT";
            } else {
                name = mi.getName();
            }
            break;
        case MESSAGE:
            Message msg = (Message) mi;
            if (msg.hasCalendarItemInfos()) {
                Set<ItemId> calItems = Sets.newHashSet();
                for (Iterator<CalendarItemInfo> it = msg.getCalendarItemInfoIterator(); it.hasNext(); ) {
                    ItemId iid = it.next().getCalendarItemId();
                    if (iid != null) {
                        calItems.add(iid);
                    }
                }
                for (ItemId i : calItems) {
                    if (extra == null) {
                        extra = "calendar=" + i.toString();
                    } else {
                        extra += ',' + i.toString();
                    }
                }
            }
            ext = "eml";
            break;
        case NOTE:
            ext = "note";
            break;
        case TASK:
            Task task = (Task) mi;
            if (!task.isPublic() && !task.allowPrivateAccess(context.getAuthAccount(), context.isUsingAdminPrivileges())) {
                return aos;
            }
            ext = "task";
            break;
        case VIRTUAL_CONVERSATION:
            return aos;
        case WIKI:
            ext = "wiki";
            break;
    }
    fldr = fldrs.get(fid);
    if (fldr == null) {
        Folder f = mi.getMailbox().getFolderById(context.opContext, fid);
        cnts.put(fid, 1);
        fldr = f.getPath();
        if (fldr.startsWith("/")) {
            fldr = fldr.substring(1);
        }
        fldr = sanitize(fldr, charsetEncoder);
        fldr = ILLEGAL_FOLDER_CHARS.matcher(fldr).replaceAll("_");
        fldrs.put(fid, fldr);
    } else if (!(mi instanceof Folder)) {
        final int BATCH = 500;
        int cnt = cnts.get(fid) + 1;
        cnts.put(fid, cnt);
        cnt /= BATCH;
        if (cnt > 0) {
            fldr = fldr + '!' + cnt;
        }
    }
    int targetBaseLength = 0;
    if (context.noHierarchy()) {
        // Parent hierarchy is not needed, so construct the folder names without parent hierarchy.
        // e.g> represent "inbox/subfolder/target" as "target".
        String targetPath = null;
        if (context.itemPath.endsWith("/")) {
            // inbox/subfolder/target/
            targetPath = context.itemPath.substring(0, context.itemPath.lastIndexOf("/"));
        } else {
            // inbox/subfolder/target
            targetPath = context.itemPath;
        }
        // "inbox/subfolder".length()
        targetBaseLength = targetPath.lastIndexOf('/');
        if (targetBaseLength >= fldr.length()) {
            // fldr is "inbox/subfolder"
            fldr = "";
        } else if (targetBaseLength > 0) {
            // fldr is "inbox/subfolder/target"
            fldr = fldr.substring(targetBaseLength + 1);
        }
    }
    try {
        ArchiveOutputEntry aoe;
        byte[] data = null;
        String path = mi instanceof Contact ? getEntryName(mi, fldr, name, ext, charsetEncoder, names) : getEntryName(mi, fldr, name, ext, charsetEncoder, !(mi instanceof Document));
        long miSize = mi.getSize();
        if (miSize == 0 && mi.getDigest() != null) {
            ZimbraLog.misc.debug("blob db size 0 for item %d", mi.getId());
            return aos;
        }
        try {
            is = mi.getContentStream();
        } catch (Exception e) {
            ZimbraLog.misc.error("missing blob for item %d: expected %d", mi.getId(), miSize);
            return aos;
        }
        if (aos == null) {
            aos = getOutputStream(context, charsetEncoder.charset().name());
        }
        if ((mi instanceof CalendarItem) && (context.getStartTime() != TIME_UNSPECIFIED || context.getEndTime() != TIME_UNSPECIFIED)) {
            Collection<Instance> instances = ((CalendarItem) mi).expandInstances(context.getStartTime(), context.getEndTime(), false);
            if (instances.isEmpty()) {
                return aos;
            }
        }
        aoe = aos.newOutputEntry(path + ".meta", mi.getType().toString(), mi.getType().toByte(), mi.getDate());
        if (mi instanceof Message && (mi.getFlagBitmask() & Flag.ID_UNREAD) != 0) {
            aoe.setUnread();
        }
        if (meta) {
            ItemData itemData = new ItemData(mi, extra);
            if (context.noHierarchy()) {
                // itemData.path is of the form /Inbox/subfolder/target and after this step it becomes /target.
                if (targetBaseLength > 0 && ((targetBaseLength + 1) < itemData.path.length())) {
                    itemData.path = itemData.path.substring(targetBaseLength + 1);
                }
            }
            byte[] metaData = itemData.encode();
            aoe.setSize(metaData.length);
            aos.putNextEntry(aoe);
            aos.write(metaData);
            aos.closeEntry();
        } else if (mi instanceof CalendarItem) {
            Browser browser = HttpUtil.guessBrowser(context.req);
            List<CalendarItem> calItems = new ArrayList<CalendarItem>();
            boolean needAppleICalHacks = Browser.APPLE_ICAL.equals(browser);
            boolean useOutlookCompatMode = Browser.IE.equals(browser);
            OperationContext octxt = new OperationContext(context.getAuthAccount(), context.isUsingAdminPrivileges());
            StringWriter writer = new StringWriter();
            calItems.add((CalendarItem) mi);
            context.targetMailbox.writeICalendarForCalendarItems(writer, octxt, calItems, useOutlookCompatMode, true, needAppleICalHacks, true);
            data = writer.toString().getBytes(charsetEncoder.charset());
        } else if (mi instanceof Contact) {
            VCard vcf = VCard.formatContact((Contact) mi);
            data = vcf.getFormatted().getBytes(charsetEncoder.charset());
        } else if (mi instanceof Message) {
            if (context.hasPart()) {
                MimeMessage mm = ((Message) mi).getMimeMessage();
                Set<String> attachmentNames = new HashSet<String>();
                for (String part : context.getPart().split(",")) {
                    BufferStream bs;
                    MimePart mp = Mime.getMimePart(mm, part);
                    long sz;
                    if (mp == null) {
                        throw MailServiceException.NO_SUCH_PART(part);
                    }
                    name = Mime.getFilename(mp);
                    ext = null;
                    sz = mp.getSize();
                    if (sz == -1) {
                        sz = miSize;
                    }
                    if (name == null) {
                        name = "attachment";
                    } else {
                        int dot = name.lastIndexOf('.');
                        if (dot != -1 && dot < name.length() - 1) {
                            ext = name.substring(dot + 1);
                            name = name.substring(0, dot);
                        }
                    }
                    bs = new BufferStream(sz, 1024 * 1024);
                    InputStream stream = mp.getInputStream();
                    try {
                        bs.readFrom(stream);
                    } finally {
                        // close the stream, it could be an instance of PipedInputStream.
                        ByteUtil.closeStream(stream);
                    }
                    aoe = aos.newOutputEntry(getEntryName(mi, "", name, ext, charsetEncoder, attachmentNames), mi.getType().toString(), mi.getType().toByte(), mi.getDate());
                    sz = bs.getSize();
                    aoe.setSize(sz);
                    aos.putNextEntry(aoe);
                    bs.copyTo(aos.getOutputStream());
                    bs.close();
                    aos.closeEntry();
                }
                return aos;
            }
        }
        aoe = aos.newOutputEntry(path, mi.getType().toString(), mi.getType().toByte(), mi.getDate());
        if (data != null) {
            aoe.setSize(data.length);
            aos.putNextEntry(aoe);
            aos.write(data);
            aos.closeEntry();
        } else if (is != null) {
            if (context.shouldReturnBody()) {
                byte[] buf = new byte[aos.getRecordSize() * 20];
                int in;
                long remain = miSize;
                aoe.setSize(miSize);
                aos.putNextEntry(aoe);
                while (remain > 0 && (in = is.read(buf)) >= 0) {
                    aos.write(buf, 0, remain < in ? (int) remain : in);
                    remain -= in;
                }
                if (remain != 0) {
                    ZimbraLog.misc.error("mismatched blob size for item %d: expected %d", mi.getId(), miSize);
                    if (remain > 0) {
                        Arrays.fill(buf, (byte) ' ');
                        while (remain > 0) {
                            aos.write(buf, 0, remain < buf.length ? (int) remain : buf.length);
                            remain -= buf.length;
                        }
                    }
                    aos.closeEntry();
                    aoe = aos.newOutputEntry(path + ".err", mi.getType().toString(), mi.getType().toByte(), mi.getDate());
                    aoe.setSize(0);
                    aos.putNextEntry(aoe);
                }
            } else {
                // Read headers into memory to compute size
                byte[] headerData = HeadersOnlyInputStream.getHeaders(is);
                aoe.setSize(headerData.length);
                aos.putNextEntry(aoe);
                aos.write(headerData);
            }
            aos.closeEntry();
        }
    } catch (Exception e) {
        throw ServiceException.FAILURE("archive error", e);
    } finally {
        ByteUtil.closeStream(is);
    }
    return aos;
}
Also used : Appointment(com.zimbra.cs.mailbox.Appointment) Task(com.zimbra.cs.mailbox.Task) EnumSet(java.util.EnumSet) Set(java.util.Set) HashSet(java.util.HashSet) MimeMessage(javax.mail.internet.MimeMessage) ParsedMessage(com.zimbra.cs.mime.ParsedMessage) Message(com.zimbra.cs.mailbox.Message) Instance(com.zimbra.cs.mailbox.CalendarItem.Instance) SearchFolder(com.zimbra.cs.mailbox.SearchFolder) Folder(com.zimbra.cs.mailbox.Folder) Document(com.zimbra.cs.mailbox.Document) ItemId(com.zimbra.cs.service.util.ItemId) CalendarItemInfo(com.zimbra.cs.mailbox.Message.CalendarItemInfo) CalendarItem(com.zimbra.cs.mailbox.CalendarItem) StringWriter(java.io.StringWriter) MimeMessage(javax.mail.internet.MimeMessage) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) OperationContext(com.zimbra.cs.mailbox.OperationContext) InputStream(java.io.InputStream) Mountpoint(com.zimbra.cs.mailbox.Mountpoint) NoSuchItemException(com.zimbra.cs.mailbox.MailServiceException.NoSuchItemException) ExportPeriodNotSpecifiedException(com.zimbra.cs.mailbox.MailServiceException.ExportPeriodNotSpecifiedException) ServiceException(com.zimbra.common.service.ServiceException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) MailServiceException(com.zimbra.cs.mailbox.MailServiceException) ExportPeriodTooLongException(com.zimbra.cs.mailbox.MailServiceException.ExportPeriodTooLongException) UserServletException(com.zimbra.cs.service.UserServletException) ParsedContact(com.zimbra.cs.mime.ParsedContact) Contact(com.zimbra.cs.mailbox.Contact) BufferStream(com.zimbra.common.util.BufferStream) MailItem(com.zimbra.cs.mailbox.MailItem) MimePart(javax.mail.internet.MimePart) SetCalendarItemData(com.zimbra.cs.mailbox.Mailbox.SetCalendarItemData) ItemData(com.zimbra.cs.service.util.ItemData) Browser(com.zimbra.common.util.HttpUtil.Browser)

Example 2 with CalendarItemInfo

use of com.zimbra.cs.mailbox.Message.CalendarItemInfo in project zm-mailbox by Zimbra.

the class ForwardAppointmentInvite method getMessagePair.

public static Pair<MimeMessage, MimeMessage> getMessagePair(Mailbox mbox, Account senderAcct, Message msg, MimeMessage mmFwdWrapper) throws ServiceException {
    Pair<MimeMessage, MimeMessage> msgPair;
    mbox.lock.lock();
    try {
        MimeMessage mmInv = msg.getMimeMessage();
        List<Invite> invs = new ArrayList<Invite>();
        for (Iterator<CalendarItemInfo> iter = msg.getCalendarItemInfoIterator(); iter.hasNext(); ) {
            CalendarItemInfo cii = iter.next();
            Invite inv = cii.getInvite();
            if (inv != null) {
                invs.add(inv);
            }
        }
        ZVCalendar cal = null;
        Invite firstInv = null;
        if (!invs.isEmpty()) {
            // Recreate the VCALENDAR from Invites.
            boolean first = true;
            for (Invite inv : invs) {
                if (first) {
                    first = false;
                    firstInv = inv;
                    cal = inv.newToICalendar(true);
                } else {
                    ZComponent comp = inv.newToVComponent(true, true);
                    cal.addComponent(comp);
                }
            }
        } else {
            // If no invites found in metadata, parse from text/calendar MIME part.
            try {
                CalPartDetectVisitor visitor = new CalPartDetectVisitor();
                visitor.accept(mmInv);
                MimeBodyPart calPart = visitor.getCalendarPart();
                if (calPart != null) {
                    String ctHdr = calPart.getContentType();
                    ContentType ct = new ContentType(ctHdr);
                    String charset = ct.getParameter(MimeConstants.P_CHARSET);
                    if (charset == null || charset.length() == 0)
                        charset = MimeConstants.P_CHARSET_UTF8;
                    InputStream is = calPart.getInputStream();
                    try {
                        cal = ZCalendarBuilder.build(is, charset);
                    } finally {
                        ByteUtil.closeStream(is);
                    }
                    List<Invite> invList = Invite.createFromCalendar(senderAcct, msg.getFragment(), cal, false);
                    if (invList != null && !invList.isEmpty())
                        firstInv = invList.get(0);
                    if (firstInv == null)
                        throw ServiceException.FAILURE("Error building Invite for calendar part in message " + msg.getId(), null);
                }
            } catch (MessagingException e) {
                throw ServiceException.FAILURE("Error getting calendar part in message " + msg.getId(), null);
            } catch (IOException e) {
                throw ServiceException.FAILURE("Error getting calendar part in message " + msg.getId(), null);
            }
        }
        msgPair = getInstanceFwdMsg(senderAcct, firstInv, cal, mmInv, mmFwdWrapper);
    } finally {
        mbox.lock.release();
    }
    return msgPair;
}
Also used : ContentType(javax.mail.internet.ContentType) MessagingException(javax.mail.MessagingException) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) IOException(java.io.IOException) CalendarItemInfo(com.zimbra.cs.mailbox.Message.CalendarItemInfo) ZComponent(com.zimbra.common.calendar.ZCalendar.ZComponent) ZVCalendar(com.zimbra.common.calendar.ZCalendar.ZVCalendar) MimeMessage(javax.mail.internet.MimeMessage) MimeBodyPart(javax.mail.internet.MimeBodyPart) Invite(com.zimbra.cs.mailbox.calendar.Invite)

Aggregations

CalendarItemInfo (com.zimbra.cs.mailbox.Message.CalendarItemInfo)2 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 ArrayList (java.util.ArrayList)2 MimeMessage (javax.mail.internet.MimeMessage)2 ZComponent (com.zimbra.common.calendar.ZCalendar.ZComponent)1 ZVCalendar (com.zimbra.common.calendar.ZCalendar.ZVCalendar)1 ServiceException (com.zimbra.common.service.ServiceException)1 BufferStream (com.zimbra.common.util.BufferStream)1 Browser (com.zimbra.common.util.HttpUtil.Browser)1 Appointment (com.zimbra.cs.mailbox.Appointment)1 CalendarItem (com.zimbra.cs.mailbox.CalendarItem)1 Instance (com.zimbra.cs.mailbox.CalendarItem.Instance)1 Contact (com.zimbra.cs.mailbox.Contact)1 Document (com.zimbra.cs.mailbox.Document)1 Folder (com.zimbra.cs.mailbox.Folder)1 MailItem (com.zimbra.cs.mailbox.MailItem)1 MailServiceException (com.zimbra.cs.mailbox.MailServiceException)1 ExportPeriodNotSpecifiedException (com.zimbra.cs.mailbox.MailServiceException.ExportPeriodNotSpecifiedException)1 ExportPeriodTooLongException (com.zimbra.cs.mailbox.MailServiceException.ExportPeriodTooLongException)1