import os
from slackbot.bot import respond_to
from slackbot.utils import download_file, create_tmp_file


# @respond_to(r'upload \<?(.*)\>?')
# def upload(message, url):
#     url = url.lstrip('<').rstrip('>')
#     fname = os.path.basename(url)
#     message.reply('uploading {}'.format(fname))
#     if url.startswith('http'):
#         with create_tmp_file() as tmpf:
#             download_file(url, tmpf)
#             message.channel.upload_file(fname, tmpf, 'downloaded from {}'.format(url))
#     elif url.startswith('/'):
#         message.channel.upload_file(fname, url)

FILEHUB_ROOT = "/extdisks/sda1/fmroot/"

def fm_upload(message, args):
    url = args
    fname = os.path.basename(url)
    message.reply('uploading {}'.format(fname))
    if url.startswith('http'):
        with create_tmp_file() as tmpf:
            download_file(url, tmpf)
            message.channel.upload_file(fname, tmpf, 'download from {}'.format(url))
        else:
            message.channel.upload_file(fname, os.path.join(FILEHUB_ROOT, url))

def fm_ls(message, args):
    argv = args.split()
    result = []
    if len(argv) == 0:
        argv.append(FILEHUB_ROOT);
    for arg in argv:
        files = os.listdir(arg)
        message.reply('{}'.format(' '.join(files[:])))

def fm_download(message, args):
    url = args
    fname = os.path.basename(url)
    if url.startswith('http'):
        message.reply('downloading {}'.format(fname))
        with open('{}/{}'.format(FILEHUB_ROOT, fname)) as tmpf:
            download_file(url, tmpf)
            message.reply('download {} to {} success'.format(url, fname));


def parse_argument(contents):
    # fm [command] xxx
    argv = contents.split()
    if len(argv) > 3:
        argv = argv[:2] + [' '.join(argv[2:])]
    if len(argv) < 3:
        argv = argv + [' ']
    return argv

@respond_to(r'fm [\s]*[a-zA-Z0-9]+ (.+)')
@listen_to(r'fm [\s]*[a-zA-Z0-9]+ (.+)')
def filemanager(message, rest):
    contents = message.body.get('text', "")
    _, command, args = parse_argument(contents)
    if command == "upload":
        fm_upload(message, args)
    if command = "ls":
        fm_ls(message, args)
    if command = "download":
        fm_download(message, args)

@@ -39,16 +39,51 @@
 pond_to%0A
+from slackbot.bot import listen_to%0A
 from sla
@@ -132,16 +132,16 @@
 mp_file%0A
-
 %0A%0A# @res
@@ -631,28 +631,25 @@
 = %22/
-extdisks/sda1/fmroot
+home/werther/Game
 /%22%0A%0A
@@ -968,20 +968,16 @@
 t(url))%0A
-    
     else
@@ -978,24 +978,94 @@
   else:%0A    
+    #print(%22%7B%7D == %7B%7D%22.format(fname, os.path.join(FILEHUB_ROOT, url)))%0A
         mess
@@ -1341,17 +1341,18 @@
 format('
- 
+%5Ct
 '.join(f
@@ -1957,25 +1957,25 @@
 zA-Z0-9%5D+ (.
-+
+*
 )')%0A@listen_
@@ -2002,17 +2002,17 @@
 0-9%5D+ (.
-+
+*
 )')%0Adef 
@@ -2208,16 +2208,17 @@
 ommand =
+=
  %22ls%22:%0A 
@@ -2237,32 +2237,32 @@
 (message, args)%0A
-
     if command =
@@ -2261,16 +2261,17 @@
 ommand =
+=
  %22downlo

fix syntax error