#!/usr/bin/env python
"""
Simple Moodle Parser for Tutors

(c) 2010 Andreas Boehler

v0.01, 2010/03/19
Initial Version
"""

import urllib, urllib2, cookielib
import sys, os, zipfile, subprocess
from optparse import OptionParser

def get_file(fn, opener):
    print 'Downloading file: ' + fn.split('/')[-1]
    webfile = opener.open(fn)
    localfile = open(fn.split('/')[-1],'w')
    localfile.write(webfile.read())
    webfile.close()
    localfile.close()
    

def find_all_names(string):
    string = string.decode('utf-8')
    pattern = '<td class="cell c1 fullname">'
    fullnames = string.split(pattern)
    namelist = []
    for name_string in fullnames:
        try:
            if name_string.startswith('<a href="'):
                name = name_string.split('>')[1]
                name = name.split('<')[0]
                fn = name_string.split('<div class="files">')[1]
                fn = fn.split('<')[2]
                fn = fn.split('"')[1]
                namelist.append([name, fn])
        except:
            pass
    return namelist
    
def unzip(file): 
    # Extract a ZIP file, taking the filepath into account
    #print 'Extracting'
    zfobj = zipfile.ZipFile(file)
    for name in zfobj.namelist():
        try:
            path, file = os.path.split(name)
            if path != '' and not os.path.exists(path):
                os.makedirs(path)            
            if name.endswith('/'):
                if not os.path.exists(os.path.join(os.getcwd(), name)):
                    os.mkdir(os.path.join(os.getcwd(), name))
            else:
                outfile = open(os.path.join(os.getcwd(), name), 'wb')
                outfile.write(zfobj.read(name))
                outfile.close()
        except:
            pass

parser = OptionParser()

parser.add_option("-u","--username",dest="username", help="Username for Login")
parser.add_option("-p","--password", dest="password", help="Password for Login")
parser.add_option("-i","--id", dest="id", help="Assignment ID to retrieve")

(opt,argv) = parser.parse_args()
if not opt.id:
    print 'No ID given, will now quit'
    sys.exit()

username = opt.username
password = opt.password

loginpage = 'http://moodle.fh-linz.at/login/index.php'
assignment_url = 'http://moodle.fh-linz.at/mod/assignment/submissions.php?id='

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
data = urllib.urlencode({"username" : username, "password" : password})
# print data
print 'Logging in as user: ' + username
f = opener.open(loginpage, data)
s = f.read()
f.close()

if '<div class="loginerrors"><span class="error">' in s:
    print "Login unsuccessful! Will now quit."
    sys.exit()


print 'Retrieving assignment overview...'
f = opener.open(assignment_url + opt.id)
s = f.read()
f.close()

name_file_list = find_all_names(s)

for name, fn in name_file_list:
    # Attention: We assume that there is a space between first and last name and nothing else
    first, last = name.split(' ')
    if not os.path.exists(last):
        os.mkdir(last)
    os.chdir(last)
    if not os.path.exists(opt.id):
        os.mkdir(opt.id)
    os.chdir(opt.id)
    get_file(fn, opener)
    if fn[-3:].lower() == 'rar':
        print 'Attempting to extract RAR archive...'
        subprocess.call(['rar', 'x',fn.split('/')[-1]])
    elif fn[-3:].lower() == 'zip':
        print 'Attempting to extract ZIP archive...'
        unzip(fn.split('/')[-1])
    os.chdir('../..')
    

