Exemple #1
0
def return_slideshare_upload_form(request):
    check_login(request)
    session = request.session
    redirect_to_google_oauth = False

    form = Form(request, schema=ImporterChoiceSchema)
    response = {'form':FormRenderer(form)}
    username = session['login'].username
    if form.validate():
        original_filename = session['original_filename']
        slideshow_id = None
        if form.data['importer'] == 'slideshare':
            slideshow_id = upload_to_slideshare("saketkc", original_filename)
            session['slideshare_id'] = slideshow_id

        if form.data['importer'] == 'google':
            if session.has_key('slideshare_oauth'):
                # RETURNING USER
                redirect_to_google_oauth = False
                oauth_token = session['slideshare_oauth']["oauth_token"]
                oauth_secret = session['slideshare_oauth']["oauth_secret"]
                guploader = GooglePresentationUploader()
                guploader.authentincate_client_with_oauth2(oauth_token,oauth_secret)
                guploader.upload(original_filename)
                guploader.get_first_revision_feed()
                guploader.publish_presentation_on_web()
                resource_id = guploader.get_resource_id().split(':')[1]
                session['google-resource-id'] = resource_id
                print "UPLOADING TO GOOGLE"
            else:
                print "NEW USER"
                redirect_to_google_oauth = True
                session['original-file-path'] = original_filename

        uploaded_filename = session['uploaded_filename']
        if slideshow_id is not None:
            slideshare_details = get_details(slideshow_id)
        cnxml = """\
<featured-links>
  <!-- WARNING! The 'featured-links' section is read only. Do not edit below.
       Changes to the links section in the source will not be saved. -->
    <link-group type="supplemental">
      <link url="""+ "\"" + uploaded_filename + "\""+""" strength="3">Download the original slides in PPT format</link>"""
        if slideshow_id is not None:
            cnxml += """<link url="""+ "\"" + get_slideshow_download_url(slideshare_details) + "\"" +""" strength="2">SlideShare PPT Download Link</link>"""
        cnxml += """\
    </link-group>
  <!-- WARNING! The 'featured-links' section is read only. Do not edit above.
       Changes to the links section in the source will not be saved. -->
</featured-links>"""
        session['cnxml'] += cnxml

        if redirect_to_google_oauth:
            raise HTTPFound(location=request.route_url('google_oauth'))
        raise HTTPFound(location=request.route_url('enhance'))
    return {'form' : FormRenderer(form),'conversion_flag': False, 'oembed': False}
Exemple #2
0
def cnxml_view(request):
    check_login(request)
    form = Form(request, schema=CnxmlSchema)
    save_dir = os.path.join(request.registry.settings['transform_dir'], request.session['upload_dir'])
    cnxml_filename = os.path.join(save_dir, 'index.cnxml')
    transformerror = request.session.get('transformerror')

    # Check for successful form completion
    if 'cnxml' in request.POST and form.validate():
        cnxml = form.data['cnxml']

        # Keep sure we use the standard python ascii string and encode Unicode to xml character mappings
        if isinstance(cnxml, unicode):
            cnxml = cnxml.encode('ascii', 'xmlcharrefreplace')        

        # get the list of files from upload.zip if it exists
        files = []
        zip_filename = os.path.join(save_dir, 'upload.zip')
        if os.path.exists(zip_filename):
            zip_archive = zipfile.ZipFile(zip_filename, 'r')
            for filename in zip_archive.namelist():
                if filename == 'index.cnxml':
                    continue
                fp = zip_archive.open(filename, 'r')
                files.append((filename, fp.read()))
                fp.close()

        try:
            files = get_files_from_zipfile(os.path.join(save_dir, 'upload.zip'))
            save_cnxml(save_dir, cnxml, files)
            validate_cnxml(cnxml)
        except ConversionError as e:
            return render_conversionerror(request, e.msg)

        # Return to preview
        return HTTPFound(location=request.route_url('preview'), request=request)

    # Read CNXML
    try:
        with open(cnxml_filename, 'rt') as fp:
            cnxml = fp.read()
    except IOError:
        raise HTTPNotFound('index.cnxml not found')

    # Clean CNXML
    cnxml = clean_cnxml(cnxml)
    cnxml = cnxml.decode('utf-8')
    cnxml = unicode(cnxml)

    return {
        'codemirror': True,
        'form': FormRenderer(form),
        'cnxml': cnxml,
        'transformerror': transformerror,
    }
Exemple #3
0
def cnxlogin_view(request):
    check_login(request)

    config = load_config(request)
    login_url = config['login_url']

    templatePath = 'templates/cnxlogin.pt'
    response = {
        'username': request.session['login'].username,
        'password': request.session['login'].password,
        'login_url': login_url,
    }
    return render_to_response(templatePath, response, request=request)
Exemple #4
0
def cnxlogin_view(request):
    check_login(request)

    config = load_config(request)
    login_url = config['login_url']

    templatePath = 'templates/cnxlogin.pt'
    response = {
        'username': request.session['login'].username,
        'password': request.session['login'].password,
        'login_url': login_url,
    }
    return render_to_response(templatePath, response, request=request)
Exemple #5
0
def download_zip(request):
    check_login(request)

    res = Response(content_type='application/zip')
    res.headers.add('Content-Disposition', 'attachment;filename=saved-module.zip')

    save_dir = os.path.join(request.registry.settings['transform_dir'],
        request.session['upload_dir'])
    zipfile = open(os.path.join(save_dir, 'upload.zip'), 'rb')
    stat = os.fstat(zipfile.fileno())
    res.app_iter = iter(lambda: zipfile.read(4096), '')
    res.content_length = stat.st_size
    res.last_modified = datetime.datetime.utcfromtimestamp(
        stat.st_mtime).strftime('%a, %d %b %Y %H:%M:%S GMT')
    return res
Exemple #6
0
def preview_save(request):
    check_login(request)
    html = request.POST['html']
    if isinstance(html, unicode):
        html = html.encode('ascii', 'xmlcharrefreplace')        

    save_dir = os.path.join(request.registry.settings['transform_dir'],
        request.session['upload_dir'])
    # Save new html file from preview area
    save_and_backup_file(save_dir, 'index.html', html)

    conversionerror = ''

    # Get the title from aloha html. We have to do this using a separate
    # parse operation, because aloha_to_etree below does not give us a
    # tree on which path() works. A bug or this developer is just stumped.
    tree = etree.fromstring(html, etree.HTMLParser())
    try:
        edited_title = tree.xpath('/html/head/title/text()')[0]
        request.session['title'] = edited_title
    except IndexError:
        if not request.session.get('title', None):
            request.session['title'] = 'Untitled Document'

    #transform preview html to cnxml
    cnxml = None
    try:
        tree = aloha_to_etree(html)           #1 create structured HTML5 tree
        canonical_html = etree.tostring(tree, pretty_print=True)
        cnxml = etree_to_valid_cnxml(tree, pretty_print=True)
    except Exception as e:
        #return render_conversionerror(request, str(e))
        conversionerror = str(e)

    if cnxml is not None:
        save_and_backup_file(save_dir, 'index.cnxml', cnxml)
        save_and_backup_file(save_dir, 'index.structured.html', canonical_html)
        files = get_files_from_zipfile(os.path.join(save_dir, 'upload.zip'))
        save_zip(save_dir, cnxml, canonical_html, files)
        try:
            validate_cnxml(cnxml)
        except ConversionError as e:
            #return render_conversionerror(request, str(e))
            conversionerror = str(e)

    response = Response(json.dumps({'saved': True, 'error': conversionerror}))
    response.content_type = 'application/json'
    return response
Exemple #7
0
def preview_save(request):
    check_login(request)
    html = request.POST['html']
    if isinstance(html, unicode):
        html = html.encode('ascii', 'xmlcharrefreplace')

    save_dir = os.path.join(request.registry.settings['transform_dir'],
                            request.session['upload_dir'])
    # Save new html file from preview area
    save_and_backup_file(save_dir, 'index.html', html)

    conversionerror = ''

    # Get the title from aloha html. We have to do this using a separate
    # parse operation, because aloha_to_etree below does not give us a
    # tree on which path() works. A bug or this developer is just stumped.
    tree = etree.fromstring(html, etree.HTMLParser())
    try:
        edited_title = tree.xpath('/html/head/title/text()')[0]
        request.session['title'] = edited_title
    except IndexError:
        if not request.session.get('title', None):
            request.session['title'] = 'Untitled Document'

    #transform preview html to cnxml
    cnxml = None
    try:
        tree = aloha_to_etree(html)  #1 create structured HTML5 tree
        canonical_html = etree.tostring(tree, pretty_print=True)
        cnxml = etree_to_valid_cnxml(tree, pretty_print=True)
    except Exception as e:
        #return render_conversionerror(request, str(e))
        conversionerror = str(e)

    if cnxml is not None:
        save_and_backup_file(save_dir, 'index.cnxml', cnxml)
        save_and_backup_file(save_dir, 'index.structured.html', canonical_html)
        files = get_files_from_zipfile(os.path.join(save_dir, 'upload.zip'))
        save_zip(save_dir, cnxml, canonical_html, files)
        try:
            validate_cnxml(cnxml)
        except ConversionError as e:
            #return render_conversionerror(request, str(e))
            conversionerror = str(e)

    response = Response(json.dumps({'saved': True, 'error': conversionerror}))
    response.content_type = 'application/json'
    return response
Exemple #8
0
def download_zip(request):
    check_login(request)

    res = Response(content_type='application/zip')
    res.headers.add('Content-Disposition',
                    'attachment;filename=saved-module.zip')

    save_dir = os.path.join(request.registry.settings['transform_dir'],
                            request.session['upload_dir'])
    zipfile = open(os.path.join(save_dir, 'upload.zip'), 'rb')
    stat = os.fstat(zipfile.fileno())
    res.app_iter = iter(lambda: zipfile.read(4096), '')
    res.content_length = stat.st_size
    res.last_modified = datetime.datetime.utcfromtimestamp(
        stat.st_mtime).strftime('%a, %d %b %Y %H:%M:%S GMT')
    return res
Exemple #9
0
def do_login():
    username = request.forms.get('username')
    password = request.forms.get('password')
    if utils.check_login(username, password):
        return "<p>Your login information was correct.</p>"
    else:
        return "<p>Login failed.</p>"
Exemple #10
0
def admin_config_view(request):
    """
    Configure default UI parameter settings
    """

    check_login(request)
    subjects = [
        "Arts", "Business", "Humanities", "Mathematics and Statistics",
        "Science and Technology", "Social Sciences"
    ]
    form = Form(request, schema=ConfigSchema)
    config = load_config(request)

    # Check for successful form completion
    if 'form.submitted' in request.POST:
        form.validate()
        for key in ['service_document_url', 'workspace_url']:
            config[key] = form.data[key]
        for key in [
                'title', 'summary', 'subject', 'keywords', 'language',
                'google_code'
        ]:
            config['metadata'][key] = form.data[key]
        for key in [
                'authors', 'maintainers', 'copyright', 'editors', 'translators'
        ]:
            config['metadata'][key] = [
                x.strip() for x in form.data[key].split(',')
            ]
        save_config(config, request)

    response = {
        'form':
        FormRenderer(form),
        'subjects':
        subjects,
        'languages':
        languages,
        'roles': [('authors', 'Authors'), ('maintainers', 'Maintainers'),
                  ('copyright', 'Copyright holders'), ('editors', 'Editors'),
                  ('translators', 'Translators')],
        'request':
        request,
        'config':
        config,
    }
    return response
Exemple #11
0
def unfollow_user(request):
    '''Unfollows a user.

	Request Parameters -
		request - Django request object.

	Response Parameters - 
		200 - Unfollowed successfully.
		400 - Invalid request. (missing parameters or username)
		400 - Cannot unfollow self.
		400 - Invalid username or unfollow_user.
		403 - Authentication failure.
		409 - Already unfollowed.
	'''
    body = request.body.decode('utf8')
    body = json.loads(body)

    username = request.GET.get('username')
    unfollow_user = body.get('unfollow_user')

    if not (username and unfollow_user):
        return JsonResponse({'data': {'msg': 'Invalid request.'}}, status=400)

    if not check_login(username):
        return JsonResponse(
            {'data': {
                'msg': 'Authentication failure. Please login.'
            }},
            status=403)

    if username == unfollow_user:
        return JsonResponse({'data': {
            'msg': 'Cannot unfollow self.'
        }},
                            status=400)

    user = authenticate_username(username)
    unfol_user = authenticate_username(unfollow_user)

    if not (user and unfol_user):
        return JsonResponse(
            {'data': {
                'msg': 'Invalid username or unfollow_user.'
            }},
            status=400)

    followUnfollowHandler = FollowUnfollowHandler()
    response = followUnfollowHandler.unfollow(user, unfol_user)

    if response:
        return JsonResponse({'data': {'msg': 'Unfollowed user successfully.'}})

    else:
        return JsonResponse(
            {'data': {
                'msg': 'The requested user is already unfollowed.'
            }},
            status=409)
def preview_save(request):
    check_login(request)
    html = request.POST['html']
    if isinstance(html, unicode):
        html = html.encode('ascii', 'xmlcharrefreplace')        

    save_dir = os.path.join(request.registry.settings['transform_dir'],
        request.session['upload_dir'])
    # Save new html file from preview area
    save_and_backup_file(save_dir, 'index.html', html)

    conversionerror = ''

    #transform preview html to cnxml
    cnxml = None
    try:
        structured_html = aloha_to_html(html)           #1 create structured HTML5
        # parse the new title from structured HTML
        tree = etree.fromstring(structured_html, etree.HTMLParser())
        try:
            edited_title = tree.xpath('/html/head/title/text()')[0]
            request.session['title'] = edited_title
        except:
            request.session['title'] = 'Untitled Document'

        cnxml = html_to_valid_cnxml(structured_html)    #2 create cnxml from structured HTML5
    except Exception as e:
        #return render_conversionerror(request, str(e))
        conversionerror = str(e)

    if cnxml is not None:
        save_and_backup_file(save_dir, 'index.cnxml', cnxml)
        files = get_files_from_zipfile(os.path.join(save_dir, 'upload.zip'))
        save_zip(save_dir, cnxml, html, files)
        try:
            validate_cnxml(cnxml)
        except ConversionError as e:
            #return render_conversionerror(request, str(e))
            conversionerror = str(e)

    response = Response(json.dumps({'saved': True, 'error': conversionerror}))
    response.content_type = 'application/json'
    return response
Exemple #13
0
def do_login():

    postdata = request.body.read()
    dici = translate(postdata)

    res = check_login(dici['user'], dici['pass'])

    if res != False:
        token = hash_str(dici['user'])
        response.set_cookie("token", token)
        save_token(dici['user'], token)
        return "true"
    else:
        return "false"
Exemple #14
0
def admin_config_view(request):
    """
    Configure default UI parameter settings
    """

    check_login(request)
    subjects = ["Arts", "Business", "Humanities", "Mathematics and Statistics",
                "Science and Technology", "Social Sciences"]
    form = Form(request, schema=ConfigSchema)
    config = load_config(request)

    # Check for successful form completion
    if 'form.submitted' in request.POST:
        form.validate()
        for key in ['service_document_url', 'workspace_url']:
            config[key] = form.data[key]
        for key in ['title', 'summary', 'subject', 'keywords', 'language', 'google_code']:
            config['metadata'][key] = form.data[key]
        for key in ['authors', 'maintainers', 'copyright', 'editors', 'translators']:
            config['metadata'][key] = [x.strip() for x in form.data[key].split(',')]
        save_config(config, request)

    response =  {
        'form': FormRenderer(form),
        'subjects': subjects,
        'languages': languages,
        'roles': [('authors', 'Authors'),
                  ('maintainers', 'Maintainers'),
                  ('copyright', 'Copyright holders'),
                  ('editors', 'Editors'),
                  ('translators',
                  'Translators')
                 ],
        'request': request,
        'config': config,
    }
    return response
Exemple #15
0
def user_login(request):
    '''Login a user.

	Request Parameters -
		request - Django request object.

	Response Parameters - 
		200 - Login successful.
		400 - Invalid request. (missing parameters or username)
		401 - Invalid Credentials.
		409 - User is already logged in.
	'''
    body = request.body.decode('utf8')
    body = json.loads(body)

    username = request.GET.get('username')
    password = body.get('password')

    if not (username and password):
        return JsonResponse({'data': {
            'msg': 'Invalid request body.'
        }},
                            status=400)

    userAuthhandler = UserAuthhandler()
    auth = userAuthhandler.authenticate(username=username, password=password)

    if auth:
        if check_login(username):
            return JsonResponse(
                {'data': {
                    'msg': 'User is already logged in.'
                }}, status=409)

        else:
            if userAuthhandler.login_user(username):
                return JsonResponse({'data': {'msg': 'Login successful.'}})

            else:
                return JsonResponse({'data': {
                    'msg': 'Username not found.'
                }},
                                    status=404)

    else:
        return JsonResponse({'data': {
            'msg': 'Invalid credentials'
        }},
                            status=401)
def login():
    req_data = request.get_json()
    username = req_data.get('user')
    password = req_data.get('password')

    user = utils.check_login(username, password, request.remote_addr)

    if user:
        # add metric for failed login
        statsd.increment('login', tags=["outcome:success"])
        return jsonify({"outcome": "success"}), 200
    else:
        # add metric for successful login
        statsd.increment('login', tags=["outcome:failure"])
        return jsonify({"outcome": "failure"}), 401
    if not dry_run:
        print '  Closing on bugzilla.'
        res = requests.put(url, params=creds, json=kw)
        res.raise_for_status()


if __name__ == '__main__':
    product = sys.argv[1]
    component = sys.argv[2]
    days = int(sys.argv[3])
    dry_run = '--dry-run' in sys.argv

    print('Product: {}, component: {}, days since: {}'.format(
        product, component, days))
    if dry_run:
        print 'This is a dry run, won\'t actually close any bugs.'

    closed = 0
    assert days > 30, 'Probably best to test for more than 30 days.'
    check_login()
    bugs = fetch(product, component)
    for bug in bugs:
        should_close = last_occurred(bug, days)
        if should_close:
            closed += 1
            close(bug, days, dry_run)

    print 'Found: {} bugs'.format(len(bugs))
    print 'Closed: {} bugs'.format(closed)
    print 'Complete.'
Exemple #18
0
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)
Exemple #19
0
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)
Exemple #20
0
def run():
    if check_login():
        plugin.run()
def return_slideshare_upload_form(request):
    check_login(request)
    session = request.session
    redirect_to_google_oauth = False
    if session.has_key('original-file-location'):
        del session['original-file-location']
    form = Form(request, schema=ImporterChoiceSchema)
    response = {'form':FormRenderer(form)}
    validate_form = form.validate()
    if validate_form:
        original_filename = session['original_filename']
        upload_to_google = form.data['upload_to_google']
        upload_to_ss = form.data['upload_to_ss']
        username = session['username']
        if (upload_to_ss=="true"):

            slideshow_id = upload_to_slideshare("saketkc",original_filename)
            session['slideshare_id'] = slideshow_id
        if (upload_to_google == "true"):
            if is_returning_google_user(username):
                print "RETURNING USER"
                redirect_to_google_oauth = False
                oauth_token_and_secret = get_oauth_token_and_secret(username)
                oauth_token = oauth_token_and_secret["oauth_token"]
                oauth_secret = oauth_token_and_secret["oauth_secret"]
                guploader = GooglePresentationUploader()
                guploader.authentincate_client_with_oauth2(oauth_token,oauth_secret)
                guploader.upload(original_filename)
                guploader.get_first_revision_feed()
                guploader.publish_presentation_on_web()
                resource_id = guploader.get_resource_id().split(':')[1]
                session['google-resource-id'] = resource_id
                print "UPLOADING TO GOOGLE"
            else:
                print "NEW USER"
                redirect_to_google_oauth = True
                session['original-file-path'] = original_filename
        else:
            print "NO GOOGLE FOUND"
        username = session['username']
        uploaded_filename = session['uploaded_filename']
        slideshare_details = get_details(slideshow_id)
        slideshare_download_url = get_slideshow_download_url(slideshare_details)
        session['transcript'] = get_transcript(slideshare_details)
        cnxml = """<featured-links>
  <!-- WARNING! The 'featured-links' section is read only. Do not edit below.
       Changes to the links section in the source will not be saved. -->
    <link-group type="supplemental">
      <link url="""+ "\"" + uploaded_filename + "\""+""" strength="3">Download the original slides in PPT format</link>
      <link url="""+ "\"" +slideshare_download_url + "\"" +""" strength="2">SlideShare PPT Download Link</link>
    </link-group>
  <!-- WARNING! The 'featured-links' section is read only. Do not edit above.
       Changes to the links section in the source will not be saved. -->
</featured-links>"""
        session['cnxml'] += cnxml



        #print deposit_receipt.metadata #.get("dcterms_title")
        if redirect_to_google_oauth:
            raise HTTPFound(location=request.route_url('google_oauth'))
        raise HTTPFound(location=request.route_url('enhance'))
    return {'form' : FormRenderer(form),'conversion_flag': False, 'oembed': False}
def tweet(request):

	if request.method == 'POST':
		'''Creates a tweet.

		Request Parameters -
			request - Django request object.

		Response Parameters - 
			201 - Tweet created successfully.
			400 - Invalid request. (missing parameters or username)
			403 - Authentication failure.
		'''
		body = request.body.decode('utf8')
		body = json.loads(body)

		username = request.GET.get('username')
		tweet_text = body.get('tweet_text')

		if not (username and tweet_text):
			return JsonResponse({
				'data': {
					'msg': 'Invalid request'
					}
				}, status=400)

		if not check_login(username):
			return JsonResponse({
				'data': {
					'msg': 'Authentication failure. Please login.'
					}
				}, status=403)

		tweetHandler = TweetHandler()
		tweetHandler.create_tweet(username, tweet_text)

		return JsonResponse({
			'data': {
				'msg': 'Tweet created successfully.'
				}
			}, status=201)

	elif request.method == 'GET':
		'''Reads tweets.

		Request Parameters -
			request - Django request object.

		Response Parameters - 
			200 - List of tweets of given username.
			400 - Invalid request. (missing parameters or username)
			403 - Authentication failure.
		'''
		body = request.body.decode('utf8')
		body = json.loads(body)

		username = request.GET.get('username')

		if not username:
			return JsonResponse({
				'data': {
					'msg': 'Invalid request'
					}
				}, status=400)

		if not check_login(username):
			return JsonResponse({
				'data': {
					'msg': 'Authentication failure. Please login.'
					}
				}, status=403)

		tweetHandler = TweetHandler()
		data, code = tweetHandler.get_tweets(username)

		return JsonResponse({
			'data': data
			}, status=code)
	elif request.method == 'DELETE':
		'''Deletes a tweet.

		Request Parameters -
			request - Django request object.

		Response Parameters - 
			200 - Tweet deleted successfully.
			400 - Invalid request. (missing parameters or username)
			403 - Authentication failure.
			404 - tweet with given id not found.
		'''
		body = request.body.decode('utf8')
		body = json.loads(body)

		username = request.GET.get('username')
		tweet_id = body.get('id')

		if not (username or tweet_id):
			return JsonResponse({
				'data': {
					'msg': 'Invalid request'
					}
				}, status=400)

		if not check_login(username):
			return JsonResponse({
				'data': {
					'msg': 'Authentication failure. Please login.'
					}
				}, status=403)

		tweetHandler = TweetHandler()
		if tweetHandler.delete_tweet(username, tweet_id):
			return JsonResponse({
				'data': {
					'msg': 'Tweet is successfully deleted.'
					}
				}, status=200)
		else:
			return JsonResponse({
				'data': {
					'msg': 'Tweet not found or cannot be deleted.'
					}
				}, status=404)
Exemple #23
0
	def do_POST(self):
		""" Handles the HTTP POST request.

		The POST endpoints are:
		* /login
		When a post is made to login the server check if the hashes of the login data matchs the hashes of the user and password stored in the server.
		If the data match the server create a session with a cookie which still alive for 1200 seconds. Else the server will redirect to a error page.
		* /configuration
		First the server will check if the data type is correct, then it will check if the values are in the permited ranges and after that it will change the configuration.
		This endpoint change the number of samples shown in the home page, the frequency of the temperature sensor and the size of the dara files stored in the device.
		* /scp
		After check the session and the data type the server will set the scp target address and start the scp daemon. If the checkbox is mark, the server will store the configuration of the scp.
		* /pmnormal handles post to set power saving mode normal
		First the server will check if the session is ok, then it will set up the normal power saving mode.
		* /pm1 handles post to set power saving mode 1
		First the server will check if the session is ok, then it will set up the first power saving mode.
		* /pm2_multiple handles post to set power saving mode 2 in the advanced formulary.
		After check the session and the data the server will set up the second power mode and will write the crontab which fits the schedule created by the user.
		* /pm2_one handles post to set power saving mode 2 with one interval for all days.
		After check the session and the data the server will set up the second power mode and will write the crontab which fits the schedule created by the user.
		* /pm2_eachday handles post to set power saving mode 2 with one different every day.
		After check the session and the data the server will set up the second power mode and will write the crontab which fits the schedule created by the user.
		* /pm3_multiple handles post to set power saving mode 3 in the advanced formulary.
		After check the session and the data the server will set up the third power mode and will write the crontab which fits the schedule created by the user.
		* /pm3_one post to set power saving mode 3 with one interval for all days.
		After check the session and the data the server will set up the third power mode and will write the crontab which fits the schedule created by the user.
		* /pm3_eachday handles post to set power saving mode 3 with one different every day.
		After check the session and the data the server will set up the third power mode and will write the crontab which fits the schedule created by the user.


		"""
		global configuration_path

		if(self.path == '/login'):
			print "[Login Post]"
			form = cgi.FieldStorage(
				fp=self.rfile,
				headers=self.headers,
				environ={'REQUEST_METHOD':'POST',
						'CONTENT_TYPE':self.headers['Content-Type'],
						})
			
			login = form["login"].value.strip()
			password = form["password"].value.strip()

			if(utils.check_login(login, password)):
				#Cookie creation
				c = Cookie.SimpleCookie()
				hash_object = hashlib.md5(str(datetime.now()).encode())
				c['cookietemp'] = str(hash_object.hexdigest())
				c['cookietemp']['domain'] = utils.getConfiguration("domain")
				c['cookietemp']['expires'] = 1200
				c['cookietemp']['path'] = "/"
				c['cookietemp']['httponly'] = "true"
				cookie_storage.store_cookie(c)

				self.send_response(200)
				self.send_header('Content-type','text/html')
				self.send_header('Set-Cookie', c.output(attrs=['path', 'expires'], header="Cookie:"))
				
				self.end_headers()
				f = open(curdir + sep + "web/html/configuration.html")
				self.wfile.write(f.read())
				f.close()
			else:
				self.answerPost(curdir + sep + "web/html/login-fail.html", 200)

		if(self.path == '/configuration'):
			global samples_show
			isDataCorrect = True

			print "[Configuration Post]"
			form = cgi.FieldStorage(
				fp=self.rfile,
				headers=self.headers,
				environ={'REQUEST_METHOD':'POST',
						'CONTENT_TYPE':self.headers['Content-Type'],
						})

			#Session check
			if (cookie_storage.check_session(self.headers)):
				#Data validation
				if not re.match("^[0-9]+$", form["samples"].value):
					self.answerPost(curdir + sep + "web/html/configuration-fail.html", 200)
				elif not re.match("^[0-9]+$", form["frequency"].value):
					self.answerPost(curdir + sep + "web/html/configuration-fail.html", 200)
				elif not re.match("^[0-9]+$", form["websamples"].value):
					self.answerPost(curdir + sep + "web/html/configuration-fail.html", 200)
				elif not re.match("^([0-9]+|-[0-9]+)$", form["error"].value):
					self.answerPost(curdir + sep + "web/html/configuration-fail.html", 200)
				else:
					if( utils.isInt( form["websamples"].value ) and int( form["websamples"].value ) > 0 ):
						samples_show = int(form["websamples"].value)
						utils.setConfiguration("samples_show" , samples_show)
					else:
						isDataCorrect = False

					if( utils.isInt( form["error"].value )):
						utils.setConfiguration("sensor_error" , int(form["error"].value))
					else:
						isDataCorrect = False

					if( utils.isInt( form["samples"].value ) and int( form["samples"].value ) > 0 ):
						utils.setConfiguration("file_size" , int(form["samples"].value))
					else:
						isDataCorrect = False

					if( utils.isInt( form["frequency"].value ) and int( form["frequency"].value ) > 0 ):
						frequency = int(form["frequency"].value)
						utils.setConfiguration("frequency_temp" , frequency)
					else:
						isDataCorrect = False

					if( isDataCorrect ):
						self.answerPost(curdir + sep + "web/html/configuration-changed.html", 200)
					else:
						self.answerPost(curdir + sep + "web/html/configuration-fail.html", 200)
			else:
				self.answerPost(curdir + sep + "web/html/session-fail.html", 200)


		if(self.path == '/scp'):
			#Session check
			if (cookie_storage.check_session(self.headers)):
				global store_data
				isDataCorrect = False

				print "[SCP Post]"
				form = cgi.FieldStorage(
					fp=self.rfile,
					headers=self.headers,
					environ={'REQUEST_METHOD':'POST',
							'CONTENT_TYPE':self.headers['Content-Type'],
							})

				if 'check' in form:
					store_data = True
				else:
					store_data = False

				#Data validation
				if utils.isInt(form["scpfrequency"].value) and utils.isInt(form["port"].value) and form["scp"].value and form["user"].value and form["directory"].value and form["password"].value:
					isDataCorrect = True

				utils.setConfiguration("frequency_scp", form["scpfrequency"].value)

				#Store data if user wants.
				if store_data:
					with file("./config/scp",'w+') as scpfile:
						scpfile.write(form["user"].value+"\n")
						scpfile.write(form["scp"].value+"\n")
						scpfile.write(form["directory"].value+"\n")
						scpfile.write(form["port"].value+"\n")
						scpfile.write(form["password"].value+"\n")
					scpfile.close()
				else:
					system("sudo rm ./config/scp")

				#Create scp task.
				#TODO encriptar datos que se pasan al script (?)
				p = subprocess.Popen(["python", "scpdaemon.py", "start", form["scp"].value, form["user"].value, form["port"].value, form["directory"].value], stdin=PIPE, stdout=PIPE)
				print p.communicate(form["password"].value)
				#TODO check that is correct, subprocess.check~

				#Redirect to configuration.
				if( isDataCorrect ):
					self.answerPost(curdir + sep + "web/html/configuration-changed.html", 200)
				else:
					self.answerPost(curdir + sep + "web/html/configuration-fail.html", 200)
			else:
				self.answerPost(curdir + sep + "web/html/session-fail.html", 200)

		if(self.path == '/pmnormal'):
			#Session check
			if (cookie_storage.check_session(self.headers)):
				#TODO eliminar datos de otros modos, overclock etc.
				print "[Power mode normal Post]"
				self.setPowerSavingModeNormal()
				utils.setConfiguration("powermode", "0")
				self.answerPost(curdir + sep + "web/html/configuration-changed.html", 200)
			else:
				self.answerPost(curdir + sep + "web/html/session-fail.html", 200)
			
		if(self.path == '/pm1'):
			#Session check
			if (cookie_storage.check_session(self.headers)):
				#TODO pmnormal.sh -> wifi activado, con underclock, eliminar datos que generen los otros modos etc
				print "[Power mode 1 Post]"
				self.setPowerSavingMode1()
				utils.setConfiguration("powermode", "1")
				self.answerPost(curdir + sep + "web/html/configuration-changed.html", 200)
			else:
				self.answerPost(curdir + sep + "web/html/session-fail.html", 200)

		if(self.path == '/pm2_multiple'):
			if (cookie_storage.check_session(self.headers)):
				configuration_path = './web/html/configuration_mode2.html'
				#TODO elimnar datos de los otros modos
				print "[Power mode 2 Post: Multiple intervals]"

				#Post form recover
				form = cgi.FieldStorage(
					fp=self.rfile,
					headers=self.headers,
					environ={'REQUEST_METHOD':'POST',
							'CONTENT_TYPE':self.headers['Content-Type'],
							})
				if(utils.validateInterval_multiple(form)):
					utils.create_crontab(form, True)
					utils.setConfiguration("powermode", "2")
					self.answerPost(curdir + sep + "web/html/configuration-changed.html", 200)
				else:
					self.answerPost(curdir + sep + "web/html/configuration-fail.html", 200)
			else:
				self.answerPost(curdir + sep + "web/html/session-fail.html", 200)

		if(self.path == '/pm2_one'):
			if(cookie_storage.check_session(self.headers)):
				configuration_path = './web/html/configuration_mode2.html'
				print "[Power mode 2 Post: One interval]"

				#Post form recover
				form = cgi.FieldStorage(
					fp=self.rfile,
					headers=self.headers,
					environ={'REQUEST_METHOD':'POST',
							'CONTENT_TYPE':self.headers['Content-Type'],
							})

				#validation
				if(utils.validateInterval(form["start"].value, form["end"].value)):
					monday = tuesday = wednesday = thursday = friday = saturday = sunday = (int(form["start"].value),int(form["end"].value))
					utils.write_crontab([monday, tuesday, wednesday, thursday, friday, saturday, sunday], False)
					utils.setConfiguration("powermode", "2")
					self.answerPost(curdir + sep + "web/html/configuration-changed.html",200)
				else:
					self.answerPost(curdir + sep + "web/html/configuration-fail.html", 200)
			else:
				self.answerPost(curdir + sep + "web/html/session-fail.html", 200)

		if(self.path == '/pm2_eachday'):
			if (cookie_storage.check_session(self.headers)):
				configuration_path = './web/html/configuration_mode2.html'
				print "[Power mode 2 Post: Multiple intervals]"

				#Post form recover
				form = cgi.FieldStorage(
					fp=self.rfile,
					headers=self.headers,
					environ={'REQUEST_METHOD':'POST',
							'CONTENT_TYPE':self.headers['Content-Type'],
							})

				if(utils.validateInterval_eachDay(form)):
					utils.create_crontab(form, False)
					utils.setConfiguration("powermode", "2")
					self.answerPost(curdir + sep + "web/html/configuration-changed.html", 200)
				else:
					self.answerPost(curdir + sep + "web/html/configuration-fail.html", 200)
			else:
				self.answerPost(curdir + sep + "web/html/session-fail.html", 200)

		if(self.path == '/pm3'):
			configuration_path = './web/html/configuration_mode3.html'
			print "[Power mode 3 Post]"
			utils.setConfiguration("powermode", "3")
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 session['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['username'])
        config['metadata'][role] = ', '.join(config['metadata'][role]).replace('_USER_', session['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['username'],
                                    user_pass=session['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)
Exemple #25
0
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)
Exemple #26
0
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)