Completed
Pull Request — master (#355)
by
unknown
02:32
created

elodie.media.media.Media.get_exiftool_attributes()   A

Complexity

Conditions 3

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 7
nop 1
dl 0
loc 15
rs 10
c 0
b 0
f 0
1
"""
2
The media module provides a base :class:`Media` class for media objects that
3
are tracked by Elodie. The Media class provides some base functionality used
4
by all the media types, but isn't itself used to represent anything. Its
5
sub-classes (:class:`~elodie.media.audio.Audio`,
6
:class:`~elodie.media.photo.Photo`, and :class:`~elodie.media.video.Video`)
7
are used to represent the actual files.
8
9
.. moduleauthor:: Jaisen Mathai <[email protected]>
10
"""
11
from __future__ import print_function
12
13
import os
14
15
# load modules
16
from elodie.external.pyexiftool import ExifTool
17
from elodie.media.base import Base
18
19
class Media(Base):
20
21
    """The base class for all media objects.
22
23
    :param str source: The fully qualified path to the video file.
24
    """
25
26
    __name__ = 'Media'
27
28
    d_coordinates = {
29
        'latitude': 'latitude_ref',
30
        'longitude': 'longitude_ref'
31
    }
32
33
    def __init__(self, source=None):
34
        super(Media, self).__init__(source)
35
        self.exif_map = {
36
            'date_taken': [
37
                'EXIF:DateTimeOriginal',
38
                'EXIF:CreateDate',
39
                'EXIF:ModifyDate'
40
            ]
41
        }
42
        self.camera_make_keys = ['EXIF:Make', 'QuickTime:Make']
43
        self.camera_model_keys = ['EXIF:Model', 'QuickTime:Model']
44
        self.album_keys = ['XMP-xmpDM:Album', 'XMP:Album']
45
        self.title_key = 'XMP:Title'
46
        self.latitude_keys = ['EXIF:GPSLatitude']
47
        self.longitude_keys = ['EXIF:GPSLongitude']
48
        self.latitude_ref_key = 'EXIF:GPSLatitudeRef'
49
        self.longitude_ref_key = 'EXIF:GPSLongitudeRef'
50
        self.original_name_key = 'XMP:OriginalFileName'
51
        self.set_gps_ref = True
52
        self.exif_metadata = None
53
54
    def get_album(self):
55
        """Get album from EXIF
56
57
        :returns: None or string
58
        """
59
        if(not self.is_valid()):
60
            return None
61
62
        exiftool_attributes = self.get_exiftool_attributes()
63
        if exiftool_attributes is None:
64
            return None
65
66
        for album_key in self.album_keys:
67
            if album_key in exiftool_attributes:
68
                return exiftool_attributes[album_key]
69
70
        return None
71
72
    def get_coordinate(self, type='latitude'):
73
        """Get latitude or longitude of media from EXIF
74
75
        :param str type: Type of coordinate to get. Either "latitude" or
76
            "longitude".
77
        :returns: float or None if not present in EXIF or a non-photo file
78
        """
79
80
        exif = self.get_exiftool_attributes()
81
        if not exif:
82
            return None
83
84
        # The lat/lon _keys array has an order of precedence.
85
        # The first key is writable and we will give the writable
86
        #   key precence when reading.
87
        direction_multiplier = 1.0
88
        for key in self.latitude_keys + self.longitude_keys:
89
            if key not in exif:
90
                continue
91
92
            # Assign coordinate to variable
93
            this_coordinate = exif[key]
94
95
            # If exiftool GPS output is empty, the data returned will be a str
96
            # with 0 length.
97
            # https://github.com/jmathai/elodie/issues/354
98
            if len(this_coordinate) == 0:
99
                continue
100
101
            # Cast coordinate to a float due to a bug in exiftool's
102
            #   -json output format.
103
            # https://github.com/jmathai/elodie/issues/171
104
            # http://u88.n24.queensu.ca/exiftool/forum/index.php/topic,7952.0.html  # noqa
105
            if not isinstance(this_coordinate, float):
106
                this_coordinate = float(this_coordinate)
107
108
            # TODO: verify that we need to check ref key
109
            #   when self.set_gps_ref != True
110
            if type == 'latitude' and key in self.latitude_keys:
111
                if self.latitude_ref_key in exif and \
112
                        exif[self.latitude_ref_key] == 'S':
113
                    direction_multiplier = -1.0
114
                return this_coordinate * direction_multiplier
115
            elif type == 'longitude' and key in self.longitude_keys:
116
                if self.longitude_ref_key in exif and \
117
                        exif[self.longitude_ref_key] == 'W':
118
                    direction_multiplier = -1.0
119
                return this_coordinate * direction_multiplier
120
121
        return None
122
123
    def get_exiftool_attributes(self):
124
        """Get attributes for the media object from exiftool.
125
126
        :returns: dict, or False if exiftool was not available.
127
        """
128
        source = self.source
129
130
        #Cache exif metadata results and use if already exists for media
131
        if(self.exif_metadata is None):
132
            self.exif_metadata = ExifTool().get_metadata(source)
133
134
        if not self.exif_metadata:
135
            return False
136
137
        return self.exif_metadata
138
139
    def get_camera_make(self):
140
        """Get the camera make stored in EXIF.
141
142
        :returns: str
143
        """
144
        if(not self.is_valid()):
145
            return None
146
147
        exiftool_attributes = self.get_exiftool_attributes()
148
149
        if exiftool_attributes is None:
150
            return None
151
152
        for camera_make_key in self.camera_make_keys:
153
            if camera_make_key in exiftool_attributes:
154
                return exiftool_attributes[camera_make_key]
155
156
        return None
157
158
    def get_camera_model(self):
159
        """Get the camera make stored in EXIF.
160
161
        :returns: str
162
        """
163
        if(not self.is_valid()):
164
            return None
165
166
        exiftool_attributes = self.get_exiftool_attributes()
167
168
        if exiftool_attributes is None:
169
            return None
170
171
        for camera_model_key in self.camera_model_keys:
172
            if camera_model_key in exiftool_attributes:
173
                return exiftool_attributes[camera_model_key]
174
175
        return None
176
177
    def get_original_name(self):
178
        """Get the original name stored in EXIF.
179
180
        :returns: str
181
        """
182
        if(not self.is_valid()):
183
            return None
184
185
        exiftool_attributes = self.get_exiftool_attributes()
186
187
        if exiftool_attributes is None:
188
            return None
189
190
        if(self.original_name_key not in exiftool_attributes):
191
            return None
192
193
        return exiftool_attributes[self.original_name_key]
194
195
    def get_title(self):
196
        """Get the title for a photo of video
197
198
        :returns: str or None if no title is set or not a valid media type
199
        """
200
        if(not self.is_valid()):
201
            return None
202
203
        exiftool_attributes = self.get_exiftool_attributes()
204
205
        if exiftool_attributes is None:
206
            return None
207
208
        if(self.title_key not in exiftool_attributes):
209
            return None
210
211
        return exiftool_attributes[self.title_key]
212
213
    def reset_cache(self):
214
        """Resets any internal cache
215
        """
216
        self.exiftool_attributes = None
217
        self.exif_metadata = None
218
        super(Media, self).reset_cache()
219
220
    def set_album(self, album):
221
        """Set album for a photo
222
223
        :param str name: Name of album
224
        :returns: bool
225
        """
226
        if(not self.is_valid()):
227
            return None
228
229
        tags = {self.album_keys[0]: album}
230
        status = self.__set_tags(tags)
231
        self.reset_cache()
232
233
        return status
234
235
    def set_date_taken(self, time):
236
        """Set the date/time a photo was taken.
237
238
        :param datetime time: datetime object of when the photo was taken
239
        :returns: bool
240
        """
241
        if(time is None):
242
            return False
243
244
        tags = {}
245
        formatted_time = time.strftime('%Y:%m:%d %H:%M:%S')
246
        for key in self.exif_map['date_taken']:
247
            tags[key] = formatted_time
248
249
        status = self.__set_tags(tags)
250
        self.reset_cache()
251
        return status
252
253
    def set_location(self, latitude, longitude):
254
        if(not self.is_valid()):
255
            return None
256
257
        # The lat/lon _keys array has an order of precedence.
258
        # The first key is writable and we will give the writable
259
        #   key precence when reading.
260
        tags = {
261
            self.latitude_keys[0]: latitude,
262
            self.longitude_keys[0]: longitude,
263
        }
264
265
        # If self.set_gps_ref == True then it means we are writing an EXIF
266
        #   GPS tag which requires us to set the reference key.
267
        # That's because the lat/lon are absolute values.
268
        if self.set_gps_ref:
269
            if latitude < 0:
270
                tags[self.latitude_ref_key] = 'S'
271
272
            if longitude < 0:
273
                tags[self.longitude_ref_key] = 'W'
274
275
        status = self.__set_tags(tags)
276
        self.reset_cache()
277
278
        return status
279
280
    def set_original_name(self, name=None):
281
        """Sets the original name EXIF tag if not already set.
282
283
        :returns: True, False, None
284
        """
285
        if(not self.is_valid()):
286
            return None
287
288
        # If EXIF original name tag is set then we return.
289
        if self.get_original_name() is not None:
290
            return None
291
292
        source = self.source
293
294
        if not name:
295
            name = os.path.basename(source)
296
297
        tags = {self.original_name_key: name}
298
        status = self.__set_tags(tags)
299
        self.reset_cache()
300
        return status
301
302
    def set_title(self, title):
303
        """Set title for a photo.
304
305
        :param str title: Title of the photo.
306
        :returns: bool
307
        """
308
        if(not self.is_valid()):
309
            return None
310
311
        if(title is None):
312
            return None
313
314
        tags = {self.title_key: title}
315
        status = self.__set_tags(tags)
316
        self.reset_cache()
317
318
        return status
319
320
    def __set_tags(self, tags):
321
        if(not self.is_valid()):
322
            return None
323
324
        source = self.source
325
326
        status = ''
327
        status = ExifTool().set_tags(tags,source)
328
329
        return status != ''
330