Subversion Repositories basico

Rev

Rev 360 | Rev 368 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
355 t00mlabs 1
#!/usr/bin/python
2
# -*- coding: utf-8 -*-
3
"""
4
# File: srv_attach.py
5
# Author: Tomás Vírseda
6
# License: GPL v3
7
# Description: Attachment service
8
"""
9
 
10
import os
11
import json
12
import uuid
13
import glob
356 t00mlabs 14
import shutil
355 t00mlabs 15
from os.path import sep as SEP
16
 
17
from basico.core.mod_env import FILE, LPATH
18
from basico.core.mod_srv import Service
19
 
20
 
21
class Attachment(Service):
22
    def initialize(self):
23
        '''
24
        Setup Attachment Service
25
        '''
26
        self.get_services()
27
 
28
 
29
    def get_services(self):
30
        self.srvutl = self.get_service('Utils')
31
 
32
 
356 t00mlabs 33
    def gen_tid(self, sid='000000000'):
355 t00mlabs 34
        '''
35
        Generate new attachment id (same as for annotations)
36
        '''
356 t00mlabs 37
        return "%s@T%s" % (sid, str(uuid.uuid4()))
355 t00mlabs 38
 
39
 
358 t00mlabs 40
    def create(self, path, aid):
356 t00mlabs 41
        sid = self.get_sid(aid)
42
        tid = self.gen_tid(sid)
43
        metadata = self.srvutl.get_file_metadata(path)
44
        metadata['AID'] = aid
45
        metadata['TID'] = tid
46
        metadata['Source'] = path
47
        metadata['Created'] = self.srvutl.timestamp()
358 t00mlabs 48
        self.log.debug("\tAID: %s", aid)
49
        self.log.debug("\tTID: %s", tid)
50
        self.log.debug("\tPath: %s", path)
51
        self.log.debug("\tCreated: %s", metadata['Created'])
356 t00mlabs 52
        ATTACHMENT_FILE_METADATA = LPATH['ATTACHMENTS'] + tid + '.json'
53
        ATTACHMENT_FILE_CONTENT = LPATH['ATTACHMENTS'] + tid # No extension needed
54
 
355 t00mlabs 55
        # copy attachment file to attachemnts database
56
        shutil.copy(path, ATTACHMENT_FILE_CONTENT)
57
 
58
        # Write attachment metadata
59
        with open(ATTACHMENT_FILE_METADATA, 'w') as fa:
60
            json.dump(metadata, fa)
61
 
356 t00mlabs 62
        self.log.info("Attachment '%s' (%s) created" % (metadata['Title'], metadata['TID']))
355 t00mlabs 63
 
360 t00mlabs 64
        return tid
65
 
355 t00mlabs 66
 
67
    def delete(self, aid):
68
        sid = self.get_sid(aid)
69
        ATTACHMENT_FILE_METADATA = LPATH['ATTACHMENTS'] + aid + '.json'
70
        ATTACHMENT_FILE_CONTENT = LPATH['ATTACHMENTS'] + aid
71
        title = self.get_title(aid)
72
 
73
        if os.path.exists(ATTACHMENT_FILE_METADATA):
74
            os.unlink(ATTACHMENT_FILE_METADATA)
75
 
76
        if os.path.exists(ATTACHMENT_FILE_CONTENT):
77
            os.unlink(ATTACHMENT_FILE_CONTENT)
78
 
79
        self.log.info("Attachment '%s' (%s) deleted" % (title, aid))
80
 
81
 
82
    def get_by_sid(self, sid):
361 t00mlabs 83
        matches = set()
84
        ATTACHMENT_FILES = LPATH['ATTACHMENTS'] + '*.json'
85
        attachments = glob.glob(ATTACHMENT_FILES)        
86
        for attachment in attachments:
87
            if sid in attachment:
88
                matches.add(attachment)
89
        # ~ self.log.debug("Attachments for SAP Note %s: %s", sid, matches)
90
        return matches
355 t00mlabs 91
 
92
 
93
    def get_all(self):
94
        return glob.glob(LPATH['ATTACHMENTS'] + '*.json')
95
 
96
 
97
    def get_total(self):
98
        return len(self.get_all())
99
 
100
 
101
    def get_sid(self, aid):
102
        if '@' in aid:
103
            return aid[:aid.find('@')]
104
        else:
356 t00mlabs 105
            return '0000000000'
355 t00mlabs 106
 
107
 
108
    def get_metadata_from_aid(self, aid=None):
109
        if aid is not None:
110
            ATTACHMENT_FILE_METADATA = LPATH['ATTACHMENTS'] + aid + '.json'
111
            with open(ATTACHMENT_FILE_METADATA, 'r') as fa:
112
                attachment = json.load(fa)
113
            return attachment
114
        else:
115
            return None
116
 
117
 
118
    def get_metadata_from_file(self, filename=None):
119
        if filename is not None:
120
            if os.path.exists(filename):
121
                with open(filename, 'r') as fa:
122
                    metadata = json.load(fa)
123
                return metadata
124
            else:
125
                return None
126
 
127
 
128
    def is_valid(self, aid):
129
        ATTACHMENT_FILE_METADATA = LPATH['ATTACHMENTS'] + aid + '.json'
130
        ATTACHMENT_FILE_CONTENT = LPATH['ATTACHMENTS'] + aid
131
        ATTACHMENT_FILE = LPATH['ATTACHMENTS'] + aid + '.json'
132
        valid = os.path.exists(ATTACHMENT_FILE_METADATA) and os.path.exist(ATTACHMENT_FILE_CONTENT)
133
        if valid is False:
134
            self.log.debug("Attachment %s is not valid or it doesn't exist yet." % aid)
135
 
136
        return valid
137
 
138
 
139
    def get_title(self, aid):
140
        ATTACHMENT_FILE = LPATH['ATTACHMENTS'] + aid + '.json'
141
        with open(ATTACHMENT_FILE, 'r') as fa:
142
            metadata = json.load(fa)
143
            return metadata['Title']
144
 
145
 
146
    def search_term(self, term):
147
        matches = set()
148
        attachments = self.get_all()
149
 
150
        for fname in attachments:
151
            # search only in title
152
            with open(fname, 'r') as fa:
153
                try:
154
                    attachment = json.load(fa)
155
                    text = attachment['Title']
156
                    if term.upper() in text.upper():
157
                        # ~ self.log.debug("Found '%s' in '%s'", term, text)
158
                        matches.add(fname)
159
                except Exception as error:
160
                    self.log.error("%s: %s", fname, error)
161
 
162
            # SEARCH IN ALL PROPERTIES (DISABLED)
163
            # ~ with open(fname, 'r') as fa:
164
                # ~ try:
165
                    # ~ attachment = json.load(fa)
166
                    # ~ text = ''
167
                    # ~ for node in attachment:
168
                        # ~ text += attachment[node]
169
                    # ~ if term.upper() in text.upper():
170
                        # ~ self.log.debug("Found '%s' in '%s'", term, text)
171
                        # ~ matches.add(fname)
172
                # ~ except Exception as error:
173
                    # ~ self.log.error("%s: %s", fname, error)
174
 
175
            # SEARCH IN CONTENT (DISABLED)
176
            # ~ fcontent = fname.replace('.json', '.adoc')
177
            # ~ text = open(fcontent, 'r').read()
178
            # ~ if term.upper() in text.upper():
179
                # ~ matches.add(fname)
180
 
181
        return matches
182
 
183
 
184
    def finalize(self):
185
        pass
186