Completed
Pull Request — master (#352)
by
unknown
01:56
created

elodie.media.media.Media.set_original_name()   A

Complexity

Conditions 4

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 12
nop 2
dl 0
loc 21
rs 9.8
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
            # Cast coordinate to a float due to a bug in exiftool's
93
            #   -json output format.
94
            # https://github.com/jmathai/elodie/issues/171
95
            # http://u88.n24.queensu.ca/exiftool/forum/index.php/topic,7952.0.html  # noqa
96
            this_coordinate = float(exif[key])
97
98
            # TODO: verify that we need to check ref key
99
            #   when self.set_gps_ref != True
100
            if type == 'latitude' and key in self.latitude_keys:
101
                if self.latitude_ref_key in exif and \
102
                        exif[self.latitude_ref_key] == 'S':
103
                    direction_multiplier = -1.0
104
                return this_coordinate * direction_multiplier
105
            elif type == 'longitude' and key in self.longitude_keys:
106
                if self.longitude_ref_key in exif and \
107
                        exif[self.longitude_ref_key] == 'W':
108
                    direction_multiplier = -1.0
109
                return this_coordinate * direction_multiplier
110
111
        return None
112
113
    def get_exiftool_attributes(self):
114
        """Get attributes for the media object from exiftool.
115
116
        :returns: dict, or False if exiftool was not available.
117
        """
118
        source = self.source
119
120
        #Cache exif metadata results and use if already exists for media
121
        if(self.exif_metadata is None):
122
            exif_metadata = ExifTool().get_metadata(source)
123
            self.exif_metadata = exif_metadata
124
        else:
125
            exif_metadata = self.exif_metadata
126
127
        if not exif_metadata:
128
            return False
129
130
        return exif_metadata
131
132
    def get_camera_make(self):
133
        """Get the camera make stored in EXIF.
134
135
        :returns: str
136
        """
137
        if(not self.is_valid()):
138
            return None
139
140
        exiftool_attributes = self.get_exiftool_attributes()
141
142
        if exiftool_attributes is None:
143
            return None
144
145
        for camera_make_key in self.camera_make_keys:
146
            if camera_make_key in exiftool_attributes:
147
                return exiftool_attributes[camera_make_key]
148
149
        return None
150
151
    def get_camera_model(self):
152
        """Get the camera make stored in EXIF.
153
154
        :returns: str
155
        """
156
        if(not self.is_valid()):
157
            return None
158
159
        exiftool_attributes = self.get_exiftool_attributes()
160
161
        if exiftool_attributes is None:
162
            return None
163
164
        for camera_model_key in self.camera_model_keys:
165
            if camera_model_key in exiftool_attributes:
166
                return exiftool_attributes[camera_model_key]
167
168
        return None
169
170
    def get_original_name(self):
171
        """Get the original name stored in EXIF.
172
173
        :returns: str
174
        """
175
        if(not self.is_valid()):
176
            return None
177
178
        exiftool_attributes = self.get_exiftool_attributes()
179
180
        if exiftool_attributes is None:
181
            return None
182
183
        if(self.original_name_key not in exiftool_attributes):
184
            return None
185
186
        return exiftool_attributes[self.original_name_key]
187
188
    def get_title(self):
189
        """Get the title for a photo of video
190
191
        :returns: str or None if no title is set or not a valid media type
192
        """
193
        if(not self.is_valid()):
194
            return None
195
196
        exiftool_attributes = self.get_exiftool_attributes()
197
198
        if exiftool_attributes is None:
199
            return None
200
201
        if(self.title_key not in exiftool_attributes):
202
            return None
203
204
        return exiftool_attributes[self.title_key]
205
206
    def reset_cache(self):
207
        """Resets any internal cache
208
        """
209
        self.exiftool_attributes = None
210
        self.exif_metadata = None
211
        super(Media, self).reset_cache()
212
213
    def set_album(self, album):
214
        """Set album for a photo
215
216
        :param str name: Name of album
217
        :returns: bool
218
        """
219
        if(not self.is_valid()):
220
            return None
221
222
        tags = {self.album_keys[0]: album}
223
        status = self.__set_tags(tags)
224
        self.reset_cache()
225
226
        return status
227
228
    def set_date_taken(self, time):
229
        """Set the date/time a photo was taken.
230
231
        :param datetime time: datetime object of when the photo was taken
232
        :returns: bool
233
        """
234
        if(time is None):
235
            return False
236
237
        tags = {}
238
        formatted_time = time.strftime('%Y:%m:%d %H:%M:%S')
239
        for key in self.exif_map['date_taken']:
240
            tags[key] = formatted_time
241
242
        status = self.__set_tags(tags)
243
        self.reset_cache()
244
        return status
245
246
    def set_location(self, latitude, longitude):
247
        if(not self.is_valid()):
248
            return None
249
250
        # The lat/lon _keys array has an order of precedence.
251
        # The first key is writable and we will give the writable
252
        #   key precence when reading.
253
        tags = {
254
            self.latitude_keys[0]: latitude,
255
            self.longitude_keys[0]: longitude,
256
        }
257
258
        # If self.set_gps_ref == True then it means we are writing an EXIF
259
        #   GPS tag which requires us to set the reference key.
260
        # That's because the lat/lon are absolute values.
261
        if self.set_gps_ref:
262
            if latitude < 0:
263
                tags[self.latitude_ref_key] = 'S'
264
265
            if longitude < 0:
266
                tags[self.longitude_ref_key] = 'W'
267
268
        status = self.__set_tags(tags)
269
        self.reset_cache()
270
271
        return status
272
273
    def set_original_name(self, name=None):
274
        """Sets the original name EXIF tag if not already set.
275
276
        :returns: True, False, None
277
        """
278
        if(not self.is_valid()):
279
            return None
280
281
        # If EXIF original name tag is set then we return.
282
        if self.get_original_name() is not None:
283
            return None
284
285
        source = self.source
286
287
        if not name:
288
            name = os.path.basename(source)
289
290
        tags = {self.original_name_key: name}
291
        status = self.__set_tags(tags)
292
        self.reset_cache()
293
        return status
294
295
    def set_title(self, title):
296
        """Set title for a photo.
297
298
        :param str title: Title of the photo.
299
        :returns: bool
300
        """
301
        if(not self.is_valid()):
302
            return None
303
304
        if(title is None):
305
            return None
306
307
        tags = {self.title_key: title}
308
        status = self.__set_tags(tags)
309
        self.reset_cache()
310
311
        return status
312
313
    def __set_tags(self, tags):
314
        if(not self.is_valid()):
315
            return None
316
317
        source = self.source
318
319
        status = ''
320
        status = ExifTool().set_tags(tags,source)
321
322
        return status != ''
323