#-*- coding: utf-8 -*- import collections import locale import os import re import subprocess import sys import urllib ROOT = ur'D:\Movie' EXTS = '.avi,.mkv,.mp3,.mp4,.mov,.wma,.wmv'.split(',') class Locale: UTF8 = 'utf-8' LOCAL = locale.getpreferredencoding() # sys.getfilelocalencoding() def __init__(self, string): self.string = string @property def utf8(self): try: return self.string.decode(Locale.LOCAL).encode(Locale.UTF8) except UnicodeEncodeError: return self.string @property def local(self): try: return self.string.decode(Locale.UTF8).encode(Locale.LOCAL) except UnicodeEncodeError: return self.string def sort(lst): convert = lambda text: int(text) if text.isdigit() else text.lower() alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)] return sorted(lst, key=alphanum_key) def ext(path): return os.path.splitext(path)[1].lower() def find_media(dirpath): try: for entry in sort(os.listdir(dirpath)): fullpath = os.path.join(dirpath, entry) if os.path.isfile(fullpath) and ext(fullpath) in EXTS: return fullpath except: print 'except: ' + dirpath return None def play_dir(media_dir): os.startfile(find_media(media_dir)) from flask import Flask, redirect, url_for app = Flask(__name__) def html(body): BODY_KEY = u'__BODY__' with open('template.html', 'rb') as f: TEMPLATE = unicode(f.read().decode('utf-8')) return TEMPLATE.replace(BODY_KEY, body) @app.route('/') def root(): return redirect('/explore') @app.route('/explore/') @app.route('/explore/') def listing(subpath=''): body = '' fullpath = os.path.join(ROOT, subpath) for entry in sort(os.listdir(fullpath)): entrypath = os.path.join(fullpath, entry) if os.path.isfile(entrypath): continue media = find_media(entrypath) if media: rest_prefix = u'play' else: rest_prefix = u'explore' name = os.path.basename(entry) href = u'/{0}/{1}/{2}'.format(rest_prefix, subpath, entry).replace('//', '/') body += u'{1}
\n'.format(href, name) return html(body) @app.route('/play/') def play(media): media = urllib.unquote(media).replace('/', os.path.sep) media_dir = os.path.join(ROOT, media) play_dir(media_dir) closing_script = '' return closing_script def main(): app.run(host='0.0.0.0', port=80, threaded=True) if __name__ == '__main__': main()