Skip to content

Commit

Permalink
Merge pull request #85 from MatsMoll/develop
Browse files Browse the repository at this point in the history
Adding hints and other minor changes
  • Loading branch information
MatsMoll authored Oct 31, 2020
2 parents 2145e92 + 996e536 commit ef79f87
Show file tree
Hide file tree
Showing 6 changed files with 124 additions and 43 deletions.
4 changes: 3 additions & 1 deletion Public/.well-known/apple-app-site-association
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,7 @@
}
]
},
"webcredentials": ["M276UPEHPQ.no.mem.kognita.Kognita"]
"webcredentials": {
"apps": ["M276UPEHPQ.no.mem.kognita.Kognita"]
}
}
54 changes: 54 additions & 0 deletions Public/assets/js/flash-card/submit-performance.js
Original file line number Diff line number Diff line change
Expand Up @@ -193,8 +193,62 @@ function estimatedScore(shouldSetScore) {
$("#estimate-spinner").addClass("d-none");
$("#answer-estimate").text(text);
$("#answer-estimate").removeClass("d-none");
let improvements = json["improvements"];
if (improvements.lenght != 0) {
$("#estimated-score-card .card-body").append("<br>Kanskje nevn noe mer om dette?<ul>")
}
console.log(improvements);
for (const index in improvements) {
$("#estimated-score-card .card-body").append("<li>" + improvements[index]["word"] + "</li>");
}
if (improvements.lenght != 0) {
$("#estimated-score-card .card-body").append("</ul>")
}
})
.catch(function (error) {
console.log(error)
})
}

var hints = []
var hintIndex = 0;

function loadHints() {
if (hints.length > 0 && hintIndex < hints.length) {
revealHint();
return
} else if (hintIndex > 0) {
return
}
let url = "/api/practice-sessions/" + sessionID() + "/tasks/" + taskIndex() + "/estimate";

fetch(url, {
method: "POST",
headers: {
"Accept": "application/json, text/plain, */*",
"Content-Type" : "application/json"
},
body: answerJsonData("3")
})
.then(function (response) {
if (response.ok) {
return response.json();
} else {
throw new Error(response.statusText);
}
})
.then(function (json) {
hints = json["improvements"];
revealHint();
})
.catch(function (error) {
console.log(error)
})
}

function revealHint() {
if ($('#hint-card').length == 0) {
$("<div class='card'><div class='card-body' id='hint-card'></div></div>").hide().appendTo("#main-task-content .col-lg-7").fadeIn();
}
$("<div id='#hint-" + hintIndex + "'><h6>Hint nr: " + (hintIndex + 1) + "</h6><p class='text-dark'>" + hints[hintIndex++]["word"] + "</p></div>").hide().appendTo("#hint-card").fadeIn();
}
6 changes: 3 additions & 3 deletions Public/assets/js/practice-session-create.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,13 @@ function startPracticeSessionWithTopicIDs(topicIds, subjectId, useTypingTasks =
})
}

function startPracticeSessionWithSubtopicIDs(subtopicIDs, subjectId) {

let taskGoal = 10;
function startPracticeSessionWithSubtopicIDs(subtopicIDs, subjectId, useTypingTasks = true, useMultipleChoiceTasks = true, taskGoal = 5) {

let data = JSON.stringify({
"subtopicsIDs" : subtopicIDs,
"numberOfTaskGoal" : taskGoal,
"useTypingTasks" : useTypingTasks,
"useMultipleChoiceTasks" : useMultipleChoiceTasks
});

let url = "/api/subjects/" + subjectId + "/practice-sessions/start";
Expand Down
15 changes: 14 additions & 1 deletion Sources/App/Subject/SubjectWebController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ final class SubjectWebController: RouteCollection {
func boot(routes: RoutesBuilder) throws {

routes.get("subjects", use: listAll)
routes.get("subjects", "search", use: search(on:))
routes.get("subjects", "create", use: createSubject)

let subject = routes.grouped("subjects", Subject.parameter)
Expand All @@ -29,13 +30,25 @@ final class SubjectWebController: RouteCollection {
subject.get("compendium", use: compendium)
}

func search(on req: Request) throws -> EventLoopFuture<View> {

let query = try req.query.decode(Subject.ListOverview.SearchQuery.self)

return try req.repositories.subjectRepository
.allSubjects(for: req.auth.require(), searchQuery: query)
.map(Subject.Templates.ListComponent.Context.init(subjects: ))
.flatMap { context in
Subject.Templates.ListComponent().render(with: context, for: req)
}
}

func listAll(_ req: Request) throws -> EventLoopFuture<Response> {

let user = try req.auth.require(User.self)
let query = try? req.query.decode(ListAllQuery.self)

return try req.controllers.taskDiscussionResponseController
.setRecentlyVisited(on: req) // FIXME: -- Rename
.setRecentlyVisited(on: req) // FIXME: Rename
.failableFlatMap { activeDiscussion in

try req.controllers.subjectController
Expand Down
44 changes: 29 additions & 15 deletions Sources/App/configure.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,15 @@ public func configure(_ app: Application) throws {
fatalError("Need to set a ROOT_URL")
}

// Catches errors and converts to HTTP responses for developers
app.middleware.use(ErrorMiddleware.default(environment: app.environment))
// After ErrorMiddleware in order to not konvert error into html
app.middleware.use(HTMLKitErrorMiddleware<Pages.NotFoundError, Pages.ServerError>(ignorePath: "/api"))

if app.environment != .production {
// Catches errors and converts to HTTP responses for developers
app.middleware.use(ErrorMiddleware.default(environment: app.environment))
app.logger.logLevel = .debug
} else {
// Catches errors and converts to HTTP responses for users
app.middleware.use(HTMLKitErrorMiddleware<Pages.NotFoundError, Pages.ServerError>())
}

app.htmlkit.localizationPath = app.directory.workingDirectory + "Resources/Localization"
app.htmlkit.defaultLocale = "nb"

Expand All @@ -33,8 +34,8 @@ public func configure(_ app: Application) throws {
// try renderer.registerLocalization(atPath: path, defaultLocale: "nb")
// renderer.timeZone = TimeZone(identifier: "CET") ?? .current

app.verifyEmailRenderer.use { VerifyEmailRenderer.init(renderer: $0.htmlkit) }
app.resetPasswordRenderer.use { ResetPasswordMailRenderer.init(renderer: $0.htmlkit) }
app.verifyEmailRenderer.use { VerifyEmailRenderer(renderer: $0.htmlkit) }
app.resetPasswordRenderer.use { ResetPasswordMailRenderer(renderer: $0.htmlkit) }

try routes(app)
}
Expand Down Expand Up @@ -72,13 +73,19 @@ struct VerifyEmailRenderer: VerifyEmailRenderable {
}

/// Captures all errors and transforms them into an internal server error.
public final class HTMLKitErrorMiddleware<F: HTMLPage, S: HTMLPage>: Middleware {
public struct HTMLKitErrorMiddleware<F: HTMLPage, S: HTMLPage>: Middleware {

let ignorePath: String

/// Create a new ErrorMiddleware for the supplied pages.
public init(notFoundPage: F.Type, serverErrorTemplate: S.Type) {}
public init(notFoundPage: F.Type, serverErrorTemplate: S.Type, ignorePath: String) {
self.ignorePath = ignorePath
}

/// Create a new ErrorMiddleware
public init() {}
public init(ignorePath: String) {
self.ignorePath = ignorePath
}

/// See `Middleware.respond`
public func respond(to req: Request, chainingTo next: Responder) -> EventLoopFuture<Response> {
Expand All @@ -89,11 +96,18 @@ public final class HTMLKitErrorMiddleware<F: HTMLPage, S: HTMLPage>: Middleware
return res.encodeResponse(for: req)
}
}.flatMapError { error in
switch error {
case let abort as AbortError:
return self.handleError(for: req, status: abort.status)
default:
return self.handleError(for: req, status: .internalServerError)
do {
guard req.url.path.hasPrefix(ignorePath) == false else {
throw error
}
switch error {
case let abort as AbortError:
return self.handleError(for: req, status: abort.status)
default:
return self.handleError(for: req, status: .internalServerError)
}
} catch {
return req.eventLoop.future(error: error)
}
}
}
Expand Down
44 changes: 21 additions & 23 deletions set-xcodeproj-env.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,33 @@
import getpass
from pbxproj import XcodeProject
import sys
import os

file = "Kognita.xcodeproj/xcshareddata/xcschemes/Run.xcscheme"

tree = ETree.parse(file)

def environmentVariable(name, value, etree, is_enabled=True):
key = ETree.SubElement(etree, "EnvironmentVariable")
key.attrib["key"] = name
key.attrib["value"] = value
if is_enabled:
key.attrib["isEnabled"] = "YES"

# Adding Env variables
env_var_section = ETree.SubElement(tree.getroot().find("LaunchAction"), "EnvironmentVariables")
mailgun_key = ETree.SubElement(env_var_section, "EnvironmentVariable")
mailgun_key.attrib["key"] = "MAILGUN_KEY"
mailgun_key.attrib["value"] = "dd"
mailgun_key.attrib["isEnabled"] = "YES"
mailgun_domain = ETree.SubElement(env_var_section, "EnvironmentVariable")
mailgun_domain.attrib["key"] = "MAILGUN_DOMAIN"
mailgun_domain.attrib["value"] = "dd"
mailgun_domain.attrib["isEnabled"] = "YES"
database_user = ETree.SubElement(env_var_section, "EnvironmentVariable")
database_user.attrib["key"] = "DATABASE_USER"
database_user.attrib["value"] = getpass.getuser()
database_user.attrib["isEnabled"] = "YES"

text_client_url = ETree.SubElement(env_var_section, "EnvironmentVariable")
text_client_url.attrib["key"] = "TEXT_CLIENT_BASE_URL"
text_client_url.attrib["value"] = "http://127.0.0.1:5000/"
text_client_url.attrib["isEnabled"] = "YES"

root_url = ETree.SubElement(env_var_section, "EnvironmentVariable")
root_url.attrib["key"] = "ROOT_URL"
root_url.attrib["value"] = "http://localhost:8080"
root_url.attrib["isEnabled"] = "YES"
launchAction = tree.getroot().find("LaunchAction")
launchAction.set("useCustomWorkingDirectory", "YES")
launchAction.set("customWorkingDirectory", os.getcwd())

env_var_section = ETree.SubElement(launchAction, "EnvironmentVariables")

environmentVariable("MAILGUN_KEY", "dd", env_var_section)
environmentVariable("MAILGUN_DOMAIN", "dd", env_var_section)
environmentVariable("DATABASE_USER", getpass.getuser(), env_var_section)
environmentVariable("TEXT_CLIENT_BASE_URL", "127.0.0.1", env_var_section)
environmentVariable("TEXT_CLIENT_PORT", "5000", env_var_section)
environmentVariable("TEXT_CLIENT_SCHEME", "http", env_var_section)
environmentVariable("ROOT_URL", "http://localhost:8080", env_var_section)

tree.write(file)

Expand Down

0 comments on commit ef79f87

Please sign in to comment.