File size: 1,798 Bytes
1b3fb15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from peewee import BlobField, CharField, IntegrityError, Model, SqliteDatabase

import datetime
import os.path
import pickle
import tempfile

################################################################################


class Gallery(Model):

    id = CharField(primary_key=True)

    path = CharField(unique=True)

    metadata = BlobField()

    class Meta:

        database = SqliteDatabase(f'{tempfile.gettempdir()}/.db')


Gallery.create_table()

################################################################################


def delete(path):
    Gallery.delete().where(Gallery.path == path).execute()


def delete_by_id(id):
    Gallery.delete().where(Gallery.id == id).execute()


def exists(path):
    return Gallery.select().where(Gallery.path == path).exists()


def exists_by_id(id):
    return Gallery.select().where(Gallery.id == id).exists()


def get(path):
    image = Gallery.get(Gallery.path == path)
    return image.id, pickle.loads(image.metadata)


def get_by_id(id):
    image = Gallery.get(Gallery.id == id)
    return image.path, pickle.loads(image.metadata)


def tuples():
    images = []
    for id, path, metadata in Gallery.select().order_by(Gallery.id).tuples():
        images.append((id, path, pickle.loads(metadata)))
    return images


def update(path, metadata):
    metadata = pickle.dumps(metadata)

    if os.path.basename(path) == 'webcam.png':
        timestamp = datetime.datetime.fromtimestamp(
            os.path.getctime(path)).strftime('%Y%m%d_%H%M%S')

        id = f'DCIM/Camera/{timestamp}.png'
    else:
        id = f'DCIM/Upload/{os.path.basename(path)}'

    try:
        Gallery.create(id=id, path=path, metadata=metadata)
    except IntegrityError:
        Gallery.set_by_id(id, dict(path=path, metadata=metadata))

    return id