Subversion Repositories basico

Rev

Rev 356 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
# File: srv_attach.py
# Author: Tomás Vírseda
# License: GPL v3
# Description: Attachment service
"""


import os
import json
import uuid
import glob
from os.path import sep as SEP

from basico.core.mod_env import FILE, LPATH
from basico.core.mod_srv import Service


class Attachment(Service):
    def initialize(self):
        '''
        Setup Attachment Service
        '''

        self.get_services()


    def get_services(self):
        self.srvutl = self.get_service('Utils')


    def gen_aid(self, sid):
        '''
        Generate new attachment id (same as for annotations)
        '''

        return "%s@%s" % (sid, str(uuid.uuid4()))


    def create(self, path, metadata):
        ATTACHMENT_FILE_METADATA = LPATH['ATTACHMENTS'] + attachment['AID'] + '.json'
        ATTACHMENT_FILE_CONTENT = LPATH['ATTACHMENTS'] + attachment['AID'] # No extension needed
        attachment['Created'] = self.srvutl.timestamp()

        # copy attachment file to attachemnts database
        shutil.copy(path, ATTACHMENT_FILE_CONTENT)

        # Write attachment metadata
        with open(ATTACHMENT_FILE_METADATA, 'w') as fa:
            json.dump(metadata, fa)

        title = self.get_title(attachment['AID'])
        self.log.info("Attachment '%s' (%s) created" % (title, attachment['AID']))


    def delete(self, aid):
        sid = self.get_sid(aid)
        ATTACHMENT_FILE_METADATA = LPATH['ATTACHMENTS'] + aid + '.json'
        ATTACHMENT_FILE_CONTENT = LPATH['ATTACHMENTS'] + aid
        title = self.get_title(aid)

        if os.path.exists(ATTACHMENT_FILE_METADATA):
            os.unlink(ATTACHMENT_FILE_METADATA)

        if os.path.exists(ATTACHMENT_FILE_CONTENT):
            os.unlink(ATTACHMENT_FILE_CONTENT)

        self.log.info("Attachment '%s' (%s) deleted" % (title, aid))


    def get_by_sid(self, sid):
        ATTACHMENT_FILES = LPATH['ATTACHMENTS'] + '%s*.json' % sid
        attachments = glob.glob(ATTACHMENT_FILES)
        attachments.sort(reverse=True)

        return attachments


    def get_all(self):
        return glob.glob(LPATH['ATTACHMENTS'] + '*.json')


    def get_total(self):
        return len(self.get_all())


    def get_sid(self, aid):
        if '@' in aid:
            return aid[:aid.find('@')]
        else:
            return aid # aid = sid


    def get_metadata_from_aid(self, aid=None):
        if aid is not None:
            ATTACHMENT_FILE_METADATA = LPATH['ATTACHMENTS'] + aid + '.json'
            with open(ATTACHMENT_FILE_METADATA, 'r') as fa:
                attachment = json.load(fa)
            return attachment
        else:
            return None


    def get_metadata_from_file(self, filename=None):
        if filename is not None:
            if os.path.exists(filename):
                with open(filename, 'r') as fa:
                    metadata = json.load(fa)
                return metadata
            else:
                return None


    def is_valid(self, aid):
        ATTACHMENT_FILE_METADATA = LPATH['ATTACHMENTS'] + aid + '.json'
        ATTACHMENT_FILE_CONTENT = LPATH['ATTACHMENTS'] + aid
        ATTACHMENT_FILE = LPATH['ATTACHMENTS'] + aid + '.json'
        valid = os.path.exists(ATTACHMENT_FILE_METADATA) and os.path.exist(ATTACHMENT_FILE_CONTENT)
        if valid is False:
            self.log.debug("Attachment %s is not valid or it doesn't exist yet." % aid)

        return valid


    def get_title(self, aid):
        ATTACHMENT_FILE = LPATH['ATTACHMENTS'] + aid + '.json'
        with open(ATTACHMENT_FILE, 'r') as fa:
            metadata = json.load(fa)
            return metadata['Title']


    def search_term(self, term):
        matches = set()
        attachments = self.get_all()

        for fname in attachments:
            # search only in title
            with open(fname, 'r') as fa:
                try:
                    attachment = json.load(fa)
                    text = attachment['Title']
                    if term.upper() in text.upper():
                        # ~ self.log.debug("Found '%s' in '%s'", term, text)
                        matches.add(fname)
                except Exception as error:
                    self.log.error("%s: %s", fname, error)

            # SEARCH IN ALL PROPERTIES (DISABLED)
            # ~ with open(fname, 'r') as fa:
                # ~ try:
                    # ~ attachment = json.load(fa)
                    # ~ text = ''
                    # ~ for node in attachment:
                        # ~ text += attachment[node]
                    # ~ if term.upper() in text.upper():
                        # ~ self.log.debug("Found '%s' in '%s'", term, text)
                        # ~ matches.add(fname)
                # ~ except Exception as error:
                    # ~ self.log.error("%s: %s", fname, error)

            # SEARCH IN CONTENT (DISABLED)
            # ~ fcontent = fname.replace('.json', '.adoc')
            # ~ text = open(fcontent, 'r').read()
            # ~ if term.upper() in text.upper():
                # ~ matches.add(fname)

        return matches


    def finalize(self):
        pass