import os, sys
import asyncio
from appPublic.jsonConfig import getConfig
from sqlor.dbpools import DBPools
from ahserver.filestorage import FileStorage
from loadmedia import save_image_info

async def main():
	workdir = os.path.join(os.environ.get('HOME'), 'py', 'media')
	config = getConfig(workdir, {'workdir':workdir})
	imgs = []
	fs = FileStorage()
	db = DBPools(config.databases)
	async with db.sqlorContext('mediadb') as sor:
		sql = """select a.* from media a left join imageinfo b
on a.id = b.id
where a.mtype = 'image'
	and b.id is NULL
order by ownerid
"""
		imgs = await sor.sqlExe(sql, {})
	cnt = len(imgs)
	for i, img in enumerate(imgs):
		async with db.sqlorContext('mediadb') as sor:
			print(f'handle {img.mlocation} {i}/{cnt}')
			path = fs.realPath(img.mlocation)
			await save_image_info(sor, img.ownerid, img.id, path, img.ownerid)

if __name__ == '__main__':
	asyncio.get_event_loop().run_until_complete(main())
