from urllib.request import ProxyHandler, build_opener, install_opener, urlopen
import lz4
import lz4.block
from itertools import islice
from multiprocessing.dummy import Pool as ThreadPool
import os
import io
import struct
pool = ThreadPool(10)

if not os.path.exists("magicami"):
    os.makedirs("magicami")
#proxy = urllib.request.ProxyHandler({'http': 'http://192.168.1.91:8888'})
proxy = ProxyHandler({})
opener = build_opener(proxy)
opener.addheaders = [('Refere','https://api.magicami.jp/Top/Main?magicami-sessid=thus9ievqvgslol0abcd2abcdefg5abc'),('Origin','https://api.magicami.jp'),('User-Agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763')]
install_opener(opener)



def geturl(name):
	try:
		if os.path.exists('magicami\\' + name[1]):
			pass
		else:
			print('Downlaoding',name)
			myFile = urlopen(name[0]).read()
			with open('magicami\\' + name[1], 'wb') as f:
				f.write(myFile)
		
	except:
		pass


with open('magicami.bundle', "rb" ) as f:
	names = []
	bs = io.BytesIO(f.read())
	b1,b2,b3 = struct.unpack('BBB', bs.read(3))
	#print(b1,b2,b3)
	typeDict = {18: 'assetbundle', 26: 'assetbundle', 34: 'resources'}

	for i in range(0,14000):
		unk00,unk01,unk02,unk03  = struct.unpack('4B', bs.read(4))
		if unk00 == 0x2A:
			bs.seek(bs.tell() - 3,0)
			url = bs.read(struct.unpack('B', bs.read(1))[0]).decode("utf-8")
			print(url)
			break
		else:
			unk04 = struct.unpack('B', bs.read(1))[0]
			while unk04 != 0x1A:
				unk04 = struct.unpack('B', bs.read(1))[0]
			unk05 = struct.unpack('B', bs.read(1))[0]
			#print(unk00,unk01,unk02,unk03,unk04,unk05)
			#print(bs.tell())
			tmp = bs.tell()
			try:
				fileName = bs.read(unk05).decode("utf-8")
			except:
				bs.seek(tmp,0)
				fileName = bs.read(struct.unpack('B', bs.read(1))[0]).decode("utf-8")
			#print(fileName,typeDict[unk00])
			unk06 = bs.read(0x8)
			#print(unk06)
			tb = struct.unpack('B', bs.read(1))[0]
			while tb != 0x52:
				tb = struct.unpack('B', bs.read(1))[0]
			md5Size = struct.unpack('B', bs.read(1))[0]
			md5 = bs.read(md5Size).decode("ASCII")
			#print(md5)
			hVal,hSize = struct.unpack('BB', bs.read(2))
			hName = bs.read(hSize).decode("ASCII")
			#print(hVal,hSize,hName)
			unk07 = bs.read(0xB)
			#print(unk07)
			#print(hex(bs.tell()))
			if len(hName) == 6:
				url = 'https://d66zh4czgmp8a.cloudfront.net/magicami-prod-1-' + typeDict[unk00] + '/' + hName
				names.append([url,fileName])

	pool.map(geturl, names )

