Exemple #1
0
def list_saved_files(request):
    # Handle file upload
    if request.method == 'POST':

        # https://docs.djangoproject.com/en/dev/ref/request-response
        #
        # request.POST: A dictionary-like object containing all given
        # HTTP POST parameters, providing that the request contains form data.
        # Note: POST does *not* include file-upload information.
        #
        # request.FILES: A dictionary-like object containing all uploaded files.
        # Each key in FILES is the name from the <input type="file" name="" />.
        # Each value in FILES is an UploadedFile.
        # Note: This only has data if the <form> that POSTed had enctype="multipart/form-data"
        form = RecordingForm(request.POST, request.FILES)
        if form.is_valid():
            newrec = Recording(audiofile=request.FILES['audiofile'])
            newrec.save()

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('Conversation.v1.views.list'))
    else:
        form = RecordingForm()  # An empty, unbound form

    # Load documents for the list page
    recordings = Recording.objects.all()

    # Render list page with the documents and the form
    return render_to_response('v1/list.html', {
        'recordings': recordings,
        'form': form
    },
                              context_instance=RequestContext(request))
def list_saved_files(request):
    # Handle file upload
    if request.method == 'POST':

        # https://docs.djangoproject.com/en/dev/ref/request-response
        #
        # request.POST: A dictionary-like object containing all given
        # HTTP POST parameters, providing that the request contains form data.
        # Note: POST does *not* include file-upload information.
        #
        # request.FILES: A dictionary-like object containing all uploaded files.
        # Each key in FILES is the name from the <input type="file" name="" />.
        # Each value in FILES is an UploadedFile.
        # Note: This only has data if the <form> that POSTed had enctype="multipart/form-data"
        form = RecordingForm(request.POST, request.FILES)
        if form.is_valid():
            newrec = Recording(audiofile=request.FILES['audiofile'])
            newrec.save()

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('Conversation.v1.views.list'))
    else:
        form = RecordingForm()  # An empty, unbound form

    # Load documents for the list page
    recordings = Recording.objects.all()

    # Render list page with the documents and the form
    return render_to_response(
        'v1/list.html',
        {'recordings': recordings, 'form': form},
        context_instance=RequestContext(request)
    )
Exemple #3
0
def recorder_screen(request):
    if request.method == 'POST':
        newrec = Recording(audiofile=request.FILES['recording'])
        newrec.save()
        return HttpResponseRedirect(
            reverse('Conversation.v1.views.recorder_screen'))
    else:
        form = RecordingForm()

    return render_to_response('v1/Audio Recorder.html', {'form': form},
                              context_instance=RequestContext(request))
def recorder_screen(request):
    if request.method == 'POST':
        newrec = Recording(audiofile=request.FILES['recording'])
        newrec.save()
        return HttpResponseRedirect(reverse('Conversation.v1.views.recorder_screen'))
    else:
        form = RecordingForm()

    return render_to_response(
        'v1/Audio Recorder.html',
        {'form' : form},
        context_instance=RequestContext(request)
    )
Exemple #5
0
def add_recording():
    ret = {}
    prefix = request.base_url[:-len('/api/add_recording')]
    try:
        id = request.form['id']
        user_id = request.form['user_id']
        study_id = request.form['study_id']

        # recording uploads
        filename = ''
        recording_file = request.files['recording_file']

        if recording_file.filename == '':
            flash('Nop Selectd file')
            return redirect(request.url)
        if recording_file and allowed_file(recording_file.filename):
            filename = secure_filename(recording_file.filename)
            recording_file.save(
                os.path.join(app.config['UPLOAD_FOLDER'], filename))
            recording = '%s/%s' % (file_path, filename)

        save_recording_file_url = '%s/uploads/%s' % (prefix, filename)

        # save in database
        recording = Recording(id, user_id, study_id, save_recording_file_url)
        db.session.add(recording)
        db.session.commit()
        ret['success'] = True
        ret['msg'] = 'recording added successfully'
    except Exception as exp:
        print 'add_recording() :: Got excepion: %s' % exp
        print(traceback.format_exc())
        ret['msg'] = '%s' % exp
        ret['success'] = False
    return jsonify(ret)
Exemple #6
0
def save_recording_session(form, files):
    duration = float(form['duration'])
    user_id = int(form['user_id'])
    manager_id = int(form['manager_id'])
    collection_id = int(form['collection_id'])
    collection = Collection.query.get(collection_id)
    has_video = collection.configuration.has_video
    recording_objs = json.loads(form['recordings'])
    skipped = json.loads(form['skipped'])
    record_session = None
    if len(recording_objs) > 0 or len(skipped):
        record_session = Session(user_id,
                                 collection_id,
                                 manager_id,
                                 duration=duration,
                                 has_video=has_video)
        db.session.add(record_session)
        db.session.flush()
    for token_id, recording_obj in recording_objs.items():
        # this token has a recording
        file_obj = files.get('file_{}'.format(token_id))
        recording = Recording(int(token_id),
                              file_obj.filename,
                              user_id,
                              session_id=record_session.id,
                              has_video=has_video)
        if "analysis" in recording_obj:
            recording.analysis = recording_obj['analysis']
        if "cut" in recording_obj:
            recording.start = recording_obj['cut']['start']
            recording.end = recording_obj['cut']['end']
        if "transcription" in recording_obj and recording_obj['transcription']:
            recording.transcription = recording_obj['transcription']
        db.session.add(recording)
        db.session.flush()
        recording.add_file_obj(file_obj, recording_obj['settings'])
    db.session.commit()

    for token_id in recording_objs:
        token = Token.query.get(token_id)
        token.update_numbers()
    db.session.commit()

    for token_id in skipped:
        # this token was skipped and has no token
        token = Token.query.get(int(token_id))
        token.marked_as_bad = True
        token.marked_as_bad_session_id = record_session.id
    db.session.commit()

    # then update the numbers of the collection
    collection.update_numbers()
    db.session.commit()
    return record_session.id if record_session else None
Exemple #7
0
def update_recording(quip_id):
    parser = reqparse.RequestParser()
    parser.add_argument('duration', type=int, location='json')
    parser.add_argument('position', type=int, location='json')
    parser.add_argument('progress', type=int, location='json')
    parser.add_argument('isPublic', type=bool, location='json')
    update = parser.parse_args()

    Recording.objects(Q(id=quip_id)).modify(
        upsert=True,
        set__isPublic=update['isPublic']
    )

    Listen.objects(Q(user=g.user['id']) & Q(recording=quip_id)).modify(
        upsert=True,
        set__progress=update['progress'],
        set__position=update['position'],
        set__duration=update['duration'],
    )

    return QuipMapper.to_web_dto(Recording.objects.get_or_404(Q(id=quip_id))), 200
Exemple #8
0
def save_new_recording():
    parser = reqparse.RequestParser()
    parser.add_argument('audio-blob', type=FileStorage, location='files')
    parser.add_argument('description')
    form = parser.parse_args()

    file = form['audio-blob']
    current_app.logger.debug("file: '%s' type: '%s'" % (file.filename, file.content_type))

    if file and file.content_type == 'audio/ogg':
        user = User.objects.get(id=g.user['id'])

        recording = Recording()
        recording.description = form['description']
        recording.isPublic = True
        recording.user = user
        recording.save()

        recording_id = str(recording.id)
        recording_path = os.path.join(current_app.config['RECORDINGS_PATH'], recording_id + '.ogg')
        current_app.logger.debug('saving recording to: ' + recording_path)
        file.save(recording_path)

        tiny_id = tinyurl.encode(str(recording_id))

        url = url_for('spa_web.single_recording', recording_id=tiny_id)
        return {'status': 'success', 'url': url}

    # else file upload failed, show an error page
    return {'status': 'failed'}
Exemple #9
0
def get_user_recording_stats():
    num_recordings = Recording.objects(Q(user=g.user['id'])).count()
    return {
        'num_recordings': num_recordings,
        'user': g.user
    }
Exemple #10
0
def get_list_of_user_recordings(user_id):
    dbref_user_id = User.objects.get(username=user_id)

    entities = Recording.objects(Q(isPublic=True) & Q(user=dbref_user_id))[:50].order_by('-postedAt')
    return map(QuipMapper.to_web_dto, entities)
Exemple #11
0
def get_list_all_recordings():
    entities = Recording.objects(Q(isPublic=True))[:50].order_by('-postedAt')
    return map(QuipMapper.to_web_dto, entities)
Exemple #12
0
def finishRequest(request, schedule):

    post = request.POST

    # Refresh Database Changes
    flush_transaction()
    phone = post.get('To')
    rURL = post.get('RecordingUrl')
    rDuration = post.get('RecordingDuration')

    logger.info("REQUEST - FINISH - " + schedule + " - " + post['CallStatus'] +
                " - " + phone)

    call = get_call_or_none(schedule, phone)

    if not call:
        logger.error("[Error in Finish Request - " + schedule + " - " + phone +
                     "] Call does not exist!")

    else:
        # TODO: Test this
        # For info on how Recording privacy is handled check out https://docs.google.com/document/d/1LkKosw9-EMtIkx9Y5f0AxTAA418KHbJ2eTWbPOGrgoc/edit
        #            try:
        # If other caller doesn't exist, throw Exeption and don't store Recording object
        callOther = call.conference.call_set.exclude(pk=call.pk)[0]

        # Check for recording
        if not rURL or not rDuration:
            # TODO Handle this error, as this it twilio error [Log]
            logger.error("[Error in Finish Request - " + schedule + " - " +
                         phone + "] No recording in Twilio POST!")
        else:
            logger.debug(
                "[Finish Request] Perfect, got recording! Duration: " +
                rDuration + ".")

        # Create the recording if it doesn't exists, otherwise, update the recording values
        # If there are no recordings created for the other user we proceed to create a new recording with this values just in case that
        # the other user experiences an error when getting and storing the recordings from the post request

        recording = call.recording or callOther.recording or Recording()

        recording.recordingurl = rURL if rURL else ""
        recording.recordingduration = rDuration if rDuration else 0
        recording.datecreated = as_date(schedule)
        recording.call = call
        recording.save()

        call.recording = recording
        callOther.recording = recording

        call.save()
        callOther.save()

    # Setting retries to zero to limit the number of rating retries
    call.retries = 0
    call.save()

    rating = "Please rate your Wake Up Buddy Now! If you'd like to connect with " + callOther.user.username + " press one. To give " + callOther.user.profile.g(
        "him", "her"
    ) + " a thumbs up, press two. Otherwise, to give " + callOther.user.profile.g(
        "him", "her"
    ) + " thumbs down press Three. To report " + callOther.user.profile.g(
        "him", "her") + " press ZERO.! . ! . !"
    rating += "We're sorry, we didn't quite get that. To connect press One. For thumbs up press Two. For thumbs down press three. To report, please press ZERO."
    goodbye = "We hope you had a great time! See you soon!"
    data = render_to_response(
        "twilioresponse.xml", {
            'hangup': True,
            'goodbye': goodbye,
            'rating': rating,
            'ratingurl': schedule
        })

    return HttpResponse(data, mimetype="application/xml")