Edgewall Software

Ticket #7078: trac-10.4-get-attachments-as-zipfile.patch

File trac-10.4-get-attachments-as-zipfile.patch, 2.5 KB (added by mark@…, 4 years ago)
  • templates/macros.cs

     
    185190  /each ?></dl><?cs 
    186191 /if ?><?cs 
    187192 if:attach_href ?> 
    188   <form method="get" action="<?cs var:attach_href ?>"><div> 
     193  <form method="get" action="<?cs var:attach_href ?>" style="display:inline;"> 
    189194   <input type="hidden" name="action" value="new" /> 
    190195   <input type="submit" value="Attach File" /> 
    191   </div></form><?cs 
     196  </form>  <form method="get" action="<?cs var:attach_href ?>" style="display:inline;"> 
     197   <input type="hidden" name="action" value="getzip" /> 
     198   <input type="submit" value="Save all as ZIP-file" /> 
     199  </form><?cs 
    192200 /if ?><?cs if:len(attachments) ?></div><?cs /if ?><?cs 
    193201/def ?><?cs 
    194202 
  • trac/attachment.py

     
    2121import shutil 
    2222import time 
    2323import unicodedata 
     24import zipfile 
     25import tempfile 
    2426 
    2527from trac import perm, util 
    2628from trac.config import BoolOption, IntOption 
     
    343345        action = req.args.get('action', 'view') 
    344346        if action == 'new': 
    345347            attachment = Attachment(self.env, parent_type, path) 
     348        elif action == 'getzip': 
     349            segments = path.split('/') 
     350            parent_id = '/'.join(segments[:-1]) 
     351            last_segment = segments[-1] 
     352            if len(segments) == 1:     
     353                self._do_getzip(req, parent_type, last_segment) 
     354                return 'attachment.cs', None 
    346355        else: 
    347356            segments = path.split('/') 
    348357            parent_id = '/'.join(segments[:-1]) 
     
    434443 
    435444    # Internal methods 
    436445 
     446    def _do_getzip(self, req, p_type, p_id): 
     447        db = self.env.get_db_cnx() 
     448 
     449        zfname = 'Ticket%s.zip' % p_id 
     450 
     451        zfpath = os.path.join(tempfile.gettempdir(), zfname) 
     452 
     453        zf = zipfile.ZipFile(zfpath, 'w') 
     454        for attachment in Attachment.select(self.env, p_type, p_id, db): 
     455            zf.write(attachment.path, attachment.filename.encode('ascii')) 
     456        zf.close() 
     457 
     458        req.send_header('Content-Disposition', 'attachment; filename=%s' % zfname) 
     459        mime_type = 'application/octet-stream' 
     460         
     461        req.send_file(zfpath, mime_type) 
     462         
     463        os.remove(zfpath) 
     464 
    437465    def _do_save(self, req, attachment): 
    438466        perm_map = {'ticket': 'TICKET_APPEND', 'wiki': 'WIKI_MODIFY'} 
    439467        req.perm.assert_permission(perm_map[attachment.parent_type])