import os, json

def getMedia(filename, list):
    for item in list:
        if filename.split('.')[0] in item['filepath']:
            return item
    return None
    
    
data = json.loads(open('oldpins.json').read())
files = os.listdir('STORAGE')

count = 0
for file in files:
    filepath = f'STORAGE/{file}'
    
    if os.path.isdir(filepath):
        continue
    media = getMedia(file, data)
    if not media:
        continue
    
    username = media['title']
    filetype = media['type']
    filetype = 'jpg' if filetype == 'image' else 'mp4'
    filename = media['filepath'].split('/')[-1] + '.' + filetype
    
    output = os.path.join('STORAGE', username, filename)
    os.makedirs(os.path.dirname(output), exist_ok=True)
    if os.path.exists(output):
        os.remove(output)
        output = os.path.join('STORAGE', username, file)
    os.rename(filepath, output)
    
    count += 1
    print(f'File: {file}')
        
print(f'Total: {count}')