def auth(service_document_url, username, password): # Get the service document and persist what's needed. conn = sword2cnx.Connection(service_document_url, user_name=username, user_pass=password, always_authenticate=True, download_service_document=True) if not conn.sd.valid: # Invalid username of password. return None collections = [{'title': i.title, 'href': i.href} for i in \ sword2cnx.get_workspaces(conn)] # Get needed info from the service document doc = etree.fromstring(conn.sd.raw_response) # Prep the namespaces. xpath does not like a None namespace. namespaces = doc.nsmap del namespaces[None] # We need some details from the service document. # TODO: This is fragile, since it assumes a certain structure. workspace_title = doc.xpath('//atom:title', namespaces=namespaces)[0].text sword_version = doc.xpath('//sword:version', namespaces=namespaces)[0].text maxuploadsize = doc.xpath('//sword:maxuploadsize', namespaces=namespaces)[0].text return CnxSession(username, password, service_document_url, workspace_title, sword_version, maxuploadsize, collections)
def get_connection(session): login = session['login'] conn = sword2cnx.Connection(login.service_document_url, user_name=login.username, user_pass=login.password, always_authenticate=True, download_service_document=False) return conn
def _download_module(self, module_url): request = self.request session = request.session conn = sword2cnx.Connection(session['login'].service_document_url, user_name=session['login'].username, user_pass=session['login'].password, always_authenticate=True, download_service_document=False) parts = urlparse.urlsplit(module_url) path = parts.path.split('/') path = path[:path.index('sword')] module_url = '%s://%s%s' % (parts.scheme, parts.netloc, '/'.join(path)) # example: http://cnx.org/Members/user001/m17222/sword/editmedia zip_file = conn.get_cnx_module(module_url=module_url, packaging='zip') save_dir = get_save_dir(request) if save_dir is None: request.session['upload_dir'], save_dir = create_save_dir(request) extract_to_save_dir(zip_file, save_dir) cnxml_file = open(os.path.join(save_dir, 'index.cnxml'), 'rb') cnxml = cnxml_file.read() cnxml_file.close() conversionerror = None try: structuredhtml = cnxml_to_structuredhtml(cnxml) save_and_backup_file(save_dir, 'index.structured.html', structuredhtml) htmlpreview = structuredhtml_to_htmlpreview(structuredhtml) save_and_backup_file(save_dir, 'index.html', htmlpreview) files = get_files(save_dir) save_zip(save_dir, cnxml, structuredhtml, files) except libxml2.parserError: conversionerror = traceback.format_exc() raise ConversionError(conversionerror)
def update_cnx_metadata(request): """ Handle update of metadata to cnx """ check_login(request) templatePath = 'templates/update_metadata.pt' session = request.session config = load_config(request) workspaces = [ (i['href'], i['title']) for i in self.session['login'].collections] subjects = ["Arts", "Business", "Humanities", "Mathematics and Statistics", "Science and Technology", "Social Sciences", ] field_list = [ ['authors', 'authors', {'type': 'hidden'}], ['maintainers', 'maintainers', {'type': 'hidden'}], ['copyright', 'copyright', {'type': 'hidden'}], ['editors', 'editors', {'type': 'hidden'}], ['translators', 'translators', {'type': 'hidden'}], ['title', 'Title', {'type': 'text'}], ['summary', 'Summary', {'type': 'textarea'}], ['keywords', 'Keywords (One per line)', {'type': 'textarea'}], ['subject', 'Subject', {'type': 'checkbox', 'values': subjects}], ['language', 'Language', {'type': 'select', 'values': languages, 'selected_value': 'en'}], ['google_code', 'Google Analytics Code', {'type': 'text'}], ['workspace', 'Workspace', {'type': 'select', 'values': workspaces}], ] remember_fields = [field[0] for field in field_list[5:]] defaults = {} for role in ['authors', 'maintainers', 'copyright', 'editors', 'translators']: defaults[role] = ','.join(config['metadata'][role]).replace('_USER_', session['login'].username) config['metadata'][role] = ', '.join(config['metadata'][role]).replace('_USER_', session['login'].username) if 'title' in session: print('TITLE '+session['title']+' in session') defaults['title'] = session['title'] config['metadata']['title'] = session['title'] form = Form(request, schema=MetadataSchema, defaults=defaults ) # Check for successful form completion if form.validate(): for field_name in remember_fields: if form.data['keep_%s' % field_name]: session[field_name] = form.data[field_name] else: if field_name in session: del(session[field_name]) metadata = {} metadata['dcterms:title'] = form.data['title'] if form.data['title'] \ else session['filename'] metadata_entry = sword2cnx.MetaData(metadata) role_metadata = {} role_mappings = {'authors': 'dcterms:creator', 'maintainers': 'oerdc:maintainer', 'copyright': 'dcterms:rightsHolder', 'editors': 'oerdc:editor', 'translators': 'oerdc:translator'} for k, v in role_mappings.items(): role_metadata[v] = form.data[k].split(',') for key, value in role_metadata.iteritems(): for v in value: v = v.strip() if v: metadata_entry.add_field(key, '', {'oerdc:id': v}) conn = sword2cnx.Connection("http://cnx.org/sword/servicedocument", user_name=session['login'].username, user_pass=session['login'].password, always_authenticate=True, download_service_document=True) update = conn.update(edit_iri=session['edit_iri'],metadata_entry = metadata_entry,in_progress=True,metadata_relevant=True) metadata={} metadata['dcterms:title'] = form.data['title'] if form.data['title'] \ else session['filename'] metadata['dcterms:abstract'] = form.data['summary'].strip() metadata['dcterms:language'] = form.data['language'] metadata['dcterms:subject'] = [i.strip() for i in form.data['keywords'].splitlines() if i.strip()] metadata['oerdc:oer-subject'] = form.data['subject'] for key in metadata.keys(): if metadata[key] == '': del metadata[key] add = conn.update_metadata_for_resource(edit_iri=session['edit_iri'],metadata_entry = metadata_entry,in_progress=True) metadata['oerdc:analyticsCode'] = form.data['google_code'].strip() for key in metadata.keys(): if metadata[key] == '': del metadata[key] metadata_entry = sword2cnx.MetaData(metadata) add = conn.update(edit_iri=session['edit_iri'],metadata_entry = metadata_entry,in_progress=True) return HTTPFound(location=request.route_url('summary')) response = { 'form': FormRenderer(form), 'field_list': field_list, 'workspaces': workspaces, 'languages': languages, 'subjects': subjects, 'config': config, } return render_to_response(templatePath, response, request=request)
def enhance(request): check_login(request) session = request.session google_resource_id = "" slideshare_id = "" embed_google = False embed_slideshare = False not_converted = True show_iframe = False form = Form(request, schema=QuestionAnswerSchema) validate_form = form.validate() print form.all_errors() if session.has_key('google-resource-id'): google_resource_id = session['google-resource-id'] if session.has_key('slideshare_id'): slideshare_id = session['slideshare_id'] if fetch_slideshow_status(slideshare_id) == "2": not_converted = False show_iframe = True if google_resource_id != "": embed_google = True if slideshare_id != "": embed_slideshare = True templatePath = "templates/google_ss_preview.pt" if validate_form: introductory_paragraphs = request.POST.get('introductory_paragraphs') question_count = 0 cnxml = session[ "cnxml"] + """<content><section id="intro-section-title"><title id="introtitle">Introduction</title><para id="introduction-1">""" + introductory_paragraphs + """</para></section><section id="slides-embed"><title id="slide-embed-title">View the slides</title><figure id="ss-embed-figure"><media id="slideshare-embed" alt="slideshare-embed"><iframe src="http://www.slideshare.net/slideshow/embed_code/""" + slideshare_id + """" width="425" height="355" /></media></figure></section>""" for i in range(1, 6): form_question = request.POST.get('question-' + str(i)) if form_question: form_radio_answer = request.POST.get( 'radio-' + str(i) ) #this give us something like 'answer-1-1'. so our solution is this question_count += 1 if question_count == 1: cnxml += """<section id="test-section"><title>Test your knowledge</title>""" itemlist = "" for j in range(1, 10): try: form_all_answers = request.POST.get('answer-' + str(i) + '-' + str(j)) if form_all_answers: itemlist += "<item>" + form_all_answers + "</item>" except: print "No element found" if form_radio_answer: solution = request.POST.get(form_radio_answer) cnxml += """<exercise id="exercise-""" + str( i ) + """"><problem id="problem-""" + str( i ) + """"><para id="para-""" + str(i) + """">""" + str( form_question ) + """<list id="option-list-""" + str( i ) + """" list-type="enumerated" number-style="lower-alpha">""" + str( itemlist) + """</list></para></problem>""" else: print "ELESE CONDUITION OF radio" solution = request.POST.get('answer-' + str(i) + '-1') cnxml += """<exercise id="exercise-""" + str( i) + """"><problem id="problem-""" + str( i) + """"><para id="para-""" + str( i) + """">""" + str( form_question) + """</para></problem>""" print "FORM RADIO ANSWER", form_radio_answer print "SOLUTION", solution cnxml += """ <solution id="solution-""" + str( i ) + """"> <para id="solution-para-""" + str( i ) + """">""" + solution + """</para></solution></exercise>""" """form_solution = request.POST.get('solution-'+str(i)) all_post_data = {"data":{"options":form_options,"solution":form_solution,"question":form_question}} for question in all_post_data: options = all_post_data[question]['options'] solution = all_post_data[question]['solution'] asked_question = all_post_data[question]['question'] optionlist="" for option in options: optionlist+="<item>"+option+"</item>""" #cnxml+="""<exercise id="exercise-"""+str(j)+""""><problem id="problem-"""+str(j)+""""><para id="para-"""+str(j)+"""">"""+str(asked_question)+"""<list id="option-list-"""+str(j)+"""" list-type="enumerated" number-style="lower-alpha">"""+str(optionlist)+"""</list></para></problem>""" #cnxml+=""" <solution id="solution-"""+str(j)+""""> <para id="solution-para-"""+str(j)+"""">"""+solution+"""</para></solution></exercise>""" #j+=1 metadata = session['metadata'] if question_count >= 1: cnxml += "</section></content></document>" else: cnxml += "</content></document>" workspaces = [(i['href'], i['title']) for i in session['login'].collections] metadata_entry = sword2cnx.MetaData(metadata) zipped_filepath = session['userfilepath'] zip_archive = zipfile.ZipFile(zipped_filepath, 'w') zip_archive.writestr("index.cnxml", cnxml) zip_archive.close() conn = sword2cnx.Connection("http://cnx.org/sword/servicedocument", user_name=session['login'].username, user_pass=session['login'].password, always_authenticate=True, download_service_document=True) collections = [{ 'title': i.title, 'href': i.href } for i in sword2cnx.get_workspaces(conn)] session['login'].collections = collections workspaces = [(i['href'], i['title']) for i in session['login'].collections] session['workspaces'] = workspaces with open(zipped_filepath, 'rb') as zip_file: deposit_receipt = conn.create( col_iri=workspaces[0][0], metadata_entry=metadata_entry, payload=zip_file, filename='upload.zip', mimetype='application/zip', packaging='http://purl.org/net/sword/package/SimpleZip', in_progress=True) session['dr'] = deposit_receipt session['deposit_receipt'] = deposit_receipt.to_xml() soup = BeautifulSoup(deposit_receipt.to_xml()) data = soup.find("link", rel="edit") edit_iri = data['href'] session['edit_iri'] = edit_iri creator = soup.find('dcterms:creator') username = session['login'].username email = creator["oerdc:email"] url = "http://connexions-oerpub.appspot.com/" post_values = { "username": username, "email": email, "slideshow_id": slideshare_id } data = urllib.urlencode(post_values) google_req = urllib2.Request(url, data) google_response = urllib2.urlopen(google_req) now_string = datetime.datetime.now().strftime('%Y%m%d-%H%M%S') temp_dir_name = '%s-%s' % (request.session['login'].username, now_string) save_dir = os.path.join(request.registry.settings['transform_dir'], temp_dir_name) os.mkdir(save_dir) request.session['upload_dir'] = temp_dir_name cnxml = clean_cnxml(cnxml) save_cnxml(save_dir, cnxml, []) return HTTPFound(location=request.route_url('metadata')) #return HTTPFound(location=request.route_url('updatecnx')) response = { 'form': FormRenderer(form), "slideshare_id": slideshare_id, "google_resource_id": google_resource_id, "embed_google": embed_google, "embed_slideshare": embed_slideshare, "not_converted": not_converted, "show_iframe": show_iframe } return render_to_response(templatePath, response, request=request)