aboutsummaryrefslogtreecommitdiffstats
path: root/scan.py
blob: 3b47df108a70b5ef7121945ab4d13ccc4a8758dc (plain)
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
#!/usr/bin/python3

import os
import uuid
import time
import pickle


START_DIR = "/storage/animes"
DB_FILENAME = "/storage/animes.db"
uuid_msg = '''{uuid}
creation_date: {date}
orig_hostname: {hostname}
'''


def create_uuid_txt(root, hostname=os.uname()[1]):
    my_uuid = str(uuid.uuid4())
    with open(os.path.join(root, 'uuid.txt'), 'w') as out:
        out.write(uuid_msg.format(uuid=my_uuid,
                                  date=time.strftime('%F %T'),
                                  hostname=hostname))
    return my_uuid


def partition(pred, iterable):
    'Use a predicate to partition entries into false and true entries'
    result = [], []
    for x in iterable:
        result[pred(x)].append(x)
    return result


def main():
    db = []
    with open(DB_FILENAME + '.new', 'wb') as out:
        for root, dirs, files in os.walk(START_DIR):
            if not len(files):
                continue
            files, uuids = partition(lambda f: '/uuid.txt' in f,
                                    (os.path.join(root, f) for f in files))
            if len(uuids) == 1:
                my_uuid = open(uuids[0]).readline().strip()
            else:
                if uuids:
                    print('removing:', uuids)
                for f in uuids:
                    os.unlink(f)
                my_uuid = create_uuid_txt(root)
            db.append((my_uuid, [(f, os.stat(f).st_size) for f in files]))

        pickle.dump(db, out)
    os.rename(DB_FILENAME + '.new', DB_FILENAME)


if __name__ == '__main__':
    main()