def studio_view(self, context=None): """ The staff's view of RichReviewXBlock. Staffs can upload discussion topic PDF or view the students' discussion activities """ frag = Fragment() frag.add_css(load_resource("static/css/richreview.css")) frag.add_javascript(load_resource("static/js/src/richreview_studio.js")) frag.add_content(render_template( "templates/richreview_studio.html", { 'xblock_id': self.xblock_id, 'student_id': self.anonymous_student_id, 'user_is_staff': str(self.user_is_staff), 'students_of_group': str(self.students_of_group), 'group_of_student': str(self.group_of_student), 'discussion_docid': self.discussion_docid, 'is_pdf_ready': self.is_pdf_ready, 'is_debug': False, 'pdf_url': self.fs.get_url(self.pdf_path, RESOURCE_EXPIRATION_TIME), 'pdfjs_url': self.fs.get_url(self.pdfjs_path, RESOURCE_EXPIRATION_TIME), 'loader_gif_url': self.runtime.local_resource_url(self, "public/ajax-loader.gif") } )) frag.initialize_js('RichReviewXBlockStudio', "abcd") return frag
def _staff_view(self, context): """ Render the staff view for a split test module. """ fragment = Fragment() contents = [] for group_id in self.group_id_to_child: child_location = self.group_id_to_child[group_id] child_descriptor = self.get_child_descriptor_by_location(child_location) child = self.system.get_module(child_descriptor) rendered_child = child.render(STUDENT_VIEW, context) fragment.add_frag_resources(rendered_child) contents.append({ 'group_id': group_id, 'id': child.location.to_deprecated_string(), 'content': rendered_child.content }) # Use the new template fragment.add_content(self.system.render_template('split_test_staff_view.html', { 'items': contents, })) fragment.add_css('.split-test-child { display: none; }') fragment.add_javascript_url(self.runtime.local_resource_url(self, 'public/js/split_test_staff.js')) fragment.initialize_js('ABTestSelector') return fragment
def student_view(self, context=None): """ The primary view of the SqlInjectionXBlock, shown to students when viewing courses. """ if self.problem_id not in self.AVAILABLE_PROBLEMS: frag = Fragment(u"problem_id {} is not valid".format(self.problem_id)) return frag problem_resources = self.AVAILABLE_PROBLEMS[self.problem_id] html = self.resource_string(problem_resources['html']) frag = Fragment(html.format(self=self)) for css_file in problem_resources['css']: frag.add_css(self.resource_string(css_file)) for js_file in problem_resources['js']: js_str = Template(self.resource_string(js_file)).render( Context({ 'prev_answers_json': json.dumps(getattr(self, problem_resources['log'])), 'problem_score': self.student_score, 'problem_weight': self.weight, 'attempts': self.student_attempts, })) frag.add_javascript(js_str) for js_obj in problem_resources['js_objs']: frag.initialize_js(js_obj) return frag
def student_view(self, context=None): """ The primary view of the ConceptXBlock, shown to students when viewing courses. """ html = self.resource_string("static/html/concept.html")#.replace("PLACEHOLDER_FOR_CONCEPT_MAP",json.dumps(self.concept_map)) cm = self.concept_map if not cm: cm = '{"required":[], "taught":[], "exercised":[]}' # These three lines are not strictly required, but they do # make the code more robust if, for whatever reason, the # storage ends up with nothing for the server. The client # still doesn't work without a valid server, but we don't get # an exception, so we're more likely to be able to get far # enough to fix it. server = self.server if not server: server = "" frag = Fragment(html.replace("PLACEHOLDER_FOR_CONCEPT_MAP",cm).replace("SERVER", server)) frag.add_css_url("https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css") frag.add_css(self.resource_string("static/css/concept.css")) frag.add_javascript_url("http://builds.handlebarsjs.com.s3.amazonaws.com/handlebars-v1.3.0.js") frag.add_javascript_url("https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js") frag.add_javascript(self.resource_string("static/js/concept.js")) frag.initialize_js('ConceptXBlock') return frag
def student_view(self, context=None): ''' The primary view of the XBlock, shown to students when viewing courses. ''' problem_progress = self._get_problem_progress() used_attempts_feedback = self._get_used_attempts_feedback() submit_class = self._get_submit_class() prompt = self._get_body(self.question_string) explanation = self._get_explanation(self.question_string) attributes = '' html = self.resource_string('static/html/submit_and_compare_view.html') frag = Fragment( html.format( display_name=self.display_name, problem_progress=problem_progress, used_attempts_feedback=used_attempts_feedback, submit_class=submit_class, prompt=prompt, student_answer=self.student_answer, explanation=explanation, your_answer_label=self.your_answer_label, our_answer_label=self.our_answer_label, submit_button_label=self.submit_button_label, attributes=attributes, ) ) frag.add_css(self.resource_string('static/css/submit_and_compare.css')) frag.add_javascript( self.resource_string('static/js/submit_and_compare_view.js'), ) frag.initialize_js('SubmitAndCompareXBlockInitView') return frag
def student_view(self, context=None): # pylint: disable=no-member """ The primary view of the StaffGradedAssignmentXBlock, shown to students when viewing courses. """ context = { "student_state": json.dumps(self.student_state()), "id": self.location.name.replace('.', '_'), "max_file_size": getattr( settings, "STUDENT_FILEUPLOAD_MAX_SIZE", self.STUDENT_FILEUPLOAD_MAX_SIZE ) } if self.show_staff_grading_interface(): context['is_course_staff'] = True self.update_staff_debug_context(context) fragment = Fragment() fragment.add_content( render_template( 'templates/staff_graded_assignment/show.html', context ) ) fragment.add_css(_resource("static/css/edx_sga.css")) fragment.add_javascript(_resource("static/js/src/edx_sga.js")) fragment.add_javascript(_resource("static/js/src/jquery.tablesorter.min.js")) fragment.initialize_js('StaffGradedAssignmentXBlock') return fragment
def student_view(self, context=None): """ The primary view of the XBlock, shown to students when viewing courses. """ fullUrl = self.url if self.start_time != "" and self.end_time != "": fullUrl += "#t=" + self.start_time + "," + self.end_time elif self.start_time != "": fullUrl += "#t=" + self.start_time elif self.end_time != "": fullUrl += "#t=0," + self.end_time context = { "display_name": self.display_name, "url": fullUrl, "allow_download": self.allow_download, "source_text": self.source_text, "source_url": self.source_url, } html = self.render_template("static/html/videojs_view.html", context) frag = Fragment(html) frag.add_css(self.load_resource("static/css/video-js.min.css")) frag.add_css(self.load_resource("static/css/videojs.css")) frag.add_javascript(self.load_resource("static/js/video-js.js")) frag.add_javascript(self.load_resource("static/js/videojs_view.js")) frag.initialize_js("videojsXBlockInitView") return frag
def student_view(self, context): """ Create a fragment used to display the XBlock to a student. `context` is a dictionary used to configure the display (unused) Returns a `Fragment` object specifying the HTML, CSS, and JavaScript to display. """ provider, embed_code = self.get_embed_code_for_url(self.href) # Load the HTML fragment from within the package and fill in the template html_str = pkg_resources.resource_string(__name__, "static/html/simplevideo.html") frag = Fragment(unicode(html_str).format(self=self, embed_code=embed_code)) # Load CSS css_str = pkg_resources.resource_string(__name__, "static/css/simplevideo.css") frag.add_css(unicode(css_str)) # Load JS if provider == 'vimeo.com': # Load the Froogaloop library from vimeo CDN. frag.add_javascript_url("//f.vimeocdn.com/js/froogaloop2.min.js") js_str = pkg_resources.resource_string(__name__, "static/js/simplevideo.js") frag.add_javascript(unicode(js_str)) frag.initialize_js('SimpleVideoBlock') return frag
def student_view(self, context=None): """ The primary view of the TableXBlock, shown to students when viewing courses. """ html = self.resource_string("static/html/table.html") frag = Fragment(html.format(self=self)) frag.add_css(self.resource_string("static/css/table.css")) frag.add_javascript(self.resource_string("static/js/lib/xapiwrapper.min.js")) frag.add_javascript(self.resource_string("static/js/lib/knockout-3.1.0.js")) frag.add_javascript(self.resource_string("static/js/lib/knockout.mapping-latest.debug.js")) randNum = str(randint(0, 10000)) js = self.resource_string("static/js/src/table.js") tab = self.s_tableStructure showColumns = self.s_showColumns userRows = self.userRows jsStr = js.replace('{{tableStructure}}', tab) jsStr = jsStr.replace('{{showColumns}}', showColumns) jsStr = jsStr.replace('{{userRows}}', json.dumps(userRows)) jsStr = jsStr.replace('{{display_name}}', self.display_name) jsStr = jsStr.replace('{{randFuncName}}', randNum) jsStr = jsStr.replace('{{currentStructure}}', self.currentStructure) frag.add_javascript(jsStr) frag.initialize_js('TableXBlock' + randNum) return frag
def student_view(self, context=None): """ The primary view of the SharedFieldDemoXBlock, shown to students when viewing courses. """ # get the shared field data value # user_id ("2") is hard-coded self.user_id = self.scope_ids.user_id self.shared_num_query_value = self.shared_num_query.get(xblock=self, field_name = 'count', user_id='3') self.verifed_query_value = self.verifed_query.get( xblock=self, field_name = 'verified', user_id = 'student_1', usage_id = 'toyverifyxblock.toy_verify.d0.u0') if self.verifed_query_value: self.html_text = "You need to verify before the exam" else: self.html_text = "Wonderful! Here is your exam content" html = self.resource_string("static/html/shared_field_demo.html") frag = Fragment(html.format(self=self)) frag.add_css(self.resource_string("static/css/shared_field_demo.css")) frag.add_javascript(self.resource_string("static/js/src/shared_field_demo.js")) frag.initialize_js('SharedFieldDemoXBlock') return frag
def load_view(self, filename, data=[]): """Loading the whole XBlock fragment""" frag = Fragment(self.render_template(filename, data)) frag.add_css(self.resource_string("static/css/p3exblock.css")) frag.add_javascript(self.resource_string("static/js/src/p3exblock.js")) frag.initialize_js('P3eXBlock') return frag
def student_view(self, context=None): """ The primary view of the StaffGradedAssignmentXBlock, shown to students when viewing courses. """ # Ideally we would do this when the score is entered. This write on # read pattern is pretty bad. Currently, though, the code in the # courseware application that handles the grade event will puke if the # user_id for the event is other than the logged in user. if not self.score_published: self.runtime.publish(self, 'grade', { 'value': self.score, 'max_value': self.max_score(), }) self.score_published = True template = get_template("staff_graded_assignment/show.html") context = { "student_state": json.dumps(self.student_state()), "id": "_".join(filter(None, self.location)) } if self.show_staff_grading_interface(): context['is_course_staff'] = True fragment = Fragment(template.render(Context(context))) fragment.add_css(_resource("static/css/edx_sga.css")) fragment.add_javascript(_resource("static/js/src/edx_sga.js")) fragment.initialize_js('StaffGradedAssignmentXBlock') return fragment
def student_view(self, context=None): """ The primary view of the RichReviewXBlock, shown to students when viewing courses. """ frag = Fragment() frag.add_css(load_resource("static/css/richreview.css")) frag.add_javascript(load_resource("static/js/src/richreview_student.js")) frag.add_content(render_template( "templates/richreview_student.html", { 'xblock_id': self.xblock_id, 'student_id': self.anonymous_student_id, 'user_is_staff': str(self.user_is_staff), 'students_of_group': str(self.students_of_group), 'group_of_student': str(self.group_of_student), 'discussion_docid': self.discussion_docid, 'is_debug': False, 'is_pdf_ready': self.is_pdf_ready } )) frag.initialize_js('RichReviewXBlock') return frag
def studio_view(self, context=None): fragment = Fragment() fragment.add_content(Util.render_template("static/html/uc_rtc_studio.html")) fragment.add_css(Util.load_resource("static/css/uc_rtc.css")) fragment.add_javascript(Util.load_resource("static/js/src/uc_rtc_edit.js")) fragment.initialize_js("UcRtcXBlock") return fragment
def student_view(self, context=None): """ The primary view of the ModelViewer, shown to students when viewing courses. """ template_str = self.resource_string("static/html/mt3d.html") template = Template(template_str) html = template.render(Context({ 'lres':self.model3d, 'lword':self.title, 'bg1':self.background1, 'bg2':self.background2, 'height':self.height, 'width':self.width })) frag = Fragment(html.format(self=self)) frag.add_css(self.resource_string("static/css/mt3d.css")) frag.add_javascript(self.resource_string("static/js/src/mt3d.js")) frag.add_javascript(self.resource_string("static/js/lib/jsc3d.js")) frag.add_javascript(self.resource_string("static/js/lib/jsc3d.webgl.js")) frag.add_javascript(self.resource_string("static/js/lib/jsc3d.touch.js")) frag.add_javascript(self.resource_string("static/js/lib/jsc3d.console.js")) frag.initialize_js('ModelViewer') return frag
def student_view(self, context=None): """ The primary view of the ProfileXBlock, shown to students when viewing courses. """ photo_url = self.runtime.local_resource_url(self, 'public/assets/profile.png') if self.photo_storage.exists("profile.png"): photo_url = self.photo_storage.get_url("profile.png", 600) params = { 'PHOTO_URL': photo_url } for asset in assets: params[asset] = self.runtime.local_resource_url(self, os.path.join("public/assets",asset)) html = replace_template(self.resource_string("static/html/profile.html"), params) frag = Fragment(html) frag.add_javascript_url('//cdnjs.cloudflare.com/ajax/libs/mustache.js/0.8.1/mustache.min.js') #frag.add_javascript_url(self.runtime.local_resource_url(self, 'public/3rdParty/mustache.js')) frag.add_css_url('//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.4/css/jquery-ui.min.css') #frag.add_css_url(self.runtime.local_resource_url(self, 'public/3rdParty/jquery-ui.css')) frag.add_javascript_url('//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js') # frag.add_javascript_url(self.runtime.local_resource_url(self, 'public/3rdParty/jquery-ui.min.js')) # TODO: This would give nicer selects # frag.add_css(self.resource_string("static/3rdparty/jquery.dropdown.css")) # frag.add_javascript(self.resource_string("static/3rdparty/jquery.dropdown.min.js")) frag.add_css(self.resource_string("static/css/profile.css")) frag.add_javascript(self.resource_string("static/js/src/profile.js")) profile_config = profile_json.profile_config if self.view.lower() == "peer": profile_config = profile_json.peer_profile_config frag.initialize_js('ProfileXBlock', {'profile_data': self.user_profile, 'profile_config':profile_config}) return frag
def student_view(self, context=None): questionData = self.resource_string(self.summary_question) questionData = json.loads(questionData) self.maxQuestionIndex = questionData["numQuestionsForExercise"] - 1; self.maxPoints = questionData["maxPointsForExercise"]; self.currentQuestionIndex = random.randint(0,self.maxQuestionIndex) self.questionPool = questionData["questionUrls"][:] data = self.resource_string(self.questionPool[self.currentQuestionIndex]) data = json.loads(data) html_context = Context({"question_title": data["question"]["problem"], "max_points": self.maxPoints, "score" : self.score }) html_template = Template(self.resource_string(questionData["htmlString"])) jsavContent = "" if data["usesJsav"]: jsavContent = data["jsavStuff"] frag = Fragment(html_template.render(html_context)) js_context = Context({ "numberOfPossibleAnswers" : len(data["question"]["answers"]), "answers": json.dumps(data["question"]["answers"]), "jsavStuff": jsavContent, "solution_index": data["question"]["solution_index"] }) js_template = Template(self.resource_string(questionData["jsString"])) js_str = js_template.render(js_context) frag.add_javascript(js_str) frag.add_css(self.resource_string(questionData["cssString"])) frag.initialize_js("ExerciseQuestionsXBlock") return frag
def studio_view(self, context=None): html = self.resource_string("static/html/studio.html") frag = Fragment(html.format(self=self)) frag.add_css(self.resource_string("static/css/codecheck_tutorial.css")) frag.add_javascript(self.resource_string("static/js/src/studio.js")) frag.initialize_js('CodecheckStudioXBlock') return frag
def student_view(self, context=None): """ The primary view of the GenexerciseXBlock, shown to students when viewing courses. """ """ pull answer files from gitlab """ # os.system('/var/www/zyni/script/pullFromGitlab.sh') """ statistic according to answer files """ # os.system('python /var/www/zyni/script/statistic.py') """ push result to github """ # os.system('/var/www/zyni/script/pushToGitHubStatistic.sh') html = self.resource_string("static/html/genexercise.html") frag = Fragment(html.format(self=self)) frag.add_css(self.resource_string("static/css/genexercise.css")) frag.add_javascript(self.resource_string("static/js/src/genexercise.js")) frag.initialize_js('GenexerciseXBlock') return frag
def student_view(self, context=None): """ The primary view of the DjangoBBXBlock, shown to students when viewing courses. """ #html = self.resource_string("static/html/xdjangobb.html") response = requests.get(self.service_url + self.html_service_endpoint_extension) #html = str(response.text).strip(' \t\r\n').replace('href="/', 'href="http://localhost:12345/') #html = str(response.text).strip(' \t\r\n').decode('utf8') html = str(response.text).strip(' \t\r\n') #pattern = r'<body>.*</body>' #start = re.search(pattern, html).start() #end = re.search(pattern, html).end() #html = html[start + 6 : end - 7] response = requests.get(self.service_url + self.css_service_endpoint_extension) css = str(response.text).strip(' \t\r\n') #if len(css) > 0: # html += '<p> The css has length ' + str(len(css)) + 'and has the content ' + css + ' </p>' #else: # html += '<p> NO CSS! </p>' #css = "#my-div{ border-style: solid; border-width: 5px; }" response = requests.get(self.service_url + self.js_service_endpoint_extension) js = str(response.text).strip(' \t\r\n') #if len(js) > 0: # html += '<p> The js has length ' + str(len(js)) + 'and has the content ' + js + ' </p>' #else: # html += '<p> NO JS! </p>' #js = 'function djangobb(runtime, element){alert("This works!");}' frag = Fragment(unicode(html).format(self=self)) frag.add_javascript(unicode(js)) frag.add_css(unicode(css)) frag.initialize_js('xdjangobb') return frag
def studio_view(self, context=None): """ The studio view """ banner_url1 = self.runtime.local_resource_url(self, 'public/img/banner01.jpg') banner_url2 = self.runtime.local_resource_url(self, 'public/img/banner02.jpg') banner_url3 = self.runtime.local_resource_url(self, 'public/img/banner03.jpg') fragment = Fragment() content = { 'self': self, 'banner1': banner_url1, 'banner2': banner_url2, 'banner3': banner_url3, } # Load Studio View fragment.add_content(render_template('static/html/slider_edit.html', content)) fragment.add_css(load_resource('static/css/slider_edit.css')) fragment.add_javascript(unicode(render_template('static/js/src/jquery.MultiFile.js', content))) fragment.add_javascript(unicode(render_template('static/js/src/slider_edit.js', content))) fragment.initialize_js('SliderXBlockStudio') return fragment
def student_view(self, context): """ Generate the html code to display the XBlock to a student `context` is a dictionary used to configure the display (unused). Returns a `Fragment` object specifying the HTML, CSS, and JavaScript to display. """ provider, embed_code = self.get_embed_code_for_url(self.href) # Retrieve HTML code for video iframe html_code = pkg_resources.resource_string(__name__, "static/html/cnvideo.html") frag = Fragment(unicode(html_code).format(self=self, embed_code=embed_code)) # Load CSS css_str = pkg_resources.resource_string(__name__, "static/css/cnvideo.css") frag.add_css(css_str) # Load vimeo JS API and custom js for watching views if provider == "vimeo.com": frag.add_javascript_url("//f.vimeocdn.com/js/froogaloop2.min.js") js_str = pkg_resources.resource_string(__name__, "static/js/cnvideo.js") frag.add_javascript(unicode(js_str)) frag.initialize_js("cnVideoBlock") return frag
def student_view(self, context=None): """ The primary view of the MyXBlock, shown to students when viewing courses. """ if not context: context = {} #Define path for images to be used on html template correct_icon_path=self.runtime.local_resource_url(self, 'public/imgs/correct-icon.png') incorrect_icon_path=self.runtime.local_resource_url(self, 'public/imgs/incorrect-icon.png') #Define variable to be used in HTML Template context.update({ 'test_title' : self.test_title, 'questions': self.questions, 'total_question' : self.total_question, 'correct_icon' : correct_icon_path, 'incorrect_icon' : incorrect_icon_path, }) html = Template( self.resource_string("public/html/question.html")).render(Context(context) ) frag = Fragment(html) # LOAD CSS frag.add_css(self.resource_string("public/css/question.css")) # LOAD JS frag.add_javascript(self.resource_string("public/js/src/question.js")) # CREATE XBLOCK frag.initialize_js('QuestionBlock') return frag
def student_view(self, context=None): """ The primary view of VideoQuiz, shown to students. """ # load contents of quiz if any, otherwise this is just a YouTube video player if self.quiz_content != "": self.load_quiz() print("Loading Student View") print("====================") print(">> Parameters: ") print(self.quiz_content) print(self.vid_url) # print(self.width) # print(self.height) print(">> Filled data") print("Quiz entries: " + str(self.quiz)) print("Quiz cue times: " + str(self.quiz_cuetimes)) print("Answers: " + str(self.answers)) print("Results: " + str(self.results)) fragment = Fragment() fragment.add_content(render_template('templates/html/vidquiz.html', {'self': self})) fragment.add_css(load_resource('static/css/vidquiz.css')) fragment.add_javascript(load_resource('static/js/vidquiz.js')) fragment.initialize_js('VideoQuiz') return fragment
def student_view(self, context=None): """ This renders the view for the XBlock. It poses a question and asks the student to create a musical composition as an answer. """ self.display_tune = self.tune if self.tune else self.start_tune self.display_question = self.question if self.question else "<span class='error'>no question specified</span>" # base template html = self.resource_string("static/html/musicstaff.html") frag = Fragment(html.format(self=self)) # stylesheets frag.add_css(self.resource_string("static/css/pure/pure-min.css")) frag.add_css(self.resource_string("static/css/musicstaff.css")) # library dependencies frag.add_javascript(self.resource_string("static/js/libs/raphael.js")) frag.add_javascript(self.resource_string("static/js/libs/abcjs_editor_9.9.js")) frag.add_javascript(self.resource_string("static/js/libs/jquery.typing-0.2.0.min.js")) # javascript & initialization frag.add_javascript(self.resource_string("static/js/src/musicstaff.js")) frag.initialize_js('MusicStaffXBlock') return frag
def student_view(self, context=None): """ The primary view of the XBlock, shown to students when viewing courses. """ fullUrl = self.url if self.start_time != "" and self.end_time != "": fullUrl += "#t=" + self.start_time + "," + self.end_time elif self.start_time != "": fullUrl += "#t=" + self.start_time elif self.end_time != "": fullUrl += "#t=0," + self.end_time context = { 'display_name': self.display_name, 'url': fullUrl, 'allow_download': self.allow_download, 'source_text': self.source_text, 'source_url': self.source_url, 'subtitle_url': self.sub_title_url, 'id': time.time() } html = self.render_template('public/html/videojs_view.html', context) frag = Fragment(html) frag.add_css(self.load_resource("public/css/video-js.css")) frag.add_javascript(self.load_resource("public/js/video-js.min.js")) frag.add_css(self.load_resource("public/css/videojs.css")) # frag.add_css_url(self.runtime.local_resource_url(self, 'public/css/video-js.css')) # frag.add_javascript_url(self.runtime.local_resource_url(self, 'public/js/video-js.min.js')) frag.add_javascript(self.load_resource("public/js/videojs_view.js")) frag.initialize_js('videojsXBlockInitView') return frag
def studio_view(self, context=None): if not context: context = {} #Define variable to be used in HTML Template context.update({ 'test_title' : self.test_title, 'questions': self.questions, 'total_question' : self.total_question, 'answers' : self.answers, 'learning_object_url' : self.learning_object_url, 'learning_object_name' : self.learning_object_name, 'test_type' : self.test_type, }) html = Template( self.resource_string("public/html/question_edit.html")).render(Context(context) ) frag = Fragment(html) # LOAD CSS frag.add_css(self.resource_string("public/css/question_edit.css")) # LOAD JS frag.add_javascript(self.resource_string("public/js/src/question_edit.js")) # CREATE XBLOCK frag.initialize_js('QuestionEditBlock') return frag
def student_view(self, context): """ Lab view, displayed to the student """ root = ET.fromstring(self.data) items = [] for child in root: if child.tag == 'doc': child.text = urllib.quote(child.text, '') width = child.attrib.get('width', '100%') height = child.attrib.get('height', '625') items.append((child.tag, child.text, width, height)) fragment = Fragment() context = { 'items': items, } fragment.add_content(render_template('/templates/html/carousel.html', context)) fragment.add_javascript(load_resource('public/js/jquery-ui-1.10.4.custom.js')) fragment.add_css(load_resource('public/css/responsive-carousel.css')) fragment.add_css(load_resource('public/css/responsive-carousel.slide.css')) fragment.add_javascript(load_resource('public/js/responsive-carousel.js')) fragment.add_javascript(load_resource('public/js/responsive-carousel.loop.js')) fragment.add_css_url("https://vjs.zencdn.net/4.5.1/video-js.css") fragment.add_javascript_url("https://vjs.zencdn.net/4.5.1/video.js") fragment.add_javascript(load_resource('public/js/youtube.js')) fragment.add_javascript('function CarouselBlock(runtime, element) {$(".carousel").carousel();console.log("OK");}') fragment.initialize_js('CarouselBlock') return fragment
def student_view(self, context=None): """ The primary view of the IframeWithAnonymousIDXBlock, shown to students when viewing courses. """ student_id = self.xmodule_runtime.anonymous_student_id # student_id will be "student" if called from the Studio new_iframe_url = "{0}/{1}".format(self.iframe_url, student_id) self.display_name = new_iframe_url context = { 'self': self, 'iframe_url': new_iframe_url, 'is_in_studio': student_id == 'student' } frag = Fragment() frag.add_content(render_template('/templates/html/iframe.html', context)) frag.add_css(self.resource_string("static/css/iframe.css")) frag.add_javascript(self.resource_string("static/js/src/iframe.js")) frag.initialize_js('IframeWithAnonymousIDXBlock') return frag
def student_view(self, context): html = self.resource_string('public/html/student_view.html') fragment = Fragment(html.format(self=self)) fragment.add_javascript_url(self.runtime.local_resource_url(self, 'public/js/student_view.js')) fragment.add_css(self.runtime.local_resource_url(self, 'public/css/jsav_xblock.css')) fragment.initialize_js('JSAVXBlock') return fragment
def student_view(self, context=None): """ The primary view of the CodeBrowserBlock, shown to students when viewing courses. """ student_id = self.runtime.anonymous_student_id if student_id == "student": log_text = open('/var/www/gitlab_codebrowser.log').read() html_str = pkg_resources.resource_string( __name__, "static/html/codebrowser_log.html") frag = Fragment(unicode(html_str).format(log=log_text)) css_str = pkg_resources.resource_string( __name__, "static/css/codebrowser.css") frag.add_css(unicode(css_str)) frag.initialize_js('CodeBrowserBlock') return frag real_user = self.runtime.get_real_user(student_id) email = real_user.email username = real_user.username """ save the private key and create cofig file """ rsa_file = "/var/www/.ssh/id_rsa_" + student_id if self.lab == "no_lab": src = 'http://166.111.68.45:11133/static/codebrowser/notice.html' else: conn = pymongo.Connection('localhost', 27017) db = conn.test codeview = db.codeview result = codeview.find_one({"username": username}) conn.disconnect() if result: src = result["src_html"] else: src = 'http://166.111.68.45:11133/static/codebrowser/' + student_id + '/ucore_lab/' + self.lab + '/index.html' """ pull the code from gitlab and generate the static html files """ if not os.path.isfile(rsa_file): try: conn = pymongo.Connection('localhost', 27017) db = conn.test token = db.token result = token.find_one({"username": username}) if result: private_key = result["private_key"] self.logger.info("codebrowser: username" + username + "private key" + private_key) conn.disconnect() #write config file and private key config_file = "/var/www/.ssh/config" config = "Host " + student_id + "\n HostName " + self.git_host + "\n User git\n Port " + str( self.git_port) + "\n IdentityFile " + rsa_file + "\n\n" file_rsa = open(rsa_file, 'w') file_rsa.write(private_key) file_rsa.close() file_config = open(config_file, 'wa') file_config.write(config) file_config.close() os.system("chmod 600 " + rsa_file) #create code dir dir = "/edx/var/edxapp/staticfiles/ucore/" + student_id + "/ucore_lab" os.system("mkdir -p " + dir + " && cd " + dir + " && git init") except Exception, ex: self.logger.info("Error in codebrowser(get private key) " + username + str(ex))
def student_view(self, context=None): """ The primary view of the ProctorUXBlock, shown to students when viewing courses. """ if self._is_studio(): # studio view fragment = Fragment( self._render_template('static/html/studio.html')) fragment.add_css(self.resource_string('public/css/proctoru.css')) return fragment elif self._user_is_staff(): return self.staff_view() elif self._allowed_verified(): api_obj = ProctoruAPI() fragment = Fragment() context = {} fragment.add_css(loader.load_unicode('public/css/proctoru.css')) fragment.add_css( loader.load_unicode('public/css/custom_bootstrap.css')) fragment.add_javascript( loader.load_unicode('static/js/src/proctoru.js')) if self.is_exam_ended: context.update({"self": self}) fragment.add_content( loader.render_template('static/html/exam_ended.html', context)) fragment.initialize_js('ProctorUXBlockExamEnabled') return fragment if self.is_exam_unlocked: context.update({"self": self}) fragment.add_content( loader.render_template('static/html/exam_enabled.html', context)) fragment.initialize_js('ProctorUXBlockExamEnabled') child_frags = self.runtime.render_children( block=self, view_name='student_view') html = self._render_template('static/html/sequence.html', children=child_frags) fragment.add_content(html) fragment.add_frags_resources(child_frags) return fragment elif self.is_exam_start_clicked: exam_data = api_obj.get_student_reservation_list( self.runtime.user_id) if len(exam_data) > 0: exam_found = False for exam in exam_data: start_date = exam.get('start_date') exam_obj = api_obj.get_schedule_exam_arrived( self.runtime.user_id, self.get_block_id()) # check for reseration if int(exam_obj.reservation_no) == int( exam.get('reservation_no')): exam_found = True context.update({ "self": self, "exam": api_obj.get_schedule_exam_arrived( self.runtime.user_id, self.get_block_id()) }) fragment.add_content( loader.render_template( 'static/html/exam_password.html', context)) fragment.initialize_js( 'ProctorUXBlockExamPassword') return fragment else: # if reservatin id not found schedule page exam_found = False if not exam_found: # if reservatin id not found return the self.exam_time = "" self.is_exam_scheduled = False self.is_rescheduled = False self.is_exam_canceled = False self.is_exam_start_clicked = False time_details = { 'exam_start_date_time': self.start_date, 'exam_end_date_time': self.end_date, } time_details = api_obj.get_time_details_api( time_details, self.exam_date) if time_details.get('status') == "examdatepass": context.update({ 'self': self, 'status': "examdatepass" }) fragment.add_content( loader.render_template( 'static/html/error_template.html', context)) else: context = api_obj.render_shedule_ui( self.runtime.user_id, time_details, self.duration) context.update({'self': self}) status = context.get('status') if status == "error": fragment.add_content( loader.render_template( 'static/html/error_template.html', context)) elif status == "emptylist": fragment.add_content( loader.render_template( 'static/html/shedule_form_proctoru.html', context)) else: fragment.add_content( loader.render_template( 'static/html/shedule_form_proctoru.html', context)) fragment.initialize_js('ProctorUXBlockSchedule') return fragment else: # if exam not found self.exam_time = "" self.is_exam_scheduled = False self.is_rescheduled = False self.is_exam_canceled = False self.is_exam_start_clicked = False time_details = { 'exam_start_date_time': self.start_date, 'exam_end_date_time': self.end_date, } time_details = api_obj.get_time_details_api( time_details, self.exam_date) if time_details.get('status') == "examdatepass": context.update({ 'self': self, 'status': "examdatepass" }) fragment.add_content( loader.render_template( 'static/html/error_template.html', context)) else: context = api_obj.render_shedule_ui( self.runtime.user_id, time_details, self.duration) context.update({'self': self}) status = context.get('status') if status == "error": fragment.add_content( loader.render_template( 'static/html/error_template.html', context)) elif status == "emptylist": fragment.add_content( loader.render_template( 'static/html/shedule_form_proctoru.html', context)) else: fragment.add_content( loader.render_template( 'static/html/shedule_form_proctoru.html', context)) fragment.initialize_js('ProctorUXBlockSchedule') return fragment elif api_obj.is_user_created( self.runtime.user_id) and self.is_rescheduled: time_details = { 'exam_start_date_time': self.start_date, 'exam_end_date_time': self.end_date, } time_details = api_obj.get_time_details_api( time_details, self.exam_date) if time_details.get('status') == "examdatepass": context.update({'self': self, 'status': "examdatepass"}) fragment.add_content( loader.render_template( 'static/html/error_template.html', context)) else: context = api_obj.render_shedule_ui( self.runtime.user_id, time_details, self.duration) context.update({'self': self}) exam_time_heading = api_obj.get_formated_exam_start_date( self.exam_time, self.runtime.user_id) old_exam_time = dateutil.parser.parse(self.exam_time) exam_start_date_time = time_details.get( 'str_exam_start_date') exam_end_date_time = time_details.get('exam_end_date_time') allowed_keep_old_exam = False if exam_start_date_time <= old_exam_time <= exam_end_date_time: allowed_keep_old_exam = True else: allowed_keep_old_exam = False context.update({ 'exam_time_heading': exam_time_heading, 'allowed_keep_old_exam': allowed_keep_old_exam, }) context.update({ "proctoru_user": api_obj.get_proctoru_user(self.runtime.user_id) }) timezones = api_obj.get_time_zones() context.update( {"time_zone_list": timezones.get("data", None)}) status = context.get('status') if status == "error": fragment.add_content( loader.render_template( 'static/html/error_template.html', context)) elif status == "emptylist": fragment.add_content( loader.render_template( 'static/html/reshedule_form_proctoru.html', context)) else: fragment.add_content( loader.render_template( 'static/html/reshedule_form_proctoru.html', context)) fragment.initialize_js('ProctorUXBlockSchedule') return fragment elif self.is_exam_scheduled: exam_data = api_obj.get_student_reservation_list( self.runtime.user_id) context.update({ "proctoru_user": api_obj.get_proctoru_user(self.runtime.user_id) }) timezones = api_obj.get_time_zones() context.update({"time_zone_list": timezones.get("data", None)}) if len(exam_data) > 0: exam_found = False for exam in exam_data: start_date = exam.get('start_date') exam_obj = api_obj.get_schedule_exam_arrived( self.runtime.user_id, self.get_block_id()) # check for reseration if int(exam_obj.reservation_no) == int( exam.get('reservation_no')): exam_found = True exam_obj.start_date = dateutil.parser.parse( start_date) exam_obj.save() pr_user = ProctoruUser.objects.get( student=self.runtime.user_id) start_date = dateutil.parser.parse(start_date) start_date = start_date.replace(tzinfo=pytz.utc) tzobj = pytz.timezone(win_tz[pr_user.time_zone]) start_date = start_date.astimezone(tzobj) current_time = pytz.utc.localize( datetime.datetime.utcnow()).astimezone(tzobj) diff = start_date - current_time remaining_time = (diff.days * 24 * 60) + (diff.seconds / 60) if remaining_time <= PROCTORU_EXAM_AWAY_TIMEOUT: # if examtime pass away self.exam_time = "" self.is_exam_scheduled = False self.is_rescheduled = False self.is_exam_canceled = False time_details = { 'exam_start_date_time': self.start_date, 'exam_end_date_time': self.end_date, } time_details = api_obj.get_time_details_api( time_details, self.exam_date) if time_details.get( 'status') == "examdatepass": context.update({ 'self': self, 'status': "examdatepass" }) fragment.add_content( loader.render_template( 'static/html/error_template.html', context)) else: context = api_obj.render_shedule_ui( self.runtime.user_id, time_details, self.duration) context.update({'self': self}) status = context.get('status') if status == "error": fragment.add_content( loader.render_template( 'static/html/error_template.html', context)) elif status == "emptylist": fragment.add_content( loader.render_template( 'static/html/shedule_form_proctoru.html', context)) else: fragment.add_content( loader.render_template( 'static/html/shedule_form_proctoru.html', context)) fragment.initialize_js( 'ProctorUXBlockSchedule') return fragment else: self.exam_time = start_date.isoformat() context.update({ "exam": exam_obj, "self": self }) fragment.add_content( loader.render_template( 'static/html/exam_arrived_proctoru.html', context)) fragment.initialize_js('ProctorUXBlockArrived') return fragment else: # if reservatin id not found schedule page exam_found = False if not exam_found: # if reservatin id not found return the self.exam_time = "" self.is_exam_scheduled = False self.is_rescheduled = False self.is_exam_canceled = False time_details = { 'exam_start_date_time': self.start_date, 'exam_end_date_time': self.end_date, } time_details = api_obj.get_time_details_api( time_details, self.exam_date) if time_details.get('status') == "examdatepass": context.update({ 'self': self, 'status': "examdatepass" }) fragment.add_content( loader.render_template( 'static/html/error_template.html', context)) else: context = api_obj.render_shedule_ui( self.runtime.user_id, time_details, self.duration) context.update({'self': self}) status = context.get('status') if status == "error": fragment.add_content( loader.render_template( 'static/html/error_template.html', context)) elif status == "emptylist": fragment.add_content( loader.render_template( 'static/html/shedule_form_proctoru.html', context)) else: fragment.add_content( loader.render_template( 'static/html/shedule_form_proctoru.html', context)) fragment.initialize_js('ProctorUXBlockSchedule') return fragment else: # if exam not found self.exam_time = "" self.is_exam_scheduled = False self.is_rescheduled = False self.is_exam_canceled = False time_details = { 'exam_start_date_time': self.start_date, 'exam_end_date_time': self.end_date, } time_details = api_obj.get_time_details_api( time_details, self.exam_date) if time_details.get('status') == "examdatepass": context.update({ 'self': self, 'status': "examdatepass" }) fragment.add_content( loader.render_template( 'static/html/error_template.html', context)) else: context = api_obj.render_shedule_ui( self.runtime.user_id, time_details, self.duration) context.update({'self': self}) status = context.get('status') if status == "error": fragment.add_content( loader.render_template( 'static/html/error_template.html', context)) elif status == "emptylist": fragment.add_content( loader.render_template( 'static/html/shedule_form_proctoru.html', context)) else: fragment.add_content( loader.render_template( 'static/html/shedule_form_proctoru.html', context)) fragment.initialize_js('ProctorUXBlockSchedule') return fragment elif api_obj.is_user_created( self.runtime.user_id) and not self.is_exam_scheduled: self.exam_time = "" self.is_exam_scheduled = False self.is_rescheduled = False self.is_exam_canceled = False time_details = { 'exam_start_date_time': self.start_date, 'exam_end_date_time': self.end_date, } time_details = api_obj.get_time_details_api( time_details, self.exam_date) if time_details.get('status') == "examdatepass": context.update({'self': self, 'status': "examdatepass"}) fragment.add_content( loader.render_template( 'static/html/error_template.html', context)) else: context = api_obj.render_shedule_ui( self.runtime.user_id, time_details, self.duration) context.update({'self': self}) context.update({ "proctoru_user": api_obj.get_proctoru_user(self.runtime.user_id) }) timezones = api_obj.get_time_zones() context.update( {"time_zone_list": timezones.get("data", None)}) status = context.get('status') if status == "error": fragment.add_content( loader.render_template( 'static/html/error_template.html', context)) elif status == "emptylist": fragment.add_content( loader.render_template( 'static/html/shedule_form_proctoru.html', context)) else: fragment.add_content( loader.render_template( 'static/html/shedule_form_proctoru.html', context)) fragment.initialize_js('ProctorUXBlockSchedule') return fragment else: api_obj = ProctoruAPI() timezones = api_obj.get_time_zones() context.update({"self": self}) context.update({"timezones": timezones.get("data", None)}) fragment.add_content( loader.render_template('static/html/proctoru.html', context)) fragment.initialize_js('ProctorUXBlockCreate') return fragment else: fragment = Fragment() context = {} context.update({"self": self}) fragment.add_content( loader.render_template('static/html/blank.html', context)) fragment.initialize_js('ProctorUXBlockBlank') return fragment
def student_view(self, context=None): """ The primary view of the GenesysXBlock, shown to students when viewing courses. """ no_name = False studio_runtime = False bugs_email = getattr(settings, 'BUGS_EMAIL', '') # Check if the runtime is cms or lms if settings.ROOT_URLCONF == 'cms.urls': studio_runtime = True student_account_url = '' else: student_account_url = reverse('account_settings') # If no invitation has been received, call Genesys invitations endpoint try: user = self.runtime.get_real_user( self.runtime.anonymous_student_id) if not user.first_name or not user.last_name: no_name = True except Exception as e: logger.error(str(e)) if self.respondent_id is None and no_name is False: try: invitation = self.get_genesys_invitation(user) except Exception as e: logger.error(str(e)) elif not self.test_completed: # If an invitation has been received, # try fetch the results, ideally this should happen when the webhook is POSTed to try: result = self.get_genesys_test_result() except Exception as e: logger.error(str(e)) else: pass context = { "no_name": no_name, "invitation_successful": self.invitation_successful, "src_url": self.invitation_url, "display_name": self.display_name, "instruction": self.instruction, "start_now": self.start_now, "completed": self.test_completed, "test_started": self.test_started, "studio_runtime": studio_runtime, "completed_message": self.completed_message, "student_account_url": student_account_url, "bugs_email": bugs_email, "insufficient_credit": self.insufficient_credit } frag = Fragment( loader.render_django_template("static/html/genesys.html", context).format(self=self)) frag.add_css(self.resource_string("static/css/genesys.css")) frag.add_javascript(self.resource_string("static/js/src/genesys.js")) frag.initialize_js('GenesysXBlock') return frag
def student_view(self, context=None): """Provide the default student view.""" if context is None: context = {} context = self.calc_context(context) result = Fragment() named_child_frags = [] # self.children is an attribute obtained from ChildrenModelMetaclass, so disable the # static pylint checking warning about this. for child_id in self.children: # pylint: disable=E1101 child = self.runtime.get_block(child_id) frag = self.runtime.render_child(child, "problem_view", context) result.add_frag_resources(frag) named_child_frags.append((child.name, frag)) result.add_css(""" .problem { border: solid 1px #888; padding: 3px; } """) result.add_content( self.runtime.render_template("problem.html", named_children=named_child_frags)) result.add_javascript(""" function ProblemBlock(runtime, element) { function callIfExists(obj, fn) { if (typeof obj[fn] == 'function') { return obj[fn].apply(obj, Array.prototype.slice.call(arguments, 2)); } else { return undefined; } } function handleCheckResults(results) { $.each(results.submitResults || {}, function(input, result) { callIfExists(runtime.childMap(element, input), 'handleSubmit', result); }); $.each(results.checkResults || {}, function(checker, result) { callIfExists(runtime.childMap(element, checker), 'handleCheck', result); }); } // To submit a problem, call all the named children's submit() // function, collect their return values, and post that object // to the check handler. $(element).find('.check').bind('click', function() { var data = {}; var children = runtime.children(element); for (var i = 0; i < children.length; i++) { var child = children[i]; if (child.name !== undefined) { data[child.name] = callIfExists(child, 'submit'); } } var handlerUrl = runtime.handlerUrl(element, 'check') $.post(handlerUrl, JSON.stringify(data)).success(handleCheckResults); }); $(element).find('.rerandomize').bind('click', function() { var handlerUrl = runtime.handlerUrl(element, 'rerandomize'); $.post(handlerUrl, JSON.stringify({})); }); } """) result.initialize_js('ProblemBlock') return result
def student_view(self, _context=None): # pylint: disable=unused-argument """ The primary view of the RecommenderXBlock, shown to students when viewing courses. """ self.recommendations = ( data_structure_upgrade(self.recommendations) or data_structure_upgrade(self.default_recommendations) or {} ) # Transition between two versions. In the previous version, there is # no endorsed_recommendation_reasons. Thus, we add empty reasons to # make the length of the two lists equal # # TODO: Go through old lists of resources in course, and remove this # code. The migration should be done. while len(self.endorsed_recommendation_ids) > len(self.endorsed_recommendation_reasons): self.endorsed_recommendation_reasons.append('') global template_lookup if not template_lookup: self._init_template_lookup() # Ideally, we'd estimate score based on votes, such that items with # 1 vote have a sensible ranking (rather than a perfect rating) # We pre-generate URLs for all resources. We benchmarked doing this # for 44 URLs, and the time per URL was about 8ms. The 44 URLs were # all of the images added by students over several problem sets. If # load continues to be as-is, pre-generation is not a performance # issue. If students make substantially more resources, we may want # to paginate, and generate in sets of 5-20 URLs per load. resources = [{ 'id': strip_and_clean_html_elements(r['id']), 'title': strip_and_clean_html_elements(r['title']), "votes": strip_and_clean_html_elements(r['upvotes'] - r['downvotes']), 'url': strip_and_clean_url(r['url']), 'description': self._get_onetime_url(strip_and_clean_html_elements(r['description'])), 'descriptionText': strip_and_clean_html_elements(r['descriptionText']) } for r in self.recommendations.values()] resources = sorted(resources, key=lambda r: r['votes'], reverse=True) frag = Fragment( template_lookup.get_template("recommender.html").render( resources=resources, upvoted_ids=self.upvoted_ids, downvoted_ids=self.downvoted_ids, endorsed_recommendation_ids=self.endorsed_recommendation_ids, endorsed_recommendation_reasons=self.endorsed_recommendation_reasons, flagged_ids=self.flagged_ids, flagged_reasons=self.flagged_reasons ) ) frag.add_css_url("//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css") frag.add_javascript_url("//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js") frag.add_javascript(self.resource_string('static/js/src/mustache.min.js')) frag.add_javascript_url('//cdnjs.cloudflare.com/ajax/libs/intro.js/0.5.0/intro.min.js') frag.add_css(self.resource_string("static/css/tooltipster.css")) frag.add_css(self.resource_string("static/css/recommender.css")) frag.add_css(self.resource_string("static/css/introjs.css")) frag.add_javascript(self.resource_string("static/js/src/jquery.tooltipster.min.js")) frag.add_javascript(self.resource_string("static/js/src/cats.js")) frag.add_javascript(self.resource_string("static/js/src/recommender.js")) frag.initialize_js('RecommenderXBlock', self.get_client_configuration()) return frag
def student_view(self, context=None): """The main view of OpenAssessmentBlock, displayed when viewing courses. The main view which displays the general layout for Open Ended Assessment Questions. The contents of the XBlock are determined dynamically based on the assessment workflow configured by the author. Args: context: Not used for this view. Returns: (Fragment): The HTML Fragment for this XBlock, which determines the general frame of the Open Ended Assessment Question. """ # On page load, update the workflow status. # We need to do this here because peers may have graded us, in which # case we may have a score available. try: self.update_workflow_status() except AssessmentWorkflowError: # Log the exception, but continue loading the page logger.exception( 'An error occurred while updating the workflow on page load.') ui_models = self._create_ui_models() # All data we intend to pass to the front end. context_dict = { "title": self.title, "prompts": self.prompts, "rubric_assessments": ui_models, "show_staff_area": self.is_course_staff and not self.in_studio_preview, } template = get_template("openassessmentblock/oa_base.html") context = Context(context_dict) fragment = Fragment(template.render(context)) i18n_service = self.runtime.service(self, 'i18n') if hasattr(i18n_service, 'get_language_bidi') and i18n_service.get_language_bidi(): css_url = "static/css/openassessment-rtl.css" else: css_url = "static/css/openassessment-ltr.css" if settings.DEBUG: fragment.add_css_url(self.runtime.local_resource_url( self, css_url)) self.add_javascript_files(fragment, "static/js/src/oa_shared.js") self.add_javascript_files(fragment, "static/js/src/oa_server.js") self.add_javascript_files(fragment, "static/js/src/lms") else: # TODO: load CSS and JavaScript as URLs once they can be served by the CDN fragment.add_css(load(css_url)) fragment.add_javascript( load("static/js/openassessment-lms.min.js")) js_context_dict = { "ALLOWED_IMAGE_MIME_TYPES": self.ALLOWED_IMAGE_MIME_TYPES, "ALLOWED_FILE_MIME_TYPES": self.ALLOWED_FILE_MIME_TYPES, "FILE_EXT_BLACK_LIST": self.FILE_EXT_BLACK_LIST, "FILE_TYPE_WHITE_LIST": self.white_listed_file_types, } fragment.initialize_js('OpenAssessmentBlock', js_context_dict) return fragment
def student_view(self, context=None): """ The primary view of the FeedbackXBlock, shown to students when viewing courses. """ # Figure out which prompt we show. We set self.prompt_choice to # the index of the prompt. We set it if it is out of range (either # uninitiailized, or incorrect due to changing list length). Then, # we grab the prompt, prepopulated with defaults. if self.prompt_choice < 0 or self.prompt_choice >= len(self.prompts): self.prompt_choice = random.randint(0, len(self.prompts) - 1) prompt = self.get_prompt() # Now, we render the FeedbackXBlock. html = self.resource_string("static/html/feedback.html") # Staff see vote totals, so we have slightly different HTML here. if self.vote_aggregate and self.is_staff(): scale_item = self.resource_string("static/html/staff_item.html") else: scale_item = self.resource_string("static/html/scale_item.html") # The replace allows us to format the HTML nicely without getting # extra whitespace scale_item = scale_item.replace('\n', '') # We have five Likert fields right now, but we'd like this to # be dynamic indexes = range(5) # If the user voted before, we'd like to show that active_vote = ["checked" if i == self.user_vote else "" for i in indexes] # Confirm that we do have vote totals (this may be uninitialized # otherwise). This should probably go into __init__ or similar. self.init_vote_aggregate() votes = self.vote_aggregate # We grab the icons. This should move to a Filesystem field so # instructors can upload new ones def get_url(icon_type, i): ''' Helper function to generate the URL for the icons shown in the tool. Takes the type of icon (active, inactive, etc.) and the number of the icon. Note that some icon types may not be actively used in the styling. For example, at the time of this writing, we do selected through CSS, rather than by using those icons. ''' templates = {'inactive': 'public/default_icons/i{set}{i}.png?raw', 'active': 'public/default_icons/a{set}{i}.png?raw', 'selected': 'public/default_icons/s{set}{i}.png?raw'} template = templates[icon_type] icon_file = template.format(i=i, set=prompt['icon_set']) return self.runtime.local_resource_url(self, icon_file) ina_urls = [get_url('inactive', i) for i in range(1, 6)] act_urls = [get_url('active', i) for i in range(1, 6)] sel_urls = [get_url('selected', i) for i in range(1, 6)] # Render the Likert scale (not the whole page) scale = u"".join( scale_item.format(scale_text=scale_text, unicode_icon=unicode_icon, idx=idx, active=active, vote_cnt=vote_cnt, ina_icon=ina_icon, act_icon=act_icon, sel_icon=sel_icon) for (scale_text, unicode_icon, idx, active, vote_cnt, act_icon, ina_icon, sel_icon) in zip(prompt['scale_text'], ICON_SETS[(prompt['icon_set'])], indexes, active_vote, votes, act_urls, ina_urls, sel_urls) ) if self.user_vote != -1: _ = self.runtime.service(self, 'i18n').ugettext response = _("Thank you for voting!") else: response = "" # Now, render the whole page rendered = html.format(self=self, scale=scale, freeform_prompt=prompt['freeform'], likert_prompt=prompt['likert'], response=response, placeholder=prompt['placeholder']) # We initialize self.p_user if not initialized -- this sets whether # or not we show it. From there, if it is less than odds of showing, # we set the fragment to the rendered XBlock. Otherwise, we return # empty HTML. There ought to be a way to return None, but XBlocks # doesn't support that. if self.p_user == -1: self.p_user = random.uniform(0, 100) if self.p_user < self.p: frag = Fragment(rendered) else: frag = Fragment(u"") # Finally, we do the standard JS+CSS boilerplate. Honestly, XBlocks # ought to have a sane default here. frag.add_css(self.resource_string("static/css/feedback.css")) frag.add_javascript(self.resource_string("static/js/src/feedback.js")) frag.initialize_js('FeedbackXBlock') return frag
def _create_fragment(self, template, context_dict, initialize_js_func, additional_css=None, additional_js=None): """ Creates a fragment for display. """ fragment = Fragment(template.render(context_dict)) if additional_css is None: additional_css = [] if additional_js is None: additional_js = [] i18n_service = self.runtime.service(self, 'i18n') if hasattr(i18n_service, 'get_language_bidi') and i18n_service.get_language_bidi(): css_url = "static/css/openassessment-rtl.css" else: css_url = "static/css/openassessment-ltr.css" if settings.DEBUG: for css in additional_css: fragment.add_css_url(self.runtime.local_resource_url( self, css)) fragment.add_css_url(self.runtime.local_resource_url( self, css_url)) for js in additional_js: # pylint: disable=invalid-name self.add_javascript_files(fragment, js) self.add_javascript_files(fragment, "static/js/src/oa_shared.js") self.add_javascript_files(fragment, "static/js/src/oa_server.js") self.add_javascript_files(fragment, "static/js/src/lms") else: # TODO: load CSS and JavaScript as URLs once they can be served by the CDN for css in additional_css: fragment.add_css(load(css)) fragment.add_css(load(css_url)) # minified additional_js should be already included in 'make javascript' fragment.add_javascript( load("static/js/openassessment-lms.min.js")) js_context_dict = { "ALLOWED_IMAGE_MIME_TYPES": self.ALLOWED_IMAGE_MIME_TYPES, "ALLOWED_FILE_MIME_TYPES": self.ALLOWED_FILE_MIME_TYPES, "FILE_EXT_BLACK_LIST": self.FILE_EXT_BLACK_LIST, "FILE_TYPE_WHITE_LIST": self.white_listed_file_types, "MAXIMUM_FILE_UPLOAD_COUNT": self.MAX_FILES_COUNT, "TEAM_ASSIGNMENT": self.teams_enabled and self.team_submissions_enabled() } fragment.initialize_js(initialize_js_func, js_context_dict) return fragment
def student_view(self, context=None): """ The primary view of the PeerInstructionXBlock, shown to students when viewing courses. """ # convert key into integers as json.dump and json.load convert integer dictionary key into string self.sys_selected_answers = { int(k): v for k, v in self.sys_selected_answers.items() } # generate a random seed for student student_item = self.get_student_item_dict() random.seed(student_item['student_id']) answers = self.get_answers_for_student() html = "" html += self.resource_string("static/html/ubcpi.html") frag = Fragment(html) frag.add_css(self.resource_string("static/css/ubcpi.css")) frag.add_javascript_url( "//ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.js") frag.add_javascript_url( "//ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular-messages.js" ) frag.add_javascript_url( "//ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular-sanitize.js" ) frag.add_javascript_url( "//ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular-cookies.js" ) frag.add_javascript_url( "//cdnjs.cloudflare.com/ajax/libs/angular-gettext/2.3.8/angular-gettext.min.js" ) frag.add_javascript_url( "//cdnjs.cloudflare.com/ajax/libs/d3/3.3.13/d3.min.js") frag.add_javascript(self.resource_string("static/js/src/d3-pibar.js")) frag.add_javascript(self.resource_string("static/js/src/ubcpi.js")) frag.add_javascript( self.resource_string( "static/js/src/ubcpi-answer-result-directive.js")) frag.add_javascript( self.resource_string("static/js/src/ubcpi-barchart-directive.js")) frag.add_javascript( self.resource_string("static/js/src/translations.js")) # convert image URLs question = deepcopy(self.question_text) question.update( {'image_url': self.get_asset_url(question.get('image_url'))}) options = deepcopy(self.options) for option in options: if option.get('image_url'): option.update( {'image_url': self.get_asset_url(option.get('image_url'))}) js_vals = { 'answer_original': answers.get_vote(0), 'rationale_original': answers.get_rationale(0), 'answer_revised': answers.get_vote(1), 'rationale_revised': answers.get_rationale(1), 'display_name': self.ugettext(self.display_name), 'question_text': question, 'weight': self.weight, 'options': options, 'rationale_size': self.rationale_size, 'user_role': self.get_user_role(), 'all_status': { 'NEW': STATUS_NEW, 'ANSWERED': STATUS_ANSWERED, 'REVISED': STATUS_REVISED }, 'lang': translation.get_language(), } if answers.has_revision(0) and not answers.has_revision(1): js_vals['other_answers'] = self.other_answers_shown # reveal the correct answer in the end if answers.has_revision(1): js_vals['correct_answer'] = self.correct_answer js_vals['correct_rationale'] = self.correct_rationale # Pass the answer to out Javascript frag.initialize_js('PeerInstructionXBlock', js_vals) self.publish_event_from_dict(self.event_namespace + '.accessed', {}) return frag
def student_view(self, context=None): """ The primary view of the QuestionGeneratorXBlock, shown to students when viewing courses. """ context = {} if self.xblock_id is None: self.xblock_id = unicode( self.location.replace(branch=None, version=None)) if self.newly_created_block: self.newly_created_block = (qgb_db_service.is_block_in_db( self.xblock_id) is False) if (self.newly_created_block is True): # generate question template for newly created XBlock self.question_template, self.variables, self.answer_template = qgb_question_service.generate_question_template( ) qgb_db_service.create_question_template(self.xblock_id, self.question_template, self.variables, self.answer_template) self.newly_created_block = False else: # existing question template in dbms self.load_data_from_dbms() # generate question from template if necessary if (self.generated_question == ""): self.generated_question, self.generated_variables = qgb_question_service.generate_question( self.question_template, self.variables) # load submission data to display the previously submitted result submissions = sub_api.get_submissions(self.student_item_key, 1) if submissions: latest_submission = submissions[0] # parse the answer answer = latest_submission['answer'] # saved "answer information" self.generated_question = answer['generated_question'] # self.generated_answer = answer['generated_answer'] # teacher's generated answer self.student_answer = answer[ 'student_answer'] # student's submitted answer if ('variable_values' in answer): # backward compatibility saved_generated_variables = json.loads( answer['variable_values']) for var_name, var_value in saved_generated_variables.iteritems( ): self.generated_variables[var_name] = var_value self.attempt_number = latest_submission['attempt_number'] if (self.attempt_number >= self.max_attempts): context['disabled'] = 'disabled' else: context['disabled'] = '' self.serialize_data_to_context(context) context['image_url'] = self.image_url context['student_answer'] = self.student_answer context['attempt_number'] = self.attempt_number_string context['point_string'] = self.point_string context['question'] = self.generated_question context['xblock_id'] = self.xblock_id context['show_answer'] = self.show_answer frag = Fragment() frag.content = loader.render_template( 'static/html/question_generator_block.html', context) frag.add_css( self.resource_string("static/css/question_generator_block.css")) frag.add_javascript( self.resource_string("static/js/src/question_generator_block.js")) frag.initialize_js('QuestionGeneratorXBlock') return frag
def student_view(self, context=None): # runtime error if not hasattr(self.runtime, "anonymous_student_id"): return self.message_view( "Error in ibm_docker (get anonymous student id)" + "Cannot get anonymous_student_id in runtime", None) # preview in studio if self.runtime.anonymous_student_id == "student": cluster_list = [] conn = pymongo.Connection('localhost', 27017) db = conn.test db.authenticate(self.mongo_admin, self.mongo_pwd) cluster = db.cluster for i in cluster.find(): new_cluster = Cluster() new_cluster.set_name(i["cluster_name"]) new_cluster.set_user(i["username"]) new_cluster.set_id(i["cluster_id"]) new_cluster.set_creation_time(i["creation_time"]) new_cluster.set_status(i["status"]) new_cluster.set_ip(i["ip"]) cluster_list.append(new_cluster.object_to_dict()) context_dict = {"clusters": cluster_list, "message": ""} fragment = Fragment() fragment.add_content( Util.render_template('static/html/ibm_clusters.html', context_dict)) fragment.add_css(Util.load_resource("static/css/ibm_docker.css")) #fragment.add_javascript(Util.load_resource("static/js/src/uc_lab.js")) fragment.initialize_js("IBMDockerTestXBlock") return fragment student = self.runtime.get_real_user(self.runtime.anonymous_student_id) email = student.email name = student.first_name + " " + student.last_name username = student.username # temporary code ,not used in next course conn = pymongo.Connection('localhost', 27017) db = conn.test db.authenticate(self.mongo_admin, self.mongo_pwd) token = db.token result = token.find_one({"username": username}) conn.disconnect() #I dont now why the cluster cannot be shown in page directly temp_clusters = self.clusters if self.is_new and not result: # create git account when first visiting # get teacher id #result, message = GitLabUtil.get_user(self.git_host, self.git_port, self.git_teacher_token) #self.logger.info("get teacher id") #self.logger.info(result) #self.logger.info(message) #if not result: # return self.message_view("Error in get teacher info") #try: # message = json.loads(message) # teacher_id = message["id"] #except Exception: # return self.message_view("Error in uc_docker (load json string)", message, context) #add teacher to developer #result, message = GitLabUtil.add_project_developer(self.git_host, self.git_port, self.git_user_token, username, self.git_project_name, teacher_id) #self.logger.info("add developer result:") #self.logger.info(result) #self.logger.info(message) #if not result: # return self.message_view("Error in uc_docker (add teacher to developer)", message, context) conn = pymongo.Connection('localhost', 27017) db = conn.test db.authenticate(self.mongo_admin, self.mongo_pwd) ibm = db.ibm result = ibm.find_one({"email": email}) if not result: return self.message_view( "Error in ibm_docker (get shibboleth account info). detail" + message, temp_clusters) self.ldap_name = result["name"] self.ldap_pwd = result["password"] #get user id by email result, message = GitLabUtil.get_userid(self.git_host, self.git_port, self.git_admin_token, self.ldap_name) self.logger.info("get user id result:") self.logger.info(result) self.logger.info(message) if not result: return self.message_view( "Error in ibm_docker (get user id). detail" + message, temp_clusters) self.git_id = message["id"] self.save() result, message = GitLabUtil.create_project( self.git_host, self.git_port, self.git_admin_token, self.git_import_url, self.git_project_name, self.git_id) self.logger.info("add project result:") self.logger.info(result) self.logger.info(message) if not result: return self.message_view( "Error in ibm_docker (add project). detail:" + message, temp_clusters) try: conn = pymongo.Connection('localhost', 27017) db = conn.test db.authenticate(self.mongo_admin, self.mongo_pwd) token = db.token result = token.find_one({"username": username}) if not result: self.private_key, self.public_key = Util.gen_ssh_keys( email) #self.logger.info("private_key:" + self.private_key) self.save() token.insert({ "username": username, "private_key": self.private_key, "public_key": self.public_key }) else: self.private_key = result["private_key"] self.public_key = result["public_key"] self.save() conn.disconnect() except Exception, ex: return self.message_view( "Error in ibm_docker (gen ssh key). detail:" + ex, context) result, message = GitLabUtil.add_ssh_key( self.git_host, self.git_port, self.git_admin_token, "ucore default", self.public_key, self.git_id) self.logger.info("add_ssh_key result:") self.logger.info(result) self.logger.info(message) if not result: return self.message_view( "Error in ibm_docker (add git ssh key). detail:" + message, temp_clusters) self.is_new = False self.save()
def student_view(self, context=None, authoring=False): scheme = 'https' if settings.HTTPS == 'on' else 'http' lms_base = settings.ENV_TOKENS.get('LMS_BASE') if isinstance(context, QueryDict): context = context.dict() if microsite.is_request_in_microsite(): subdomain = microsite.get_value( "domain_prefix", None) or microsite.get_value('microsite_config_key') lms_base = "{}.{}".format(subdomain, lms_base) scorm_player_url = "" course_directory = self.scorm_file if self.scorm_player == 'SCORM_PKG_INTERNAL': # TODO: support initial filename other than index.html for internal players #scorm_player_url = '{}://{}{}'.format(scheme, lms_base, self.scorm_file) scorm_player_url = '{}{}'.format(self.scorm_file, '/index.html') elif self.scorm_player: player_config = DEFINED_PLAYERS[self.scorm_player] player = player_config['location'] if '://' in player: scorm_player_url = player else: scorm_player_url = '{}://{}{}'.format(scheme, lms_base, player) course_directory = '{}://{}{}'.format( scheme, lms_base, self.runtime.handler_url(self, "proxy_content")) html = self.resource_string("static/html/scormxblock.html") # don't call handlers if student_view is not called from within LMS # (not really a student) if not authoring: get_url = '{}://{}{}'.format( scheme, lms_base, self.runtime.handler_url(self, "get_raw_scorm_status")) set_url = '{}://{}{}'.format( scheme, lms_base, self.runtime.handler_url(self, "set_raw_scorm_status")) # PreviewModuleSystem (runtime Mixin from Studio) won't have a hostname else: # we don't want to get/set SCORM status from preview get_url = set_url = '#' # if display type is popup, don't use the full window width for the host iframe iframe_width = self.display_type == 'popup' and DEFAULT_IFRAME_WIDTH or self.display_width iframe_height = self.display_type == 'popup' and DEFAULT_IFRAME_HEIGHT or self.display_height try: player_config = json.loads(self.player_configuration) except ValueError: player_config = {} frag = Fragment() frag.add_content( MakoTemplate(text=html.format( self=self, scorm_player_url=scorm_player_url, get_url=get_url, set_url=set_url, iframe_width=iframe_width, iframe_height=iframe_height, player_config=player_config, scorm_file=course_directory)).render_unicode()) frag.add_css(self.resource_string("static/css/scormxblock.css")) context['block_id'] = self.url_name js = self.resource_string("static/js/src/scormxblock.js") jsfrag = MakoTemplate(js).render_unicode(**context) frag.add_javascript(jsfrag) # TODO: this will only work to display staff debug info if 'scormxblock' is one of the # categories of blocks that are specified in lms/templates/staff_problem_info.html so this will # for now have to be overridden in theme or directly in edx-platform # TODO: is there another way to approach this? key's location.category isn't mutable to spoof 'problem', # like setting the name in the entry point to 'problem'. Doesn't seem like a good idea. Better to # have 'staff debuggable' categories configurable in settings or have an XBlock declare itself staff debuggable if SCORM_DISPLAY_STAFF_DEBUG_INFO and not authoring: # don't show for author preview from courseware.access import has_access from courseware.courses import get_course_by_id course = get_course_by_id(self.xmodule_runtime.course_id) dj_user = self.xmodule_runtime._services['user']._django_user has_instructor_access = bool( has_access(dj_user, 'instructor', course)) if has_instructor_access: disable_staff_debug_info = settings.FEATURES.get( 'DISPLAY_DEBUG_INFO_TO_STAFF', True) and False or True block = self view = 'student_view' frag = add_staff_markup(dj_user, has_instructor_access, disable_staff_debug_info, block, view, frag, context) frag.initialize_js('ScormXBlock_{0}'.format(context['block_id'])) return frag
def student_view(self, context): """ Player view, displayed to the student """ try: workgroup = self.workgroup except OutsiderDisallowedError as ode: error_fragment = Fragment() error_fragment.add_content( render_template('/templates/html/loading_error.html', {'error_message': unicode(ode)})) error_fragment.add_javascript( load_resource('public/js/group_project_error.js')) error_fragment.initialize_js('GroupProjectError') return error_fragment user_id = self.user_id group_activity = GroupActivity.import_xml_string( self.data, self.is_admin_grader) try: group_activity.update_submission_data( self.project_api.get_latest_workgroup_submissions_by_id( workgroup["id"])) except: pass if self.is_group_member: try: team_members = [ self.project_api.get_user_details(tm["id"]) for tm in workgroup["users"] if user_id != int(tm["id"]) ] except: team_members = [] try: assess_groups = self.project_api.get_workgroups_to_review( user_id, self.course_id, self.content_id) except: assess_groups = [] else: team_members = [] assess_groups = [workgroup] context = { "group_activity": group_activity, "team_members": json.dumps(team_members), "assess_groups": json.dumps(assess_groups), "ta_graded": (self.group_reviews_required_count < 1), } fragment = Fragment() fragment.add_content( render_template('/templates/html/group_project.html', context)) fragment.add_css(load_resource('public/css/group_project.css')) fragment.add_javascript_url( self.runtime.local_resource_url( self, 'public/js/vendor/jquery.ui.widget.js')) fragment.add_javascript_url( self.runtime.local_resource_url( self, 'public/js/vendor/jquery.fileupload.js')) fragment.add_javascript_url( self.runtime.local_resource_url( self, 'public/js/vendor/jquery.iframe-transport.js')) fragment.add_javascript(load_resource('public/js/group_project.js')) fragment.initialize_js('GroupProjectBlock') return fragment
def studio_view(self, _context): """ Render a form for XBlock editing. """ fragment = Fragment() player = self.get_player() languages = [{'label': label, 'code': lang} for lang, label in ALL_LANGUAGES] languages.sort(key=lambda l: l['label']) transcripts = self.get_enabled_transcripts() download_transcript_handler_url = self.runtime.handler_url(self, 'download_transcript') auth_error_message = '' # Authenticate to API of the player video platform and update metadata with auth information. # Note that there is no need to authenticate to Youtube API, # whilst for Wistia, a sample authorised request is to be made to ensure authentication succeeded, # since it is needed for the auth status message generation and the player's state update with auth status. if self.token: _auth_data, auth_error_message = self.authenticate_video_api(self.token.encode(encoding='utf-8')) initial_default_transcripts, transcripts_autoupload_message = self._update_default_transcripts( player, transcripts ) log.debug("Fetched default transcripts: {}".format(initial_default_transcripts)) # Prepare basic_fields and advanced_fields for them to be rendered basic_fields = self.prepare_studio_editor_fields(player.basic_fields) advanced_fields = self.prepare_studio_editor_fields(player.advanced_fields) context = { 'advanced_fields': advanced_fields, 'auth_error_message': auth_error_message, 'basic_fields': basic_fields, 'courseKey': self.course_key, 'languages': languages, 'player_name': self.player_name, # for players identification 'players': PlayerName, 'sources': list(TranscriptSource.to_dict().items()), # transcripts context: 'transcripts': filter_transcripts_by_source( transcripts, sources=[TranscriptSource.THREE_PLAY_MEDIA], exclude=True ), 'transcripts_fields': self.prepare_studio_editor_fields(player.trans_fields), 'three_pm_fields': self.prepare_studio_editor_fields(player.three_pm_fields), 'transcripts_type': '3PM' if self.threeplaymedia_streaming else 'manual', 'default_transcripts': self.default_transcripts, 'enabled_default_transcripts': filter_transcripts_by_source(transcripts), 'enabled_managed_transcripts': self.get_enabled_managed_transcripts(), 'initial_default_transcripts': initial_default_transcripts, 'transcripts_autoupload_message': transcripts_autoupload_message, 'download_transcript_handler_url': download_transcript_handler_url, } fragment.content = render_template('studio-edit.html', **context) fragment.add_css(resource_string("static/css/student-view.css")) fragment.add_css(resource_string("static/css/transcripts-upload.css")) fragment.add_css(resource_string("static/css/studio-edit.css")) fragment.add_css(resource_string("static/css/studio-edit-accordion.css")) fragment.add_javascript(resource_string("static/js/runtime-handlers.js")) fragment.add_javascript(resource_string("static/js/studio-edit/utils.js")) fragment.add_javascript(resource_string("static/js/studio-edit/studio-edit.js")) fragment.add_javascript(resource_string("static/js/studio-edit/transcripts-autoload.js")) fragment.add_javascript(resource_string("static/js/studio-edit/transcripts-manual-upload.js")) fragment.initialize_js('StudioEditableXBlock') return fragment
self.runtime.anonymous_student_id) username = student.username print 'OK' context_dict = { "labs": self._get_available_labs(), "dockers": self.dockers, "password": self.git_password, "username": username, "message": "", "report": "" } fragment = Fragment() fragment.add_content( Util.render_template('static/html/uc_docker.html', context_dict)) fragment.add_css(Util.load_resource("static/css/uc_docker.css")) fragment.add_javascript( Util.load_resource("static/js/src/uc_docker.js")) fragment.initialize_js("UcDockerXBlock") return fragment def studio_view(self, context=None): # to add new lab context_dict = { "labs": self.labs, "docker_file": """FROM uclassroom/ucore-vnc-base MAINTAINER ggxx<*****@*****.**> RUN cd / && git clone https://github.com/chyyuu/ucore_lab.git my_lab && cd /my_lab/ && git remote remove origin ENTRYPOINT ["bash"] """,
def student_view(self, context=None): """ The primary view of the UploaderDownloaderXBlock, shown to students when viewing courses. """ from .models import FileUploadAndUrl from xmodule.modulestore.django import modulestore unit_location = modulestore().get_parent_location(self.location) unit_id = unit_location.name course_level = self.get_course_level() data = FileUploadAndUrl.objects.filter(unit_id=unit_id, course_level=course_level) context.update({ "self": self, "data": data, "paginate": self.paginate, "aws_key": settings.AWS_ACCESS_KEY_ID, "unit_id": unit_id, "s3_mid_folder": self.s3_mid_folder, "s3_bucket": self.s3_bucket, "course_level": course_level, "general_title": self.general_title, "size_limit": self.size_limit, "bin_icon": self.runtime.local_resource_url(self, 'static/img/bin.png'), "gear_icon": self.runtime.local_resource_url(self, 'static/img/gear.png') }) frag = Fragment() frag.add_content( loader.render_template("static/html/list_download.html", context)) frag.add_css_url( "https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css") frag.add_javascript_url( "https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js") frag.add_css(self.resource_string("static/css/s3uploader.css")) display_to_students = self.runtime.user_is_staff or self.uploadable_by_students if "username" in context and display_to_students: frag.add_content( self.resource_string("static/html/s3uploader.html")) css_context = dict( continue_gif=self.runtime.local_resource_url( self, 'static/img/continue.gif'), edit=self.runtime.local_resource_url(self, 'static/img/edit.gif'), loading=self.runtime.local_resource_url( self, 'static/img/loading.gif'), pause=self.runtime.local_resource_url(self, 'static/img/pause.gif'), processing=self.runtime.local_resource_url( self, 'static/img/processing.gif'), retry=self.runtime.local_resource_url(self, 'static/img/retry.gif'), trash=self.runtime.local_resource_url(self, 'static/img/trash.gif'), ) css = loader.render_template( 'static/css/fine-uploader-gallery.css', css_context) frag.add_css(css) frag.add_css( self.resource_string("static/css/fine-uploader.min.css")) frag.add_css(self.resource_string("static/css/bootstrap.min.css")) frag.add_css( self.resource_string("static/css/bootstrap-grid.min.css")) frag.add_css( self.resource_string("static/css/bootstrap-reboot.min.css")) frag.add_javascript_url( "https://npmcdn.com/[email protected]/dist/js/tether.min.js") frag.add_javascript_url( "https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.1.3/js.cookie.min.js" ) frag.add_javascript( self.resource_string("static/js/src/bootstrap.min.js")) frag.add_javascript( self.resource_string("static/js/src/dnd.min.js")) frag.add_javascript( self.resource_string( "static/js/src/s3.fine-uploader.core.min.js")) frag.add_javascript( self.resource_string("static/js/src/s3.fine-uploader.js")) frag.add_javascript( self.resource_string( "static/js/src/s3.jquery.fine-uploader.min.js")) frag.add_javascript( loader.render_template("static/js/src/s3uploader_downloader.js", context)) frag.initialize_js('UploaderDownloaderXBlock') return frag
def student_view(self, context=None): # runtime error if not hasattr(self.runtime, "anonymous_student_id"): return self.message_view( "Error in uc_docker (get anonymous student id)", "Cannot get anonymous_student_id in runtime", context) # preview in studio if self.runtime.anonymous_student_id == "student": result, message = GitLabUtil.get_user_projects( self.git_host, self.git_port, self.git_teacher_token) if not result: return self.message_view( "Error in uc_docker (get git projects)", "Cannot get user's projects in git", context) context_dict = {"labs": self.labs, "message": ""} fragment = Fragment() fragment.add_content( Util.render_template('static/html/uc_lab.html', context_dict)) fragment.add_css(Util.load_resource("static/css/uc_docker.css")) fragment.add_javascript( Util.load_resource("static/js/src/uc_lab.js")) fragment.initialize_js("UcDockerXBlock") return fragment # student view in open-edx if self.is_new: # create git account when first visiting student = self.runtime.get_real_user( self.runtime.anonymous_student_id) email = student.email name = student.first_name + " " + student.last_name username = student.username self.git_password = Util.create_random_password() self.save() # first_name, last_name are empty if name == " ": name = username self.logger.info("password is " + self.git_password) # create ldap account l = ldap.initialize(self.ldap_url) l.bind(self.principal_name, self.ldap_password) dn = "uid=" + username + "," + self.base_dn attrs = {} attrs['objectclass'] = ['top', 'inetOrgPerson', 'eduPerson'] attrs['cn'] = str(username) attrs['sn'] = str(username) attrs['givenName'] = str(username) attrs['uid'] = str(username) attrs['userPassword'] = str(self.git_password) attrs['description'] = 'ldap user for shibboleth' attrs['eduPersonPrincipalName'] = str(email) # Convert our dict to nice syntax for the add-function using modlist-module ldif = modlist.addModlist(attrs) l.add_s(dn, ldif) l.unbind_s() self.logger.info("create ldap account " + username + "," + dn) self.logger.info(self.git_host + "," + str(self.git_port) + "," + self.git_admin_token + "," + name + "," + username + "," + email + "," + self.git_password) result, message = GitLabUtil.create_account( self.git_host, self.git_port, self.git_admin_token, name, username, email, self.git_password) self.logger.info("create_account result:") self.logger.info(result) self.logger.info(message) if not result: return self.message_view( "Error in uc_docker (create git account)", message, context) result, message = GitLabUtil.login(self.git_host, self.git_port, username, self.git_password) self.logger.info("login result:") self.logger.info(result) self.logger.info(message) if not result: return self.message_view( "Error in uc_docker (login git account)", message, context) try: message = json.loads(message) self.git_id = message["id"] self.git_user_token = message["private_token"] self.save() except Exception, ex: return self.message_view( "Error in uc_docker (load json string)", message, context) try: self.private_key, self.public_key = Util.gen_ssh_keys(email) self.logger.info("private_key:" + self.private_key) self.save() conn = pymongo.Connection('localhost', 27017) db = conn.test token = db.token token.insert({ "username": username, "token": message["private_token"], "password": self.git_password, "private_key": self.private_key, "public_key": self.public_key }) conn.disconnect() except Exception, ex: return self.message_view("Error in uc_docker (gen ssh key)", ex, context)
def student_view(self, context, authoring=False): """ Player view, displayed to the student """ xmltree = etree.fromstring(self.data) description = self._get_description(xmltree) hotspots = self._get_hotspots(xmltree) background = self._get_background(xmltree) has_youtube = False has_ooyala = False for hotspot in hotspots: width = 'width:{0}px'.format( hotspot.feedback.width ) if hotspot.feedback.width else 'width:300px' height = 'height:{0}px'.format( hotspot.feedback.height) if hotspot.feedback.height else '' max_height = '' if not hotspot.feedback.height: max_height = 'max-height:{0}px'.format(hotspot.feedback.max_height) if \ hotspot.feedback.max_height else 'max-height:300px' hotspot.reveal_style = 'style="{0};{1};{2}"'.format( width, height, max_height) if hotspot.feedback.youtube: has_youtube = True if hotspot.feedback.ooyala: has_ooyala = True context = { 'title': self.display_name, 'hotspot_coordinates_centered': self.hotspot_coordinates_centered, 'description_html': description, 'hotspots': hotspots, 'background': background, 'ie_uid': uuid.uuid4().hex[:15], } fragment = Fragment() fragment.add_content( loader.render_django_template( '/templates/html/image_explorer.html', context=context, i18n_service=self.runtime.service(self, 'i18n'))) hotspot_image_url = self.runtime.local_resource_url( self, 'public/images/hotspot-sprite.png') fragment.add_css(self.resource_string('public/css/image_explorer.css')) fragment.add_javascript_url( self.runtime.local_resource_url(self, 'public/js/image_explorer.js')) if has_youtube: fragment.add_javascript_url('https://www.youtube.com/iframe_api') if has_ooyala: fragment.add_javascript_url( '//player.ooyala.com/core/10efd95b66124001b415aa2a4bee29c8?plugins=main,bm' ) fragment.add_javascript_url( self.runtime.local_resource_url(self, 'public/js/ooyala_player.js')) fragment.initialize_js( 'ImageExplorerBlock', { 'hotspot_image': hotspot_image_url, 'authoring_view': 'true' if authoring else 'false' }) return fragment
def _base_view(self, context=None): annoto_auth = self.get_annoto_settings() horizontal, vertical = self.get_position() translator = self.runtime.service(self, 'i18n').translator lang = getattr( translator, 'get_language', lambda: translator.info().get( 'language', settings.LANGUAGE_CODE))() rtl = getattr(translator, 'get_language_bidi', lambda: lang in settings.LANGUAGES_BIDI)() course = self.get_course_obj() course_overview = CourseOverview.objects.get(id=self.course_id) js_params = { 'clientId': annoto_auth.get('client_id'), 'horizontal': horizontal, 'vertical': vertical, 'tabs': self.tabs, 'overlayVideo': self.overlay_video, 'initialState': self.initial_state, 'privateThread': self.discussions_scope, 'mediaTitle': self.get_parent().display_name, 'language': lang, 'rtl': rtl, 'courseId': self.course_id.to_deprecated_string(), 'courseDisplayName': course.display_name, 'courseDescription': course_overview.short_description, 'courseImage': course_image_url(course), 'demoMode': not bool(annoto_auth.get('client_id')), } context['error'] = {} if not annoto_auth.get('client_id'): context['error']['type'] = 'warning' context['error']['messages'] = [ self.i18n_service.gettext( 'You did not provide annoto credentials. And you view it in demo mode.' ), self.i18n_service.gettext( 'Please add "annoto-auth:<CLIENT_ID>:<CLIENT_SECRET>" to "Advanced Settings" > "LTI Passports"' ), ] else: try: jwt.PyJWS().decode(annoto_auth.get('client_id'), verify=False) except: context['error']['type'] = 'error' context['error']['messages'] = [ self.i18n_service.gettext( '"CLIENT_ID" is not a valid JWT token.'), self.i18n_service.gettext( 'Please provide valid "CLIENT_ID" in ' '"Advanced Settings" > "LTI Passports" > "annoto-auth:<CLIENT_ID>:<CLIENT_SECRET>"' ), ] else: if not annoto_auth.get('client_secret'): context['error']['type'] = 'error' context['error']['messages'] = [ self.i18n_service.gettext( '"CLIENT_SECRET" is required when "CLIENT_ID" provided.' ), self.i18n_service.gettext( 'Please add "CLIENT_SECRET" to ' '"Advanced Settings" > "LTI Passports" > "annoto-auth:<CLIENT_ID>:<CLIENT_SECRET>"' ), ] template = Template(self.resource_string("static/html/annoto.html")) html = template.render(Context(context)) frag = Fragment(html) frag.add_css(self.resource_string("static/css/annoto.css")) frag.add_javascript(self.resource_string("static/js/src/annoto.js")) frag.initialize_js('AnnotoXBlock', json_args=js_params) return frag
def recap_blocks_listing_view(self, context=None): """This view is used in the Racap tab in the LMS Instructor Dashboard to display all available course Recap xblocks. Args: context: contains two items: "recap_items" - all course items with names and parents, example: [{"parent_name": "Vertical name", "name": "Recap Display Name", }, ...] Returns: (Fragment): The HTML Fragment for this XBlock. """ course_id = self.location.course_key recap_blocks = self.get_recap_course_blocks(course_id) recap_name_list = [] for block in recap_blocks: recap_name_list.append((block.display_name, block.xblock_list)) make_pdf_json = reverse('xblock_handler', args=[course_id, block.location, 'make_pdf_json']) refresh_table = reverse('xblock_handler', args=[course_id, block.location, 'refresh_table']) user = self.runtime.get_real_user(self.runtime.anonymous_student_id) lang_prefs = get_user_preference(user, LANGUAGE_KEY) context_dict = { "make_pdf_json": make_pdf_json, "refresh_table": refresh_table, "recap_name_list": recap_name_list, "lang_prefs": lang_prefs } instructor_dashboard_fragment = Fragment() instructor_dashboard_fragment.content = loader.render_django_template( 'static/html/recap_dashboard.html', context_dict ) instructor_dashboard_fragment.add_css( self.resource_string("static/css/recap.css") ) instructor_dashboard_fragment.add_css( self.resource_string("public/DataTables/css/jquery.dataTables.css") ) instructor_dashboard_fragment.add_javascript_url( self.runtime.local_resource_url( self, 'public/FileSaver.js/FileSaver.min.js' ) ) instructor_dashboard_fragment.add_javascript_url( self.runtime.local_resource_url( self, 'public/jsPDF-1.3.2/jspdf.min.js' ) ) instructor_dashboard_fragment.add_javascript_url( self.runtime.local_resource_url( self, 'public/jsPDF-1.3.2/html2canvas.min.js' ) ) instructor_dashboard_fragment.add_javascript_url( self.runtime.local_resource_url( self, 'public/jsPDF-1.3.2/html2pdf.js' ) ) instructor_dashboard_fragment.add_javascript_url( self.runtime.local_resource_url( self, 'public/DataTables/js/jquery.dataTables.js' ) ) instructor_dashboard_fragment.add_javascript_url( self.runtime.local_resource_url( self, "public/recap_dashboard.js" ) ) instructor_dashboard_fragment.initialize_js('RecapDashboard') return instructor_dashboard_fragment
def student_view(self, context=None): """ The primary view of the XBadgeXBlock, shown to students when viewing courses. """ # Setup for local images local_resource_url0 = [] local_resource_url1 = [] if self.myReset: for i in range(self.nBadges): local_resource_url0.append( self.runtime.local_resource_url( self, 'public/images/Badge_A_Gray.png')) local_resource_url1.append( self.runtime.local_resource_url( self, 'public/images/Badge_A_Color.png')) # Get current student id STUDENT_ID = self.scope_ids.user_id if not isinstance(STUDENT_ID, (int, long)): STUDENT_ID = 31 if 'passwd' in DB: db = MySQLdb.connect(host=DB['host'], user=DB['user'], passwd=DB['passwd'], db=DB['db']) else: db = MySQLdb.connect(host=DB['host'], user=DB['user'], db=DB['db']) cur = db.cursor() # Find COURSE_ID part1 = "SELECT id FROM course_overviews_courseoverview WHERE id LIKE '%" part2 = "%'" query = part1 + self.myCourseNum + "+" + self.myCourseRun + part2 cur.execute(query) COURSE_ID = "" for row in cur.fetchall(): COURSE_ID = row[0] # Get course structure CHA_video = [] try: for j in range(self.nBadges): temp_video = [] for i in range(len(self.videoArr)): if self.videoMap[i][j] == 1: temp = self.videoDic.keys()[ self.videoDic.values().index(self.videoArr[i])] temp_video.append(temp) CHA_video.append(temp_video) except: CHA_video = [] CHA_quiz = [] try: for j in range(self.nBadges): temp_quiz = [] for i in range(len(self.quizArr)): if self.quizMap[i][j] == 1: temp = self.quizDic.keys()[self.quizDic.values().index( self.quizArr[i])] temp_quiz.append(temp) CHA_quiz.append(temp_quiz) except: CHA_quiz = [] # Check Video Watched part1 = "SELECT module_id FROM courseware_studentmodule WHERE course_id = '" part2 = "' AND student_id = " part3 = " AND module_type = 'video';" query = part1 + COURSE_ID + part2 + str(STUDENT_ID) + part3 cur.execute(query) flag_video = [] student_video = [] for row in cur.fetchall(): student_video.append(row[0]) temp = [] try: videoLen = max(32, len(CHA_video[0][0])) for v in student_video: temp.append(v[-videoLen:]) except: temp = [] miss_video = [] try: for value in CHA_video: if len(list(set(temp) & set(value))) >= len(value): i = 1 else: i = 0 flag_video.append(i) for require in value: if require not in temp: miss_video.append(require) except: flag_video = [0] * self.nBadges display_list = [] for chapter in CHA_video: myString = "" for video_id in chapter: if video_id in miss_video: myString += self.videoDic[video_id] + ". " display_list.append(myString.decode('utf-8')) self.myVideo = display_list # Check Quiz Passed query = "SELECT grade,max_grade,module_id FROM courseware_studentmodule WHERE max_grade >0 AND course_id = '" + COURSE_ID + "';" cur.execute(query) for row in cur.fetchall(): try: sample_quiz = row[2] except: sample_quiz = "" new_CHA_quiz = [] try: prefix = sample_quiz[0:-videoLen] for chapter in CHA_quiz: new_quiz = [] for quiz_id in chapter: if len(quiz_id) == videoLen: temp = prefix + quiz_id new_quiz.append(temp.encode('UTF-8')) new_CHA_quiz.append(new_quiz) part1 = "SELECT grade,max_grade,module_id FROM courseware_studentmodule WHERE max_grade >0 AND course_id = '" part1a = "'" part2 = " AND student_id = " part3 = " AND module_id " part4 = ";" flag_quiz = [] for quiz in new_CHA_quiz: if len(quiz) > 1: part3a = "in " part3b = " GROUP BY module_id" partx = tuple(quiz) elif len(quiz) == 1: part3a = "= '" part3b = "' GROUP BY module_id" partx = quiz[0] else: flag_quiz.append(1) continue query = part1 + COURSE_ID + part1a + part3 + part3a + str( partx) + part3b + part4 cur.execute(query) y = 0 for row in cur.fetchall(): try: y += int(row[1]) except: y = y query = part1 + COURSE_ID + part1a + part2 + str( STUDENT_ID) + part3 + part3a + str(partx) + part3b + part4 cur.execute(query) x = 0 for row in cur.fetchall(): try: x += int(row[0]) except: x = x if y == 0: flag_quiz.append(1) elif float(x) / float(y) >= self.quizPass / 100.0: flag_quiz.append(1) else: flag_quiz.append(0) except: flag_quiz = [1] * self.nBadges self.myQuiz = flag_quiz # Check Badge Earned my_flag = [] for i in range(self.nBadges): try: my_flag.append(flag_video[i] * flag_quiz[i]) except: my_flag.append(0) self.myFlag = my_flag db.close() # Link to Images local_resource_url = [] try: for i in range(self.nBadges): if my_flag[i] == 1: if self.myReset: local_resource_url.append(local_resource_url1[i]) else: local_resource_url.append(self.myColor[i]) else: if self.myReset: local_resource_url.append(local_resource_url0[i]) else: local_resource_url.append(self.myGrey[i]) except: local_resource_url = [] self.myBadges = local_resource_url # Render student view html_charts = self.resource_string("public/html/xbadge.html") template = Template(html_charts) html = template.render(Context({})) frag = Fragment(html) frag.add_css(self.resource_string("public/css/xbadge.css")) frag.add_javascript(self.resource_string("public/js/src/xbadge.js")) frag.initialize_js('XBadgeXBlock') return frag
def student_view(self, context=None): # runtime error if not hasattr(self.runtime, "anonymous_student_id"): return self.message_view( "Error in uc_docker (get anonymous student id)", "Cannot get anonymous_student_id in runtime", context) # preview in studio if self.runtime.anonymous_student_id == "student": result, message = GitLabUtil.get_user_projects( self.git_host, self.git_port, self.git_teacher_token) if not result: return self.message_view( "Error in uc_docker (get git projects)", "Cannot get user's projects in git", context) context_dict = {"labs": self.labs, "message": ""} fragment = Fragment() fragment.add_content( Util.render_template('static/html/uc_lab.html', context_dict)) fragment.add_css(Util.load_resource("static/css/uc_docker.css")) fragment.add_javascript( Util.load_resource("static/js/src/uc_lab.js")) fragment.initialize_js("UcDockerXBlock") return fragment # student view in open-edx if self.is_new: # create git account when first visiting student = self.runtime.get_real_user( self.runtime.anonymous_student_id) email = student.email name = student.first_name + " " + student.last_name username = student.username self.git_password = Util.create_random_password() self.save() # first_name, last_name are empty if name == " ": name = username self.logger.info("password is " + self.git_password) self.logger.info(self.git_host + "," + str(self.git_port) + "," + self.git_admin_token + "," + name + "," + username + "," + email + "," + self.git_password) result, message = GitLabUtil.create_account( self.git_host, self.git_port, self.git_admin_token, name, username, email, self.git_password) self.logger.info("create_account result:") self.logger.info(result) self.logger.info(message) if not result: return self.message_view( "Error in uc_docker (create git account)", message, context) result, message = GitLabUtil.login(self.git_host, self.git_port, username, self.git_password) self.logger.info("login result:") self.logger.info(result) self.logger.info(message) if not result: return self.message_view( "Error in uc_docker (login git account)", message, context) try: message = json.loads(message) self.git_id = message["id"] self.git_user_token = message["private_token"] self.save() except Exception, ex: return self.message_view( "Error in uc_docker (load json string)", message, context) try: self.private_key, self.public_key = Util.gen_ssh_keys(email) self.logger.info("private_key:" + self.private_key) self.save() conn = pymongo.Connection('192.168.122.183', 27017) db = conn.test token = db.token token.insert({ "username": username, "token": message["private_token"], "password": self.git_password, "private_key": self.private_key, "public_key": self.public_key }) conn.disconnect() except Exception, ex: return self.message_view("Error in uc_docker (gen ssh key)", ex, context)
def student_view(self, context): """ Lab view, displayed to the student """ dummy_data = textwrap.dedent(""" <carousel> <image> <link>http://met-content.bu.edu/etr2/content/images/Slide1.JPG</link> <description>Slide 1 description comes here</description> </image> <image> <link>http://met-content.bu.edu/etr2/content/images/Slide2.JPG</link> <description>Slide 2 description comes here</description> </image> <image> <link>http://met-content.bu.edu/etr2/content/images/Slide3.JPG</link> <description>Slide 3 description comes here</description> </image> <video> <link>http://www.youtube.com/watch?v=7uHeNryKUWk</link> <description>Video Description goes here</description> </video> <document> <link>http://www.bu.edu/met-eti/files/2013/03/Final_VirtualLaboratoriesForLearning.pdf</link> <description>documentument Description goes here</description> </document> </carousel> """) #root = ET.fromstring(self.data) #root = etree.parse(StringIO(self.data.replace('&', '&'))).getroot() root = etree.fromstring(self.data.replace('&', '&')) items = [] for child in root: text_data = child.find('link').text if child.tag == 'document': text_data = urllib.quote(text_data, '') try: full_screen_link = child.find("full_screen_link").text except: full_screen_link = "" description = child.find('description') description1 = ET.tostring(description) description1 = description1.replace('<description>', '') description1 = description1.replace('</description>', '') description1 = description1.replace('&', '&') description1 = urllib2.unquote( HTMLParser.HTMLParser().unescape(description1)) full_screen_link = full_screen_link if full_screen_link else '' width = child.attrib.get('width', '100%') height = child.attrib.get('height', '625') items.append((child.tag, text_data, width, height, description1, full_screen_link)) fragment = Fragment() context = { 'items': items, } fragment.add_content( render_template('/templates/html/carousel.html', context)) fragment.add_javascript_url( "https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/jquery.magnific-popup.min.js" ) fragment.add_css_url( "https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/magnific-popup.min.css" ) fragment.add_javascript( load_resource('public/js/jquery-ui-1.10.4.custom.js')) fragment.add_css(load_resource('public/css/responsive-carousel.css')) fragment.add_css( load_resource('public/css/responsive-carousel.slide.css')) fragment.add_javascript( load_resource('public/js/responsive-carousel.js')) fragment.add_css_url("https://vjs.zencdn.net/4.5.1/video-js.css") fragment.add_javascript_url("https://vjs.zencdn.net/4.5.1/video.js") fragment.add_javascript(load_resource('public/js/youtube.js')) fragment.add_javascript( 'function CarouselBlock(runtime, element) { console.log("success..."); }' ) fragment.add_javascript(load_resource('public/js/carousel.js')) fragment.initialize_js('CarouselBlock') return fragment
def _base_view(self, context=None): context = context is None and {'is_author_view': False} or context annoto_auth = self.get_annoto_settings() horizontal, vertical = self.get_position() translator = self.runtime.service(self, 'i18n').translator lang = getattr( translator, 'get_language', lambda: translator.info().get( 'language', settings.LANGUAGE_CODE))() rtl = getattr(translator, 'get_language_bidi', lambda: lang in settings.LANGUAGES_BIDI)() course = self.get_course_obj() course_overview = CourseOverview.objects.get(id=self.course_id) course_id = str(self.course_id) course_display_name = course.display_name user = self._get_user() if not context[ 'is_author_view'] and user and self.discussions_scope == 'cohort': from openedx.core.djangoapps.course_groups.cohorts import get_cohort cohort = get_cohort(user, self.course_id) if cohort: course_id = u'{}_{}'.format(course_id, cohort.id) course_display_name = u'{} [{}]'.format( course_display_name, cohort.name) js_params = { 'objectType': self.object_type, 'clientId': annoto_auth.get('client_id'), 'horizontal': horizontal, 'vertical': vertical, 'tabs': self.tabs, 'overlayVideo': self.overlay_video, 'initialState': self.initial_state, 'privateThread': self.discussions_scope != 'site', 'mediaTitle': self.get_parent().display_name, 'language': lang, 'rtl': rtl, 'courseId': course_id, 'courseDisplayName': course_display_name, 'courseDescription': course_overview.short_description, 'courseImage': course_image_url(course), 'demoMode': not bool(annoto_auth.get('client_id')), 'isLive': self.video_type == 'stream', 'comments': 'comments' in self.features, 'privateNotes': 'notes' in self.features, 'videoBlockID': self.video_block_id, } context['error'] = {} if not annoto_auth.get('client_id'): context['error']['type'] = 'warning' context['error']['messages'] = [ self.i18n_service.gettext( 'You did not provide annoto credentials. And you view it in demo mode.' ), self.i18n_service.gettext( 'Please add "annoto-auth:<CLIENT_ID>:<CLIENT_SECRET>" to "Advanced Settings" > "LTI Passports"' ), ] else: try: jwt.PyJWS().decode(annoto_auth.get('client_id'), verify=False) except: context['error']['type'] = 'error' context['error']['messages'] = [ self.i18n_service.gettext( '"CLIENT_ID" is not a valid JWT token.'), self.i18n_service.gettext( 'Please provide valid "CLIENT_ID" in ' '"Advanced Settings" > "LTI Passports" > "annoto-auth:<CLIENT_ID>:<CLIENT_SECRET>"' ), ] else: if not annoto_auth.get('client_secret'): context['error']['type'] = 'error' context['error']['messages'] = [ self.i18n_service.gettext( '"CLIENT_SECRET" is required when "CLIENT_ID" provided.' ), self.i18n_service.gettext( 'Please add "CLIENT_SECRET" to ' '"Advanced Settings" > "LTI Passports" > "annoto-auth:<CLIENT_ID>:<CLIENT_SECRET>"' ), ] template = Template(self.resource_string("static/html/annoto.html")) html = template.render(Context(context)) frag = Fragment(html) frag.add_css(self.resource_string("static/css/annoto.css")) frag.add_javascript(self.resource_string("static/js/src/annoto.js")) frag.initialize_js('AnnotoXBlock', json_args=js_params) return frag
def student_view(self, context=None): """ The primary view of the RecapXBlock seen in LMS """ blocks = [] for usage_key, xblock_type in self.get_blocks(self.xblock_list): block = self.runtime.get_block(usage_key) if hasattr(block, 'custom_report_format'): question = str(block.display_name) try: user = self.runtime.get_real_user(self.runtime.anonymous_student_id) except TypeError: user = None answer = block.custom_report_format( user=user, block=block, ) blocks.append((question, answer)) elif xblock_type == 'problem': answer = u"" question = u"" try: question = str(block.display_name) answer = self.get_submission(usage_key) if answer is None: answer = block.lcp.get_question_answer_text() blocks.append((question, answer)) except Exception as e: logger.warn(str(e)) answer = block.lcp.get_question_answer_text() blocks.append((question, answer)) layout = self.get_user_layout(blocks) idArray = self.scope_ids.usage_id._to_string().split('@') xblockId = idArray[len(idArray) - 1] context = { 'recap_answers_id': 'recap_answers_' + xblockId, 'recap_editor_id': 'recap_editor_' + xblockId, 'recap_cmd_id': 'recap_cmd_' + xblockId, 'blocks': blocks, 'layout': layout, 'allow_download': self.allow_download, 'download_text': self.download_text, } frag = Fragment( loader.render_django_template( "static/html/recap.html", context).format(self=self) ) if (self.css_file): frag.add_css(self.css_file) frag.add_css(self.resource_string("static/css/recap.css")) frag.add_javascript_url( self.runtime.local_resource_url( self, 'public/FileSaver.js/FileSaver.min.js' ) ) frag.add_javascript_url( self.runtime.local_resource_url( self, 'public/jsPDF-1.3.2/jspdf.min.js' ) ) frag.add_javascript_url( self.runtime.local_resource_url( self, 'public/jsPDF-1.3.2/html2canvas.min.js' ) ) frag.add_javascript_url( self.runtime.local_resource_url( self, 'public/jsPDF-1.3.2/html2pdf.js' ) ) frag.add_javascript(self.resource_string("static/js/src/recap.js")) frag.initialize_js('RecapXBlock', { 'recap_answers_id': 'recap_answers_' + xblockId, 'recap_editor_id': 'recap_editor_' + xblockId, 'recap_cmd_id': 'recap_cmd_' + xblockId, }) return frag
def author_view(self, context=None): context_html = self.get_context() template = self.render_template('static/html/author_view.html', context_html) frag = Fragment(template) frag.add_css(self.resource_string("static/css/eolconditional.css")) return frag
def student_view(self, context): """ The primary view for the students """ # Setup data to claim a badge self.n_user_id = self.get_student_id() self.claim_db_user_data = self.DB_get_user_data() self.claim_db_user_id = self.claim_db_user_data[0] self.claim_db_user_course = self.claim_db_user_data[1] self.claim_db_user_name = self.claim_db_user_data[2] self.claim_db_user_email = self.claim_db_user_data[3] self.claim_db_user_score = self.claim_db_user_data[4] self.claim_db_problems_lists = self.claim_db_user_data[5] self.claim_db_problems_total_score = self.claim_db_user_data[6] self.claim_db_problems_partial_score = self.claim_db_user_data[7] self.claim_db_problems_percent_score = self.claim_db_user_data[8] self.claim_db_badge_problems_score = self.claim_db_user_data[9] self.user_score = self.claim_db_user_data[4] claim_name = self.claim_db_user_name claim_mail = self.claim_db_user_email self.claim_badge_errors = self.claim_badge_errors self.claim_badge_form = '' self.check_earned = '' self.preview_badge = '' # Check out provider badge data if self.claim_badge_errors == "": self.claim_prov_access_token = self.iblclient.get_auth_token(self.claim_prov_usr, self.claim_prov_pwd) if self.claim_prov_access_token !="": badge_info = self.iblclient.get_badge_data(self.claim_prov_access_token,self.bg_id,'info') badge_params = self.iblclient.get_badge_data(self.claim_prov_access_token,self.bg_id,'params') obj_badge = self.iblclient.create_obj_badge(badge_info,badge_params) self.check_earned = self.iblclient.check_earn_badge(self.claim_prov_access_token,self.claim_db_user_email,self.bg_id) self.preview_badge = self.iblclient.build_badge_preview(obj_badge) if obj_badge : # check if user has been awarded yet if self.check_earned!='': self.award_earn_prov = self.iblclient.get_award_result ( self.check_earned ) self.award_earned = self.iblclient.get_award_result_formatted(self.award_earn_prov,self.congratulations_text) else: self.claim_badge_form = self.iblclient.build_badge_form(self.claim_db_user_name,self.claim_db_user_email,self.form_text,obj_badge) else: self.claim_badge_errors = 'Could not retrieve the information associated with the Badge ID selected. Please, verify your data.' else: self.claim_badge_errors = 'Could not connect to provider. Please, verify your credentials.' # Initialize html view self.claim_data = "" if self.claim_badge_errors == "": if self.debug_mode == "1": html = self.resource_string("static/html/debug.html") else: if int(self.user_score) < int(self.required_score): html = self.resource_string("static/html/student_view_noscore.html") else: if self.check_earned!='': html = self.resource_string("static/html/student_view_earn_badge.html") else: html = self.resource_string("static/html/student_view_claim_badge.html") frag = Fragment(html.format(self=self)) frag.add_css(self.resource_string("static/css/style.css")) if self.check_earned =='': frag.add_javascript(self.resource_string("static/js/src/student_view_scripts.js")) frag.initialize_js('StudentViewBadge') else: if self.debug_mode == "1": html = self.resource_string("static/html/result_errors_debug.html") else: html = self.resource_string("static/html/result_errors.html") frag = Fragment(html.format(self=self)) frag.add_css(self.resource_string("static/css/style.css")) return frag