notifications.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. /*
  2. ArozOS Desktop - Notifications and calendar
  3. The panel the tray clock opens: a column of two cards at the bottom
  4. right, the notifications (newest first, each with its relative time) and
  5. a month calendar that opens the Calendar app on a day. Also desktop
  6. notifications sent by WebApps (sendNotification), server side
  7. notifications polled from /system/notification and the transient toasts
  8. and browser push messages.
  9. Kept for other code: toggleNotification(action), sendNotification(title,
  10. content, icon, windowOpenOption), openNotification, closeThisNotification,
  11. clearAllNotification, and the .notification.object class the tray clock
  12. counts for its dot (updateClockTime in dock.js).
  13. Part of desktop.html, see README.md in this folder for the load order.
  14. */
  15. //Open ("show"), close ("hide") or flip the notification and calendar panel
  16. function toggleNotification(action=undefined){
  17. var panel = $(".notificationbar");
  18. if (action == undefined && typeof trayToggleAllowed == "function" && !trayToggleAllowed("notifications")){
  19. return;
  20. }
  21. var open = (action == "show") || (action == undefined && !panel.is(":visible"));
  22. if (!open){
  23. panel.stop(true, true).fadeOut(120);
  24. return;
  25. }
  26. if (typeof trayClosePanels == "function"){
  27. trayClosePanels(".notificationbar");
  28. }
  29. ncCalendarMonth = null;
  30. ncRenderCalendar();
  31. ncUpdateTimes();
  32. ncUpdateHeader();
  33. $("#ncOpenCalendar").toggle(getModuleInfoFromName("Calendar") != false);
  34. panel.stop(true, true).fadeIn(120);
  35. }
  36. /*
  37. Notification and Notification bar related functions
  38. Usage:
  39. title -> The title of the notification
  40. content -> The content of the notification
  41. icon (optional) -> The icon of the notification
  42. windowOpenOption (optional) -> The window opening option for user onclick redirection
  43. */
  44. function sendNotification(title, content, icon="info circle", windowOpenOption=null){
  45. content = String(content);
  46. var shortenContent = content.length > 300 ? content.substring(0, 300) + "..." : content;
  47. var onClickOpenWindowOption = encodeURIComponent(JSON.parse(windowOpenOption));
  48. var card = $('<div class="notification object" onclick="openNotification(this);">' +
  49. '<div class="notifyIcon"><i class="icon"></i></div>' +
  50. '<div class="notifyBody"><div class="notifyHead"><span class="title"></span><span class="notifyTime"></span></div>' +
  51. '<div class="notifycontent"></div></div>' +
  52. '<div class="closebtn" onclick="event.stopImmediatePropagation(); closeThisNotification(this);"><i class="close icon"></i></div>' +
  53. '</div>');
  54. card.attr({"originalcontent": content, "redirect": onClickOpenWindowOption, "data-time": Date.now()});
  55. card.find(".notifyIcon i").addClass(icon);
  56. //Callers pass text, already escaped where it comes from the server
  57. card.find(".title").html(title);
  58. card.find(".notifycontent").html(shortenContent);
  59. $("#notificationlist").prepend(card);
  60. $(".nonotification").hide();
  61. ncUpdateTimes();
  62. ncUpdateHeader();
  63. updateClockTime();
  64. }
  65. function openNotification(obj){
  66. newWindowOpeningOption = JSON.parse(decodeURIComponent($(obj).attr("redirect")));
  67. if (newWindowOpeningOption == null){
  68. //Ignore
  69. }else{
  70. //Start a floatWindow to the given target
  71. newFloatWindow(newWindowOpeningOption);
  72. toggleNotification("hide");
  73. }
  74. //Clear the notiication
  75. closeThisNotification($(obj).find(".closebtn"));
  76. }
  77. function closeThisNotification(obj){
  78. $(obj).parent().slideUp(150, function(){
  79. $(this).remove();
  80. if ($(".notification.object").length == 0){
  81. $(".nonotification").show();
  82. }
  83. ncUpdateHeader();
  84. updateClockTime();
  85. });
  86. }
  87. function clearAllNotification(){
  88. var cards = $(".notification.object");
  89. if (cards.length == 0){
  90. return;
  91. }
  92. cards.slideUp(150).promise().done(function(){
  93. cards.remove();
  94. $(".nonotification").show();
  95. ncUpdateHeader();
  96. updateClockTime();
  97. });
  98. }
  99. //"Clear All" only when there is something to clear
  100. function ncUpdateHeader(){
  101. $(".notificationbar .clearall").toggle($(".notification.object").length > 0);
  102. }
  103. /*
  104. Relative times on the cards ("now", "5 minutes ago"), in the user's language
  105. */
  106. function ncLanguage(){
  107. if (typeof applocale != "undefined" && applocale.lang){
  108. return applocale.lang;
  109. }
  110. return navigator.language || "en";
  111. }
  112. function ncRelativeTime(timestamp){
  113. var seconds = Math.round((timestamp - Date.now()) / 1000);
  114. try {
  115. var rtf = new Intl.RelativeTimeFormat(ncLanguage(), {numeric: "auto"});
  116. if (Math.abs(seconds) < 60){
  117. return rtf.format(0, "second");
  118. }
  119. var minutes = Math.round(seconds / 60);
  120. if (Math.abs(minutes) < 60){
  121. return rtf.format(minutes, "minute");
  122. }
  123. var hours = Math.round(minutes / 60);
  124. if (Math.abs(hours) < 24){
  125. return rtf.format(hours, "hour");
  126. }
  127. return rtf.format(Math.round(hours / 24), "day");
  128. } catch (ex) {
  129. return new Date(timestamp).toLocaleTimeString();
  130. }
  131. }
  132. function ncUpdateTimes(){
  133. $("#notificationlist .notification.object").each(function(){
  134. var time = parseInt($(this).attr("data-time"));
  135. if (!isNaN(time)){
  136. $(this).find(".notifyTime").text(ncRelativeTime(time));
  137. }
  138. });
  139. }
  140. setInterval(function(){
  141. if ($(".notificationbar").is(":visible")){
  142. ncUpdateTimes();
  143. }
  144. }, 30000);
  145. /*
  146. Calendar card: today's date and a month grid, weeks starting on Sunday,
  147. names from the browser in the user's language. A day opens the Calendar
  148. app on that day (it reads {"date": "YYYY-MM-DD", "view": "day"} from its
  149. URL hash); without the app the days are only shown.
  150. */
  151. var ncCalendarMonth = null; //First day of the month on screen, null for this month
  152. function ncDateKey(date){
  153. return date.getFullYear() + "-" + zeropad(date.getMonth() + 1, 2) + "-" + zeropad(date.getDate(), 2);
  154. }
  155. function ncRenderCalendar(){
  156. var today = new Date();
  157. if (ncCalendarMonth == null){
  158. ncCalendarMonth = new Date(today.getFullYear(), today.getMonth(), 1);
  159. }
  160. var lang = ncLanguage();
  161. var format = function(date, options){
  162. try {
  163. return date.toLocaleDateString(lang, options);
  164. } catch (ex) {
  165. return date.toLocaleDateString(undefined, options);
  166. }
  167. };
  168. $("#ncWeekday").text(format(today, {weekday: "long"}));
  169. $("#ncDate").text(format(today, {year: "numeric", month: "long", day: "numeric"}));
  170. $("#ncMonthLabel").text(format(ncCalendarMonth, {year: "numeric", month: "long"}));
  171. var hasCalendarApp = getModuleInfoFromName("Calendar") != false;
  172. var grid = $("#ncDays").empty().toggleClass("clickable", hasCalendarApp);
  173. for (var i = 0; i < 7; i++){
  174. //2023-01-01 was a Sunday
  175. grid.append($('<div class="ncWeekday"></div>').text(format(new Date(2023, 0, 1 + i), {weekday: "narrow"})));
  176. }
  177. var first = ncCalendarMonth;
  178. var start = new Date(first.getFullYear(), first.getMonth(), 1 - first.getDay());
  179. var todayKey = ncDateKey(today);
  180. //Always six weeks, so the card keeps its height from month to month
  181. for (var d = 0; d < 42; d++){
  182. var day = new Date(start.getFullYear(), start.getMonth(), start.getDate() + d);
  183. var cell = $('<div class="ncDay"></div>').text(day.getDate());
  184. cell.attr({"data-date": ncDateKey(day), "title": format(day, {year: "numeric", month: "long", day: "numeric"})});
  185. cell.toggleClass("otherMonth", day.getMonth() != first.getMonth());
  186. cell.toggleClass("today", ncDateKey(day) == todayKey);
  187. grid.append(cell);
  188. }
  189. }
  190. function ncShiftMonth(delta){
  191. if (ncCalendarMonth == null){
  192. var today = new Date();
  193. ncCalendarMonth = new Date(today.getFullYear(), today.getMonth(), 1);
  194. }
  195. ncCalendarMonth = new Date(ncCalendarMonth.getFullYear(), ncCalendarMonth.getMonth() + delta, 1);
  196. ncRenderCalendar();
  197. }
  198. //Open the Calendar app, on a day (YYYY-MM-DD) when one is given
  199. function ncOpenCalendar(dateKey){
  200. var mod = getModuleInfoFromName("Calendar");
  201. if (!mod){
  202. return;
  203. }
  204. var url = (mod.SupportFW && mod.LaunchFWDir) ? mod.LaunchFWDir : mod.StartDir;
  205. if (dateKey){
  206. url += "#" + encodeURIComponent(JSON.stringify({date: dateKey, view: "day"}));
  207. }
  208. var size = (mod.SupportFW && Array.isArray(mod.InitFWSize)) ? mod.InitFWSize : [undefined, undefined];
  209. toggleNotification("hide");
  210. newFloatWindow({
  211. url: url,
  212. width: size[0],
  213. height: size[1],
  214. appicon: mod.IconPath || "img/system/favicon.png",
  215. title: mod.Name
  216. });
  217. }
  218. $("#ncPrevMonth").on("click", function(){ ncShiftMonth(-1); });
  219. $("#ncNextMonth").on("click", function(){ ncShiftMonth(1); });
  220. //The month label brings the calendar back to this month
  221. $("#ncMonthLabel").on("click", function(){
  222. ncCalendarMonth = null;
  223. ncRenderCalendar();
  224. });
  225. $("#ncDays").on("click", ".ncDay", function(){
  226. ncOpenCalendar($(this).attr("data-date"));
  227. });
  228. $("#ncOpenCalendar").on("click", function(){
  229. ncOpenCalendar();
  230. });
  231. /*
  232. Server-side notification delivery (Notification Agent: desktop)
  233. The desktop notification agent (mod/notification/agents/desktopn)
  234. buffers notifications for this user on the server. We poll it on a
  235. timer and, for each new one, add it to the notification list, show a
  236. transient toast, and — only when this page is not focused — raise a
  237. browser (Chrome) push notification instead.
  238. */
  239. var arozNotificationSeenIds = {};
  240. var arozNotificationPollTimer = null;
  241. function arozNotificationIcon(priority){
  242. switch (String(priority || "").toLowerCase()){
  243. case "high": return "exclamation circle";
  244. case "low": return "info circle";
  245. default: return "bell";
  246. }
  247. }
  248. //pageIsFocused reports whether the desktop tab is currently in the
  249. //foreground, so we can pick a toast (focused) vs a browser push (not).
  250. function pageIsFocused(){
  251. if (typeof document.hidden === "boolean" && document.hidden) return false;
  252. if (typeof document.hasFocus === "function") return document.hasFocus();
  253. return true;
  254. }
  255. function requestDesktopNotificationPermission(){
  256. try {
  257. if (typeof Notification !== "undefined" && Notification.permission === "default"){
  258. Notification.requestPermission();
  259. }
  260. } catch (e) { /* Notification API unavailable */ }
  261. }
  262. //showNotificationToast renders a transient popup in the bottom-right of
  263. //the desktop. It auto-dismisses and can be closed manually.
  264. function showNotificationToast(title, message, priority){
  265. var container = document.getElementById("notificationToastContainer");
  266. if (!container) return;
  267. var p = String(priority || "medium").toLowerCase();
  268. //Use the shared, unit-tested helpers when available, with local fallbacks.
  269. var priorityClass = (typeof NotificationUI !== "undefined")
  270. ? NotificationUI.toastPriorityClass(p)
  271. : ("priority-" + (p === "high" || p === "low" ? p : "medium"));
  272. var durationMs = (typeof NotificationUI !== "undefined")
  273. ? NotificationUI.toastDurationMs(p)
  274. : (p === "high" ? 9000 : 5000);
  275. var toast = document.createElement("div");
  276. toast.className = "notificationToast " + priorityClass;
  277. toast.innerHTML =
  278. '<i class="' + arozNotificationIcon(p) + ' icon toastIcon"></i>' +
  279. '<div class="toastBody">' +
  280. '<p class="toastTitle"></p>' +
  281. '<p class="toastMessage"></p>' +
  282. '</div>' +
  283. '<i class="remove icon toastClose"></i>';
  284. //Assign text via textContent so notification content cannot inject markup.
  285. toast.querySelector(".toastTitle").textContent = title;
  286. toast.querySelector(".toastMessage").textContent = message;
  287. function dismiss(){
  288. toast.classList.remove("show");
  289. setTimeout(function(){ if (toast.parentNode) toast.parentNode.removeChild(toast); }, 300);
  290. }
  291. toast.querySelector(".toastClose").addEventListener("click", dismiss);
  292. toast.addEventListener("click", function(e){
  293. if (e.target && e.target.classList.contains("toastClose")) return;
  294. toggleNotification("show"); //open the full list on click
  295. dismiss();
  296. });
  297. container.appendChild(toast);
  298. //Trigger the enter transition on the next frame.
  299. requestAnimationFrame(function(){ toast.classList.add("show"); });
  300. //Auto dismiss (longer for high priority).
  301. setTimeout(dismiss, durationMs);
  302. }
  303. function showBrowserPush(title, body, priority){
  304. try {
  305. if (typeof Notification !== "undefined" && Notification.permission === "granted"){
  306. var n = new Notification(title, { body: body });
  307. //Focus this tab when the user clicks the OS notification.
  308. n.onclick = function(){ try { window.focus(); } catch (e) {} n.close(); };
  309. //Auto-close low/medium priority pushes so they do not pile up.
  310. if (String(priority).toLowerCase() !== "high"){
  311. setTimeout(function(){ try { n.close(); } catch (e) {} }, 8000);
  312. }
  313. }
  314. } catch (e) { /* ignore push errors */ }
  315. }
  316. function escapeNotificationText(text){
  317. return String(text)
  318. .replace(/&/g, "&amp;").replace(/</g, "&lt;")
  319. .replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
  320. }
  321. function renderServerNotification(item){
  322. if (!item) return;
  323. if (item.id && arozNotificationSeenIds[item.id]) return;
  324. if (item.id) arozNotificationSeenIds[item.id] = true;
  325. var title = item.title || "Notification";
  326. var message = item.message || "";
  327. if (item.sender){
  328. message = message + (message ? " " : "") + "(" + item.sender + ")";
  329. }
  330. //An optional payload carries the float window to open when the
  331. //notification is clicked (e.g. the share link of a file shared
  332. //with this user). sendNotification takes it double encoded.
  333. var clickTarget = null;
  334. if (item.payload){
  335. try {
  336. var openOption = JSON.parse(item.payload);
  337. if (openOption && typeof openOption.url === "string"){
  338. clickTarget = JSON.stringify(JSON.stringify(openOption));
  339. }
  340. } catch (e) { /* not a window option, ignore */ }
  341. }
  342. //Always add it to the persistent notification list. Server text is
  343. //plain text (it can carry file names), so escape it for the list.
  344. sendNotification(escapeNotificationText(title), escapeNotificationText(message), arozNotificationIcon(item.priority), clickTarget);
  345. //Surface it: the in-page toast is shown whether or not the desktop
  346. //is focused, so the notification is never silently swallowed; a
  347. //browser (OS) push is additionally raised only when the desktop is
  348. //not focused, to reach the user when they are looking elsewhere.
  349. var channels = (typeof NotificationUI !== "undefined")
  350. ? NotificationUI.deliveryChannelsForFocus(pageIsFocused())
  351. : (pageIsFocused() ? ["toast"] : ["toast", "push"]);
  352. if (channels.indexOf("toast") >= 0){
  353. showNotificationToast(title, message, item.priority);
  354. }
  355. if (channels.indexOf("push") >= 0){
  356. showBrowserPush(title, message, item.priority);
  357. }
  358. }
  359. function pollServerNotifications(){
  360. $.ajax({
  361. url: "system/notification/desktop/list",
  362. method: "GET",
  363. dataType: "json",
  364. success: function(items){
  365. if (!Array.isArray(items)) return;
  366. items.forEach(renderServerNotification);
  367. },
  368. error: function(){ /* transient; retry on next tick */ }
  369. });
  370. }
  371. function startServerNotificationPolling(){
  372. if (arozNotificationPollTimer !== null) return;
  373. requestDesktopNotificationPermission();
  374. pollServerNotifications();
  375. arozNotificationPollTimer = setInterval(pollServerNotifications, 15000);
  376. }
  377. //Begin polling once the desktop scripts have loaded.
  378. $(document).ready(function(){
  379. startServerNotificationPolling();
  380. });