Skip to content

Instantly share code, notes, and snippets.

@pixaline
Created May 25, 2016 01:55
Show Gist options
  • Save pixaline/84fa92a189e7a40b7509a93ead937426 to your computer and use it in GitHub Desktop.
Save pixaline/84fa92a189e7a40b7509a93ead937426 to your computer and use it in GitHub Desktop.
#!/bin/python
import urllib.request, json, argparse
# python miui.py --category='Simple' --h | sort -k2h
# - will print Featured themes in category Simple, sorted by size
# this script doesn't work anymore, but i thought i'd upload it.
def sizeof_fmt(num):
for x in ['bytes','KB','MB','GB','TB']:
if num < 1024.0:
return "%3.1f %s" % (num, x)
num /= 1024.0
def search(keyword, opt={}):
ro={'category': 'Compound', 'capability': 'w', 'apk': 100, 'page':0, 'keywords': keyword}
ro.update(opt)
url = "http://market.xiaomi.com/thm/search?" + urllib.parse.urlencode(ro)
# print('search:', url)
return json.loads(urllib.request.urlopen(url).readall().decode('utf-8'))
def info(id, opt={}):
ro={'capability': 'w'}
ro.update(opt)
url = "http://market.xiaomi.com/thm/details/" + id + "?" + urllib.parse.urlencode(ro)
# print('info:',url)
return json.loads(urllib.request.urlopen(url).readall().decode('utf-8'))
def subject(subcat, opt={}):
ro={'capability': 'w', 'page': 0, 'clazz': 'Simple', 'apk': 100} #assume simple
ro.update(opt)
url = "http://market.xiaomi.com/thm/subject/" + subcat + "?" + urllib.parse.urlencode(ro)
# print('subject:',url)
return json.loads(urllib.request.urlopen(url).readall().decode('utf-8'))
def get_subjects():
url = "http://market.xiaomi.com/thm/page/380e5eaa-05ff-11e3-b877-a26510237d0b?" + urllib.parse.urlencode({'capability': 'w', 'apk': 100})
js = json.loads(urllib.request.urlopen(url).readall().decode('utf-8'))
rr= {}
for i in js['pageItemViews'][0]['shopWindowViews']:
for m in i['pageMetas']:
for a in m['pageGroup']:
s = urllib.request.urlsplit(a['subjectUrl'])
url=(s.path.split('/')[1])
cat = urllib.parse.parse_qs(s.query)['clazz'][0]
if cat == 'Unknown': cat = 'Cute' #idk why they didn't fix it...
title = a['title']
if title == '精品': title = 'Featured'
elif title == '收费': title = 'Paid'
elif title == '免费': title = 'Free'
else: title = 'New'
if cat not in rr: rr[cat] = {}
rr[cat].update({title: url})
return rr
def download_images(imglist):
for ii, i in enumerate(imglist):
data = urllib.request.urlopen(i).read()
filename = i.split('/').pop()
f = open(filename, 'wb')
f.write(data)
print('['+str(ii+1)+'/'+str(len(imglist))+'] Downloaded ' + filename)
f.close()
def download_theme(apklist):
for ii, i in enumerate(apklist):
print(i)
data = urllib.request.urlopen(i).read()
filename = i.split('/').pop()
f = open(filename, 'wb')
f.write(data)
print('['+str(ii+1)+'/'+str(len(apklist))+'] Downloaded ' + filename)
f.close()
if __name__ == '__main__':
p = argparse.ArgumentParser (description = 'A tool for searching/listing/downloading miui themes')
p.add_argument('--info', type = str, help = 'get information about a theme')
p.add_argument('--search', type = str, help = 'search for a keyword')
p.add_argument('--category', type = str, help = 'list from category')
p.add_argument('--section', type = str, default='Featured', help = 'list from category')
p.add_argument('--select', type=int, nargs='+', help = 'select a query result to investigate')
p.add_argument('--only-description', action='store_true', help = 'return only the description')
p.add_argument('--only-name', action='store_true', help = 'return only the name')
p.add_argument('--only-select', action='store_true', help = 'return only the selected search results')
p.add_argument('--apk', type = int, help = 'number of results to return')
p.add_argument('--page', type = int, help = 'what page to return')
p.add_argument('--type', type = str, default = 'png', help = 'the type of the theme screenshots')
p.add_argument('--width', type = int, help = 'the width of the theme screenshots')
p.add_argument('--height', type = int, help = 'the height of the theme screenshots')
p.add_argument('--quality', type = int, help = 'the quality of the theme screenshots')
p.add_argument('--download-images', action='store_true', help = 'download the images')
p.add_argument('--download-theme', action='store_true', help = 'download the theme(s)')
p.add_argument('--h', action='store_true', help = 'human readable sizes')
# p.add_argument('--translate', action='store_true', help = 'translate it')
args = p.parse_args()
oo = vars(args)
options = { k : oo[k] for k in oo if oo[k] != None }
theme_subjects = get_subjects()
def ckey(category, section):
if category in theme_subjects:
if section in theme_subjects[category]:
return theme_subjects[category][section]
# print('options:', options)
def hrs(s): return sizeof_fmt(s) if options['h'] == True else s
apk_list=[]
img_list=[]
def apk(a): return apk_list.append('http://market.xiaomi.com/thm/download/' + a)
def apkinfo(m, s, ppp=' '):
js = info(m, s)
author = js['author']
name = js['name']
size = hrs(js['fileSize'])
desc = js['description']
downs = js['downloads']
url_theme= 'http://market.xiaomi.com/thm/download/' + m
imgs = []
imgop = {'w': 512, 'q': 100}
if 'width' in options: imgop.update({'w': int(options['width'])})
if 'height' in options: imgop.update({'h': int(options['height'])})
if 'quality' in options: imgop.update({'q': int(options['quality'])})
imgop = "".join("{!s}{!r}".format(key,val) for (key,val) in imgop.items())
for a in js['snapshotsUrl']: imgs.append(js['downloadUrlRoot'] + options['type']+'/' + imgop + '/' + a)
if options['download_images'] == True:
img_list.extend(imgs)
if options['only_description'] == True:
print(desc)
elif options['only_name'] == True:
print(name)
else:
print(ppp,author, ':\t', name)
print(ppp,size, '('+str(downs)+' downloads)')
print(ppp,desc)
searchopts = { k: options[k] for k in options if k == 'apk' or k == 'page' }
if args.category or args.search:
if args.category:
searchopts['clazz']=options['category']
print('Listing ['+options['section']+'] themes in '+options['category']+'.')
js = subject(ckey(options['category'], options['section']), searchopts)
else:
js = search(args.search, searchopts)
for k,i in enumerate(js['Compound']):
size = hrs(i['fileSize'])
name = i['name']
module = i['moduleId']
if options['download_theme'] == True and 'select' not in options: apk(module)
ne = name
if args.search:
ww=name.find(args.search)
w2=len(args.search)
ne=name[:ww] + '\033[93m' + args.search + '\033[0m' + name[ww+w2:]
if options['only_name'] == True:
print(name)
elif options['only_select'] == False:
print(module,'\t',size,'\t',ne)
if 'select' in options and k in options['select']:
apkinfo(module, searchopts, '└' if options['only_select'] == False else '')
if options['download_theme'] == True:
apk(module)
print('') #empty line for breathing space
elif args.info:
apkinfo(args.info, searchopts)
if options['download_images'] == True:
download_images(img_list)
if options['download_theme'] == True:
download_theme(apk_list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment