Skip to content

Commit

Permalink
Merge pull request #48 from nightscout/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
unsoluble authored Aug 23, 2019
2 parents d2320da + 3b5430d commit 2379706
Show file tree
Hide file tree
Showing 8 changed files with 103 additions and 65 deletions.
2 changes: 1 addition & 1 deletion app.js
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ function create (env, ctx) {
if (fs.existsSync(process.cwd() + '/tmp/cacheBusterToken')) {
tmpFiles = express.static('tmp', {
maxAge: maxAge
});
});
} else {
tmpFiles = express.static(__dirname + '/tmp', {
maxAge: maxAge
Expand Down
2 changes: 1 addition & 1 deletion lib/client/careportal.js
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ function init (client, $) {

console.log('Validating careportal entry: ', data.eventType);

if (data.eventType == 'Temporary Target') {
if (data.duration !== 0 && data.eventType == 'Temporary Target') {
if (isNaN(data.targetTop) || isNaN(data.targetBottom) || !data.targetBottom || !data.targetTop) {
console.log('Bottom or Top target missing');
allOk = false;
Expand Down
43 changes: 30 additions & 13 deletions lib/client/clock-client.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,27 @@ client.settings = browserSettings(client, window.serverSettings, $);

client.query = function query () {
console.log('query');
$.ajax('/api/v1/entries.json?count=3', {
var parts = (location.search || '?').substring(1).split('&');
var token = '';
parts.forEach(function (val) {
if (val.startsWith('token=')) {
token = val.substring('token='.length);
}
});

var secret = localStorage.getItem('apisecrethash');
var src = '/api/v1/entries.json?count=3&t=' + new Date().getTime();

if (secret) {
src += '&secret=' + secret;
} else if (token) {
src += '&token=' + token;
}

$.ajax(src, {
success: client.render
});
}
};

client.render = function render (xhr) {
console.log('got data', xhr);
Expand All @@ -32,7 +49,7 @@ client.render = function render (xhr) {
let now = new Date();

// Convert BG to mmol/L if necessary.
if (window.serverSettings.settings.units == 'mmol') {
if (window.serverSettings.settings.units === 'mmol') {
var displayValue = window.Nightscout.units.mgdlToMMOL(rec.sgv);
} else {
displayValue = rec.sgv;
Expand All @@ -42,7 +59,7 @@ client.render = function render (xhr) {
$('#bgnow').html(displayValue);

// Insert the trend arrow.
$('#arrow').attr('src', '/images/' + rec.direction + '.svg');
$('#arrow').attr('src', '/images/' + (!rec.direction || rec.direction === 'NOT COMPUTABLE' ? 'NONE' : rec.direction) + '.svg');

// Time before data considered stale.
let staleMinutes = 13;
Expand All @@ -52,13 +69,13 @@ client.render = function render (xhr) {
$('#bgnow').toggleClass('stale', (now - last > threshold));

// Generate and insert the clock.
let timeDivisor = (client.settings.timeFormat) ? client.settings.timeFormat : 12;
let timeDivisor = parseInt(client.settings.timeFormat ? client.settings.timeFormat : 12, 10);
let today = new Date()
, h = today.getHours() % timeDivisor;
if (timeDivisor == 12) {
h = (h == 0) ? 12 : h; // In the case of 00:xx, change to 12:xx for 12h time
if (timeDivisor === 12) {
h = (h === 0) ? 12 : h; // In the case of 00:xx, change to 12:xx for 12h time
}
if (timeDivisor == 24) {
if (timeDivisor === 24) {
h = (h < 10) ? ("0" + h) : h; // Pad the hours with a 0 in 24h time
}
let m = today.getMinutes();
Expand All @@ -67,14 +84,14 @@ client.render = function render (xhr) {

var queryDict = {};
location.search.substr(1).split("&").forEach(function(item) { queryDict[item.split("=")[0]] = item.split("=")[1] });

if (!window.serverSettings.settings.showClockClosebutton || !queryDict['showClockClosebutton']) {
$('#close').css('display', 'none');
}

// defined in the template this is loaded into
// eslint-disable-next-line no-undef
if (clockFace == 'clock-color') {
if (clockFace === 'clock-color') {

var bgHigh = window.serverSettings.settings.thresholds.bgHigh;
var bgLow = window.serverSettings.settings.thresholds.bgLow;
Expand Down Expand Up @@ -138,12 +155,12 @@ client.render = function render (xhr) {
$('#arrow').css('filter', 'brightness(100%)');
}
}
}
};

client.init = function init () {
console.log('init');
client.query();
setInterval(client.query, 1 * 60 * 1000);
}
};

module.exports = client;
module.exports = client;
15 changes: 14 additions & 1 deletion lib/client/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,20 @@ client.init = function init (callback) {
console.log('Already tried to get settings after auth, but failed');
} else {
client.settingsFailed = true;
language.set('en');

// detect browser language
var lang = Storages.localStorage.get('language') || (navigator.language || navigator.userLanguage).toLowerCase();
if (lang !== 'zh_cn' && lang !== 'zh-cn' && lang !== 'zh_tw' && lang !== 'zh-tw') {
lang = lang.substring(0, 2);
} else {
lang = lang.replace('-', '_');
}
if (language.languages.find(l => l.code === lang)) {
language.set(lang);
} else {
language.set('en');
}

client.translate = language.translate;
// auth failed, hide loader and request for key
$('#centerMessagePanel').hide();
Expand Down
2 changes: 1 addition & 1 deletion lib/client/renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -938,7 +938,7 @@ function init (client, d3) {
var lastbasal = 0;

if (!profile.activeProfileToTime(from)) {
window.alert(translate('Wrong profile setting.\nNo profile defined to displayed time.\nRedirecting to profile editor to create new profile.'));
window.alert(translate('Redirecting you to the Profile Editor to create a new profile.'));
try {
window.location.href = '/profile';
} catch (err) {
Expand Down
20 changes: 11 additions & 9 deletions lib/hashauth.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ hashauth.init = function init(client, $) {
});
return hashauth;
};

hashauth.removeAuthentication = function removeAuthentication(event) {

Storages.localStorage.remove('apisecrethash');
Expand All @@ -74,16 +74,18 @@ hashauth.init = function init(client, $) {
}
return false;
};

hashauth.requestAuthentication = function requestAuthentication (eventOrNext) {
var translate = client.translate;
hashauth.injectHtml();
$( '#requestauthenticationdialog' ).dialog({
width: 350
, height: 240
width: 400
, height: 270
, closeText: ''
, buttons: [
{
text: translate('Update')
id: 'requestauthenticationdialog-btn'
, text: translate('Update')
, click: function() {
var dialog = this;
hashauth.processSecret($('#apisecret').val(), $('#storeapisecret').is(':checked'), function done (close) {
Expand All @@ -102,9 +104,9 @@ hashauth.init = function init(client, $) {
}
]
, open: function open ( ) {
$('#requestauthenticationdialog').keypress(function pressed (e) {
$('#apisecret').off('keyup').on('keyup' ,function pressed (e) {
if (e.keyCode === $.ui.keyCode.ENTER) {
$(this).parent().find('button.ui-button-text-only').trigger('click');
$('#requestauthenticationdialog-btn').trigger('click');
}
});
$('#apisecret').val('').focus();
Expand All @@ -117,7 +119,7 @@ hashauth.init = function init(client, $) {
}
return false;
};

hashauth.processSecret = function processSecret(apisecret, storeapisecret, callback) {
var translate = client.translate;

Expand Down Expand Up @@ -170,7 +172,7 @@ hashauth.init = function init(client, $) {
var html =
'<div id="requestauthenticationdialog" style="display:none" title="'+translate('Device authentication')+'">'+
'<label for="apisecret">'+translate('Your API secret')+': </label>'+
'<input type="password" id="apisecret" size="20" />'+
'<input type="password" id="apisecret" size="20" style="width: 100%;"/>'+
'<br>'+
'<input type="checkbox" id="storeapisecret" /> <label for="storeapisecret">'+translate('Store hash on this computer (Use only on private computers)')+'</label>'+
'<div id="apisecrethash">'+
Expand Down
38 changes: 11 additions & 27 deletions lib/language.js
Original file line number Diff line number Diff line change
Expand Up @@ -9735,36 +9735,12 @@ function init() {
,tr: 'Veri profili değişikliği yükleniyor'
,zh_cn: '载入配置文件交换数据'
}
,'Profile is going to be saved in newer format used in Nightscout 0.9.0 and above and will not be usable in older versions anymore.\nAre you sure?' : {
cs: 'Profil bude uložen v novějším formátu používaném v Nightscoutu 0.9.0 a novějších. Již nebude použitelný se starší verzí.\nJste si jistý?'
,he: 'הפרופיל עומד להישמר בתבנית חדשה יותר בשימוש ב- Nightscout 0.9.0 ומעלה ולא יהיה ניתן להשתמש בו בגרסאות ישנות יותר. \n האם אתה בטוח? '
,el: 'Το προφίλ πρόκειται να αποθηκευτεί με τη νέα του μορφή (έκδοση Nighscout 0.9.0 και πάνω) και δεν πρόκειται να μπορεί να χρησιμοποιηθεί σε παλαιότερες εκδόσεις. \nΕίστε σίγουροι?'
,fr: 'Le profil va être sauvegardé dans un nouveau format utilisé par Nightscout 0.9.0 et suivants, et il ne pourra plus être utilisé par les versions antérieures. \nÊtes-vous sûr?'
,ro: 'Profilul va fi salvat într-un format nou, folosit în Nightscout 0.9.0 și superior și nu va mai fi posibilă folosirea pentru versiunile mai vechi.\nSunteți de acord?'
,de: 'Profil wird in einem neuem Format für Nightscout 0.9.0 und höher gespeichert und ist in älteren Versionen nicht mehr nutzbar. Sind Sie sicher?'
,dk: 'Profilen gemmes i et nyere format som ikke kommer til at virke med tidligere versioner af Nightscout (<0.9.0). \nEr du sikker?'
,es: 'El perfil se guarda en un nuevo formato para Nightscout 0.9.0 y superior y ya no se puede usar en versiones anteriores. Estas seguro?'
,sv: 'Profilen sparas i ett nyare format som ej kommer fungera i tidigare versioner av Nightscout (<0.9.0). \nÄr du säker?'
,nb: 'Profilen lagres i ett nyere format som ikke kommer til å fungera i tidigere versioner av Nightscout (<0.9.0). \nEr du sikker?'
,bg: 'Профилът ще бъде запаметен в нов формат, който се ползва от Nightscout 0.9.0 и нагоре и няма да бъде съвместим с по-стари версии. \nСигурен ли си ?'
,hr: 'Profil će biti spremljen u novijem formatu korištenom u Nightscout 0.9.0 i kasnije te neće više biti upotrebljiv u starijim verzijama.\nJeste li sigurni?'
,fi: 'Profiili tallennetaan uuteen Nightscout 0.9.0 käyttämään muotoon, eikä sitä voi enää käyttää vanhempien versioiden kanssa.\nOletko varma?'
,ru: 'Профиль будет сохранен в более позднем формате Nightscout 0.9.0 и выше и не сможет более использоваться в старых версиях. Вы согласны? '
,sk: 'Profil bude uložený v novšom formáte používanom od verzie Nightscout 0.9.0 a novších. Nebude už použiteľný v starších verziách.\nSte si istý?'
,pl: 'Dane profilu będą zapisane w nowym formacie Nighscout 0.9.0 i wyższym. Dane te nie będa mogły być użyte w starszych wersjach.\nJesteś pewien?'
,pt: 'O perfil será salvo no novo format usado no Nightscout 0.9.0 e acima e não será mais utilizado em versões mais antigas. \nTem certeza de que quer fazer isso?'
,ko: '프로파일은 Nightscout 0.9.0 에서 새로운 형식으로 저장될 예정입니다. 구버전은 더이상 사용되지 않을 예정입니다. 확인 하셨습니까?'
,it: 'Profilo sta per essere salvato nel formato più recente utilizzato in Nightscout 0.9.0 e/o superiori e non sarà più possibile utilizzarlo nelle versioni precedenti. \nSei sicuro?'
,nl: 'Profiel wordt opgeslagen in een nieuw formaat dat gebruikt wordt vanaf Nightscout 0.9.0 hierdoor is deze niet meer bruikbaar voor oudere versies. \nWil je doorgaan?'
,tr: 'Profil, Nightscout 0.9.0 ve sonraki sürümlerinde kullanılan daha yeni bir formatta kaydedilecek ve artık eski sürümlerde kullanılamayacaktır.\nemin misiniz?'
,zh_cn: '配置文件将使用0.9.0版本之后的新格式保存,旧版本程序将无法使用。\n你确定吗?'
}
,'Wrong profile setting.\nNo profile defined to displayed time.\nRedirecting to profile editor to create new profile.' : {
,'Redirecting you to the Profile Editor to create a new profile.' : {
cs: 'Chybě nastavený profil.\nNení definovaný žádný platný profil k času zobrazení.\nProvádím přesměrování na editor profilu.'
,he: 'הגדרת פרופיל שגוי. \n פרופיל מוגדר לזמן המוצג. מפנה מחדש לעורך פרופיל כדי ליצור פרופיל חדש. '
,el: 'Λάθος προφίλ. Παρακαλώ δημιουργήστε ένα νέο προφίλ'
,fr: 'Erreur de réglage de profil. \nAucun profil défini pour indiquer l\'heure. \nRedirection vers la création d\'un nouveau profil. '
,de: 'Falsche Profileinstellung.\nKein Profil festgelegt zur angezeigten Zeit.\n Weiter zum Profileditor, um ein neues Profil zu erstellen.'
,de: 'Sie werden zum Profil-Editor weitergeleitet, um ein neues Profil anzulegen.'
,dk: 'Forkert profilindstilling.\nIngen profil defineret til at vise tid.\nOmdirigere til profil editoren for at lave en ny profil.'
,es: 'Configuración incorrecta del perfil. \n No establecido ningún perfil en el tiempo mostrado. \n Continuar en editor de perfil para crear perfil nuevo.'
,bg: 'Грешни настройки на профила. \nНяма определен профил към избраното време. \nПрепращане към редактора на профила, за създаване на нов профил.'
Expand Down Expand Up @@ -14066,24 +14042,32 @@ function init() {
},
'Protein': {
fi: 'Proteiini'
, de: 'Protein'
},
'Fat': {
fi: 'Rasva'
, de: 'Fett'
},
'Protein average': {
fi: 'Proteiini keskiarvo'
, de: 'Proteine Durchschnitt'
},
'Fat average': {
fi: 'Rasva keskiarvo'
, de: 'Fett Durchschnitt'

},
'Total carbs': {
fi: 'Hiilihydraatit yhteensä'
, de: 'Kohlenhydrate gesamt'
},
'Total protein': {
fi: 'Proteiini yhteensä'
, de: 'Protein gesamt'
},
'Total fat': {
fi: 'Rasva yhteensä'
, de: 'Fett gesamt'
}
};

Expand Down Expand Up @@ -14143,7 +14127,7 @@ function init() {
language.lang = newlang;

language.languages.forEach(function (l) {
if (l.code == language.lang && l.speechCode) language.speechCode = l.speechCode;
if (l.code === language.lang && l.speechCode) language.speechCode = l.speechCode;
});

return language();
Expand Down
46 changes: 34 additions & 12 deletions views/clockviews/shared.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="apple-mobile-web-app-capable" content="yes">

<title>Nightscout</title>

<link href="/images/round1.png" rel="icon" id="favicon" type="image/png" />
<link rel="apple-touch-icon" sizes="57x57" href="/images/apple-touch-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="/images/apple-touch-icon-60x60.png">
Expand All @@ -16,11 +16,11 @@
<link rel="apple-touch-icon" sizes="144x144" href="/images/apple-touch-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="/images/apple-touch-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-180x180.png">

<style type="text/css">
@import url("//fonts.googleapis.com/css?family=Open+Sans:700");
@import url("//fonts.googleapis.com/css?family=Open+Sans:700");
<%- include(face + '.css', {}); %>

</style>
</head>

Expand All @@ -30,19 +30,41 @@
<div class="inner">
<div id="trend">
<div id="bgnow"></div>
<div id="arrowDiv"><img id="arrow" src=""/></div>
<div id="arrowDiv"><img id="arrow" src="" alt="arrow"/></div>
</div>
<div id="clock"></div>
<div id="staleTime"></div>
</div>
</main>

<script src="/api/v1/status.js"></script>
<script src="<%= locals.bundle %>/js/bundle.clock.js?v=<%= locals.cachebuster %>"></script>

<script type="text/javascript">
let clockFace = "<%= face %>"; // can now be used in scripts
window.Nightscout.client.init( );
var clockFace = "<%= face %>"; // can now be used in scripts

var parts = (location.search || '?').substring(1).split('&');
var token = '';
parts.forEach(function (val) {
if (val.startsWith('token=')) {
token = val.substring('token='.length);
}
});

var secret = typeof localStorage !== 'undefined' ? localStorage.getItem('apisecrethash') : '';
var src = '/api/v1/status.js?t=' + Date.now();

if (secret) {
src += '&secret=' + secret;
} else if (token) {
src += '&token=' + token;
}

var script = document.createElement('script');
script.onload = function () {
window.Nightscout.client.init( );
};
script.src = src;

document.head.appendChild(script); //or something of the likes
</script>
</body>
</html>
</html>

0 comments on commit 2379706

Please sign in to comment.