Esempio n. 1
3
	def ignore_test_should_understand_redirects_to_external_targets(self):
		web = Web()
		moodle = Moodle(web)
		username = ""
		password = ""
		moodle.login(username, password)
		paeps = [ course for course in moodle.my_courses() if u"dagogische Psychologie" in course.name ].pop()
		materials = moodle.material_page_for(paeps.id)
		links = materials.find_links_in_content(materials.markup)
		for link in links:
			resource = Resource(link.getText(), link.get('href'), web, "http://elearning.uni-heidelberg.de/mod/resource/")
			response = web.head(resource.url)
			print resource.name
			print resource.url
			print response.getcode()
Esempio n. 2
2
    parser.add_argument('quiz', help="The category to check", default='TEST 1')
    args = parser.parse_args()


    config = ConfigParser.ConfigParser()
    config.read([args.config, os.path.expanduser('~/.moodleapi.cfg')])

    username = config.get("account", "user")
    password = config.get("account", "pass")
    course = args.course

    if args.user:
        username = parser.user
    if args.password:
        password = args.password

    m = Moodle(args.url)
    m.login(username, password)
    m.course = course
    result = m.extract_quiz(args.quiz)
    with open("overview.csv", "w") as f:
        f.write("duration,points\n")
        for r in result:
            f.write("{0},{1}\n".format(r["duration"].total_seconds(), r["total_points"]))

    for i in [0, 1]:
        with open("q.csv".format(i+1), "w") as f:
            f.write("duration,tries,points\n")
            for r in result:
                f.write("{0},{1},{2}\n".format(r["duration"].total_seconds(), r["questions"][i]["tries"], r["questions"][i]["points"]))
Esempio n. 3
1
    def __init__(self, username, password):
        self.output_dir = "output/"
        self.database = "database.json"
        self.db = {}

        self.moodle = Moodle(username, password)
        if not self.moodle.login():
            exit()

        self.initDatabase()
Esempio n. 4
0
	def __init__(self, username, password, chat_id):
		self.username = username
		self.password = password
		self.chat_id = chat_id
		self.moodle = Moodle()
		self.can_upload = False
		self.data = {}
Esempio n. 5
0
def uploadMoodleQuizScores():
  config = utils.getConfig()

  m = Moodle(config['moodleLogin'], config['moodlePasswd'])
  _, scores = m.getScores(config['moodleCourseId'])
  # Fields: 0:FN, 1:LN, 2:pid, 3:inst, 4:dpt, 5:email, 6:total, 7:score
  data = [{'name': '%s, %s' % (row[1], row[0]), 'score': row[7], 'pid': row[2], 'email': row[5]} for row in scores if row[7] not in [0, '0', '-', '']]
  
  utils.check("Moodle data: ", data)

  g = Gradesource(config['gradesourceLogin'], config['gradesourcePasswd'])
  g.importScoresBy(data, 'pid')
Esempio n. 6
0
def getFeedback(reportId, column):
  gradesource = Gradesource('quentin', getpass('Gradesource password: '******'Emails', emails)

  moodle = Moodle('qpleple', getpass('Moodle password: '******'Feedback', feedback)
  
  GSnames = gradesource.matchNames(feedback.keys(), emails.keys())
  
  data = {}
  for name, content in feedback.items():
    # print '%s %s %s' % (name, colored(email, 'blue'), colored(content, 'green'))
    # answer = raw_input()
    data[name] = {
      'email': emails[GSnames[name]],
      'feedback': content,
    }
    
  utils.check('Feedback', data)
  
  return data
from moodle import Moodle
import sys
import pprint
import wget
import urllib
import configparser

# get config
config = configparser.RawConfigParser()
config.read('config.cfg')
endpoint = config.get('moodle', 'endpoint')
wstoken = config.get('moodle', 'wstoken')

# create webservice client
moodle = Moodle(endpoint, wstoken)

# get assignment cm id from command line
if len(sys.argv) != 2:
    print("\nUsage:\n")
    print("pythong3 ams.py <assignment id>\n")
    sys.exit(0)
cmid = sys.argv[1]

# look up cmid to get assignment instanceid (hopefully)
cm = moodle.core_course_get_course_module(cmid)
instance = cm['instance']
modname = cm['modname']
name = cm['name']
print("\nGET COURSE MODULE FOR id=" + cmid)
print("    instance = " + str(instance))
print("    name = " + name)
Esempio n. 8
0
class User():
	def __init__(self, username, password, chat_id):
		self.username = username
		self.password = password
		self.chat_id = chat_id
		self.moodle = Moodle()
		self.can_upload = False
		self.data = {}

	def SELECT_DOWNLECTURES(self):
		self.can_upload = False
		courses = self.moodle.core_course_get_courses(self.username, self.password)
		if len(courses) != 0:
			inlinekeyboard = InlineKeyboardMarkup(row_width = 2)
			course_list = []
			for i in courses:
				course_list.append(InlineKeyboardButton(' '.join(i.split()[:-1]), callback_data=i.split()[-1]))
			inlinekeyboard.add(*course_list)
			bot.send_message(self.chat_id, 'Fanlar:' +'\n' + '\n'.join([' '.join(i.split()[:-1]) for i in courses]), reply_markup=inlinekeyboard)	 	
		else:
			bot.send_message(self.chat_id, 'Saytdan ma\'lumot kelmadi. Agarda login-parolingizni almashtirgan bo\'lsangiz, botga qayta\
				/start bering!')
	def SELECT_LOADFILES(self):
		self.can_upload = False
		courses = self.moodle.core_course_get_courses(self.username, self.password)
		if len(courses) != 0:
			list = []
			inlinekeyboard = InlineKeyboardMarkup(row_width=2)
			for i in range(0, len(courses)):
				# InlineKeyboardButtonning callback_datasiga course_id ni yozadi, Text iga course_name  
				list.append(InlineKeyboardButton(' '.join(courses[i].split()[:-1]), callback_data=courses[i].split()[-1] + '#'))
			inlinekeyboard.add(*list)
			bot.send_message(self.chat_id, 'Qaysi fanga topshiriq joylamoqchisiz ?', reply_markup=inlinekeyboard)	 	
		else:
			bot.send_message(self.chat_id, 'Saytdan ma\'lumot kelmadi. Agarda login-parolingizni almashtirgan bo\'lsangiz, botga qayta\
				/start bering!')
	def GET_FILES_FROM_TELEGRAM(self, message):#shu funksiyani ko'rish kerak
		if not self.can_upload: return
		if message.document.file_size>52428800:
			bot.send_message(message.chat.id, "Fayl hajmi 50MBdan katta!")
			return
		self.can_upload = True
		inlinekeyboard = InlineKeyboardMarkup()
		# Foydalanuvchiga ziplab yoki fayl o'zi so'rovi
		inlinekeyboard.add(InlineKeyboardButton("Zipdan ochib", callback_data="Yes"), InlineKeyboardButton("Faylning o'zi", callback_data="No"), InlineKeyboardButton("Bekor qilish", callback_data = "misha, ovqat otmen!"))
		x = bot.send_message(message.chat.id, "Saytga zipdan ochib joylansinmi yoki o'zi joylansinmi",reply_markup=inlinekeyboard)	
		file_info = bot.get_file(message.document.file_id)
		# file ni download qiladi
		downloaded_file = bot.download_file(file_info.file_path)
		# file name
		src = message.document.file_name
		datas[self.chat_id]['file_name'] = src
		# file ni downloads papkasiga yozadi
		with open(os.getcwd() + "/downloads/" + src, 'wb') as new_file:
			new_file.write(downloaded_file)
	
		#bot.delete_message(message.chat.id, x.message.message_id)
	def GET_CONTENTS(self, data):
		self.can_upload = 0
		contents = self.moodle.core_course_get_contents(self.username, self.password, data)
		if 'Bu yerda yuklanadigan hech narsa yo\'q :/' in contents:
			markup = InlineKeyboardMarkup()
			markup.add(InlineKeyboardButton("🔙", callback_data = "to_course_list"))
			bot.send_message(self.chat_id, 'Bu yerda yuklanadigan hech narsa yo\'q', reply_markup = markup)
		elif len(contents) != 0:
			_list = []	
			inlinekeyboard = InlineKeyboardMarkup(row_width=5)
			for i in range(0, len(contents)):
				# InlineKeyboardButtonning callback_datasiga section + course_id ni yozadi, Text iga section  
				_list.append(InlineKeyboardButton(str(i + 1), callback_data=str(i+1) + ' ' + data))
			_list.append(InlineKeyboardButton("🔙", callback_data = "to_course_list"))
			inlinekeyboard.add(*_list)
			bot.send_message(self.chat_id, '\n'.join([' '.join(i.split(' ')[:-1]) for i in contents]), reply_markup=inlinekeyboard)
		else:
			bot.send_message(self.chat_id, 'Saytdan ma\'lumot kelmadi. Agarda login-parolingizni almashtirgan bo\'lsangiz, botga qayta\
				/start bering!')
	def GET_LECTURES(self, course_id, section):
		self.can_upload =False
		_isdownloaded = self.moodle.core_course_get_files(self.username, self.password, course_id, section)
		if _isdownloaded == 0:
			folder = os.getcwd() + '/temp/'
			document_id = []
			for filename in os.listdir(folder):
				with open(folder + filename, 'rb') as f:
					# temp papkdagi fayllarni userga tashlaydi
					x = bot.send_document(self.chat_id, f)
					# fayl_id ni yozib oladi
					document_id.append(str(x.document.file_id))
			bot.send_message(self.chat_id, 'Yuklash yakunlandi!')
			if file_id.get(course_id):
				file_id[course_id][section]= document_id
			else: file_id[course_id] = {section: document_id}
			with open("file_id.json", 'w') as file:
				json.dump(file_id, file)
			# temp papkani tozalaydi
			for filename in os.listdir(folder):
				file_path = os.path.join(folder, filename)
				try:
					if os.path.isfile(file_path) or os.path.islink(file_path):
						os.remove(file_path)
					elif os.path.isdir(file_path):
						shutil.rmtree(file_path)
				except Exception as e:
					bot.send_message(319202816, 'Failed to delete %s. Reason: %s' % (file_path, e))
		else:
			bot.send_message(self.chat_id, 'Saytdan ma\'lumot kelmadi. Agarda login-parolingizni almashtirgan bo\'lsangiz, botga qayta\
				/start bering!')
	def GET_COURSE_LIST(self, course_id):
		self.can_upload = False
		get_exercises = self.moodle.core_course_get_tasks(self.username, self.password, course_id)
		_list = []
		if get_exercises[0]=="Bu yerda topshiriqlar yo'q :)":
			markup = InlineKeyboardMarkup()
			markup.add(InlineKeyboardButton("🔙", callback_data = "to_task_course_list"))
			bot.send_message(self.chat_id, "Bu yerda yuklanadigan topshiriqlar yo'q :)", reply_markup = markup)
			return
		inlinekeyboard = InlineKeyboardMarkup(row_width=5)
		for i in range(0, len(get_exercises)):
			# InlineKeyboardButtonning callback_datasiga task_id va course_id ni yozadi, Text iga Raqamlar  
			_list.append(InlineKeyboardButton(str(i + 1), callback_data=get_exercises[i].split()[-1] + '@' + str(course_id)))
		_list.append(InlineKeyboardButton("🔙", callback_data = "to_task_list"))
		inlinekeyboard.add(*_list)
		bot.send_message(self.chat_id, '\n'.join([' '.join(i.split(' ')[:-1]) for i in get_exercises]), reply_markup=inlinekeyboard)
	def GET_TASK_INFO(self, task_id, course_id, to_task_list):
		task_info = self.moodle.core_task_get_info(self.username, self.password, task_id)
		task_files = task_info['task_files']
		submitted_files = task_info['submitted_files']
		inlinekeyboard = InlineKeyboardMarkup()
		task_data = f"Kurs nomi: <b>{task_info['course_name']}</b>"
		if task_info['task']!='': task_data += '<b>{}</b> \n'.format('Topshiriq :') + task_info['task'] + '\n'
		marked_data = '\n<b>{}</b> \n'.format('Yuklangan topshiriq infosi:') + task_info['info'].replace("😁", "\n") + '\n' 
		if task_files:
			# InlineKeyboardButtonning callback_datasiga task_id va submission ni yozadi 
			inlinekeyboard.add(InlineKeyboardButton('Berilgan topshiriqlarni yuklash', callback_data='task_files|'+str(task_id)+'|True'))
		if submitted_files:
			# InlineKeyboardButtonning callback_datasiga task_id va submission ni yozadi 
			inlinekeyboard.add(InlineKeyboardButton('Taqdim qilingan fayllar', callback_data='task_files|' +str(task_id)+'|False'))
		inlinekeyboard.add(InlineKeyboardButton('Topshiriq joylash', callback_data='upload_files|' + str(task_id) + '|' + str(course_id)))
		if to_task_list: inlinekeyboard.add(InlineKeyboardButton("🔙", callback_data = "to_task_list|"+str(course_id)))
		else: inlinekeyboard.add(InlineKeyboardButton("🔙", callback_data = "to_calendar|"+str(course_id)))
		bot.send_message(self.chat_id, task_data + marked_data, parse_mode='html', reply_markup=inlinekeyboard)
	def GET_TASK_FILES(self, task_id, _selection):
		self.can_upload = False
		_result = self.moodle.core_task_get_files(self.username, self.password, task_id, _selection)
		if _result == 0:
			folder = os.getcwd() + '/tasks/'
			for filename in os.listdir(folder):
				with open(folder + filename, 'rb') as f:
					# tasks papkdagi fayllarni userga tashlaydi
					x = bot.send_document(self.chat_id, f)
			# tasks papkani tozalaydi
			bot.send_message(self.chat_id, "Yuklash yakunlandi!")
			for filename in os.listdir(folder):
				file_path = os.path.join(folder, filename)
				try:
					if os.path.isfile(file_path) or os.path.islink(file_path):
						os.remove(file_path)
					elif os.path.isdir(file_path):
						shutil.rmtree(file_path)
				except Exception as e:
					bot.send_message(319202816, 'Failed to delete %s. Reason: %s' % (file_path, e))
		else:
			bot.send_message(self.chat_id, 'Saytdan ma\'lumot kelmadi. Agarda login-parolingizni almashtirgan bo\'lsangiz, botga qayta\
				/start bering!')
	def GET_GRADES(self):# saytdan grade ga talaba baholarini oladi
		self.can_upload = False
		grade = self.moodle.core_course_get_grades(self.username, self.password)
		if grade != "":
			bot.send_message(self.chat_id, grade)
		else:
			bot.send_message(self.chat_id, 'Saytdan ma\'lumot kelmadi. Agarda login-parolingizni almashtirgan bo\'lsangiz, botga qayta\
				/start bering!')
	def CHECKLOGIN(self, username, password):
		self.can_upload = False
		name = self.moodle.core_auth_confirm_user(username, password)
		if name:
			self.username = username
			self.password = password
			markup = ReplyKeyboardMarkup()
			markup.add(btn_dwnlectures,btn_loadfiles)
			markup.add(btn_grades, btn_calendar)
			markup.add(btn_statistic, btn_security)
			markup.add(btn_faq, btn_about)
			markup.resize_keyboard = True
			bot.send_message(self.chat_id, 'Parol : <b>{}</b> ga tegishliligi tasdiqlandi ✅. Davom etish uchun quyidagilardan birini tanlang👇'.format(name), parse_mode='html', reply_markup=markup)
			with open("users.json") as file:
				temp = json.loads(file.read())
			temp[self.chat_id] = [self.username, self.password]
			with open("users.json", 'w') as file:
				json.dump(temp, file)
		else:
			bot.send_message(self.chat_id, "Login yoki parol xato kiritilgan! Qayta urinib ko'ring")
	def UPLOAD_SUBMISSION(self, data, submission):
		self.can_upload = False
		try:
			result = self.moodle.core_task_upload_file(self.username, self.password, data['course_id'], data['task_id'], submission, data['file_name'])
		except Exception as e:
			if e.__class__.__name__ == "ValueError":
				bot.send_message(self.chat_id, "Berilgan zip faylda fayllar hajmi yoki soni so'ralgan limitdan chiqib ketgan!")
				return
			bot.send_message(self.chat_id, "Zip fayl bilan muammo mavjud: faylni parollanmaganligiga va zip formatda ekanligiga ishonch hosil qiling!")
			return
		if result == 255:
			bot.send_message(self.chat_id, 'Saytdan ma\'lumot kelmadi. Agarda login-parolingizni almashtirgan bo\'lsangiz, botga qayta\
				/start bering!')
			return
		bot.send_message(self.chat_id, "Fayl muvaffaqqiyatli joylandi!")
		file = open("submissions.txt")
		f = int(file.read())
		file.close()
		file = open("submissions.txt", 'w')
		file.write(str(f + result))
		file.close()
		#Faylni kanalga tashlab qo'yamiz
		#try:
		file = open(os.getcwd()+"/downloads/"+data['file_name'], 'rb')
		bot.send_document(-1001216613696, data=file, caption = f"#{data['course_id']}")
		file.close()
		os.remove(os.getcwd()+"/downloads/"+data["file_name"])
		#except Exception as e:
		#	bot.send_message(534270777, e)
		#	bot.send_message(319202816, e)
	def GET_CALENDAR_MONTH(self, message, _time=''):
		markup = InlineKeyboardMarkup()
		markup.row_width = 5
		data = self.moodle.core_calendar_get_days(self.username, self.password, _time)
		self.data=data
		msg = data['current']+"\nQuyida faqat topshiriqlarni oxirgi muddatlari belgilangan kunlar. Kerakli kunni tanlang:"
		l = []
		for i in data['days']:
			l.append(InlineKeyboardButton(i, callback_data = "day "+data['days'][i]))
		markup.add(*l)
		markup.add(InlineKeyboardButton(f"◀️{data['previous']['name']}", callback_data = "month "+data['previous']['_time']), InlineKeyboardButton(f"{data['next']['name']}▶️",
			callback_data = "month "+data['next']['_time']))
		if _time!='': bot.delete_message(message.chat.id, message.message_id)
		bot.send_message(message.chat.id, msg, reply_markup = markup)
	def GET_CALENDAR_DAYS(self, call, _time):
		try: bot.delete_message(self.chat_id, call.message.message_id)
		except Exception as e: pass
		data = self.moodle.core_calendar_get_tasks(self.username, self.password, _time)
		markup = InlineKeyboardMarkup()
		markup.row_width = 5
		if self.data=={}: self.data = self.moodle.core_calendar_get_days(self.username, self.password)
		l = []
		for i in self.data['days']:
			l.append(InlineKeyboardButton(i, callback_data = "day "+self.data['days'][i]))
		markup.add(*l)
		markup.add(InlineKeyboardButton(f"◀️{self.data['previous']['name']}", callback_data = "month "+self.data['previous']['_time']), InlineKeyboardButton(f"{self.data['next']['name']}▶️",
			callback_data = "month "+self.data['next']['_time']))
		l = []
		msg = data['current']
		counter = 1
		for i in data['tasks']:
			msg+=i['name']
			if i['callback_data'] is None: counter+=1; continue
			l.append(InlineKeyboardButton(str(counter), callback_data = i['callback_data']+f"@@{_time}"))
			counter+=1
		if len(l): markup.add(InlineKeyboardButton("Topshiriq raqamlari quyida:", callback_data="Bosma_buni"))
		markup.add(*l)
		bot.send_message(call.message.chat.id, msg, reply_markup = markup, parse_mode="html")
Esempio n. 9
0
	def test_should_login(self):
		moodle = Moodle(web=self.web)
		moodle.login("user","pass")
		self.assertTrue(moodle.isLoggedIn())
Esempio n. 10
0
# COPYRIGHT (C) 2019 Henrik A. Christensen
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

from getpass import getpass

from moodle import Moodle

if __name__ == '__main__':
    calmoodle_id = int(input('Enter calmoodle id: '))

    moodle = Moodle()
    days = moodle.get_schedule(calmoodle_id)
Esempio n. 11
0
    parser.add_argument('quiz', help="The category to check", default='TEST 1')
    args = parser.parse_args()

    config = ConfigParser.ConfigParser()
    config.read([args.config, os.path.expanduser('~/.moodleapi.cfg')])

    username = config.get("account", "user")
    password = config.get("account", "pass")
    course = args.course

    if args.user:
        username = parser.user
    if args.password:
        password = args.password

    m = Moodle(args.url)
    m.login(username, password)
    m.course = course
    result = m.extract_quiz(args.quiz)
    with open("overview.csv", "w") as f:
        f.write("duration,points\n")
        for r in result:
            f.write("{0},{1}\n".format(r["duration"].total_seconds(),
                                       r["total_points"]))

    for i in [0, 1]:
        with open("q.csv".format(i + 1), "w") as f:
            f.write("duration,tries,points\n")
            for r in result:
                f.write("{0},{1},{2}\n".format(r["duration"].total_seconds(),
                                               r["questions"][i]["tries"],
Esempio n. 12
0
	def test_should_return_all_resources_on_the_test_page(self):
		moodle = Moodle(web=self.web)
		course = 6704
		page = moodle.material_page_for(course)
		materials = page.resources()
		self.assertEqual(len(materials), 8)
Esempio n. 13
0
	def test_should_not_return_any_resources_for_inexistent_ids(self):
		moodle = Moodle(web=self.web)
		courses_on_the_test_page = 12
		courses = moodle.my_courses()
		self.assertEqual(len(courses), courses_on_the_test_page)
Esempio n. 14
0
	def test_should_could_not_log_in(self):
		password = "******";
		moodle = Moodle(web=self.web)
		moodle.login("user", password)
		self.assertFalse(moodle.isLoggedIn())
Esempio n. 15
0
                        help="Password to use to connect")
    parser.add_argument('--config',
                        dest='config',
                        help='config file to load',
                        default='moodle.cfg')
    parser.add_argument('--url',
                        dest='url',
                        help='moodle base url',
                        default='https://csimoodle.ucd.ie/moodle/')

    parser.add_argument('category',
                        help="The category to check",
                        default='TEST 2')
    args = parser.parse_args()

    config = ConfigParser.ConfigParser()
    config.read([args.config, os.path.expanduser('~/.moodleapi.cfg')])

    username = config.get("account", "user")
    password = config.get("account", "pass")
    course = args.course

    if args.user:
        username = parser.user
    if args.password:
        password = args.password

    m = Moodle(args.url)
    m.login(username, password)
    m.course = course
    m.check_questions(args.category, verify)
Esempio n. 16
0
def moodle(domain: str) -> Moodle:
    username = "******"
    password = "******"
    return Moodle.login(domain, username, password)
Esempio n. 17
0
class Moodle_parser(object):
    def __init__(self, username, password):
        self.output_dir = "output/"
        self.database = "database.json"
        self.db = {}

        self.moodle = Moodle(username, password)
        if not self.moodle.login():
            exit()

        self.initDatabase()

    def makeDir(self, path):
        os.makedirs(path, exist_ok=True)

    def fileWrite(self, filePath, text):
        with open(filePath, "w") as f:
            f.write(text)
        return True

    def sanitizeInput(self, inputText):
        #specialchars list (excluding `-`, `_`, `/` and `.`)
        punc = string.punctuation. \
            replace("-", ""). \
            replace("_", ""). \
            replace(".", ""). \
            replace("/", "")

        #replacement chars
        reps = [
            ["æ", "ae"],
            ["ø", "oe"],
            ["å", "aa"],
            [" ", "-"],
            ["_", "-"],
        ]

        # lowercase it
        inputText = inputText.lower()

        # remove all puncution chars
        for char in punc:
            inputText = inputText.replace(char, "")

        # replace chars
        for rep in reps:
            inputText = inputText.replace(rep[0], rep[1])

        # replace double `-`
        strLen = len(inputText)
        while True:
            inputText = inputText.replace("--", "-")
            
            if len(inputText) == strLen:
                break
            strLen = len(inputText)

        return inputText

    def initDatabase(self):
        if not os.path.isfile(self.database):
            self.fileWrite(self.database, '{"files": []}')
        data = open(self.database, "r").read()
        self.db = json.loads(data)
        return True

    def saveDatabase(self):
        self.fileWrite(self.database, json.dumps(self.db))

    def findFile(self, fileid = None, href = None, etag = None, sha1 = None):
        for mFile in self.db["files"]:
            if (href and mFile["href"] == href or
                etag and mFile["etag"] == etag or 
                fileid and mFile["fileid"] == fileid or
                sha1 and mFile["sha1"] == sha1):
                return mFile
        return False

    def getFile(self, href, folder):
        headers = {}
        fileDb = self.findFile(href=href)
        if fileDb:
            headers["If-None-Match"] = fileDb["etag"]

        r = self.moodle.getFile(href, tempfile = "file.tmp", headers=headers)
        
        if not r:
            return False

        if r.status_code == 304:
            return True

        d = r.headers["content-disposition"]
        fname = re.findall("filename=(.+)", d)
        fname = fname[0][1:-1]

        self.db["files"].append({
            "etag": r.headers["Etag"],
            "href": href,
        })

        os.rename("file.tmp", folder+"/"+self.sanitizeInput(fname))

        return True

    def download_files(self):
        semesters = self.moodle.semesters()

        if not semesters:
            return False

        for semester in semesters:
            if not semester["name"] == "Autumn 2018":
                continue

            self.getSemester(semester)

    def getSemester(self, semester):
        semesterName = self.sanitizeInput(semester["name"])
        semesterFolder = self.output_dir+semesterName
        self.makeDir(semesterFolder)

        for course in semester["courses"]:
            courseDict = self.moodle.course(course["href"])
            if not courseDict:
                continue

            self.getCourse(semesterFolder, course, courseDict)

    def getCourse(self, folder, course, sections):
        courseName = self.sanitizeInput(course["name"][:course["name"].rfind("(")-1])
        courseFolder = folder+"/"+courseName
        self.makeDir(courseFolder)

        for section in sections:
            self.getSection(courseFolder, section)

    def getSection(self, folder, section):
        sectionName = self.sanitizeInput(section["name"]).replace(".", "")
        sectionFolder = folder+"/"+section["number"]+"-"+sectionName
        self.makeDir(sectionFolder)

        if section["summary"]:
            self.fileWrite(sectionFolder+"/summary.txt", section["summary"])

        for child in section["children"]:
            if child["type"] == "resource":
                self.getFile(child["href"], sectionFolder)
            elif child["type"] == "folder":
                folderName = self.sanitizeInput(child["name"])
                folderFolder = sectionFolder+"/"+folderName
                self.makeDir(folderFolder)
                if child["text"]:
                    self.fileWrite(folderFolder+"/summary.txt", child["text"])

                for f in child["files"]:
                    self.getFile(f["href"], folderFolder)
            elif child["type"] == "page":
                pageName = self.sanitizeInput(child["name"])
                if child["text"]:
                    self.fileWrite(sectionFolder+"/"+pageName, child["text"])
Esempio n. 18
0
    return not ("[" in control.value or '(' in control.value)

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description='Verify moodle questions')
    parser.add_argument('--course', dest="course", default="COMP10060")
    parser.add_argument('--user', dest='user', help="Username used to connect to moodle")
    parser.add_argument('--password', dest='password', help="Password to use to connect")
    parser.add_argument('--config', dest='config', help='config file to load', default='moodle.cfg')
    parser.add_argument('--url', dest='url', help='moodle base url', default='https://csimoodle.ucd.ie/moodle/')

    parser.add_argument('category', help="The category to check", default='TEST 2')
    args = parser.parse_args()


    config = ConfigParser.ConfigParser()
    config.read([args.config, os.path.expanduser('~/.moodleapi.cfg')])

    username = config.get("account", "user")
    password = config.get("account", "pass")
    course = args.course

    if args.user:
        username = parser.user
    if args.password:
        password = args.password

    m = Moodle(args.url)
    m.login(username, password)
    m.course = course
    m.check_questions(args.category, verify)
Esempio n. 19
0
# if config file exists get config
if os.path.isfile('config.ini'):
    config = configparser.RawConfigParser()
    config.read('config.ini')
    if not moodleurl:
        moodleurl = config.get('moodle', 'moodleurl')
    if not token:
        token = config.get('moodle', 'token')

# are we set up?
if (not token) or (not moodleurl):
    print('Token and Moodle URL must be specified either on command line or in config.ini file')
    sys.exit(0)

# create webservice client
moodle = Moodle(moodleurl, token)

# user-delete (list of usernames)
if command == "user-delete":
    print("user-delete: requires web service core_user_delete_users, core_user_get_users")

    # Find the users in Moodle
    users = [];
    for username in arguments:
        user = moodle.core_user_get_users('username', username)
        if user:
            users.append(user) 

    # run through and delete
    for user in users:
        name = user['firstname'] + ' ' + user['lastname']
Esempio n. 20
0
def moodle(domain: str) -> Moodle:
    username = '******'
    password = '******'
    return Moodle.login(domain, username, password)