File: media.py

package info (click to toggle)
python-pyaarlo 0.8.0.15-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 556 kB
  • sloc: python: 6,064; makefile: 6; sh: 1
file content (529 lines) | stat: -rw-r--r-- 16,843 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
import os
import threading
from datetime import datetime, timedelta
from string import Template
from slugify import slugify

from .constant import (
    LIBRARY_PATH,
    RATLS_LIBRARY_PATH,
    RATLS_DOWNLOAD_PATH,
    VIDEO_CONTENT_TYPES
)
from .util import arlotime_strftime, arlotime_to_datetime, http_get, http_stream


class ArloMediaDownloader(threading.Thread):
    def __init__(self, arlo, save_format):
        super().__init__()
        self._arlo = arlo
        self._save_format = save_format
        self._lock = threading.Condition()
        self._queue = []
        self._stopThread = False
        self._downloading = False

    # noinspection PyPep8Naming
    def _output_name(self, media):
        """Calculate file name from media object.

        Uses `self._save_format` to work out the substitions.

        :param media: ArloMediaObject to download
        :return: The file name.
        """
        when = arlotime_to_datetime(media.created_at)
        Y = str(when.year).zfill(4)
        m = str(when.month).zfill(2)
        d = str(when.day).zfill(2)
        H = str(when.hour).zfill(2)
        M = str(when.minute).zfill(2)
        S = str(when.second).zfill(2)
        F = f"{Y}-{m}-{d}"
        T = f"{H}:{M}:{S}"
        t = f"{H}-{M}-{S}"
        s = str(int(when.timestamp())).zfill(10)
        try:
            return (
                Template(self._save_format).substitute(
                    SN=media.camera.device_id,
                    N=media.camera.name,
                    NN=slugify(media.camera.name, separator='_'),
                    Y=Y,
                    m=m,
                    d=d,
                    H=H,
                    M=M,
                    S=S,
                    F=F,
                    T=T,
                    t=t,
                    s=s,
                )
                + f".{media.extension}"
            )
        except KeyError as _e:
            self._arlo.error(f"format error: {self._save_format}")
            return None

    def _download(self, media):
        """Download a single piece of media.

        :param media: ArloMediaObject to download
        :return: 1 if a file was downloaded, 0 if the file present and skipped or -1 if an error occured
        """
        # Calculate name.
        save_file = self._output_name(media)
        if save_file is None:
            return -1
        try:
            # See if it exists.
            os.makedirs(os.path.dirname(save_file), exist_ok=True)
            if not os.path.exists(save_file):
                # Download to temporary file before renaming it.
                self.debug(f"dowloading for {media.camera.name} --> {save_file}")
                save_file_tmp = f"{save_file}.tmp"
                media.download_video(save_file_tmp)
                os.rename(save_file_tmp, save_file)
                return 1
            else:
                self.vdebug(
                    f"skipping dowload for {media.camera.name} --> {save_file}"
                )
                return 0
        except OSError as _e:
            self._arlo.error(f"failed to download: {save_file}")
            return -1

    def run(self):
        if self._save_format == "":
            self.debug("not starting downloader")
            return
        with self._lock:
            while not self._stopThread:
                media = None
                result = 0
                if len(self._queue) > 0:
                    media = self._queue.pop(0)
                    self._downloading = True

                self._lock.release()
                if media is not None:
                    result = self._download(media)
                self._lock.acquire()

                self._downloading = False
                # Nothing else to do then just wait.
                if len(self._queue) == 0:
                    self.vdebug(f"waiting for media")
                    self._lock.wait(60.0)
                # We downloaded a file so inject a small delay.
                elif result == 1:
                    self._lock.wait(0.5)

    def queue_download(self, media):
        if self._save_format == "":
            return
        with self._lock:
            self._queue.append(media)
            if len(self._queue) == 1:
                self._lock.notify()

    def stop(self):
        if self._save_format == "":
            return
        with self._lock:
            self._stopThread = True
            self._lock.notify()
        self.join(10)

    @property
    def processing(self):
        with self._lock:
            return len(self._queue) > 0 or self._downloading

    def debug(self, msg):
        self._arlo.debug(f"media-downloader: {msg}")

    def vdebug(self, msg):
        self._arlo.vdebug(f"media-downloader: {msg}")


class ArloMediaLibrary(object):
    """Arlo Library Media module implementation."""

    def __init__(self, arlo):
        self._arlo = arlo
        self._lock = threading.Lock()
        self._load_cbs_ = []
        self._count = 0
        self._videos = []
        self._video_keys = []
        self._snapshots = {}
        self._base = None

        self._downloader = ArloMediaDownloader(arlo, self._arlo.cfg.save_media_to)
        self._downloader.name = "ArloMediaDownloader"
        self._downloader.daemon = True
        self._downloader.start()

    def __repr__(self):
        return "<{0}:{1}>".format(self.__class__.__name__, self._arlo.cfg.name)

    def _fetch_library(self, date_from, date_to):
        return self._arlo.be.post(
            LIBRARY_PATH, {"dateFrom": date_from, "dateTo": date_to}
        )

    # grab recordings from last day, add to existing library if not there
    def update(self):
        self.debug("updating image library")

        # grab today's images
        date_to = datetime.today().strftime("%Y%m%d")
        data = self._fetch_library(date_to, date_to)

        # get current videos
        with self._lock:
            keys = self._video_keys

        # add in new images
        videos = []
        snapshots = {}
        for video in data:

            # camera, skip if not found
            camera = self._arlo.lookup_camera_by_id(video.get("deviceId"))
            if not camera:
                continue

            # snapshots, use first found
            if video.get("reason", "") == "snapshot":
                if camera.device_id not in snapshots:
                    self.debug(f"adding snapshot for {camera.name}")
                    snapshots[camera.device_id] = ArloSnapshot(
                        video, camera, self._arlo, camera.base_station
                    )
                continue

            content_type = video.get("contentType", "")

            # videos, add missing
            if content_type.startswith("video/") or content_type in VIDEO_CONTENT_TYPES:
                key = "{0}:{1}".format(
                    camera.device_id, arlotime_strftime(video.get("utcCreatedDate"))
                )
                if key in keys:
                    self.vdebug(f"skipping {key} for {camera.name}")
                    continue
                self.debug(f"adding {key} for {camera.name}")
                video = ArloVideo(video, camera, self._arlo, self._base)
                videos.append(video)
                self._downloader.queue_download(video)
                keys.append(key)

        # note changes and run callbacks
        with self._lock:
            self._count += 1
            self._videos = videos + self._videos
            self._video_keys = keys
            self._snapshots = snapshots
            self.debug("update-count=" + str(self._count))
            cbs = self._load_cbs_
            self._load_cbs_ = []

        # run callbacks with no locks held
        for cb in cbs:
            cb()

    def load(self):

        # set beginning and end
        days = self._arlo.cfg.library_days
        now = datetime.today()
        date_from = (now - timedelta(days=days)).strftime("%Y%m%d")
        date_to = now.strftime("%Y%m%d")
        self.debug("loading image library ({} days)".format(days))

        # save videos for cameras we know about
        data = self._fetch_library(date_from, date_to)

        if data is None:
            self._arlo.warning("error loading the image library")
            return

        videos = []
        keys = []
        snapshots = {}
        for video in data:

            # Look for camera, skip if not found.
            camera = self._arlo.lookup_camera_by_id(video.get("deviceId"))
            if camera is None:
                key = "{0}:{1}".format(
                    video.get("deviceId"),
                    arlotime_strftime(video.get("utcCreatedDate")),
                )
                self.vdebug("skipping {0}".format(key))
                continue

            # snapshots, use first found
            if video.get("reason", "") == "snapshot":
                if camera.device_id not in snapshots:
                    self.debug(f"adding snapshot for {camera.name}")
                    snapshots[camera.device_id] = ArloSnapshot(
                        video, camera, self._arlo, camera.base_station
                    )
                continue

            # videos, add all
            content_type = video.get("contentType", "")
            if content_type.startswith("video/") or content_type in VIDEO_CONTENT_TYPES:
                key = "{0}:{1}".format(
                    video.get("deviceId"),
                    arlotime_strftime(video.get("utcCreatedDate")),
                )
                self.vdebug(f"adding {key} for {camera.name}")
                video = ArloVideo(video, camera, self._arlo, self._base)
                videos.append(video)
                self._downloader.queue_download(video)
                keys.append(key)
                continue

        # set update count, load() never runs callbacks
        with self._lock:
            self._count += 1
            self._videos = videos
            self._video_keys = keys
            self._snapshots = snapshots
            self.debug("load-count=" + str(self._count))

    def snapshot_for(self, camera):
        with self._lock:
            return self._snapshots.get(camera.device_id, None)

    @property
    def videos(self):
        with self._lock:
            return self._count, self._videos

    @property
    def count(self):
        with self._lock:
            return self._count

    def videos_for(self, camera):
        camera_videos = []
        with self._lock:
            for video in self._videos:
                if camera.device_id == video.camera.device_id:
                    camera_videos.append(video)
            return self._count, camera_videos

    def queue_update(self, cb):
        with self._lock:
            if not self._load_cbs_:
                self.debug("queueing image library update")
                self._arlo.bg.run_low_in(self.update, 2)
            self._load_cbs_.append(cb)

    def stop(self):
        self._downloader.stop()

    def debug(self, msg):
        self._arlo.debug(f"media-library: {msg}")

    def vdebug(self, msg):
        self._arlo.vdebug(f"media-library: {msg}")


class ArloBaseStationMediaLibrary(ArloMediaLibrary):
    """Arlo Media Library for Base Stations"""
    def __init__(self, arlo, base):
        super().__init__(arlo)
        self._base = base

    def _fetch_library(self, date_from, date_to):
        list = []

        # Fetch each page individually, since the base station still only return results for one date at a time
        for date in range(int(date_from), int(date_to) + 1):
            for camera in self._arlo.cameras:
                if camera.parent_id == self._base.device_id:
                    # This URL is mysterious -- it won't return multiple days of videos
                    data = self._base.ratls.get(f"{RATLS_LIBRARY_PATH}/{date}/{date}/{camera.device_id}")
                    if data and "data" in data:
                        list += data["data"]

        return list


class ArloMediaObject(object):
    """Object for Arlo Video file."""

    def __init__(self, attrs, camera, arlo, base):
        """Video Object."""
        self._arlo = arlo
        self._attrs = attrs
        self._camera = camera
        self._base = base

    def __repr__(self):
        """Representation string of object."""
        return "<{0}:{1}>".format(self.__class__.__name__, self.name)

    @property
    def name(self):
        return "{0}:{1}".format(
            self._camera.device_id, arlotime_strftime(self.created_at)
        )

    # pylint: disable=invalid-name
    @property
    def id(self):
        """Returns unique id representing the video."""
        return self._attrs.get("name", None)

    @property
    def created_at(self):
        """Returns date video was creaed."""
        return self._attrs.get("utcCreatedDate", None)

    def created_at_pretty(self, date_format=None):
        """Returns date video was taken formated with `last_date_format`"""
        if date_format:
            return arlotime_strftime(self.created_at, date_format=date_format)
        return arlotime_strftime(self.created_at)

    @property
    def created_today(self):
        """Returns `True` if video was taken today, `False` otherwise."""
        return self.datetime.date() == datetime.today().date()

    @property
    def datetime(self):
        """Returns a python datetime object of when video was created."""
        return arlotime_to_datetime(self.created_at)

    @property
    def content_type(self):
        """Returns the video content type.

        Usually `video/mp4`
        """
        return self._attrs.get("contentType", None)

    @property
    def extension(self):
        if self.content_type.endswith("mp4"):
            return "mp4"
        if self.content_type in VIDEO_CONTENT_TYPES:
            return "mp4"
        return "jpg"

    @property
    def camera(self):
        return self._camera

    @property
    def triggered_by(self):
        return self._attrs.get("reason", None)

    @property
    def url(self):
        """Returns the URL of the video."""
        return self._attrs.get("presignedContentUrl", None)

    @property
    def thumbnail_url(self):
        """Returns the URL of the thumbnail image."""
        return self._attrs.get("presignedThumbnailUrl", None)

    def download_thumbnail(self, filename=None):
        return http_get(self.thumbnail_url, filename)


class ArloVideo(ArloMediaObject):
    """Object for Arlo Video file."""

    def __init__(self, attrs, camera, arlo, base):
        """Video Object."""
        super().__init__(attrs, camera, arlo, base)

    @property
    def media_duration_seconds(self):
        """Returns how long the recording last."""
        return self._attrs.get("mediaDurationSecond", None)

    @property
    def object_type(self):
        """Returns what object caused the video to start.

        Currently is `vehicle`, `person`, `animal` or `other`.
        """
        return self._attrs.get("objCategory", None)

    @property
    def object_region(self):
        """Returns the region of the thumbnail showing the object."""
        return self._attrs.get("objRegion", None)

    @property
    def video_url(self):
        """Returns the URL of the video."""
        return self._attrs.get("presignedContentUrl", None)

    def download_video(self, filename=None):
        video_url = self.video_url

        if self._base:
            video_url = f"{RATLS_DOWNLOAD_PATH}/{video_url}"

            response = self._base.ratls.get(video_url, raw=True)

            if response is None:
                return False

            with open(filename, "wb") as data:
                data.write(response.read())

            return True
        else:

            return http_get(video_url, filename)

    @property
    def created_at(self):
        """Returns date video was creaed, adjusted to ms"""
        timestamp = super().created_at
        if self._base:
            if timestamp:
                return timestamp * 1000
            return None
        return timestamp

    @property
    def stream_video(self):
        if self._base:
            response = self._base.ratls.get(f"{RATLS_DOWNLOAD_PATH}/{self.video_url}", raw=True)
            response.raise_for_status()
            for data in response.iter_content(4096):
                yield data
        else:
            http_stream(self.video_url)


class ArloSnapshot(ArloMediaObject):
    """Object for Arlo Snapshot file."""

    def __init__(self, attrs, camera, arlo, base):
        """Snapshot Object."""
        super().__init__(attrs, camera, arlo, base)

    @property
    def image_url(self):
        """Returns the URL of the video."""
        return self._attrs.get("presignedContentUrl", None)


# vim:sw=4:ts=4:et: