How to play DRM content using native WebOS player - webos

We are trying to play video content using native WebOS player and com.webos.service.drm service. The goal is to play at least some DRM content (dash+widevine or hls+widevine). Clear content works fine, but DRM content stucks completely, and no diagnostic messages appear.
The same result happens on WebOS 3.4, 4.4, and 6.0. Is there any working example of DRM content playback?
Our code is given below.
var appId = "com.zodiac.app";
// Define DRM Type
var drmType = "widevine";
function webos_request(service, params)
{
var caller = arguments.callee.caller.name;
console.log("REQ: %s: %s %s", caller, service, JSON.stringify(params))
return new Promise( function(resolve, reject) {
webOS.service.request(service, Object.assign({}, params, {
onSuccess: function (result) { console.log("REQ SUCCESS: %s: %s %s: %s", caller, service, params.method, JSON.stringify(result)); resolve(result) },
// onFailure: function (result) {
// console.log("[" + result.errorCode + "] " + result.errorText);
// reject()
// }
onFailure: function (result) { console.error("REQ ERROR: %s: %s %s: %s", caller, service, params.method, JSON.stringify(result)); reject(result) }
}))
});
}
function webos_subscribe(service, params, method)
{
var caller = arguments.callee.caller.name;
var completed = false
return new Promise( function(resolve, reject) {
params.parameters = params.parameters || {}
params.parameters.subscribe = true;
console.log("SUB: %s: %s %s", caller, service, JSON.stringify(params))
webOS.service.request("luna://com.webos.service.drm", Object.assign({}, params, {
onSuccess: function (result) { // Subscription Callback
if (!completed) {
completed = true;
if (result.subscribed) {
console.log("SUB: %s: %s: SUCCESS", caller, service)
resolve(result)
}
else {
console.error("SUB: %s: %s: FAILED", caller, service)
reject();
}
}
else
method(result)
},
onFailure: function (result) {
console.error("SUB: %s: %s: onFailure", caller, service, result)
// console.log('Player.subscribeLicensingError onFailure: ' + '[' + result.errorCode + '] ' + result.errorText);
completed = true;
reject()
}
}));
});
}
function unloadDrmClient(clientId)
{
webos_request("luna://com.webos.service.drm",
{
method:"unload",
parameters: {
"clientId": result.clientId
}
});
}
function loadDrmClient()
{
return webos_request( "luna://com.webos.service.drm", {
method:"load",
parameters: {
"drmType": drmType,
"appId": appId
}})
.then(function (result) {
console.log("DRM Client is loaded successfully. %s", JSON.stringify(result));
document.addEventListener('visibilitychange', function() {
if (document.visibilityState === 'hidden') {
unloadDrmClient(result.clientId)
}
})
return result.clientId
})
}
function sendRightInformation(clientId, url, la_url) {
var msgId;
// Message format for widevine
var msg = [
'<?xml version="1.0" encoding="utf-8"?>',
'<WidevineCredentialsInfo xmlns="http://www.smarttv-alliance.org/DRM/widevine/2012/protocols/">',
'<ContentURL>' + url + '</ContentURL>',
'<DeviceID></DeviceID>',
'<StreamID></StreamID>',
'<ClientIP></ClientIP>',
'<DRMServerURL>' + la_url + '</DRMServerURL>',
'<DRMAckServerURL></DRMAckServerURL>',
'<DRMHeartBeatURL></DRMHeartBeatURL>',
'<DRMHeartBeatPeriod>0</DRMHeartBeatPeriod>',
'<UserData></UserData>',
'<Portal></Portal>',
'<StoreFront></StoreFront>',
'<BandwidthCheckURL></BandwidthCheckURL>',
'<BandwidthCheckInterval></BandwidthCheckInterval>',
'</WidevineCredentialsInfo>',
].join("")
// Message type for widevine
var msgType = "application/widevine+xml";
// Unique ID of DRM system
var drmSystemId = "urn:dvb:casystemid:19156";
return webos_request( "luna://com.webos.service.drm", {
method:"sendDrmMessage",
parameters: {
"clientId": clientId,
"msgType": msgType,
"msg": msg,
"drmSystemId": drmSystemId
}})
.then( function (result) {
// DRM API does not return the msgId, resultCode, resultMsg for Widevine type.
console.log("sendDrmMessage succeeded. %s", JSON.stringify(result));
return
});
}
function subscribeLicensingError(clientId, msgId)
{
return webos_subscribe("luna://com.webos.service.drm", {
method:"getRightsError",
parameters: {
"clientId": clientId
}},
function (result) { // Subscription Callback
var contentId = result.contentId;
if (contentId == msgId) {
if ( 0 == result.errorState) {
console.log("No license");
// Do something for error handling
}
else if ( 1 == result.errorState) {
console.log("Invalid license");
// Do something for error handling
}
else {
console.log("Unknown errorState: %s", JSON.stringify(result));
}
}
else {
console.log("skip notification %s", JSON.stringify(result));
}
});
}
var video = document.getElementById('myVideo');
function playback()
{
var config = {
'dash+wv': {
type: "application/dash+xml",
mediaTransportType: "WIDEVINE",
url: 'https://bitmovin-a.akamaihd.net/content/art-of-motion_drm/mpds/11331.mpd',
la_url: 'https://widevine-proxy.appspot.com/proxy'
},
'hls+wv': {
type: "application/x-mpegURL",
mediaTransportType: "HLS",
url: 'https://storage.googleapis.com/shaka-demo-assets/angel-one-widevine-hls/hls.m3u8',
la_url: 'https://cwip-shaka-proxy.appspot.com/no_auth'
},
'mp4': {
type: "video/mp4",
url: "https://jsoncompare.org/LearningContainer/SampleFiles/Video/MP4/Sample-MP4-Video-File-Download.mp4"
},
'hls': {
type: "application/vnd.apple.mpegurl",
url: "https://bitdash-a.akamaihd.net/content/MI201109210084_1/m3u8s/f08e80da-bf1d-4e3d-8899-f0f6155f6efa.m3u8",
},
'dash': {
type: "application/dash+xml",
url: 'https://storage.googleapis.com/shaka-demo-assets/bbb-dark-truths/dash.mpd'
}
}
var stream = config['hls+wv']
var prepare
if (stream.la_url) {
prepare = loadDrmClient()
.then( function(id) {
subscribeLicensingError(id, undefined);
document.body.addEventListener("unload", function() {
webOS.service.request("luna://com.webos.service.drm", {
method:"unload",
parameters: { "clientId": id },
onSuccess: function (result) {
console.log("DRM Client is unloaded successfully.");
},
onFailure: function (result) {
console.log("[" + result.errorCode + "] " + result.errorText);
// Do something for error handling
}
});
})
return sendRightInformation(id, stream.url, stream.la_url).then( function () { return id; })
})
}
else {
prepare = Promise.resolve()
}
return prepare.then( function (id) {
var type = stream.type
if (stream.la_url) {
var options = {
mediaTransportType: stream.mediaTransportType,
option: {
drm: {
type: drmType,
clientId: id,
}
}
};
console.log("Options: %s", JSON.stringify(options));
var mediaOption = encodeURIComponent(JSON.stringify(options));
type += ';mediaOption=' + mediaOption;
}
console.log("open url: %s", stream.url)
console.log("type : %s", type)
var source = document.createElement("source");
source.setAttribute('src', stream.url);
source.setAttribute('type', type);
video.addEventListener('loadedmetadata', function(event) {
console.log("loadedmetadata %O", event)
});
video.addEventListener('error', function(e) {
console.error('error', e);
});
video.addEventListener('stalled', function(e) {
console.log('stalled', e);
});
video.addEventListener('loadeddata', function() {
console.log('[Device_Webos_Player] loadeddata');
});
video.addEventListener('loadedmetadata', function() {
console.log('[Device_Webos_Player] loadedmetadata');
});
video.addEventListener('canplay', function () {
console.log('[Device_Webos_Player] canplay');
});
video.addEventListener('durationchange', function() {
console.log('[Device_Webos_Player] durationchange: ' + video.duration);
});
video.addEventListener('timeupdate', function() {
console.log('[Device_Webos_Player] timeupdate: ' + video.currentTime);
}, { once: true});
video.appendChild(source);
// video.load()
video.play()
})
}
playback()

Finally the idea is [see here]
MPEG-DASH streaming is officially not supported on the webOS TV.
HLS plays AES-128 DRM only in public version
HTML5 EME/MSE can use both widevine and playready
See "Streaming Protocol & DRM Combination" here

Related

Unable to call any API from onAppointmentSend? Is this a limtation? Codes working on web outlook but not for Desktop Outlook

these are similar issues posted online
Relative fetch or XHR in a UI-Less Outlook add-in on Windows
How to make a http request in Outlook add-ins?
Officejs - Addin Outlook - SmartAlerts
Add-in built on jQuery framework works well on web-based outlook but doesn't on Desktop App
Outlook OnNewMessageCompose event not firing in Windows client
In outlook add-ins make salesforce oauth2 auth request getting CORS error
Common JavaScript function for Outlook Add-ins
React fetch not working with localhost endpoint with spring boot backend but ok with dummy JSON data
What is the easiest way to integrate Outlook web add-in into an existing ASP.NET Core 6 application?
Outlook Addin getting CORS when making request to ewsURL
if (_contextInfo.platform == "PC") {
console.log("PC");
Office.context.mailbox.item.subject.setAsync("Set by: New", { "asyncContext": event },
function (asyncResultPC) {
if (asyncResultPC.status !== Office.AsyncResultStatus.Succeeded) {
console.error("Failed to set subject2: " + JSON.stringify(asyncResultPC.error));
}
asyncResult.asyncContext.completed();
});
$.when(GetToken()).done(function () {
Office.context.mailbox.item.subject.setAsync("GetToken" + objResourceCurrent.token, { "asyncContext": event },
function (asyncResultToken) {
if (asyncResultToken.status !== Office.AsyncResultStatus.Succeeded) {
console.error("Failed to set subject2: " + JSON.stringify(asyncResultToken.error));
}
asyncResult.asyncContext.completed();
});
/*if (isNotNull(originalAppointment)) {
SetResourceAvailabilityByDatetimeRequest(originalAppointment);
if (objResourceCurrent.token != "" && objResourceCurrent.availabilityCriteria.length > 0) {
GetResourceAvailabilityByDatetime();
}
}*/
});
event.completed({ allowEvent: false, errorMessage: "From Desktop" });
}
else if (_contextInfo.platform == "OfficeOnline") {
console.log("OfficeOnline");
Office.context.mailbox.item.start.getAsync((asyncResultStartDt) => {
if (asyncResultStartDt.status !== Office.AsyncResultStatus.Succeeded) {
console.error(`Start Error:: ${asyncResultStartDt.error.message}`);
event.completed();
return;
}
originalAppointment.start = convertDateCS(asyncResultStartDt.value);
Office.context.mailbox.item.end.getAsync(function (asyncResultEndDt) {
if (asyncResultEndDt.status !== Office.AsyncResultStatus.Succeeded) {
console.error(`End Error:: ${asyncResultEndDt.error.message}`);
event.completed();
return;
}
originalAppointment.end = convertDateCS(asyncResultEndDt.value);
Office.context.mailbox.item.sessionData.getAsync("bookingObject", function (asyncResultBO) {
if (asyncResultBO.status !== Office.AsyncResultStatus.Succeeded) {
console.error(`BO Error:: ${asyncResultBO.error.message}`);
event.completed();
return;
}
const bookingObjectAllData = JSON.parse(asyncResultBO.value);
$.each(bookingObjectAllData["Office365AddInBookingItem"], function (index, item) { if (item.IsAddon == false) { ResourceIds = ResourceIds + item.ResourceId + ","; } });
originalAppointment.ResourceIds = ResourceIds;
result = checkRoomAvailabilityOutlook(originalAppointment.ResourceIds, originalAppointment.start, originalAppointment.end);
if (result) {
$.each(result, function (id, item) {
if (item.Value) {
availableRooms.push(item.Key)
}
else {
unAvailableRooms.push(item.Key)
}
});
}
else {
event.completed({ allowEvent: false, errorMessage: "checkRoomAvailabilityOutlook API Responsed with No Data" });
}
if (unAvailableRooms.length > 0) {
$.each(bookingObjectAllData["Office365AddInBookingItem"], function (index, item) {
if ($.inArray(item.ResourceId, unAvailableRooms) !== -1)
unavailableEmails = unavailableEmails !== '' ? unavailableEmails + ', ' + item.ResourceEmailId : item.ResourceEmailId;
});
event.completed({ allowEvent: false, errorMessage: "Unavailable room(s): " + unavailableEmails });
}
else {
if (availableRooms.length > 0) {
$.each(bookingObjectAllData["Office365AddInBookingItem"], function (index, item) {
if ($.inArray(item.ResourceId, availableRooms) !== -1)
availableEmails = availableEmails !== '' ? availableEmails + ', ' + item.ResourceEmailId : item.ResourceEmailId;
});
}
}
var itemId = Office.context.mailbox.item.itemId;
if (itemId === null || itemId == undefined) {
Office.context.mailbox.item.saveAsync(function (asyncResultSave) {
if (asyncResultSave.status !== Office.AsyncResultStatus.Succeeded) {
console.error(`End Error:: ${asyncResultSave.error.message}`);
event.completed();
return;
}
bookingObjectAllData.ExchangeReferenceNumber = asyncResultSave.value;
createSaveBookingRequest(bookingObjectAllData, originalAppointment);
saveBooking(bookingObj);
console.log(JSON.stringify(bookingObjectAllData));
event.completed({ allowEvent: true, errorMessage: "ItemId: " + asyncResultSave.value });
});
}
else {
console.log("Item already saved");
}
});
});
});
}
I tried XMLHttpRequest and fetch. both fails.
function GetToken() {
return $.ajax({
cache: false,
type: "POST",
contentType: "application/json",
url: "https://xyz/xyz/token",
data: {
username: "abc...",
password: "r6COP...",
grant_type: "password",
},
success: function (result) {
objResourceCurrent.token = result.access_token;
},
error: function (error) {
console.log("GetToken Error ", error);
}
});
}
Update
My above issue is still not resolved however As a test, I am able to call this open weather API. It working just fine with Windows Desktop/Web Outlook's OnSend or timeChange event handlers.
function onAppointmentSendHandler(event) {
console.log("onAppointmentSendHandler");
const _contextInfo = Office.context.diagnostics;
if (_contextInfo.platform == "PC") {
var url = 'https://api.openweathermap.org/data/2.5/weather?lat=28.644800&lon=77.216721&appid=efc8b889e4d57fbcc6fb2b523d2558c8';
var request = new XMLHttpRequest();
request.onreadystatechange = state_change;
request.open("POST", url, true);
request.send();
function state_change() {
if (request.readyState == "4") {
if (request.status == "200") {
console.log(request.responseText);
const myObj = JSON.parse(request.responseText)
var _Dtext = "From Desktop: City: " + myObj.name + ", Temp: " + myObj.main.temp + "f";
Office.context.mailbox.item.subject.setAsync(_Dtext, { "asyncContext": event }, function (asyncResultWeb) {
if (asyncResultWeb.status !== Office.AsyncResultStatus.Succeeded) {
console.error("Failed to set subject2: " + JSON.stringify(asyncResultWeb.error));
}
asyncResultWeb.asyncContext.completed();
event.completed({ allowEvent: false });
});
}
else {
console.log("Problem retrieving data PC");
console.log(this.responseXML);
}
}
}
}
else if (_contextInfo.platform == "OfficeOnline") {
console.log("Office Online");
var url = 'https://api.openweathermap.org/data/2.5/weather?lat=28.474388&lon=77.503990&appid=efc8b889e4d57fbcc6fb2b523d2558c8';
var request = new XMLHttpRequest();
request.onreadystatechange = state_change;
request.open("POST", url, true);
request.send();
function state_change() {
if (request.readyState == "4") {
if (request.status == "200") {
//console.log(request.responseText);
const myObj = JSON.parse(request.responseText)
var _Otext = "From Online: City: " + myObj.name + ", Temp: " + myObj.main.temp + "f";
Office.context.mailbox.item.subject.setAsync(_Otext, { "asyncContext": event }, function (asyncResultWeb) {
if (asyncResultWeb.status !== Office.AsyncResultStatus.Succeeded) {
console.error("Failed to set subject2: " + JSON.stringify(asyncResultWeb.error));
}
asyncResultWeb.asyncContext.completed();
event.completed({ allowEvent: false });
});
}
else {
console.log("Problem retrieving data Office Online");
console.log(this.responseXML);
}
}
}
}
}
function onAppointmentTimeChangedHandler(event) {
console.log("onAppointmentTimeChangedHandler");
var url = 'https://api.openweathermap.org/data/2.5/weather?lat=23.669296&lon=86.151115&appid=efc8b889e4d57fbcc6fb2b523d2558c8';
var request = new XMLHttpRequest();
request.onreadystatechange = state_change;
request.open("POST", url, true);
request.send();
function state_change() {
if (request.readyState == "4") {
if (request.status == "200") {
console.log(request.responseText);
const myObj = JSON.parse(request.responseText)
var _text = "From Time Change: City: " + myObj.name + ", Temp: " + myObj.main.temp + "f";
Office.context.mailbox.item.subject.setAsync(_text, { "asyncContext": event }, function (asyncResultWeb) {
if (asyncResultWeb.status !== Office.AsyncResultStatus.Succeeded) {
console.error("Failed to set subject2: " + JSON.stringify(asyncResultWeb.error));
}
asyncResultWeb.asyncContext.completed();
});
}
else {
console.log("Problem retrieving data");
console.log(this.responseXML);
}
}
}
}
Office.actions.associate("onAppointmentTimeChangedHandler", onAppointmentTimeChangedHandler);
Office.actions.associate("onAppointmentSendHandler", onAppointmentSendHandler);
Update 2 I am testing another API with 3 fields Subject, StartDate and End Date. Please note: This below code runs perfectly on Web outlook for OnSend/TimeChange events but not for Desktop Outlook OnSend /TimeChange events. And I do not get any error message or something.
Any help is much appriciated.
function onAppointmentSendHandler(event) {
console.log("onAppointmentSendHandler");
const _contextInfo = Office.context.diagnostics;
if (_contextInfo.platform == "PC") {
var obj = JSON.stringify({
Subject: "Azure Desktop 1",
StartDate: "03/02/2023",
EndDate: "03/31/2023"
});
username = "admin1";
password = "pass#123";
var url = 'https://externalwebapi.azurewebsites.net/api/save';
var request = new XMLHttpRequest();
request.onreadystatechange = state_change;
request.open("POST", url, true);
request.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password));
request.setRequestHeader('Content-type', 'application/json; charset=utf-8');
request.send(obj);
function state_change() {
if (request.readyState == "4") {
if (request.status == "200") {
console.log(request.responseText);
var _Dtext = "Azure Desktop 1";
Office.context.mailbox.item.subject.setAsync(_Dtext, { "asyncContext": event }, function (asyncResultWeb) {
if (asyncResultWeb.status !== Office.AsyncResultStatus.Succeeded) {
console.error("Failed to set subject1: " + JSON.stringify(asyncResultWeb.error));
}
asyncResultWeb.asyncContext.completed();
event.completed({ allowEvent: false });
});
}
else {
console.log("Problem retrieving data PC");
console.log(this.responseXML);
}
}
}
}
else if (_contextInfo.platform == "OfficeOnline") {
console.log("Office Online");
var obj = JSON.stringify({
Subject: "Azure WebSite 1",
StartDate: "02/02/2023",
EndDate: "02/28/2023"
});
//console.log(obj);
username = "admin1";
password = "pass#123";
var url = 'https://externalwebapi.azurewebsites.net/api/save';
var request = new XMLHttpRequest();
request.onreadystatechange = state_change;
request.open("POST", url, true);
request.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password));
request.setRequestHeader('Content-type', 'application/json; charset=utf-8');
request.send(obj);
function state_change() {
if (request.readyState == "4") {
if (request.status == "200") {
console.log(request.responseText);
var _Dtext = "Azure WebSite 1";
Office.context.mailbox.item.subject.setAsync(_Dtext, { "asyncContext": event }, function (asyncResultWeb) {
if (asyncResultWeb.status !== Office.AsyncResultStatus.Succeeded) {
console.error("Failed to set subject2: " + JSON.stringify(asyncResultWeb.error));
}
asyncResultWeb.asyncContext.completed();
event.completed({ allowEvent: false });
});
}
else {
console.log("Problem retrieving data Web");
console.log(this.responseXML);
}
}
}
}
}
function onAppointmentTimeChangedHandler(event) {
console.log("onAppointmentTimeChangedHandler");
var obj = JSON.stringify({
Subject: "Azure Time",
StartDate: "02/02/2023",
EndDate: "02/28/2023"
});
username = "admin1";
password = "pass#123";
var url = 'https://externalwebapi.azurewebsites.net/api/save';
var request = new XMLHttpRequest();
request.onreadystatechange = state_change;
request.open("POST", url, true);
request.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password));
request.setRequestHeader('Content-type', 'application/json; charset=utf-8');
request.send(obj);
function state_change() {
if (request.readyState == "4") {
if (request.status == "200") {
console.log(request.responseText);
var _Dtext = "Azure Time";
Office.context.mailbox.item.subject.setAsync(_Dtext, { "asyncContext": event }, function (asyncResultWeb) {
if (asyncResultWeb.status !== Office.AsyncResultStatus.Succeeded) {
console.error("Failed to set subject2: " + JSON.stringify(asyncResultWeb.error));
}
asyncResultWeb.asyncContext.completed();
event.completed({ allowEvent: false });
});
}
else {
console.log("Problem retrieving data Web");
console.log(this.responseXML);
}
}
}
}
Office.actions.associate("onAppointmentTimeChangedHandler", onAppointmentTimeChangedHandler);
Office.actions.associate("onAppointmentSendHandler", onAppointmentSendHandler);
REST API calls are supported and can be made from the onSend event handlers (callbacks). You just need to make sure that CORS is addressed in the add-in. The very first link in your post contains the valid answer to your case.
The same-origin policy enforced by the browser prevents a script loaded from one domain from getting or manipulating properties of a webpage from another domain. This means that, by default, the domain of a requested URL must be the same as the domain of the current webpage. For example, this policy will prevent a webpage in one domain from making XmlHttpRequest web-service calls to a domain other than the one where it is hosted.
Because Office Add-ins are hosted in a browser control, the same-origin policy applies to script running in their web pages as well.
The same-origin policy can be an unnecessary handicap in many situations, such as when a web application hosts content and APIs across multiple subdomains. There are a few common techniques for securely overcoming same-origin policy enforcement. The Addressing same-origin policy limitations in Office Add-ins article can only provide the briefest introduction to some of them.

Service Worker "notificationclick" not firing

The notification is showing fine, but when I click on it, or any of the actions, nothing happens. I see no logging, no error messages, but the notification does close (although it closes even when I comment out the event.notification.close()).
I've tried using the Chrome debugger, and I can set a break point in the code that shows the notification, but all breakpoints within the notificationclick handler fail to pause execution.
I've spent days trying to get this to work and I'm at my wits' end.
const auth = firebase.auth();
const functions = firebase.functions();
const done = functions.httpsCallable("done");
const snooze = functions.httpsCallable("snooze");
self.addEventListener("notificationclick", event => {
console.log("notificationclick", event);
const uid = auth.currentUser.uid;
const { id, url } = event.notification.data;
event.notification.close();
event.waitUntil(() => {
switch (event.action) {
case "done":
console.log("Done");
return done({ uid, id });
case "snooze1":
console.log("Snooze 1 Hour");
return snooze({ uid, id, hours: 1 });
case "snooze24":
console.log("Snooze 1 Day");
return snooze({ uid, id, hours: 24 });
default:
console.log("Open App");
return clients
.matchAll({
includeUncontrolled: true,
type: "window"
})
.then(clientList => {
for (let i = 0; i < clientList.length; i++) {
let client = clientList[i];
if (url[0] === "#") {
if (client.url.endsWith(url) && "focus" in client) {
return client.focus();
}
} else {
if (
client.url.replace(/#.*$/, "") === url &&
"focus" in client
) {
return client.focus();
}
}
}
if (clients.openWindow) {
return clients.openWindow(location.origin + url);
}
});
}
});
});
firebase
.messaging()
.setBackgroundMessageHandler(({ data: { title, options } }) => {
options = JSON.parse(options);
options.actions = [
{ action: "done", title: "Done" },
{ action: "snooze1", title: "Snooze 1 Hour" },
{ action: "snooze24", title: "Snooze 1 Day" }
];
return self.registration.showNotification(title, options);
});
Hi Could you try below code and see if this is getting called-
self.addEventListener('notificationclick', function (event) {
event.notification.close();
var redirectUrl = null;
var tag = event.notification.tag;
if (event.action) {
redirectUrl = event.action
}
if (redirectUrl) {
event.waitUntil(async function () {
var allClients = await clients.matchAll({
includeUncontrolled: !0
});
var chatClient;
for (const client of allClients) {
if (redirectUrl != '/' && client.url.indexOf(redirectUrl) >= 0) {
client.focus();
chatClient = client;
break
}
}
if (chatClient == null || chatClient == 'undefined') {
chatClient = clients.openWindow(redirectUrl);
return chatClient
}
}().then(result => {
if (tag) {
//PostAction(tag, "click")
}
}))
}
});
Edited-
Attaching both js files. it is working at my end.
firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js');
var config = {
apiKey: "your api key",
authDomain: "you firebase domain",
databaseURL: "your firbase db url",
projectId: "your project id",
storageBucket: "",
messagingSenderId: "sender id"
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload.data);
var notificationTitle = payload.data.Title;
var notificationOptions = {
body: payload.data.Body,
icon: payload.data.Icon,
image: payload.data.Image,
action: payload.data.ClickAction
};
console.log("strated sending msg" + notificationOptions);
return self.registration.showNotification(notificationTitle,notificationOptions);
});
self.addEventListener('notificationclick', function (event) {
console.log('On notification click: ', event.notification);
event.notification.close();
var redirectUrl = null;
if (event.notification.data) {
if (event.notification.data.FCM_MSG) {
redirectUrl = event.notification.data.FCM_MSG.data ? event.notification.data.FCM_MSG.data.click_action : null
} else {
redirectUrl = event.notification.data ? event.notification.data.click_action : null
}
}
console.log("redirect url is : " + redirectUrl);
if (redirectUrl) {
event.waitUntil(async function () {
var allClients = await clients.matchAll({
includeUncontrolled: true
});
var chatClient;
for (var i = 0; i < allClients.length; i++) {
var client = allClients[i];
if (client['url'].indexOf(redirectUrl) >= 0) {
client.focus();
chatClient = client;
break;
}
}
if (chatClient == null || chatClient == 'undefined') {
chatClient = clients.openWindow(redirectUrl);
return chatClient;
}
}());
}
});
self.addEventListener("notificationclose", function (event) {
event.notification.close();
console.log('user has clicked notification close');
});
application.js file :
/// <reference path="scripts/jquery-3.3.1.js" />
try {
var config = {
apiKey: "your api key",
authDomain: "you firebase domain",
databaseURL: "your firbase db url",
projectId: "your project id",
storageBucket: "",
messagingSenderId: "sender id"
};
firebase.initializeApp(config);
if ('serviceWorker' in navigator && 'PushManager' in window) {
console.log('Service Worker and Push is supported');
navigator.serviceWorker
.register('/firebase-messaging-sw.js')
.then((swReg) => {
firebase.messaging().useServiceWorker(swReg);
askForPermissioToReceiveNotifications();
})
.catch(function (error) {
console.error('Service Worker Error', error);
window.alert("Service Worker Error" + error);
})
} else {
console.warn('Push messaging is not supported');
window.alert("Push messaging is not supported " + (navigator.serviceWorker));
}
const askForPermissioToReceiveNotifications = async () => {
try {
const messaging = firebase.messaging();
console.log(messaging);
await messaging.requestPermission();
const token = await messaging.getToken();
if (token !== null || token !== 'undefined') {
await sendDeviceTokenToServerSide(token);
}
console.log('Got token : ' + token);
messaging.onMessage(function (payload) {
console.log('onMessage: ', payload);
setTimeout(() => {
navigator.serviceWorker.ready.then(function (registration) {
var notificationTitle = payload.notification.title;
var notificationOptions = {
body: payload.notification.body,
data: payload.data,
icon: payload.notification.icon,
image: payload.data.Image,
requireInteraction: payload.notification.requireInteraction,
tag: payload.notification.tag,
click_action: payload.data.click_action,
requireInteraction: true
};
registration.showNotification(notificationTitle, notificationOptions);
},50)
});
});
}
catch (e) { console.log('error in getting token: ' + e); window.alert("error in getting token: " + e); }
}
function sendDeviceTokenToServerSide(token) {
$.ajax({
type: 'POST',
url: '/Home/StoreToken',
timeout: 5000000,
data: { token: token },
success: function (success) {
console.log("device token is sent to server");
},
error: function (error) {
console.log("device error sending token to server : " + error);
window.alert("device error sending token to server : " + error);
}
});
}
} catch (e) {
window.alert("error: " + e);
}
function GetFcmUserToken(messaging) {
messaging.onTokenRefresh(function () {
messaging.getToken()
.then(function (refreshedToken) {
console.log('Token refreshed.');
return refreshedToken;
})
.catch(function (err) {
console.log('Unable to retrieve refreshed token ', err);
showToken('Unable to retrieve refreshed token ', err);
});
});
}
self.addEventListener('notificationclick', function (event) {
const clickedNotification = event.notification;
// Do something as the result of the notification click
const promiseChain = clients.openWindow(clickedNotification.data.Url);
event.waitUntil(promiseChain);
});
This code inside service worker js worked fine for me on chrome Desktop and Android.

uploading profile pic in hapijs 17.0

I am using hapijs version 17.0.1. I am trying to upload an image using ajax request on a hapijs route. Here is my AJAX code to upload profile pic:
var image_file_input = document.getElementById("user_profile_upload");
image_file_input.onchange = function () {
if(this.files != undefined)
{
if(this.files[0] != undefined)
{
var formData = tests.formdata ? new FormData() : null;
if (tests.formdata)
{
//alert(file)
formData.append('image_file', this.files[0]);
formData.append('userId', user_id);
formData.append('memberId', member_id);
}
$.ajax({
url: "/v1/User/uploadUserPic",
data: formData,
type: "POST",
dataType: "json",
contentType: false,
processData: false,
contentType: "multipart/form-data",
success: function(data){
console.log(data);
var errMsg = null;
var resData = null;
if(data.statusCode == 200)
{
resData = data.result;
}
else
{
alert(data.message)
}
},
error: function(error){
alert(error);
}
});
}
}
}
And here is my Hapijs route Code:
var uploadUserPic = {
method: 'POST',
path: '/v1/Module/uploadUserPic',
config: {
description: 'Update Image For User',
tags: ['api', 'User'],
auth: 'session',
payload: {
output: 'stream',
parse: true,
allow: 'multipart/form-data'
},
validate: {
payload: {
userId : Joi.string().regex(/^[a-f\d]{24}$/i).required(),
memberId: Joi.string().required(),
image_file: Joi.object().required(),
},
failAction: FailCallBack
}
},
handler: function (request, reply) {
var resultData = null;
var error = null;
return new Promise(function (resolve) {
var multiparty = require('multiparty');
var fs = require('fs');
var form = new multiparty.Form();
form.parse(request.payload, function (err, fields, files) {
if(err)
{
error = err;
resolve();
}
else
{
var mkdirp = require('mkdirp');
var img_dir = "./files/users/";
mkdirp(img_dir, function (err) {
if (err)
{
error = err;
console.error(err);
resolve();
}
else
{
var oldpath = files.image_file.path;
var newpath = "./files/users/"+requestPayload.userId+".png";
fs.rename(oldpath, newpath, function (err) {
if(err)
{
error = err;
}
resolve();
});
}
});
}
});
}).then(function (err, result) {
if(err) return sendError(err);
if(error) return sendError(error)
return {
"statusCode": 200,
"success": true
};
});
}
}
The above code gives me following error cannot read property 'content-length' of undefined on line form.parse(request.payload, function (err, fields, files) {});
Please let me know If I am doing something wrong. If I replace the url in ajax request with anohter url that I have written in php then it works perfectly. which means that something is wrong with my hapijs/nodejs code.
There's a good post on how to handle file uploads in Hapi.js (written in version 16) https://scotch.io/bar-talk/handling-file-uploads-with-hapi-js
Since you are using payload.parse = true, I am not seeing a particular reason why you have to use multiparty. I have the following working code that would save files (of any type) uploaded from client into uploads directory on the server (Please do not use directly on production as no sanitation is done)
{
path: '/upload',
method: 'POST',
config: {
payload: {
output: 'stream',
parse: true,
allow: 'multipart/form-data'
},
validate: {
payload: {
files: Joi.array().single()
}
}
},
handler: function(request) {
const p = request.payload, files = p.files
if(files) {
console.log(`${files.length} files`)
files.forEach(async file => {
const filename= file.hapi.filename
console.log(`Saving ${filename} to ./uploads`)
const out = fs.createWriteStream(`./uploads/${filename}`)
await file.pipe(out)
})
}
return {result: 'ok'}
}
}
You can use the following curl command to test
curl http://localhost:8080/upload -F 'files=#/path/to/a/note.txt' -F 'files=#/path/to/test.png' -vvv
There are a few issues with your code. First in your $.ajax call, you have specified contentType twice, although it's not a syntax error but it's careless to code like that. Second the function's signature inside your .then() block is incorrect. You are mixing the idea of Promise and callback. I don't think the following line will be triggered
if(err) return sendError(err);
One last trivial thing, you said you are using Hapi 17 but based on the handler function's signature
handler: function (request, reply) {
...
Seems you are not totally onboard with Hapi17 as the new signature is
handler: function (request, h) {
And it's not just the rename of reply to h.

How to stop Kendo UI dropdown from sorting alphabetically

I have been given the fun job on taking on someone elses code and trying to figure it out...
I have been tearing my hair out trying to figure out how to to stop a Kendo UI dropdown from sorting alphabetically ?
<select id="ddlArtworkStatuses" onlyPreparedValues="true"
readOnlyInput="true" data-bind="idNameOptions: artworkStatuses,
comboboxSelectedValue: artworkStatusId"></select>
For some reason this sorts althabetically but I want it to keep the order in the datasource. I have double checked to make sure it is in the order I want.
It doesn't use the standard way of using Kendo UI and I can't find any examples anywhere of using it this way?
It binds the view to the model with this line at the top of the view I believe?
<!-- ko with: fabricationModel -->
The vm.fabrication file is this:
(function (app) {
app.namespace("models");
var resources = {
unableToDeleteArtworkMessage: "This artwork cannot be deleted because it is linked to one or more of the following: Movements, Shows, POs. Or it has Imported Costs, Sales or Restoration Cases.",
unableToBlankArtworkFullyMessage: "This artwork has some data that will not be blanked if you continue. This could be one or more of the following: Movements, Shows, POs, Imported Costs, Sales or Restoration Cases. Do you want to continue?",
deleteArtworkTitle: "Delete artwork",
blankArtworkTitle: "Blank Artwork",
duplicateTitle: "New artwork form is pre-populated",
duplicateMessage: "You can make changes to Fabrication form fields. Record will be created after you press save button",
saveError: 'An error occured during artwork saving. Changes were not saved.'
};
app.models.FabricationModel = function (datasource) {
var emitter = new app.events.EventEmitter(),
self = this,
duplicateArtwork = ko.observable(false);
this.isNewArtwork = ko.observable(false);
this.isActivated = ko.observable(false);
this.showCreationInformation = ko.observable(true);
this.wipeArtworkModel = new app.models.WipeArtworkDialogModel(datasource);
this.internalArtworkModel = ko.observable();
this.editCategoryModel = new app.models.EditDhCategoryModel();
// alert("data=" + this.artworkStatuses);
this.isReadOnly = ko.computed(function () {
if (!self.internalArtworkModel()) {
return true;
}
return self.internalArtworkModel().isReadOnly();
});
this.canSaveStudioStatusOnly = ko.computed(function () {
if (!self.internalArtworkModel()) {
return false;
}
return self.internalArtworkModel().isUnblockStatusActive()
&& self.internalArtworkModel().isReadOnly()
&& self.internalArtworkModel().isStudioStatusVisible();
});
this.canSaveCatRaisOnly = ko.computed(function () {
if (!self.internalArtworkModel()) {
return false;
}
return self.internalArtworkModel().isReadOnly()
&& self.internalArtworkModel().isArchiveProvenanceWriter();
});
this.isNewOrDuplicating = ko.computed(function () {
return self.isNewArtwork() || duplicateArtwork();
});
this.activate = function (params) {
var id = params.id || 0;
self.isNewArtwork(!id);
return self.loadArtworkDetails(id);
};
this.isValid = function () {
return self.internalArtworkModel() && self.internalArtworkModel().errors().length == 0;
};
this.loadArtworkDetails = function (id) {
var action = self.isNewArtwork() ? datasource.artworks.getEmpty : datasource.artworks.getById;
return action(id)
.done(function (result) {
var mapper = app.mappers["fabrication"],
model = mapper.map(result.data);
self.internalArtworkModel(model);
self.editCategoryModel.categoryId(model.defaultDhCategoryId);
self.editCategoryModel.setModeAsCategoryChanging();
if (self.isNewArtwork()) {
self.editCategoryModel.setModeAsCreation();
self.editCategoryModel.show();
}
self.isActivated(true);
duplicateArtwork(false);
$("a#science-link").attr("href", window.location.href);
triggerLoadEvent();
});
};
this.saveArtwork = function () {
if (self.isValid()) {
return saveInternal($.noop);
}
};
this.editCategory = function () {
self.editCategoryModel.show();
};
this.onLoad = function (callback) {
emitter.subscribe("load", callback);
};
this.onCategoryChanged = function (callback) {
emitter.subscribe("category-changed", callback);
};
this.onDelete = function (callback) {
emitter.subscribe("delete", callback);
};
this.onCreated = function (callback) {
emitter.subscribe("artwork-created", callback);
};
this.onUpdated = function (callback) {
emitter.subscribe("artwork-updated", callback);
};
this.onBlanked = function (callback) {
emitter.subscribe("blanked", callback);
};
this.saveStudioStatusInt = function () {
return saveStudioStatusInternal($.noop);
};
this.saveCatRaisInt = function () {
return saveCatRaisInternal($.noop);
};
this.saveStudioStatus = ko.asyncCommand({
execute: function (complete) {
saveStudioStatusInternal(complete);
},
canExecute: function (isExecuting) {
return !isExecuting && self.canSaveStudioStatusOnly();
}
});
this.saveCatRais = ko.asyncCommand({
execute: function (complete) {
saveCatRaisInternal(complete);
},
canExecute: function (isExecuting) {
return !isExecuting && self.canSaveCatRaisOnly();
}
});
this.save = ko.asyncCommand({
execute: function (complete) {
return saveInternal(complete);
},
canExecute: function (isExecuting) {
if (!self.isValid()) {
showErrors();
}
return !isExecuting && self.isValid();
}
});
function saveStudioStatusInternal(completeCallback) {
var model = self.internalArtworkModel();
triggerSaveStudioStatusEvent();
datasource.artworks.saveStudioStatus(model.artworkId(), model.artworkStatusId(), model.studioStatusId).always(completeCallback);
}
function saveCatRaisInternal(completeCallback) {
var model = self.internalArtworkModel();
triggerSaveStudioStatusEvent();
datasource.artworks.saveCatRais(model.artworkId(), model.inclusion(), model.image(), model.details(), model.crReady(), model.selectedVolume.selected.value).always(completeCallback);
}
this.onSaveStudioStatus = function (callback) {
emitter.subscribe("saveStudioStatus", callback);
};
function triggerSaveStudioStatusEvent() {
emitter.publish("saveStudioStatus");
}
this.beginArtworkDeletion = function () {
if (!self.internalArtworkModel().canBeBlanked) {
jAlert(resources.unableToDeleteArtworkMessage, resources.deleteArtworkTitle);
return;
}
self.wipeArtworkModel.beginArtworkDeletion(self.internalArtworkModel().artworkId());
};
this.beginArtworkBlanking = function () {
if (!self.internalArtworkModel().canBeBlanked) {
//jAlert(resources.unableToBlankArtworkMessage, resources.blankArtworkTitle);
app.alerts.appConfirm(resources.unableToBlankArtworkFullyMessage, resources.blankArtworkTitle, function (ok) {
if (ok) {
self.wipeArtworkModel.beginArtworkBlanking(self.internalArtworkModel().artworkId());
}
});
return;
}
self.wipeArtworkModel.beginArtworkBlanking(self.internalArtworkModel().artworkId());
};
this.duplicateArtwork = function () {
if (!self.internalArtworkModel()) {
return;
}
duplicateArtwork(true);
resetModelBeforeDuplication();
if (self.isValid()) {
showErrors();
}
jAlert(resources.duplicateMessage, resources.duplicateTitle);
};
function saveInternal(completeCallback) {
var mapper = app.mappers["fabrication"];
//alert("saving now...");
var unmappedModel = mapper.toJS(self.internalArtworkModel());
if (duplicateArtwork()) {
return saveDuplicatedArtwork(unmappedModel, completeCallback);
}
if (unmappedModel.artworkId) {
return updateArtwork(unmappedModel, completeCallback);
}
return createArtwork(unmappedModel, completeCallback);
}
function saveDuplicatedArtwork(model, completeCallback) {
return datasource.artworks.duplicate(model)
.always(completeCallback)
.fail(function (response) {
jAlert(resources.saveError);
})
.done(function (id) {
triggerArtworkCreatedEvent(id);
duplicateArtwork(false);
self.showCreationInformation(true);
});
}
function updateArtwork(model, completeCallback) {
return datasource.artworks.save(model)
.always(completeCallback)
.fail(function (response) {
jAlert(resources.saveError);
})
.done(function (result) {
if (!result) {
return;
}
var mapper = app.mappers["fabrication"],
mappedModel = mapper.map(result.data);
triggerUpdateEvent(
{
dhCategory: mappedModel.dhCategory(),
refNumber: mappedModel.refNumber(),
computedTitle: mappedModel.computedTitle()
});
self.internalArtworkModel(mappedModel);
});
}
function createArtwork(model, completeCallback) {
return datasource.artworks.save(model)
.always(completeCallback)
.fail(function (response) {
jAlert(resources.saveError);
})
.done(function (id) {
if (id) {
triggerArtworkCreatedEvent(id);
}
});
}
function triggerLoadEvent() {
var model = self.internalArtworkModel();
emitter.publish("load", {
artworkId: model.artworkId() || 0,
dhCategory: model.dhCategory() || "",
refNumber: model.refNumber() || "",
computedTitle: model.computedTitle() || "",
isForSale: model.isForSale
});
}
function triggerArtworkCreatedEvent(artworkId) {
emitter.publish("artwork-created", artworkId);
}
function triggerCategoryChangedEvent() {
emitter.publish("category-changed", {
name: self.internalArtworkModel().dhCategoryName(),
id: self.internalArtworkModel().dhCategoryId()
});
}
function triggerDeleteEvent(e, artworkId) {
emitter.publish("delete", artworkId);
}
function triggerUpdateEvent(data) {
var model = self.internalArtworkModel();
data.isCategoryChanged = model.initialCategoryId !== model.dhCategoryId();
emitter.publish("artwork-updated", data);
}
function showErrors() {
var model = self.internalArtworkModel();
if (model) {
model.errors.showAllMessages();
}
}
function resetModelBeforeDuplication() {
var model = self.internalArtworkModel();
model.refNumber("");
model.computedTitle("");
model.isOnDisplay(false);
model.isOnRestoration(false);
model.salesStatus("Not set");
model.creationDate("");
model.creatorName("");
model.isFramed(false);
model.framedDate("");
model.framedUserName("");
model.framedUserInitials("");
model.framedUserId(null);
model.locations(null);
model.isInsuranceComponent(false);
model.dateWebsiteWork("");
model.dateWebsiteReady("");
model.dateWebsiteUploaded("");
model.dateRemovedFromWebsite("");
model.collectionListing("");
model.salesStatusChangedDate("");
model.salesStatusChangerUserInitials("");
model.salesStatusChangerUserName("");
self.showCreationInformation(false);
}
function triggerBlanked(artworkId) {
emitter.publish("blanked", { artworkId: artworkId, flag: true });
}
(function () {
self.editCategoryModel.onChanged(function (e, categoryId) {
self.internalArtworkModel().dhCategoryId(categoryId);
triggerCategoryChangedEvent();
});
self.editCategoryModel.onCancel(function () {
if (self.isNewArtwork()) {
self.isNewArtwork(false);
app.router.back();
}
});
self.wipeArtworkModel.onDelete(triggerDeleteEvent);
self.wipeArtworkModel.onBlank(function (e, artworkId) {
self.loadArtworkDetails(artworkId);
triggerBlanked(artworkId);
});
})();
};
})(app);
It also uses a mapper:
(function (app, ko) {
app.namespace("mappers");
var s = app.urls.shared,
datasource = app.datasource;
var mapSettings = {
selectedMedium: {
create: function (options) {
return new ListModel({
isRemoteSource: true,
url: s.get('dictionaryUrl'),
listType: datasource.dictionaryTypes.get("medium"),
currentValue: options.data,
nobutton: true,
templateName: "textAreaTemplate"
});
}
},
artist: {
create: function (options) {
return new ListModel({
isRemoteSource: true,
url: s.get('dictionaryUrl'),
listType: datasource.dictionaryTypes.get("artist"),
currentValue: options.data,
onlyPreparedValues: false
});
}
},
manager: {
create: function (options) {
return new ListModel({
isRemoteSource: true,
url: s.get('dictionaryUrl'),
listType: datasource.dictionaryTypes.get("manager"),
currentValue: options.data,
onlyPreparedValues: false
});
}
},
managerStatus: {
create: function (options) {
return new ListModel({
isRemoteSource: true,
url: s.get('dictionaryUrl'),
listType: datasource.dictionaryTypes.get("managerStatus"),
currentValue: options.data,
onlyPreparedValues: false
});
}
},
selectedVolume: {
create: function (options) {
return new ListModel({
isRemoteSource: true,
url: s.get('dictionaryUrl'),
listType: datasource.dictionaryTypes.get("volume"),
currentValue: options.data,
onlyPreparedValues: false,
readonly: !options.parent.isArchiveProvenanceWriter(),
editable: options.parent.isArchiveProvenanceWriter()
});
}
},
salesStatus: {
create: function (options) {
var value = options.data || "Not set";
return ko.observable(value);
}
},
oldReferences: {
create: function (options) {
return ko.observable(options.data);
}
},
copy: ['defaultDhCategoryId', "canBeDeleted", "canBeBlanked", "isForSale"],
ignore: ["dimensions", "dimensionUnits", "selectedMediumTypes", "selectedSeries", "selectedSubSeries", "selectedAkaNames", "selectedWebSiteMediumTypes", 'selectedWebSiteCategoryIds', "locations", "hasInTransitLocations"]
},
unmapSettings = {
ignore: ["selectedMedium", "artist", "manager", "managerStatus", "mediumTypesModel", "dimensionModel", "seriesModel", "subSeriesModel", "akaModel", "webSiteMediumTypesModel", "webSiteCategoriesModel", "selectedVolume"]
},
map = function (json) {
var convertedObject = ko.utils.parseJson(json);
var model = ko.mapping.fromJS(convertedObject, mapSettings);
model.artworkStatusesModel = new ListModel({
isRemoteSource: false,
currentValue: convertedObject.selectedArtworkStatus,
data: convertedObject.artworkStatuses,
//data: filteredSalesStatuses,
onlyPreparedValues: true,
allowNull: false,
readonly: true
});
alert("mooo=" + model.artworkStatuses()[0].name());
alert("mooo=" + model.artworkStatuses()[1].name());
alert("mooo=" + model.artworkStatuses()[2].name());
//alert("mooo=" + model.artworkStatuses()[3].name());
//alert("mooo=" + model.artworkStatuses()[4].name());
model.dhCategoryName = ko.computed(function () {
var categories = model.dhCategories();
for (var i = 0; i < categories.length; i++) {
var category = categories[i];
if (category.id() == model.dhCategoryId()) {
return category.name();
}
}
return "";
});
model.initialCategoryId = convertedObject.dhCategoryId;
model.dimensionModel = new app.models.DimensionModel(convertedObject.dimensions);
ko.utils.arrayForEach(convertedObject.dimensionUnits, function (unit) {
model.dimensionModel.units.push(unit);
});
model.locations = ko.observable(convertedObject.locations ? {
archivedLocations: $.map(convertedObject.locations, function (elem) {
return elem.isArchived ? elem : null;
}),
activeLocations: $.map(convertedObject.locations, function (elem) {
return elem.isArchived ? null : elem;
}),
hasInTransitLocations: convertedObject.hasInTransitLocations
} : convertedObject.locations);
model.mediumTypesModel = new app.models.MultilistModel(convertedObject.selectedMediumTypes, { url: s.get("mediumTypesUrl") });
model.seriesModel = new app.models.MultilistModel(convertedObject.selectedSeries, { url: s.get("seriesUrl") });
model.subSeriesModel = new app.models.MultilistModel(convertedObject.selectedSubSeries, { url: s.get("subSeriesUrl") });
model.akaModel = new app.models.MultilistModel(convertedObject.selectedAkaNames, { url: s.get("akaUrl") });
model.webSiteMediumTypesModel = new app.models.MultilistModel(convertedObject.selectedWebSiteMediumTypes, { url: s.get("webSiteMediumTypeUrl") });
model.webSiteCategoriesModel = new app.models.MultilistModel(convertedObject.selectedWebSiteCategories, { url: s.get("webSiteCategoryUrl") });
model.isStudioStatusVisible = ko.computed(function () {
var foundStatuses = ko.utils.arrayFilter(model.artworkStatuses(), function (status) {
return status.id() == model.artworkStatusId();
});
var currentStatus = foundStatuses[0];
if (currentStatus) {
return currentStatus.name().toLowerCase() == "in progress";
}
return false;
});
addValidationOptions(model);
return model;
},
toJS = function (artwork) {
var result = ko.mapping.toJS(artwork, unmapSettings);
result.artist = artwork.artist.toJS();
result.manager = artwork.manager.toJS();
result.managerStatus = artwork.managerStatus.toJS();
result.selectedMedium = artwork.selectedMedium.toJS();
result.selectedVolume = artwork.selectedVolume.toJS();
result.dimensions = artwork.dimensionModel.toJS();
result.selectedMediumTypes = artwork.mediumTypesModel.toJS();
result.selectedSeries = artwork.seriesModel.toJS();
result.selectedSubSeries = artwork.subSeriesModel.toJS();
result.selectedAkaNames = artwork.akaModel.toJS();
result.selectedWebSiteMediumTypes = artwork.webSiteMediumTypesModel.toJS();
result.selectedWebSiteCategories = artwork.webSiteCategoriesModel.toJS();
return result;
};
function isValidationRequired(model) {
var artworkStatus = ko.utils.unwrapObservable(model.artworkStatusId);
var dhCategory = ko.utils.unwrapObservable(model.dhCategoryId);
return artworkStatus == app.global.dictionary.get("compiteArtworkStatus")
&& dhCategory != app.global.dictionary.get("ignoreDHCatigory");
}
function addValidationOptions(model) {
model.artworkStatusId.extend({ required: true });
model.title.extend({ required: true });
model.artist.selected.value.extend({ required: true });
model.startYear.extend({
lessEqualThan: {
params: model.endYear,
onlyIf: function () {
return (model.endYear() != undefined && model.endYear() != null);
},
message: 'From Date should be less or equal than a To Date'
}
});
model.endYear.extend({
required: {
params: true,
onlyIf: function () {
return isValidationRequired(model);
},
message: "To Date field is required"
}
});
model.selectedMedium.selected.value.extend({
required: {
params: true,
onlyIf: function () {
return isValidationRequired(model);
},
message: "Medium is required"
}
});
model.mediumTypesModel.hasValue.extend({
equal: {
params: true,
onlyIf: function () {
return isValidationRequired(model);
},
message: "Medium Type is required"
}
});
model.akaModel.hasValue.extend({
equal: {
params: true,
onlyIf: function () {
return isValidationRequired(model);
},
message: "Aka is required"
}
});
model.isInsuranceComponent.extend({
equal: {
params: true,
onlyIf: function () {
return isValidationRequired(model);
},
message: "At least 1 Insurance component should be chosen"
}
});
model.dimensionModel.hasDimensions.extend({
equal: {
params: true,
onlyIf: function () {
return isValidationRequired(model);
},
message: "The Dimension fields should be filled"
}
});
model.errors = ko.validation.group(model, { deep: true });
}
app.mappers.fabrication = {
settings: mapSettings,
map: map,
toJS: toJS
};
})(app, ko);
Where I have the alerts, the items are in the right order, so somewhere they are getting sorted but cant find out where?!
I hope someone can help?
It would be really appreciated.
Many thanks,
David.

AJAX POST request never completes. Data posts to server

I am sending a post request via AJAX. The data successfully posts but the AJAX call never completes. Backbone on the front; Node on the back. I am including the save function from my backbone view and the express route.
save: function(event) {
event.preventDefault();
console.log( 'You signed up for ' + this.model.get('name'));
var name = this.model.get('name');
var courseDay = this.model.get('courseDay');
var time = this.model.get('time');
var location = this.model.get('location');
jQuery.post("/test/signups", {
"name" : name,
"courseDay" : courseDay,
"time" : time,
"location" : location,
}, function (data, textStatus, jqXHR) {
console.log("Post response:");
console.dir(data);
console.log(textStatus);
console.dir(jqXHR);
});
}
Route:
app.post('/test/signups', isLoggedIn, function (req, res){
User.findOne({'_id': req.user.id }, function(err, user) {
if (err)
return done(err);
if (user) {
user.signup.name = req.body.name;
user.signup.courseDay = req.body.courseDay;
user.signup.time = req.body.time;
user.signup.location = req.body.location;
user.signup.modified = req.body.modified;
user.update({$push: { "signup" :
{ name: user.signup.name,
courseDay: user.signup.courseDay,
time: user.signup.time,
location: user.signup.location,
modified: user.signup.modified
}
}},{safe:true, upsert:true},function(err){
if(err){
console.log(err);
} else {
console.log("Successfully added" + user.signup);
}
});
}
});
});
Your server side code needs to send a response. Try something like below. Note I try to cover all cases of an error, user not found, and user found.
app.post('/test/signups', isLoggedIn, function (req, res){
User.findOne({'_id': req.user.id }, function(err, user) {
if (err) {
return res.status(500).send(err);
}
if (user) {
user.signup.name = req.body.name;
user.signup.courseDay = req.body.courseDay;
user.signup.time = req.body.time;
user.signup.location = req.body.location;
user.signup.modified = req.body.modified;
user.update({$push: { "signup" :
{ name: user.signup.name,
courseDay: user.signup.courseDay,
time: user.signup.time,
location: user.signup.location,
modified: user.signup.modified
}
}},{safe:true, upsert:true},function(err){
if(err){
return res.status(500).send(err);
}
console.log("Successfully added" + user.signup);
res.send(user);
});
} else {
res.status(404).send();
}
});
});

Resources