Ejemplo n.º 1
0
 internal static async Task<SvcStatus> CreateJob(ParticipantResult participantResult, ParticipantActivity activity)
 {
     CFJobRequest job = new CFJobRequest()
         {
             Title = (participantResult.User.App == Crowd.Model.Data.User.AppType.Speeching) ? "Speeching " : "Fluent" + participantResult.Id,
             Instructions = "Please listen to the audio clip(s) and complete the following tasks, making sure that your computer's volume is loud enough to hear the voice samples clearly",
             PaymentCents = 5,
             UnitsPerAssignment = 2,
             Css = "div.grp { border: solid thin gray; margin: 10px 0; }",
             WebhookUri = ConfidentialData.ApiUrl + "/api/CFWebhook/",
             SupportEmail = ConfidentialData.SupportEmail,
             ResourceUrl = participantResult.ResourceUrl
         };
     return await job.CreateAudioJob(participantResult, activity);
 }
        public async Task<HttpResponseMessage> Post(ParticipantResult result)
        {
            using (CrowdContext db = new CrowdContext())
            {
                User user = await AuthenticateUser(GetAuthentication(), db);
                if (user == null)
                {
                    return new HttpResponseMessage(HttpStatusCode.Unauthorized);
                }

                if (!ModelState.IsValid) return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
                if (result == null)
                    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Activity result cannot be null");

                result.User = user;
                result.UploadedAt = DateTime.Now;
                result = db.ParticipantResults.Add(result);
                user.Submissions.Add(result);
                if (result.IsAssessment)
                {
                    user.LastAssessment = result;
                }

                try
                {
                    db.SaveChanges();
                }
                catch (Exception ex)
                {
                    return Request.CreateResponse(HttpStatusCode.ExpectationFailed, ex.Message);
                }
                SvcStatus status = await CrowdFlowerApi.CreateJob(result,
                    await db.ParticipantActivities.FindAsync(result.ParticipantActivityId));

                if (status.Level == 0)
                {
                    string json = await status.Response.Content.ReadAsStringAsync();
                    CFJobResponse jobRes = JsonConvert.DeserializeObject<CFJobResponse>(json);

                    result.CrowdJobId = jobRes.id;

                    if (status.CreatedRows != null)
                    {
                        foreach (CrowdRowResponse row in status.CreatedRows)
                        {
                            db.CrowdRowResponses.Add(row);
                        }
                    }

                    try
                    {
                        db.SaveChanges();
                    }
                    catch (Exception e)
                    {
                        throw new HttpResponseException(Request.CreateResponse(
                            HttpStatusCode.ExpectationFailed, e.Message));
                    }

                    status = CrowdFlowerApi.LaunchJob(jobRes.id, status.Count);
                    return status.Response;
                }
                db.DebugMessages.Add(new DebugMessage
                {
                    Message = status.Description,
                    Filename = "ActivityResultController",
                    FunctionName = "Post"
                });
                await db.SaveChangesAsync();
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, status.Description + " \n\n " + status.Response.ToString());
            }
        }
        // PUT api/ActivityResult/5
        public async Task<HttpResponseMessage> Put(int id, ParticipantResult result)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            if (id != result.Id)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            using (CrowdContext db = new CrowdContext())
            {
                User user = await AuthenticateUser(GetAuthentication(), db);
                if (user == null || !user.IsAdmin)
                {
                    return new HttpResponseMessage(HttpStatusCode.Unauthorized);
                }

                db.ParticipantResults.Attach(result);
                db.Entry(result).State = EntityState.Modified;
                try
                {
                    db.SaveChanges();
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
                }
                return Request.CreateResponse(HttpStatusCode.OK);
            }
        }
Ejemplo n.º 4
0
        internal async Task<SvcStatus> CreateAudioJob(ParticipantResult result, ParticipantActivity activity)
        {
            SvcStatus status = new SvcStatus();
            try
            {
                string userKey = result.User.Email;

                using (HttpClient client = new HttpClient())
                {
                    FormUrlEncodedContent reqContent = CreateRequestCUrlData(result.User.App);
                    Uri baseAddress = new Uri(CrowdflowerBaseUri + "jobs.json?key=" + CrowdflowerKey);
                    HttpResponseMessage response = client.PostAsync(baseAddress, reqContent).Result;

                    if (response.IsSuccessStatusCode)
                    {
                        CFJobResponse jobRes = await response.Content.ReadAsAsync<CFJobResponse>();
                        List<string> audioFiles = await SvcUtil.DownloadAndExtractZip(ResourceUrl, jobRes.id.ToString(), userKey, activity.Id.ToString());

                        if (!audioFiles.Any()) return status;

                        CFUnitRequest unitsReq = new CFUnitRequest();
                        int count = 0;
                        string uploadUnitsJson = AudioUnit.CreateCFData(audioFiles, activity, result, out count);

                        Rows = await unitsReq.SendCfUnits(jobRes.id, uploadUnitsJson);

                        foreach (CrowdRowResponse unit in Rows)
                        {
                            unit.ParticipantResultId = result.Id;
                        }

                        status = new SvcStatus()
                        {
                            Level = 0,
                            Count = count,
                            Description = "Job created",
                            Response = response,
                            CreatedRows = Rows
                        };
                    }
                    else
                    {
                        status = new SvcStatus() { Level = 2, Description = "Failed to create the job", Response = response };
                    }
                }
            }
            catch (Exception e)
            {
                status = new SvcStatus() { Level = 2, Description = e.Message, Response = new HttpResponseMessage(HttpStatusCode.InternalServerError) };
            }
            
            return status;
        }
Ejemplo n.º 5
0
        public static string CreateCFData(IEnumerable<string> audioPaths, ParticipantActivity activity, ParticipantResult result, out int count)
        {
            count = 0;
            string json = "";
            if (!audioPaths.Any())
                return json;

            using (CrowdContext db = new CrowdContext())
            {
                result = db.ParticipantResults.Find(result.Id);
                CrowdRowResponse[] lastAssessResponses = null;
                CrowdRowResponse[] lastNormResponses = null;
                int lastAssessTaskId = -1;
                int lastNormTaskId = -1;
                string extraData = "";
                if (result.User.App == User.AppType.Speeching)
                {
                    foreach (var path in audioPaths)
                    {
                        string[] options = null;
                        string taskType = "Other";
                        CrowdRowResponse comparionResponse = null;

                        ParticipantResultData thisData = (from data in result.Data
                                                          where data.FilePath == Path.GetFileName(path)
                                                          select data).FirstOrDefault();

                        if (thisData == null)
                        {
                            continue;
                        }

                        int assTaskId = -1;
                        int normTaskId = -1;

                        if (thisData.ParticipantAssessmentTask != null) // Is assessment
                        {
                            ParticipantAssessmentTask task = thisData.ParticipantAssessmentTask;
                            assTaskId = task.Id;

                            List<string> quickFireOptions = new List<string>();
                            foreach (var prompt in task.PromptCol.Prompts)
                            {
                                quickFireOptions.Add(prompt.Value);
                            }
                            options = quickFireOptions.ToArray();

                            switch (task.TaskType)
                            {
                                case ParticipantAssessmentTask.AssessmentTaskType.QuickFire:
                                    taskType = "MP";
                                    break;
                                case ParticipantAssessmentTask.AssessmentTaskType.ImageDesc:
                                    taskType = "Image";
                                    break;
                            }

                            string filename = Path.GetFileNameWithoutExtension(path);
                            string promptId = "";
                            bool started = false;

                            // Get the prompt index from the filename
                            foreach (char c in filename)
                            {
                                if (c == '-')
                                {
                                    started = true;
                                    continue;
                                }
                                if (started && char.IsDigit(c))
                                {
                                    promptId += c;
                                }
                            }

                            if (!string.IsNullOrWhiteSpace(promptId))
                            {
                                extraData = promptId;
                            }

                            if (lastAssessTaskId != task.Id)
                            {
                                lastAssessResponses = (from rowResp in db.CrowdRowResponses
                                                       where rowResp.ParticipantAssessmentTaskId == task.Id &&
                                                             rowResp.ParticipantResult.User.Key == result.User.Key
                                                       orderby rowResp.CreatedAt
                                                       select rowResp).ToArray();
                                lastAssessTaskId = assTaskId;
                            }

                            if (lastAssessResponses != null)
                            {
                                foreach (CrowdRowResponse resp in lastAssessResponses)
                                {
                                    // Can't use GetFileName in LINQ expressions so have to do in memory
                                    bool matches = Path.GetFileName(resp.RecordingUrl) == Path.GetFileName(path);
                                    if (!matches) continue;

                                    comparionResponse = resp;
                                    break;
                                }
                            }

                        }
                        else if (thisData.ParticipantTask != null) // Not assessment
                        {
                            normTaskId = thisData.ParticipantTask.Id;
                            if (lastNormTaskId != normTaskId)
                            {
                                lastNormResponses = (from rowResp in db.CrowdRowResponses
                                                     where rowResp.ParticipantTaskId == normTaskId &&
                                                           rowResp.ParticipantResult.User.Key == result.User.Key
                                                     orderby rowResp.CreatedAt
                                                     select rowResp).ToArray();
                                lastNormTaskId = normTaskId;
                            }
                            if (lastNormResponses != null)
                            {
                                foreach (CrowdRowResponse resp in lastNormResponses)
                                {
                                    // Can't use GetFileName in LINQ expressions so have to do in memory
                                    bool matches = Path.GetFileName(resp.RecordingUrl) == Path.GetFileName(path);
                                    if (!matches) continue;

                                    comparionResponse = resp;
                                    break;
                                }
                            }
                        }

                        string choices = "";
                        string comparisonPath = "";
                        int prevLoud = -1;
                        int prevPace = -1;
                        int prevPitch = -1;

                        if (options != null)
                        {
                            // Shuffle the words
                            Random rnd = new Random();
                            options = options.OrderBy(x => rnd.Next()).ToArray();

                            for (int i = 0; i < options.Length; i++)
                            {
                                choices += options[i];
                                if (i < options.Length - 1) choices += ", ";
                            }
                        }

                        if (comparionResponse != null)
                        {
                            comparisonPath = comparionResponse.RecordingUrl;
                            prevLoud = GetAverageRes(comparionResponse, "rlstvolume");
                            prevPace = GetAverageRes(comparionResponse, "rlstpace");
                            prevPitch = GetAverageRes(comparionResponse, "rlstpitch");
                        }

                        json += createUnit(path, taskType, assTaskId, normTaskId, choices, prevLoud, prevPace, prevPitch, comparisonPath, extraData);

                        count += 1;
                    }
                }
                else //Fluent
                {
                    json += string.Format("{{\"AudioUrls\":\"{0}\", " +
                                              "\"FeedbackQuery\":\"{1}\"}}\r\n"
                            , String.Join(",", audioPaths), result.FeedbackQuery);
                    count += 1;
                }

            }
            json += TestQuestions();
            json = json.TrimEnd();

            return json;
        }
 public HttpResponseMessage Pause(ParticipantResult crowdResult)
 {
     throw new NotImplementedException();
 }
 public HttpResponseMessage CreateAndPublish(ParticipantResult crowdResult)
 {
     throw new NotImplementedException();
 }