helpers.js 144 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604
  1. /**
  2. * Copyright (C) 2024 Puter Technologies Inc.
  3. *
  4. * This file is part of Puter.
  5. *
  6. * Puter is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License as published
  8. * by the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Affero General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Affero General Public License
  17. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. */
  19. import path from "./lib/path.js"
  20. import mime from "./lib/mime.js";
  21. import UIAlert from './UI/UIAlert.js'
  22. import UIItem from './UI/UIItem.js'
  23. import UIWindow from './UI/UIWindow.js'
  24. import UIWindowLogin from './UI/UIWindowLogin.js';
  25. import UIWindowSaveAccount from './UI/UIWindowSaveAccount.js';
  26. import update_username_in_gui from './helpers/update_username_in_gui.js';
  27. import update_title_based_on_uploads from './helpers/update_title_based_on_uploads.js';
  28. import content_type_to_icon from './helpers/content_type_to_icon.js';
  29. import truncate_filename from './helpers/truncate_filename.js';
  30. import { PROCESS_RUNNING, PortalProcess, PseudoProcess } from "./definitions.js";
  31. import UIWindowProgress from './UI/UIWindowProgress.js';
  32. window.is_auth = ()=>{
  33. if(localStorage.getItem("auth_token") === null || window.auth_token === null)
  34. return false;
  35. else
  36. return true;
  37. }
  38. window.suggest_apps_for_fsentry = async (options)=>{
  39. let res = await $.ajax({
  40. url: window.api_origin + "/suggest_apps",
  41. type: 'POST',
  42. contentType: "application/json",
  43. data: JSON.stringify({
  44. uid: options.uid ?? undefined,
  45. path: options.path ?? undefined,
  46. }),
  47. headers: {
  48. "Authorization": "Bearer "+window.auth_token
  49. },
  50. statusCode: {
  51. 401: function () {
  52. window.logout();
  53. },
  54. },
  55. success: function (res){
  56. if(options.onSuccess && typeof options.onSuccess == "function")
  57. options.onSuccess(res);
  58. }
  59. });
  60. return res;
  61. }
  62. /**
  63. * Formats a binary-byte integer into the human-readable form with units.
  64. *
  65. * @param {integer} bytes
  66. * @returns
  67. */
  68. window.byte_format = (bytes)=>{
  69. const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
  70. if (bytes === 0) return '0 Byte';
  71. const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
  72. return (bytes / Math.pow(1024, i)).toFixed(2) + ' ' + sizes[i];
  73. };
  74. /**
  75. * A function that generates a UUID (Universally Unique Identifier) using the version 4 format,
  76. * which are random UUIDs. It uses the cryptographic number generator available in modern browsers.
  77. *
  78. * The generated UUID is a 36 character string (32 alphanumeric characters separated by 4 hyphens).
  79. * It follows the pattern: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx, where x is any hexadecimal digit
  80. * and y is one of 8, 9, A, or B.
  81. *
  82. * @returns {string} Returns a new UUID v4 string.
  83. *
  84. * @example
  85. *
  86. * let id = window.uuidv4(); // Generate a new UUID
  87. *
  88. */
  89. window.uuidv4 = ()=>{
  90. return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
  91. (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
  92. );
  93. }
  94. /**
  95. * Checks if the provided string is a valid email format.
  96. *
  97. * @function
  98. * @global
  99. * @param {string} email - The email string to be validated.
  100. * @returns {boolean} `true` if the email is valid, otherwise `false`.
  101. * @example
  102. * window.is_email("test@example.com"); // true
  103. * window.is_email("invalid-email"); // false
  104. */
  105. window.is_email = (email) => {
  106. const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  107. return re.test(String(email).toLowerCase());
  108. }
  109. /**
  110. * A function that scrolls the parent element so that the child element is in view.
  111. * If the child element is already in view, no scrolling occurs.
  112. * The function decides the best scroll direction based on which requires the smaller adjustment.
  113. *
  114. * @param {HTMLElement} parent - The parent HTML element that might be scrolled.
  115. * @param {HTMLElement} child - The child HTML element that should be made viewable.
  116. *
  117. * @returns {void}
  118. *
  119. * @example
  120. *
  121. * let parentElem = document.querySelector('#parent');
  122. * let childElem = document.querySelector('#child');
  123. * window.scrollParentToChild(parentElem, childElem);
  124. * // Scrolls parentElem so that childElem is in view
  125. *
  126. */
  127. window.scrollParentToChild = (parent, child)=>{
  128. // Where is the parent on page
  129. var parentRect = parent.getBoundingClientRect();
  130. // What can you see?
  131. var parentViewableArea = {
  132. height: parent.clientHeight,
  133. width: parent.clientWidth
  134. };
  135. // Where is the child
  136. var childRect = child.getBoundingClientRect();
  137. // Is the child viewable?
  138. var isViewable = (childRect.top >= parentRect.top) && (childRect.bottom <= parentRect.top + parentViewableArea.height);
  139. // if you can't see the child try to scroll parent
  140. if (!isViewable) {
  141. // Should we scroll using top or bottom? Find the smaller ABS adjustment
  142. const scrollTop = childRect.top - parentRect.top;
  143. const scrollBot = childRect.bottom - parentRect.bottom;
  144. if (Math.abs(scrollTop) < Math.abs(scrollBot)) {
  145. // we're near the top of the list
  146. parent.scrollTop += (scrollTop + 80);
  147. } else {
  148. // we're near the bottom of the list
  149. parent.scrollTop += (scrollBot + 80);
  150. }
  151. }
  152. }
  153. window.getItem = async function(options){
  154. return $.ajax({
  155. url: window.api_origin + "/getItem",
  156. type: 'POST',
  157. data: JSON.stringify({
  158. key: options.key,
  159. app: options.app_uid,
  160. }),
  161. async: true,
  162. contentType: "application/json",
  163. headers: {
  164. "Authorization": "Bearer "+window.auth_token
  165. },
  166. statusCode: {
  167. 401: function () {
  168. window.logout();
  169. },
  170. },
  171. success: function (result){
  172. if(options.success && typeof(options.success) === "function")
  173. options.success(result);
  174. }
  175. })
  176. }
  177. window.setItem = async function(options){
  178. return $.ajax({
  179. url: window.api_origin + "/setItem",
  180. type: 'POST',
  181. data: JSON.stringify({
  182. app: options.app_uid,
  183. key: options.key,
  184. value: options.value,
  185. }),
  186. async: true,
  187. contentType: "application/json",
  188. headers: {
  189. "Authorization": "Bearer "+window.auth_token
  190. },
  191. statusCode: {
  192. 401: function () {
  193. window.logout();
  194. },
  195. },
  196. success: function (fsentry){
  197. if(options.success && typeof(options.success) === "function")
  198. options.success(fsentry)
  199. }
  200. })
  201. }
  202. /**
  203. * Converts a glob pattern to a regular expression, with optional extended or globstar matching.
  204. *
  205. * @param {string} glob - The glob pattern to convert.
  206. * @param {Object} [opts] - Optional options for the conversion.
  207. * @param {boolean} [opts.extended=false] - If true, enables extended matching with single character matching, character ranges, group matching, etc.
  208. * @param {boolean} [opts.globstar=false] - If true, uses globstar matching, where '*' matches zero or more path segments.
  209. * @param {string} [opts.flags] - Regular expression flags to include (e.g., 'i' for case-insensitive).
  210. * @returns {RegExp} The generated regular expression.
  211. * @throws {TypeError} If the provided glob pattern is not a string.
  212. */
  213. window.globToRegExp = function (glob, opts) {
  214. if (typeof glob !== 'string') {
  215. throw new TypeError('Expected a string');
  216. }
  217. var str = String(glob);
  218. // The regexp we are building, as a string.
  219. var reStr = "";
  220. // Whether we are matching so called "extended" globs (like bash) and should
  221. // support single character matching, matching ranges of characters, group
  222. // matching, etc.
  223. var extended = opts ? !!opts.extended : false;
  224. // When globstar is _false_ (default), '/foo/*' is translated a regexp like
  225. // '^\/foo\/.*$' which will match any string beginning with '/foo/'
  226. // When globstar is _true_, '/foo/*' is translated to regexp like
  227. // '^\/foo\/[^/]*$' which will match any string beginning with '/foo/' BUT
  228. // which does not have a '/' to the right of it.
  229. // E.g. with '/foo/*' these will match: '/foo/bar', '/foo/bar.txt' but
  230. // these will not '/foo/bar/baz', '/foo/bar/baz.txt'
  231. // Lastely, when globstar is _true_, '/foo/**' is equivelant to '/foo/*' when
  232. // globstar is _false_
  233. var globstar = opts ? !!opts.globstar : false;
  234. // If we are doing extended matching, this boolean is true when we are inside
  235. // a group (eg {*.html,*.js}), and false otherwise.
  236. var inGroup = false;
  237. // RegExp flags (eg "i" ) to pass in to RegExp constructor.
  238. var flags = opts && typeof (opts.flags) === "string" ? opts.flags : "";
  239. var c;
  240. for (var i = 0, len = str.length; i < len; i++) {
  241. c = str[i];
  242. switch (c) {
  243. case "/":
  244. case "$":
  245. case "^":
  246. case "+":
  247. case ".":
  248. case "(":
  249. case ")":
  250. case "=":
  251. case "!":
  252. case "|":
  253. reStr += "\\" + c;
  254. break;
  255. case "?":
  256. if (extended) {
  257. reStr += ".";
  258. break;
  259. }
  260. // fallthrough
  261. case "[":
  262. case "]":
  263. if (extended) {
  264. reStr += c;
  265. break;
  266. }
  267. // fallthrough
  268. case "{":
  269. if (extended) {
  270. inGroup = true;
  271. reStr += "(";
  272. break;
  273. }
  274. // fallthrough
  275. case "}":
  276. if (extended) {
  277. inGroup = false;
  278. reStr += ")";
  279. break;
  280. }
  281. // fallthrough
  282. case ",":
  283. if (inGroup) {
  284. reStr += "|";
  285. break;
  286. }
  287. reStr += "\\" + c;
  288. break;
  289. case "*":
  290. // Move over all consecutive "*"'s.
  291. // Also store the previous and next characters
  292. var prevChar = str[i - 1];
  293. var starCount = 1;
  294. while (str[i + 1] === "*") {
  295. starCount++;
  296. i++;
  297. }
  298. var nextChar = str[i + 1];
  299. if (!globstar) {
  300. // globstar is disabled, so treat any number of "*" as one
  301. reStr += ".*";
  302. } else {
  303. // globstar is enabled, so determine if this is a globstar segment
  304. var isGlobstar = starCount > 1 // multiple "*"'s
  305. && (prevChar === "/" || prevChar === undefined) // from the start of the segment
  306. && (nextChar === "/" || nextChar === undefined) // to the end of the segment
  307. if (isGlobstar) {
  308. // it's a globstar, so match zero or more path segments
  309. reStr += "((?:[^/]*(?:/|$))*)";
  310. i++; // move over the "/"
  311. } else {
  312. // it's not a globstar, so only match one path segment
  313. reStr += "([^/]*)";
  314. }
  315. }
  316. break;
  317. default:
  318. reStr += c;
  319. }
  320. }
  321. // When regexp 'g' flag is specified don't
  322. // constrain the regular expression with ^ & $
  323. if (!flags || !~flags.indexOf('g')) {
  324. reStr = "^" + reStr + "$";
  325. }
  326. return new RegExp(reStr, flags);
  327. };
  328. /**
  329. * Validates the provided file system entry name.
  330. *
  331. * @function validate_fsentry_name
  332. * @memberof window
  333. * @param {string} name - The name of the file system entry to validate.
  334. * @returns {boolean} Returns true if the name is valid.
  335. * @throws {Object} Throws an object with a `message` property indicating the specific validation error.
  336. *
  337. * @description
  338. * This function checks the provided name against a set of rules to determine its validity as a file system entry name:
  339. * 1. Name cannot be empty.
  340. * 2. Name must be a string.
  341. * 3. Name cannot contain the '/' character.
  342. * 4. Name cannot be the '.' character.
  343. * 5. Name cannot be the '..' character.
  344. * 6. Name cannot exceed the maximum allowed length (as defined in window.max_item_name_length).
  345. */
  346. window.validate_fsentry_name = function(name){
  347. if(!name)
  348. throw {message: i18n('name_cannot_be_empty')}
  349. else if(!window.isString(name))
  350. throw {message: i18n('name_must_be_string')}
  351. else if(name.includes('/'))
  352. throw {message: i18n('name_cannot_contain_slash')}
  353. else if(name === '.')
  354. throw {message: i18n('name_cannot_contain_period')};
  355. else if(name === '..')
  356. throw {message: i18n('name_cannot_contain_double_period')};
  357. else if(name.length > window.max_item_name_length)
  358. throw {message: i18n('name_too_long', window.max_item_name_length)}
  359. else
  360. return true
  361. }
  362. /**
  363. * A function that generates a unique identifier by combining a random adjective, a random noun, and a random number (between 0 and 9999).
  364. * The result is returned as a string with components separated by hyphens.
  365. * It is useful when you need to create unique identifiers that are also human-friendly.
  366. *
  367. * @returns {string} A unique, hyphen-separated string comprising of an adjective, a noun, and a number.
  368. *
  369. * @example
  370. *
  371. * let identifier = window.generate_identifier();
  372. * // identifier would be something like 'clever-idea-123'
  373. *
  374. */
  375. window.generate_identifier = function(){
  376. const first_adj = ['helpful','sensible', 'loyal', 'honest', 'clever', 'capable','calm', 'smart', 'genius', 'bright', 'charming', 'creative', 'diligent', 'elegant', 'fancy',
  377. 'colorful', 'avid', 'active', 'gentle', 'happy', 'intelligent', 'jolly', 'kind', 'lively', 'merry', 'nice', 'optimistic', 'polite',
  378. 'quiet', 'relaxed', 'silly', 'victorious', 'witty', 'young', 'zealous', 'strong', 'brave', 'agile', 'bold'];
  379. const nouns = ['street', 'roof', 'floor', 'tv', 'idea', 'morning', 'game', 'wheel', 'shoe', 'bag', 'clock', 'pencil', 'pen',
  380. 'magnet', 'chair', 'table', 'house', 'dog', 'room', 'book', 'car', 'cat', 'tree',
  381. 'flower', 'bird', 'fish', 'sun', 'moon', 'star', 'cloud', 'rain', 'snow', 'wind', 'mountain',
  382. 'river', 'lake', 'sea', 'ocean', 'island', 'bridge', 'road', 'train', 'plane', 'ship', 'bicycle',
  383. 'horse', 'elephant', 'lion', 'tiger', 'bear', 'zebra', 'giraffe', 'monkey', 'snake', 'rabbit', 'duck',
  384. 'goose', 'penguin', 'frog', 'crab', 'shrimp', 'whale', 'octopus', 'spider', 'ant', 'bee', 'butterfly', 'dragonfly',
  385. 'ladybug', 'snail', 'camel', 'kangaroo', 'koala', 'panda', 'piglet', 'sheep', 'wolf', 'fox', 'deer', 'mouse', 'seal',
  386. 'chicken', 'cow', 'dinosaur', 'puppy', 'kitten', 'circle', 'square', 'garden', 'otter', 'bunny', 'meerkat', 'harp']
  387. // return a random combination of first_adj + noun + number (between 0 and 9999)
  388. // e.g. clever-idea-123
  389. return first_adj[Math.floor(Math.random() * first_adj.length)] + '-' + nouns[Math.floor(Math.random() * nouns.length)] + '-' + Math.floor(Math.random() * 10000);
  390. }
  391. /**
  392. * Checks if the provided variable is a string or an instance of the String object.
  393. *
  394. * @param {*} variable - The variable to check.
  395. * @returns {boolean} True if the variable is a string or an instance of the String object, false otherwise.
  396. */
  397. window.isString = function (variable) {
  398. return typeof variable === 'string' || variable instanceof String;
  399. }
  400. /**
  401. * A function that checks whether a file system entry (fsentry) matches a list of allowed file types.
  402. * It handles both file extensions (like '.jpg') and MIME types (like 'text/plain').
  403. * If the allowed file types string is empty or not provided, the function always returns true.
  404. * It checks the file types only if the fsentry is a file, not a directory.
  405. *
  406. * @param {Object} fsentry - The file system entry to check. It must be an object with properties: 'is_dir', 'name', 'type'.
  407. * @param {string} allowed_file_types_string - The list of allowed file types, separated by commas. Can include extensions and MIME types.
  408. *
  409. * @returns {boolean} True if the fsentry matches one of the allowed file types, or if the allowed_file_types_string is empty or not provided. False otherwise.
  410. *
  411. * @example
  412. *
  413. * let fsentry = {is_dir: false, name: 'example.jpg', type: 'image/jpeg'};
  414. * let allowedTypes = '.jpg, text/plain, image/*';
  415. * let result = window.check_fsentry_against_allowed_file_types_string(fsentry, allowedTypes);
  416. * // result would be true, as 'example.jpg' matches the '.jpg' in allowedTypes
  417. *
  418. */
  419. window.check_fsentry_against_allowed_file_types_string =function (fsentry, allowed_file_types_string) {
  420. // simple cases that are always a pass
  421. if(!allowed_file_types_string || allowed_file_types_string.trim() === '')
  422. return true;
  423. // parse allowed_file_types into an array of extensions and types
  424. let allowed_file_types = allowed_file_types_string.split(',');
  425. if(allowed_file_types.length > 0){
  426. // trim every entry
  427. for (let index = 0; index < allowed_file_types.length; index++) {
  428. allowed_file_types[index] = allowed_file_types[index].trim();
  429. }
  430. }
  431. let passes_allowed_file_type_filter = true;
  432. // check types, only if this fsentry is a file and not a directory
  433. if(!fsentry.is_dir && allowed_file_types.length > 0){
  434. passes_allowed_file_type_filter = false;
  435. for (let index = 0; index < allowed_file_types.length; index++) {
  436. const allowed_file_type = allowed_file_types[index].toLowerCase();
  437. // if type is not already set, try to set it based on the file name
  438. if(!fsentry.type)
  439. fsentry.type = mime.getType(fsentry.name);
  440. // extensions (e.g. .jpg)
  441. if(allowed_file_type.startsWith('.') && fsentry.name.toLowerCase().endsWith(allowed_file_type)){
  442. passes_allowed_file_type_filter = true;
  443. break;
  444. }
  445. // MIME types (e.g. text/plain)
  446. else if(window.globToRegExp(allowed_file_type).test(fsentry.type?.toLowerCase())){
  447. passes_allowed_file_type_filter = true;
  448. break;
  449. }
  450. }
  451. }
  452. return passes_allowed_file_type_filter;
  453. }
  454. // @author Rich Adams <rich@richadams.me>
  455. // Implements a tap and hold functionality. If you click/tap and release, it will trigger a normal
  456. // click event. But if you click/tap and hold for 1s (default), it will trigger a taphold event instead.
  457. ;(function($)
  458. {
  459. // Default options
  460. var defaults = {
  461. duration: 500, // ms
  462. clickHandler: null
  463. }
  464. // When start of a taphold event is triggered.
  465. function startHandler(event)
  466. {
  467. var $elem = jQuery(this);
  468. // Merge the defaults and any user defined settings.
  469. let settings = jQuery.extend({}, defaults, event.data);
  470. // If object also has click handler, store it and unbind. Taphold will trigger the
  471. // click itself, rather than normal propagation.
  472. if (typeof $elem.data("events") != "undefined"
  473. && typeof $elem.data("events").click != "undefined")
  474. {
  475. // Find the one without a namespace defined.
  476. for (var c in $elem.data("events").click)
  477. {
  478. if ($elem.data("events").click[c].namespace == "")
  479. {
  480. var handler = $elem.data("events").click[c].handler
  481. $elem.data("taphold_click_handler", handler);
  482. $elem.unbind("click", handler);
  483. break;
  484. }
  485. }
  486. }
  487. // Otherwise, if a custom click handler was explicitly defined, then store it instead.
  488. else if (typeof settings.clickHandler == "function")
  489. {
  490. $elem.data("taphold_click_handler", settings.clickHandler);
  491. }
  492. // Reset the flags
  493. $elem.data("taphold_triggered", false); // If a hold was triggered
  494. $elem.data("taphold_clicked", false); // If a click was triggered
  495. $elem.data("taphold_cancelled", false); // If event has been cancelled.
  496. // Set the timer for the hold event.
  497. $elem.data("taphold_timer",
  498. setTimeout(function()
  499. {
  500. // If event hasn't been cancelled/clicked already, then go ahead and trigger the hold.
  501. if (!$elem.data("taphold_cancelled")
  502. && !$elem.data("taphold_clicked"))
  503. {
  504. // Trigger the hold event, and set the flag to say it's been triggered.
  505. $elem.trigger(jQuery.extend(event, jQuery.Event("taphold")));
  506. $elem.data("taphold_triggered", true);
  507. }
  508. }, settings.duration));
  509. }
  510. // When user ends a tap or click, decide what we should do.
  511. function stopHandler(event)
  512. {
  513. var $elem = jQuery(this);
  514. // If taphold has been cancelled, then we're done.
  515. if ($elem.data("taphold_cancelled")) { return; }
  516. // Clear the hold timer. If it hasn't already triggered, then it's too late anyway.
  517. clearTimeout($elem.data("taphold_timer"));
  518. // If hold wasn't triggered and not already clicked, then was a click event.
  519. if (!$elem.data("taphold_triggered")
  520. && !$elem.data("taphold_clicked"))
  521. {
  522. // If click handler, trigger it.
  523. if (typeof $elem.data("taphold_click_handler") == "function")
  524. {
  525. $elem.data("taphold_click_handler")(jQuery.extend(event, jQuery.Event("click")));
  526. }
  527. // Set flag to say we've triggered the click event.
  528. $elem.data("taphold_clicked", true);
  529. }
  530. }
  531. // If a user prematurely leaves the boundary of the object we're working on.
  532. function leaveHandler(event)
  533. {
  534. // Cancel the event.
  535. $(this).data("taphold_cancelled", true);
  536. }
  537. // Determine if touch events are supported.
  538. var touchSupported = ("ontouchstart" in window) // Most browsers
  539. || ("onmsgesturechange" in window); // Microsoft
  540. var taphold = $.event.special.taphold =
  541. {
  542. setup: function(data)
  543. {
  544. $(this).bind((touchSupported ? "touchstart" : "mousedown"), data, startHandler)
  545. .bind((touchSupported ? "touchend" : "mouseup"), stopHandler)
  546. .bind((touchSupported ? "touchmove touchcancel" : "mouseleave"), leaveHandler);
  547. },
  548. teardown: function(namespaces)
  549. {
  550. $(this).unbind((touchSupported ? "touchstart" : "mousedown"), startHandler)
  551. .unbind((touchSupported ? "touchend" : "mouseup"), stopHandler)
  552. .unbind((touchSupported ? "touchmove touchcancel" : "mouseleave"), leaveHandler);
  553. }
  554. };
  555. })(jQuery);
  556. window.refresh_user_data = async (auth_token)=>{
  557. let whoami
  558. try{
  559. whoami = await puter.os.user();
  560. }catch(e){
  561. // Ignored
  562. }
  563. // update local user data
  564. if(whoami){
  565. window.update_auth_data(auth_token, whoami)
  566. }
  567. }
  568. window.update_auth_data = (auth_token, user)=>{
  569. window.auth_token = auth_token;
  570. localStorage.setItem('auth_token', auth_token);
  571. // Has username changed?
  572. if(window.user?.username !== user.username)
  573. update_username_in_gui(user.username);
  574. // Has email changed?
  575. if(window.user?.email !== user.email && user.email){
  576. $('.user-email').html(html_encode(user.email));
  577. }
  578. const to_storable_user = user => {
  579. const storable_user = {...user};
  580. delete storable_user.taskbar_items;
  581. return storable_user;
  582. };
  583. // update this session's user data
  584. window.user = user;
  585. localStorage.setItem('user', JSON.stringify(to_storable_user(user)));
  586. // re-initialize the Puter.js objects with the new auth token
  587. puter.setAuthToken(auth_token, window.api_origin)
  588. //update the logged_in_users array entry for this user
  589. if(window.user){
  590. let logged_in_users_updated = false;
  591. for (let i = 0; i < window.logged_in_users.length && !logged_in_users_updated; i++) {
  592. if(window.logged_in_users[i].uuid === window.user.uuid){
  593. window.logged_in_users[i] = window.user;
  594. window.logged_in_users[i].auth_token = window.auth_token;
  595. logged_in_users_updated = true;
  596. }
  597. }
  598. // no matching array elements, add one
  599. if(!logged_in_users_updated){
  600. let userobj = window.user;
  601. userobj.auth_token = window.auth_token;
  602. window.logged_in_users.push(userobj);
  603. }
  604. // update local storage
  605. localStorage.setItem('logged_in_users', JSON.stringify(
  606. window.logged_in_users.map(to_storable_user)));
  607. }
  608. window.desktop_path = '/' + window.user.username + '/Desktop';
  609. window.trash_path = '/' + window.user.username + '/Trash';
  610. window.appdata_path = '/' + window.user.username + '/AppData';
  611. window.docs_path = '/' + window.user.username + '/Documents';
  612. window.pictures_path = '/' + window.user.username + '/Pictures';
  613. window.videos_path = '/' + window.user.username + '/Videos';
  614. window.desktop_path = '/' + window.user.username + '/Desktop';
  615. window.home_path = '/' + window.user.username;
  616. if(window.user !== null && !window.user.is_temp){
  617. $('.user-options-login-btn, .user-options-create-account-btn').hide();
  618. $('.user-options-menu-btn').show();
  619. }
  620. }
  621. window.mutate_user_preferences = function(user_preferences_delta) {
  622. for (const [key, value] of Object.entries(user_preferences_delta)) {
  623. // Don't wait for set to be done for better efficiency
  624. puter.kv.set(`user_preferences.${key}`, value);
  625. }
  626. // There may be syncing issues across multiple devices
  627. window.update_user_preferences({ ...window.user_preferences, ...user_preferences_delta });
  628. }
  629. window.update_user_preferences = function(user_preferences) {
  630. window.user_preferences = user_preferences;
  631. localStorage.setItem('user_preferences', JSON.stringify(user_preferences));
  632. const language = user_preferences.language ?? 'en';
  633. window.locale = language;
  634. // Broadcast locale change to apps
  635. const broadcastService = globalThis.services.get('broadcast');
  636. broadcastService.sendBroadcast('localeChanged', {
  637. language: language,
  638. }, { sendToNewAppInstances: true });
  639. }
  640. window.sendWindowWillCloseMsg = function(iframe_element) {
  641. return new Promise(function(resolve){
  642. const msg_id = window.uuidv4();
  643. iframe_element.contentWindow.postMessage({
  644. msg: "windowWillClose",
  645. msg_id: msg_id
  646. }, '*');
  647. //register callback
  648. window.appCallbackFunctions[msg_id] = resolve;
  649. })
  650. }
  651. window.logout = ()=>{
  652. console.log('DISP LOGOUT EVENT');
  653. $(document).trigger('logout');
  654. // document.dispatchEvent(new Event("logout", { bubbles: true}));
  655. }
  656. /**
  657. * Checks if the current document is in fullscreen mode.
  658. *
  659. * @function is_fullscreen
  660. * @memberof window
  661. * @returns {boolean} Returns true if the document is in fullscreen mode, otherwise false.
  662. *
  663. * @example
  664. * // Checks if the document is currently in fullscreen mode
  665. * const inFullscreen = window.is_fullscreen();
  666. *
  667. * @description
  668. * This function checks various browser-specific properties to determine if the document
  669. * is currently being displayed in fullscreen mode. It covers standard as well as
  670. * some vendor-prefixed properties to ensure compatibility across different browsers.
  671. */
  672. window.is_fullscreen = ()=>{
  673. return (document.fullscreenElement && document.fullscreenElement !== null) ||
  674. (document.webkitIsFullScreen && document.webkitIsFullScreen !== null) ||
  675. (document.webkitFullscreenElement && document.webkitFullscreenElement !== null) ||
  676. (document.mozFullScreenElement && document.mozFullScreenElement !== null) ||
  677. (document.msFullscreenElement && document.msFullscreenElement !== null);
  678. }
  679. window.get_apps = async (app_names, callback)=>{
  680. if(Array.isArray(app_names))
  681. app_names = app_names.join('|');
  682. // 'explorer' is a special app, no metadata should be returned
  683. if(app_names === 'explorer')
  684. return [];
  685. let res = await $.ajax({
  686. url: window.api_origin + "/apps/"+app_names,
  687. type: 'GET',
  688. async: true,
  689. contentType: "application/json",
  690. headers: {
  691. "Authorization": "Bearer "+window.auth_token
  692. },
  693. success: function (res){
  694. }
  695. });
  696. if(res.length === 1)
  697. res = res[0];
  698. if(callback && typeof callback === 'function')
  699. callback(res);
  700. else
  701. return res;
  702. }
  703. /**
  704. * Sends an "itemChanged" event to all watching applications associated with a specific item.
  705. *
  706. * @function sendItemChangeEventToWatchingApps
  707. * @memberof window
  708. * @param {string} item_uid - Unique identifier of the item that experienced the change.
  709. * @param {Object} event_data - Additional data about the event to be passed to the watching applications.
  710. *
  711. * @description
  712. * This function sends an "itemChanged" message to all applications that are currently watching
  713. * the specified item. If an application's iframe is not found or no longer valid,
  714. * it is removed from the list of watchers.
  715. *
  716. * The function expects that `window.watchItems` contains a mapping of item UIDs to arrays of app instance IDs.
  717. *
  718. * @example
  719. * // Example usage to send a change event to watching applications of an item with UID "item123".
  720. * window.sendItemChangeEventToWatchingApps('item123', { property: 'value' });
  721. */
  722. window.sendItemChangeEventToWatchingApps = function(item_uid, event_data){
  723. if(window.watchItems[item_uid]){
  724. window.watchItems[item_uid].forEach(app_instance_id => {
  725. const iframe = $(`.window[data-element_uuid="${app_instance_id}"]`).find('.window-app-iframe')
  726. if(iframe && iframe.length > 0){
  727. iframe.get(0)?.contentWindow
  728. .postMessage({
  729. msg: 'itemChanged',
  730. data: event_data,
  731. }, '*');
  732. }else{
  733. window.watchItems[item_uid].splice(window.watchItems[item_uid].indexOf(app_instance_id), 1);
  734. }
  735. });
  736. }
  737. }
  738. /**
  739. * Assigns an icon to a filesystem entry based on its properties such as name, type,
  740. * and whether it's a directory, app, trashed, or specific file type.
  741. *
  742. * @function item_icon
  743. * @global
  744. * @async
  745. * @param {Object} fsentry - A filesystem entry object. It may contain various properties
  746. * like name, type, path, associated_app, thumbnail, is_dir, and metadata, depending on
  747. * the type of filesystem entry.
  748. */
  749. window.item_icon = async (fsentry)=>{
  750. // --------------------------------------------------
  751. // If this file is Trashed then set the name to the original name of the file before it was trashed
  752. // --------------------------------------------------
  753. if(fsentry.path?.startsWith(window.trash_path + '/')){
  754. if(fsentry.metadata){
  755. try{
  756. let metadata = JSON.parse(fsentry.metadata);
  757. fsentry.name = (metadata && metadata.original_name) ? metadata.original_name : fsentry.name
  758. }
  759. catch(e){
  760. // Ignored
  761. }
  762. }
  763. }
  764. // --------------------------------------------------
  765. // thumbnail
  766. // --------------------------------------------------
  767. if(fsentry.thumbnail){
  768. return {image: fsentry.thumbnail, type: 'thumb'};
  769. }
  770. // --------------------------------------------------
  771. // app icon
  772. // --------------------------------------------------
  773. else if(fsentry.associated_app && fsentry.associated_app?.name){
  774. if(fsentry.associated_app.icon)
  775. return {image: fsentry.associated_app.icon, type: 'icon'};
  776. else
  777. return {image: window.icons['app.svg'], type: 'icon'};
  778. }
  779. // --------------------------------------------------
  780. // Trash
  781. // --------------------------------------------------
  782. else if(fsentry.shortcut_to_path && fsentry.shortcut_to_path === window.trash_path){
  783. // get trash image, this is needed to get the correct empty vs full trash icon
  784. let trash_img = $(`.item[data-path="${html_encode(window.trash_path)}" i] .item-icon-icon`).attr('src')
  785. // if trash_img is undefined that's probably because trash wasn't added anywhere, do a direct lookup to see if trash is empty or no
  786. if(!trash_img){
  787. let trashstat = await puter.fs.stat(window.trash_path);
  788. if(trashstat.is_empty !== undefined && trashstat.is_empty === true)
  789. trash_img = window.icons['trash.svg'];
  790. else
  791. trash_img = window.icons['trash-full.svg'];
  792. }
  793. return {image: trash_img, type: 'icon'};
  794. }
  795. // --------------------------------------------------
  796. // Directories
  797. // --------------------------------------------------
  798. else if(fsentry.is_dir){
  799. // System Directories
  800. if(fsentry.path === window.docs_path)
  801. return {image: window.icons['folder-documents.svg'], type: 'icon'};
  802. else if (fsentry.path === window.pictures_path)
  803. return { image: window.icons['folder-pictures.svg'], type: 'icon' };
  804. else if (fsentry.path === window.home_path)
  805. return { image: window.icons['folder-home.svg'], type: 'icon' };
  806. else if (fsentry.path === window.videos_path)
  807. return { image: window.icons['folder-videos.svg'], type: 'icon' };
  808. else if (fsentry.path === window.desktop_path)
  809. return { image: window.icons['folder-desktop.svg'], type: 'icon' };
  810. // regular directories
  811. else
  812. return {image: window.icons['folder.svg'], type: 'icon'};
  813. }
  814. // --------------------------------------------------
  815. // Match icon by file extension
  816. // --------------------------------------------------
  817. // *.doc
  818. else if(fsentry.name.toLowerCase().endsWith('.doc')){
  819. return {image: window.icons['file-doc.svg'], type: 'icon'};
  820. }
  821. // *.docx
  822. else if(fsentry.name.toLowerCase().endsWith('.docx')){
  823. return {image: window.icons['file-docx.svg'], type: 'icon'};
  824. }
  825. // *.exe
  826. else if(fsentry.name.toLowerCase().endsWith('.exe')){
  827. return {image: window.icons['file-exe.svg'], type: 'icon'};
  828. }
  829. // *.gz
  830. else if(fsentry.name.toLowerCase().endsWith('.gz')){
  831. return {image: window.icons['file-gzip.svg'], type: 'icon'};
  832. }
  833. // *.jar
  834. else if(fsentry.name.toLowerCase().endsWith('.jar')){
  835. return {image: window.icons['file-jar.svg'], type: 'icon'};
  836. }
  837. // *.java
  838. else if(fsentry.name.toLowerCase().endsWith('.java')){
  839. return {image: window.icons['file-java.svg'], type: 'icon'};
  840. }
  841. // *.jsp
  842. else if(fsentry.name.toLowerCase().endsWith('.jsp')){
  843. return {image: window.icons['file-jsp.svg'], type: 'icon'};
  844. }
  845. // *.log
  846. else if(fsentry.name.toLowerCase().endsWith('.log')){
  847. return {image: window.icons['file-log.svg'], type: 'icon'};
  848. }
  849. // *.mp3
  850. else if(fsentry.name.toLowerCase().endsWith('.mp3')){
  851. return {image: window.icons['file-mp3.svg'], type: 'icon'};
  852. }
  853. // *.rb
  854. else if(fsentry.name.toLowerCase().endsWith('.rb')){
  855. return {image: window.icons['file-ruby.svg'], type: 'icon'};
  856. }
  857. // *.rss
  858. else if(fsentry.name.toLowerCase().endsWith('.rss')){
  859. return {image: window.icons['file-rss.svg'], type: 'icon'};
  860. }
  861. // *.rtf
  862. else if(fsentry.name.toLowerCase().endsWith('.rtf')){
  863. return {image: window.icons['file-rtf.svg'], type: 'icon'};
  864. }
  865. // *.sketch
  866. else if(fsentry.name.toLowerCase().endsWith('.sketch')){
  867. return {image: window.icons['file-sketch.svg'], type: 'icon'};
  868. }
  869. // *.sql
  870. else if(fsentry.name.toLowerCase().endsWith('.sql')){
  871. return {image: window.icons['file-sql.svg'], type: 'icon'};
  872. }
  873. // *.tif
  874. else if(fsentry.name.toLowerCase().endsWith('.tif')){
  875. return {image: window.icons['file-tif.svg'], type: 'icon'};
  876. }
  877. // *.tiff
  878. else if(fsentry.name.toLowerCase().endsWith('.tiff')){
  879. return {image: window.icons['file-tiff.svg'], type: 'icon'};
  880. }
  881. // *.wav
  882. else if(fsentry.name.toLowerCase().endsWith('.wav')){
  883. return {image: window.icons['file-wav.svg'], type: 'icon'};
  884. }
  885. // *.cpp
  886. else if(fsentry.name.toLowerCase().endsWith('.cpp')){
  887. return {image: window.icons['file-cpp.svg'], type: 'icon'};
  888. }
  889. // *.pptx
  890. else if(fsentry.name.toLowerCase().endsWith('.pptx')){
  891. return {image: window.icons['file-pptx.svg'], type: 'icon'};
  892. }
  893. // *.psd
  894. else if(fsentry.name.toLowerCase().endsWith('.psd')){
  895. return {image: window.icons['file-psd.svg'], type: 'icon'};
  896. }
  897. // *.py
  898. else if(fsentry.name.toLowerCase().endsWith('.py')){
  899. return {image: window.icons['file-py.svg'], type: 'icon'};
  900. }
  901. // *.xlsx
  902. else if(fsentry.name.toLowerCase().endsWith('.xlsx')){
  903. return {image: window.icons['file-xlsx.svg'], type: 'icon'};
  904. }
  905. // --------------------------------------------------
  906. // Determine icon by set or derived mime type
  907. // --------------------------------------------------
  908. else if(fsentry.type){
  909. return {image: content_type_to_icon(fsentry.type), type: 'icon'};
  910. }
  911. else{
  912. return {image: content_type_to_icon(mime.getType(fsentry.name)), type: 'icon'};
  913. }
  914. }
  915. /**
  916. * Asynchronously checks if a save account notice should be shown to the user, and if needed, displays the notice.
  917. *
  918. * This function first retrieves a key value pair from the cloud key-value storage to determine if the notice has been shown before.
  919. * If the notice hasn't been shown and the user is using a temporary session, the notice is then displayed. After the notice is shown,
  920. * the function updates the key-value storage indicating that the notice has been shown. The user can choose to save the session,
  921. * remind later or log in to an existing account.
  922. *
  923. * @param {string} [message] - The custom message to be displayed in the notice. If not provided, a default message will be used.
  924. * @global
  925. * @function window.show_save_account_notice_if_needed
  926. */
  927. window.show_save_account_notice_if_needed = function(message){
  928. window.getItem({
  929. key: "save_account_notice_shown",
  930. success: async function(value){
  931. if(!value && window.user?.is_temp){
  932. window.setItem({key: "save_account_notice_shown", value: true});
  933. // Show the notice
  934. setTimeout(async () => {
  935. const alert_resp = await UIAlert({
  936. message: message ?? `<strong>Congrats on storing data!</strong><p>Don't forget to save your session! You are in a temporary session. Save session to avoid accidentally losing your work.</p>`,
  937. body_icon: window.icons['reminder.svg'],
  938. buttons:[
  939. {
  940. label: i18n('save_session'),
  941. value: 'save-session',
  942. type: 'primary',
  943. },
  944. // {
  945. // label: 'Log into an existing account',
  946. // value: 'login',
  947. // },
  948. {
  949. label: `I'll do it later`,
  950. value: 'remind-later',
  951. },
  952. ],
  953. window_options: {
  954. backdrop: true,
  955. close_on_backdrop_click: false,
  956. }
  957. })
  958. if(alert_resp === 'remind-later'){
  959. // TODO
  960. }
  961. if(alert_resp === 'save-session'){
  962. let saved = await UIWindowSaveAccount({
  963. send_confirmation_code: false,
  964. });
  965. }else if (alert_resp === 'login'){
  966. let login_result = await UIWindowLogin({
  967. show_signup_button: false,
  968. reload_on_success: true,
  969. send_confirmation_code: false,
  970. window_options: {
  971. show_in_taskbar: false,
  972. backdrop: true,
  973. close_on_backdrop_click: false,
  974. }
  975. });
  976. // FIXME: Report login error.
  977. }
  978. }, window.desktop_loading_fade_delay + 1000);
  979. }
  980. }
  981. })
  982. }
  983. window.onpopstate = (event) => {
  984. if(event.state !== null && event.state.window_id !== null){
  985. $(`.window[data-id="${event.state.window_id}"]`).focusWindow();
  986. }
  987. }
  988. window.sort_items = (item_container, sort_by, sort_order)=>{
  989. if(sort_order !== 'asc' && sort_order !== 'desc')
  990. sort_order = 'asc';
  991. $(item_container).find(`.item[data-sortable="true"]`).detach().sort(function(a,b) {
  992. // Name
  993. if(!sort_by || sort_by === 'name'){
  994. if(a.dataset.name.toLowerCase() < b.dataset.name.toLowerCase()) { return (sort_order === 'asc' ? -1 : 1); }
  995. if(a.dataset.name.toLowerCase() > b.dataset.name.toLowerCase()) { return (sort_order === 'asc' ? 1 : -1); }
  996. return 0;
  997. }
  998. // Size
  999. else if(sort_by === 'size'){
  1000. if( parseInt(a.dataset.size) < parseInt(b.dataset.size)) { return (sort_order === 'asc' ? -1 : 1); }
  1001. if( parseInt(a.dataset.size) > parseInt(b.dataset.size)) { return (sort_order === 'asc' ? 1 : -1); }
  1002. return 0;
  1003. }
  1004. // Modified
  1005. else if(sort_by === 'modified'){
  1006. if( parseInt(a.dataset.modified) < parseInt(b.dataset.modified)) { return (sort_order === 'asc' ? -1 : 1); }
  1007. if( parseInt(a.dataset.modified) > parseInt(b.dataset.modified)) { return (sort_order === 'asc' ? 1 : -1); }
  1008. return 0;
  1009. }
  1010. // Type
  1011. else if(sort_by === 'type'){
  1012. if(path.extname(a.dataset.name.toLowerCase()) < path.extname(b.dataset.name.toLowerCase())) { return (sort_order === 'asc' ? -1 : 1); }
  1013. if(path.extname(a.dataset.name.toLowerCase()) > path.extname(b.dataset.name.toLowerCase())) { return (sort_order === 'asc' ? 1 : -1); }
  1014. return 0;
  1015. }
  1016. }).appendTo(item_container);
  1017. }
  1018. window.show_or_hide_files = (item_containers) => {
  1019. const show_hidden_files = window.user_preferences.show_hidden_files;
  1020. const class_to_add = show_hidden_files ? 'item-revealed' : 'item-hidden';
  1021. const class_to_remove = show_hidden_files ? 'item-hidden' : 'item-revealed';
  1022. $(item_containers)
  1023. .find('.item')
  1024. .filter((_, item) => item.dataset.name.startsWith('.'))
  1025. .removeClass(class_to_remove).addClass(class_to_add);
  1026. }
  1027. window.create_folder = async(basedir, appendto_element)=>{
  1028. let dirname = basedir;
  1029. let folder_name = 'New Folder';
  1030. let newfolder_op_id = window.operation_id++;
  1031. window.operation_cancelled[newfolder_op_id] = false;
  1032. let newfolder_progress_window_init_ts = Date.now();
  1033. let progwin;
  1034. // only show progress window if it takes longer than 500ms to create folder
  1035. let progwin_timeout = setTimeout(async () => {
  1036. progwin = await UIWindowProgress({
  1037. operation_id: newfolder_op_id,
  1038. // TODO: Implement cancellation.
  1039. // on_cancel: () => {
  1040. // window.operation_cancelled[newfolder_op_id] = true;
  1041. // },
  1042. });
  1043. progwin.set_status(i18n('taking_longer_than_usual'));
  1044. }, 500);
  1045. // create folder
  1046. try{
  1047. await puter.fs.mkdir({
  1048. path: dirname + '/'+folder_name,
  1049. rename: true,
  1050. overwrite: false,
  1051. success: function (data){
  1052. const el_created_dir = $(appendto_element).find('.item[data-path="'+html_encode(dirname)+'/'+html_encode(data.name)+'"]');
  1053. if(el_created_dir.length > 0){
  1054. window.activate_item_name_editor(el_created_dir);
  1055. // Add action to actions_history for undo ability
  1056. window.actions_history.push({
  1057. operation: 'create_folder',
  1058. data: el_created_dir
  1059. });
  1060. }
  1061. clearTimeout(progwin_timeout);
  1062. // done
  1063. let newfolder_duration = (Date.now() - newfolder_progress_window_init_ts);
  1064. if (progwin) {
  1065. if (newfolder_duration >= window.copy_progress_hide_delay) {
  1066. progwin.close();
  1067. } else {
  1068. setTimeout(() => {
  1069. setTimeout(() => {
  1070. progwin.close();
  1071. }, Math.abs(window.copy_progress_hide_delay - newfolder_duration));
  1072. });
  1073. }
  1074. }
  1075. }
  1076. });
  1077. }catch(err){
  1078. clearTimeout(progwin_timeout);
  1079. }
  1080. }
  1081. window.create_file = async(options)=>{
  1082. // args
  1083. let dirname = options.dirname;
  1084. let appendto_element = options.append_to_element;
  1085. let filename = options.name;
  1086. let content = options.content ? [options.content] : [];
  1087. // create file
  1088. try{
  1089. puter.fs.upload(new File(content, filename), dirname,
  1090. {
  1091. success: async function (data){
  1092. const created_file = $(appendto_element).find('.item[data-path="'+html_encode(dirname)+'/'+html_encode(data.name)+'"]');
  1093. if(created_file.length > 0){
  1094. window.activate_item_name_editor(created_file);
  1095. // Add action to actions_history for undo ability
  1096. window.actions_history.push({
  1097. operation: 'create_file',
  1098. data: created_file
  1099. });
  1100. }
  1101. }
  1102. });
  1103. }catch(err){
  1104. console.log(err);
  1105. }
  1106. }
  1107. window.create_shortcut = async(filename, is_dir, basedir, appendto_element, shortcut_to, shortcut_to_path)=>{
  1108. let dirname = basedir;
  1109. const extname = path.extname(filename);
  1110. const basename = path.basename(filename, extname) + ' - Shortcut';
  1111. filename = basename + extname;
  1112. // create file shortcut
  1113. try{
  1114. await puter.fs.upload(new File([], filename), dirname, {
  1115. overwrite: false,
  1116. shortcutTo: shortcut_to_path ?? shortcut_to,
  1117. dedupeName: true,
  1118. });
  1119. }catch(err){
  1120. console.log(err)
  1121. }
  1122. }
  1123. window.copy_clipboard_items = async function(dest_path, dest_container_element){
  1124. let copy_op_id = window.operation_id++;
  1125. window.operation_cancelled[copy_op_id] = false;
  1126. // unselect previously selected items in the target container
  1127. $(dest_container_element).children('.item-selected').removeClass('item-selected');
  1128. window.update_explorer_footer_selected_items_count($(dest_container_element).closest('.window'));
  1129. let overwrite_all = false;
  1130. (async()=>{
  1131. let copy_progress_window_init_ts = Date.now();
  1132. // only show progress window if it takes longer than 2s to copy
  1133. let progwin;
  1134. let progwin_timeout = setTimeout(async () => {
  1135. progwin = await UIWindowProgress({
  1136. operation_id: copy_op_id,
  1137. on_cancel: () => {
  1138. window.operation_cancelled[copy_op_id] = true;
  1139. },
  1140. });
  1141. }, 0);
  1142. const copied_item_paths = []
  1143. for(let i=0; i<window.clipboard.length; i++){
  1144. let copy_path = window.clipboard[i].path;
  1145. let item_with_same_name_already_exists = true;
  1146. let overwrite = overwrite_all;
  1147. progwin?.set_status(i18n('copying_file', copy_path));
  1148. do{
  1149. if(overwrite)
  1150. item_with_same_name_already_exists = false;
  1151. // cancelled?
  1152. if(window.operation_cancelled[copy_op_id])
  1153. return;
  1154. // perform copy
  1155. try{
  1156. let resp = await puter.fs.copy({
  1157. source: copy_path,
  1158. destination: dest_path,
  1159. overwrite: overwrite || overwrite_all,
  1160. // if user is copying an item to where its source is, change the name so there is no conflict
  1161. dedupeName: dest_path === path.dirname(copy_path),
  1162. });
  1163. // remove overwritten item from the DOM
  1164. if(resp[0].overwritten?.id){
  1165. $(`.item[data-uid=${resp[0].overwritten.id}]`).removeItems();
  1166. }
  1167. // copy new path for undo copy
  1168. copied_item_paths.push(resp[0].copied.path);
  1169. // skips next loop iteration
  1170. break;
  1171. }catch(err){
  1172. if(err.code==='item_with_same_name_exists'){
  1173. const alert_resp = await UIAlert({
  1174. message: `<strong>${html_encode(err.entry_name)}</strong> already exists.`,
  1175. buttons:[
  1176. {label: i18n('replace'), type: 'primary', value: 'replace'},
  1177. ... (window.clipboard.length > 1) ? [{label: i18n('replace_all'), value: 'replace_all'}] : [],
  1178. ... (window.clipboard.length > 1) ? [{label: i18n('skip'), value: 'skip'}] : [{label: i18n('cancel'), value: 'cancel'}],
  1179. ]
  1180. })
  1181. if(alert_resp === 'replace'){
  1182. overwrite = true;
  1183. }else if (alert_resp === 'replace_all'){
  1184. overwrite = true;
  1185. overwrite_all = true;
  1186. }else if(alert_resp === 'skip' || alert_resp === 'cancel'){
  1187. item_with_same_name_already_exists = false;
  1188. }
  1189. }
  1190. else{
  1191. if(err.message){
  1192. UIAlert(err.message)
  1193. }
  1194. item_with_same_name_already_exists = false;
  1195. }
  1196. }
  1197. }while(item_with_same_name_already_exists)
  1198. }
  1199. // done
  1200. // Add action to actions_history for undo ability
  1201. window.actions_history.push({
  1202. operation: 'copy',
  1203. data: copied_item_paths
  1204. });
  1205. clearTimeout(progwin_timeout);
  1206. let copy_duration = (Date.now() - copy_progress_window_init_ts);
  1207. if (progwin) {
  1208. if (copy_duration >= window.copy_progress_hide_delay) {
  1209. progwin.close();
  1210. } else {
  1211. setTimeout(() => {
  1212. setTimeout(() => {
  1213. progwin.close();
  1214. }, Math.abs(window.copy_progress_hide_delay - copy_duration));
  1215. });
  1216. }
  1217. }
  1218. })();
  1219. }
  1220. /**
  1221. * Copies the given items to the destination path.
  1222. *
  1223. * @param {HTMLElement[]} el_items - HTML elements representing the items to copy
  1224. * @param {string} dest_path - Destination path to copy items to
  1225. */
  1226. window.copy_items = function(el_items, dest_path){
  1227. let copy_op_id = window.operation_id++;
  1228. let overwrite_all = false;
  1229. (async()=>{
  1230. let copy_progress_window_init_ts = Date.now();
  1231. // only show progress window if it takes longer than 2s to copy
  1232. let progwin;
  1233. let progwin_timeout = setTimeout(async () => {
  1234. progwin = await UIWindowProgress({
  1235. operation_id: copy_op_id,
  1236. on_cancel: () => {
  1237. window.operation_cancelled[copy_op_id] = true;
  1238. },
  1239. });
  1240. }, 2000);
  1241. const copied_item_paths = []
  1242. for(let i=0; i < el_items.length; i++){
  1243. let copy_path = $(el_items[i]).attr('data-path');
  1244. let item_with_same_name_already_exists = true;
  1245. let overwrite = overwrite_all;
  1246. progwin?.set_status(i18n('copying_file', copy_path));
  1247. do{
  1248. if(overwrite)
  1249. item_with_same_name_already_exists = false;
  1250. // cancelled?
  1251. if(window.operation_cancelled[copy_op_id])
  1252. return;
  1253. try{
  1254. let resp = await puter.fs.copy({
  1255. source: copy_path,
  1256. destination: dest_path,
  1257. overwrite: overwrite || overwrite_all,
  1258. // if user is copying an item to where the source is, automatically change the name so there is no conflict
  1259. dedupeName: dest_path === path.dirname(copy_path),
  1260. })
  1261. // remove overwritten item from the DOM
  1262. if(resp[0].overwritten?.id){
  1263. $(`.item[data-uid=${resp.overwritten.id}]`).removeItems();
  1264. }
  1265. // copy new path for undo copy
  1266. copied_item_paths.push(resp[0].copied.path);
  1267. // skips next loop iteration
  1268. item_with_same_name_already_exists = false;
  1269. }catch(err){
  1270. if(err.code === 'item_with_same_name_exists'){
  1271. const alert_resp = await UIAlert({
  1272. message: `<strong>${html_encode(err.entry_name)}</strong> already exists.`,
  1273. buttons:[
  1274. { label: i18n('replace'), type: 'primary', value: 'replace' },
  1275. ... (el_items.length > 1) ? [{label: i18n('replace_all'), value: 'replace_all'}] : [],
  1276. ... (el_items.length > 1) ? [{label: i18n('skip'), value: 'skip'}] : [{label: i18n('cancel'), value: 'cancel'}],
  1277. ]
  1278. })
  1279. if(alert_resp === 'replace'){
  1280. overwrite = true;
  1281. }else if (alert_resp === 'replace_all'){
  1282. overwrite = true;
  1283. overwrite_all = true;
  1284. }else if(alert_resp === 'skip' || alert_resp === 'cancel'){
  1285. item_with_same_name_already_exists = false;
  1286. }
  1287. }
  1288. else{
  1289. if(err.message){
  1290. UIAlert(err.message)
  1291. }
  1292. else if(err){
  1293. UIAlert(err)
  1294. }
  1295. item_with_same_name_already_exists = false;
  1296. }
  1297. }
  1298. }while(item_with_same_name_already_exists)
  1299. }
  1300. // done
  1301. // Add action to actions_history for undo ability
  1302. window.actions_history.push({
  1303. operation: 'copy',
  1304. data: copied_item_paths
  1305. });
  1306. clearTimeout(progwin_timeout);
  1307. let copy_duration = (Date.now() - copy_progress_window_init_ts);
  1308. if (progwin) {
  1309. if (copy_duration >= window.copy_progress_hide_delay) {
  1310. progwin.close();
  1311. } else {
  1312. setTimeout(() => {
  1313. setTimeout(() => {
  1314. progwin.close();
  1315. }, Math.abs(window.copy_progress_hide_delay - copy_duration));
  1316. });
  1317. }
  1318. }
  1319. })()
  1320. }
  1321. /**
  1322. * Deletes the given item.
  1323. *
  1324. * @param {HTMLElement} el_item - HTML element representing the item to delete
  1325. * @param {boolean} [descendants_only=false] - If true, only deletes descendant items under the given item
  1326. * @returns {Promise<void>}
  1327. */
  1328. window.delete_item = async function(el_item, descendants_only = false){
  1329. if($(el_item).attr('data-immutable') === '1')
  1330. return;
  1331. // hide all UIItems with matching uids
  1332. $(`.item[data-uid='${$(el_item).attr('data-uid')}']`).fadeOut(150, function(){
  1333. // close all windows with matching uids
  1334. $('.window-' + $(el_item).attr('data-uid')).close();
  1335. // close all windows that belong to a descendant of this item
  1336. // todo this has to be case-insensitive but the `i` selector doesn't work on ^=
  1337. $(`.window[data-path^="${$(el_item).attr('data-path')}/"]`).close();
  1338. });
  1339. try{
  1340. await puter.fs.delete({
  1341. paths: $(el_item).attr('data-path'),
  1342. descendantsOnly: descendants_only,
  1343. recursive: true,
  1344. });
  1345. // fade out item
  1346. $(`.item[data-uid='${$(el_item).attr('data-uid')}']`).fadeOut(150, function(){
  1347. // find all parent windows that contain this item
  1348. let parent_windows = $(`.item[data-uid='${$(el_item).attr('data-uid')}']`).closest('.window');
  1349. // remove item from DOM
  1350. $(`.item[data-uid='${$(el_item).attr('data-uid')}']`).removeItems();
  1351. // update parent windows' item counts
  1352. $(parent_windows).each(function(index){
  1353. window.update_explorer_footer_item_count(this);
  1354. window.update_explorer_footer_selected_items_count(this);
  1355. });
  1356. // update all shortcuts to this item
  1357. $(`.item[data-shortcut_to_path="${html_encode($(el_item).attr('data-path'))}" i]`).attr(`data-shortcut_to_path`, '');
  1358. });
  1359. }catch(err){
  1360. UIAlert(err.responseText);
  1361. }
  1362. }
  1363. window.move_clipboard_items = function (el_target_container, target_path){
  1364. let dest_path = target_path === undefined ? $(el_target_container).attr('data-path') : target_path;
  1365. let el_items = [];
  1366. if(window.clipboard.length > 0){
  1367. for(let i=0; i<window.clipboard.length; i++){
  1368. el_items.push($(`.item[data-path="${html_encode(window.clipboard[i])}" i]`));
  1369. }
  1370. if(el_items.length > 0)
  1371. window.move_items(el_items, dest_path);
  1372. }
  1373. window.clipboard = [];
  1374. }
  1375. /**
  1376. * Initiates a download for multiple files provided as an array of paths.
  1377. *
  1378. * This function triggers the download of files from given paths. It constructs the
  1379. * download URLs using an API base URL and the given paths, along with an authentication token.
  1380. * Each file is then fetched and prompted to the user for download using the `saveAs` function.
  1381. *
  1382. * Global dependencies:
  1383. * - `api_origin`: The base URL for the download API endpoint.
  1384. * - `auth_token`: The authentication token required for the download API.
  1385. * - `saveAs`: Function to save the fetched blob as a file.
  1386. * - `path.basename()`: Function to extract the filename from the provided path.
  1387. *
  1388. * @global
  1389. * @function trigger_download
  1390. * @param {string[]} paths - An array of file paths that are to be downloaded.
  1391. *
  1392. * @example
  1393. * let filePaths = ['/path/to/file1.txt', '/path/to/file2.png'];
  1394. * window.trigger_download(filePaths);
  1395. */
  1396. window.trigger_download = (paths)=>{
  1397. let urls = [];
  1398. for (let index = 0; index < paths.length; index++) {
  1399. urls.push({
  1400. download: window.api_origin + "/down?path=" + paths[index],
  1401. filename: path.basename(paths[index]),
  1402. });
  1403. }
  1404. urls.forEach(async function (e) {
  1405. const anti_csrf = await (async () => {
  1406. const resp = await fetch(`${window.gui_origin}/get-anticsrf-token`);
  1407. const { token } = await resp.json();
  1408. return token;
  1409. })();
  1410. fetch(e.download, {
  1411. method: 'POST',
  1412. headers: {
  1413. 'Content-Type': 'application/json',
  1414. 'Authorization': 'Bearer ' + puter.authToken,
  1415. },
  1416. body: JSON.stringify({
  1417. anti_csrf,
  1418. }),
  1419. })
  1420. .then(res => res.blob())
  1421. .then(blob => {
  1422. saveAs(blob, e.filename);
  1423. });
  1424. });
  1425. }
  1426. /**
  1427. *
  1428. * @param {*} options
  1429. */
  1430. window.launch_app = async (options)=>{
  1431. const uuid = options.uuid ?? window.uuidv4();
  1432. let icon, title, file_signature;
  1433. const window_options = options.window_options ?? {};
  1434. if (options.parent_instance_id) {
  1435. window_options.parent_instance_id = options.parent_instance_id;
  1436. }
  1437. // try to get 3rd-party app info
  1438. let app_info = options.app_obj ?? await window.get_apps(options.name);
  1439. //-----------------------------------
  1440. // icon
  1441. //-----------------------------------
  1442. if(app_info.icon)
  1443. icon = app_info.icon;
  1444. else if(options.name === 'explorer')
  1445. icon = window.icons['folder.svg'];
  1446. else
  1447. icon = window.icons['app-icon-'+options.name+'.svg']
  1448. //-----------------------------------
  1449. // title
  1450. //-----------------------------------
  1451. if(app_info.title)
  1452. title = app_info.title;
  1453. else if(options.window_title)
  1454. title = options.window_title;
  1455. else if(options.name)
  1456. title = options.name;
  1457. //-----------------------------------
  1458. // maximize on start
  1459. //-----------------------------------
  1460. if(app_info.maximize_on_start && app_info.maximize_on_start === 1)
  1461. options.maximized = 1;
  1462. //-----------------------------------
  1463. // if opened a file, sign it
  1464. //-----------------------------------
  1465. if(options.file_signature)
  1466. file_signature = options.file_signature;
  1467. else if(options.file_uid){
  1468. file_signature = await puter.fs.sign(app_info.uuid, {uid: options.file_uid, action: 'write'});
  1469. // add token to options
  1470. options.token = file_signature.token;
  1471. // add file_signature to options
  1472. file_signature = file_signature.items;
  1473. }
  1474. // -----------------------------------
  1475. // Create entry to track the "portal"
  1476. // (portals are processese in Puter's GUI)
  1477. // -----------------------------------
  1478. let el_win;
  1479. let process;
  1480. //------------------------------------
  1481. // Explorer
  1482. //------------------------------------
  1483. if(options.name === 'explorer' || options.name === 'trash'){
  1484. process = new PseudoProcess({
  1485. uuid,
  1486. name: 'explorer',
  1487. parent: options.parent_instance_id,
  1488. meta: {
  1489. launch_options: options,
  1490. app_info: app_info,
  1491. }
  1492. });
  1493. const svc_process = globalThis.services.get('process');
  1494. svc_process.register(process);
  1495. if(options.path === window.home_path){
  1496. title = 'Home';
  1497. icon = window.icons['folder-home.svg'];
  1498. }
  1499. else if(options.path === window.trash_path){
  1500. title = 'Trash';
  1501. icon = window.icons['trash.svg'];
  1502. }
  1503. else if(!options.path)
  1504. title = window.root_dirname;
  1505. else
  1506. title = path.dirname(options.path);
  1507. // open window
  1508. el_win = UIWindow({
  1509. element_uuid: uuid,
  1510. icon: icon,
  1511. path: options.path ?? window.home_path,
  1512. title: title,
  1513. uid: null,
  1514. is_dir: true,
  1515. app: 'explorer',
  1516. ...window_options,
  1517. is_maximized: options.maximized,
  1518. });
  1519. }
  1520. //------------------------------------
  1521. // All other apps
  1522. //------------------------------------
  1523. else{
  1524. process = new PortalProcess({
  1525. uuid,
  1526. name: app_info.name,
  1527. parent: options.parent_instance_id,
  1528. meta: {
  1529. launch_options: options,
  1530. app_info: app_info,
  1531. }
  1532. });
  1533. const svc_process = globalThis.services.get('process');
  1534. svc_process.register(process);
  1535. //-----------------------------------
  1536. // iframe_url
  1537. //-----------------------------------
  1538. let iframe_url;
  1539. // This can be any trusted URL that won't be used for other apps
  1540. const BUILTIN_PREFIX = 'https://builtins.namespaces.puter.com/';
  1541. if(!app_info.index_url){
  1542. iframe_url = new URL('https://'+options.name+'.' + window.app_domain + `/index.html`);
  1543. } else if ( app_info.index_url.startsWith(BUILTIN_PREFIX) ) {
  1544. const name = app_info.index_url.slice(BUILTIN_PREFIX.length);
  1545. iframe_url = new URL(`${window.gui_origin}/builtin/${name}`);
  1546. } else {
  1547. iframe_url = new URL(app_info.index_url);
  1548. }
  1549. // add app_instance_id to URL
  1550. iframe_url.searchParams.append('puter.app_instance_id', uuid);
  1551. // add app_id to URL
  1552. iframe_url.searchParams.append('puter.app.id', app_info.uuid);
  1553. // add parent_app_instance_id to URL
  1554. if (options.parent_instance_id) {
  1555. iframe_url.searchParams.append('puter.parent_instance_id', options.parent_instance_id);
  1556. }
  1557. if(file_signature){
  1558. iframe_url.searchParams.append('puter.item.uid', file_signature.uid);
  1559. iframe_url.searchParams.append('puter.item.path', options.file_path ? `~/` + options.file_path.split('/').slice(1).join('/') : file_signature.path);
  1560. iframe_url.searchParams.append('puter.item.name', file_signature.fsentry_name);
  1561. iframe_url.searchParams.append('puter.item.read_url', file_signature.read_url);
  1562. iframe_url.searchParams.append('puter.item.write_url', file_signature.write_url);
  1563. iframe_url.searchParams.append('puter.item.metadata_url', file_signature.metadata_url);
  1564. iframe_url.searchParams.append('puter.item.size', file_signature.fsentry_size);
  1565. iframe_url.searchParams.append('puter.item.accessed', file_signature.fsentry_accessed);
  1566. iframe_url.searchParams.append('puter.item.modified', file_signature.fsentry_modified);
  1567. iframe_url.searchParams.append('puter.item.created', file_signature.fsentry_created);
  1568. iframe_url.searchParams.append('puter.domain', window.app_domain);
  1569. }
  1570. else if(options.readURL){
  1571. iframe_url.searchParams.append('puter.item.name', options.filename);
  1572. iframe_url.searchParams.append('puter.item.path', options.file_path ? `~/` + options.file_path.split('/').slice(1).join('/') : undefined);
  1573. iframe_url.searchParams.append('puter.item.read_url', options.readURL);
  1574. iframe_url.searchParams.append('puter.domain', window.app_domain);
  1575. }
  1576. if (app_info.godmode && app_info.godmode === 1){
  1577. // Add auth_token to GODMODE apps
  1578. iframe_url.searchParams.append('puter.auth.token', window.auth_token);
  1579. iframe_url.searchParams.append('puter.auth.username', window.user.username);
  1580. iframe_url.searchParams.append('puter.domain', window.app_domain);
  1581. } else if (options.token){
  1582. // App token. Only add token if it's not a GODMODE app since GODMODE apps already have the super token
  1583. // that has access to everything.
  1584. iframe_url.searchParams.append('puter.auth.token', options.token);
  1585. } else {
  1586. // Try to acquire app token from the server
  1587. let response = await fetch(window.api_origin + "/auth/get-user-app-token", {
  1588. "headers": {
  1589. "Content-Type": "application/json",
  1590. "Authorization": "Bearer "+ window.auth_token,
  1591. },
  1592. "body": JSON.stringify({app_uid: app_info.uid ?? app_info.uuid}),
  1593. "method": "POST",
  1594. });
  1595. let res = await response.json();
  1596. if(res.token){
  1597. iframe_url.searchParams.append('puter.auth.token', res.token);
  1598. }
  1599. }
  1600. if(window.api_origin)
  1601. iframe_url.searchParams.append('puter.api_origin', window.api_origin);
  1602. // Add options.params to URL
  1603. if(options.params){
  1604. iframe_url.searchParams.append('puter.domain', window.app_domain);
  1605. for (const property in options.params) {
  1606. iframe_url.searchParams.append(property, options.params[property]);
  1607. }
  1608. }
  1609. // Add locale to URL
  1610. iframe_url.searchParams.append('puter.locale', window.locale);
  1611. // Add options.args to URL
  1612. iframe_url.searchParams.append('puter.args', JSON.stringify(options.args ?? {}));
  1613. // ...and finally append utm_source=puter.com to the URL
  1614. iframe_url.searchParams.append('utm_source', 'puter.com');
  1615. // register app_instance_uid
  1616. window.app_instance_ids.add(uuid);
  1617. // open window
  1618. el_win = UIWindow({
  1619. element_uuid: uuid,
  1620. title: title,
  1621. iframe_url: iframe_url.href,
  1622. params: options.params ?? undefined,
  1623. icon: icon,
  1624. window_class: 'window-app',
  1625. update_window_url: true,
  1626. app_uuid: app_info.uuid ?? app_info.uid,
  1627. top: options.maximized ? 0 : undefined,
  1628. left: options.maximized ? 0 : undefined,
  1629. height: options.maximized ? `calc(100% - ${window.taskbar_height + window.toolbar_height + 1}px)` : undefined,
  1630. width: options.maximized ? `100%` : undefined,
  1631. app: options.name,
  1632. is_visible: ! app_info.background,
  1633. is_maximized: options.maximized,
  1634. is_fullpage: options.is_fullpage,
  1635. ...window_options,
  1636. show_in_taskbar: app_info.background ? false : window_options?.show_in_taskbar,
  1637. });
  1638. if ( ! app_info.background ) {
  1639. $(el_win).show();
  1640. }
  1641. // send post request to /rao to record app open
  1642. if(options.name !== 'explorer'){
  1643. // add the app to the beginning of the array
  1644. window.launch_apps.recent.unshift(app_info);
  1645. // dedupe the array by uuid, uid, and id
  1646. window.launch_apps.recent = _.uniqBy(window.launch_apps.recent, 'name');
  1647. // limit to window.launch_recent_apps_count
  1648. window.launch_apps.recent = window.launch_apps.recent.slice(0, window.launch_recent_apps_count);
  1649. // send post request to /rao to record app open
  1650. $.ajax({
  1651. url: window.api_origin + "/rao",
  1652. type: 'POST',
  1653. data: JSON.stringify({
  1654. original_client_socket_id: window.socket?.id,
  1655. app_uid: app_info.uid ?? app_info.uuid,
  1656. }),
  1657. async: true,
  1658. contentType: "application/json",
  1659. headers: {
  1660. "Authorization": "Bearer "+window.auth_token
  1661. },
  1662. })
  1663. }
  1664. }
  1665. (async () => {
  1666. const el = await el_win;
  1667. $(el).on('remove', () => {
  1668. const svc_process = globalThis.services.get('process');
  1669. svc_process.unregister(process.uuid);
  1670. // If it's a non-sdk app, report that it launched and closed.
  1671. // FIXME: This is awkward. Really, we want some way of knowing when it's launched and reporting that immediately instead.
  1672. const $app_iframe = $(el).find('.window-app-iframe');
  1673. if ($app_iframe.attr('data-appUsesSdk') !== 'true') {
  1674. window.report_app_launched(process.uuid, { uses_sdk: false });
  1675. // We also have to report an extra close event because the real one was sent already
  1676. window.report_app_closed(process.uuid);
  1677. }
  1678. });
  1679. process.references.el_win = el;
  1680. process.chstatus(PROCESS_RUNNING);
  1681. })();
  1682. }
  1683. window.open_item = async function(options){
  1684. let el_item = options.item;
  1685. const $el_parent_window = $(el_item).closest('.window');
  1686. const parent_win_id = $($el_parent_window).attr('data-id');
  1687. const is_dir = $(el_item).attr('data-is_dir') === '1' ? true : false;
  1688. const uid = $(el_item).attr('data-shortcut_to') === '' ? $(el_item).attr('data-uid') : $(el_item).attr('data-shortcut_to');
  1689. const item_path = $(el_item).attr('data-shortcut_to_path') === '' ? $(el_item).attr('data-path') : $(el_item).attr('data-shortcut_to_path');
  1690. const is_shortcut = $(el_item).attr('data-is_shortcut') === '1';
  1691. const shortcut_to_path = $(el_item).attr('data-shortcut_to_path');
  1692. const associated_app_name = $(el_item).attr('data-associated_app_name');
  1693. const file_uid = $(el_item).attr('data-uid');
  1694. //----------------------------------------------------------------
  1695. // Is this a shortcut whose source is perma-deleted?
  1696. //----------------------------------------------------------------
  1697. if(is_shortcut && shortcut_to_path === ''){
  1698. UIAlert(`This shortcut can't be opened because its source has been deleted.`)
  1699. }
  1700. //----------------------------------------------------------------
  1701. // Is this a shortcut whose source is trashed?
  1702. //----------------------------------------------------------------
  1703. else if(is_shortcut && shortcut_to_path.startsWith(window.trash_path + '/')){
  1704. UIAlert(`This shortcut can't be opened because its source has been deleted.`)
  1705. }
  1706. //----------------------------------------------------------------
  1707. // Is this a trashed file?
  1708. //----------------------------------------------------------------
  1709. else if(item_path.startsWith(window.trash_path + '/')){
  1710. UIAlert(`This item can't be opened because it's in the trash. To use this item, first drag it out of the Trash.`)
  1711. }
  1712. //----------------------------------------------------------------
  1713. // Is this a file (no dir) on a SaveFileDialog?
  1714. //----------------------------------------------------------------
  1715. else if($el_parent_window.attr('data-is_saveFileDialog') === 'true' && !is_dir){
  1716. $el_parent_window.find('.savefiledialog-filename').val($(el_item).attr('data-name'));
  1717. $el_parent_window.find('.savefiledialog-save-btn').trigger('click');
  1718. }
  1719. //----------------------------------------------------------------
  1720. // Is this a file (no dir) on an OpenFileDialog?
  1721. //----------------------------------------------------------------
  1722. else if($el_parent_window.attr('data-is_openFileDialog') === 'true' && !is_dir){
  1723. $el_parent_window.find('.window-disable-mask, .busy-indicator').show();
  1724. let busy_init_ts = Date.now();
  1725. try{
  1726. let filedialog_parent_uid = $el_parent_window.attr('data-parent_uuid');
  1727. let $filedialog_parent_app_window = $(`.window[data-element_uuid="${filedialog_parent_uid}"]`);
  1728. let parent_window_app_uid = $filedialog_parent_app_window.attr('data-app_uuid');
  1729. const initiating_app_uuid = $el_parent_window.attr('data-initiating_app_uuid');
  1730. let res = await puter.fs.sign(window.host_app_uid ?? parent_window_app_uid, {uid: uid, action: 'write'});
  1731. res = res.items;
  1732. // todo split is buggy because there might be a slash in the filename
  1733. res.path = `~/` + item_path.split('/').slice(2).join('/');
  1734. const parent_uuid = $el_parent_window.attr('data-parent_uuid');
  1735. const return_to_parent_window = $el_parent_window.attr('data-return_to_parent_window') === 'true';
  1736. if(return_to_parent_window){
  1737. window.opener.postMessage({
  1738. msg: "fileOpenPicked",
  1739. original_msg_id: $el_parent_window.attr('data-iframe_msg_uid'),
  1740. items: Array.isArray(res) ? [...res] : [res],
  1741. // LEGACY SUPPORT, remove this in the future when Polotno uses the new SDK
  1742. // this is literally put in here to support Polotno's legacy code
  1743. ...(!Array.isArray(res) && res)
  1744. }, '*');
  1745. window.close();
  1746. }
  1747. else if(parent_uuid){
  1748. // send event to iframe
  1749. const target_iframe = $(`.window[data-element_uuid="${parent_uuid}"]`).find('.window-app-iframe').get(0);
  1750. if(target_iframe){
  1751. let retobj = {
  1752. msg: "fileOpenPicked",
  1753. original_msg_id: $el_parent_window.attr('data-iframe_msg_uid'),
  1754. items: Array.isArray(res) ? [...res] : [res],
  1755. // LEGACY SUPPORT, remove this in the future when Polotno uses the new SDK
  1756. // this is literally put in here to support Polotno's legacy code
  1757. ...(!Array.isArray(res) && res)
  1758. };
  1759. target_iframe.contentWindow.postMessage(retobj, '*');
  1760. }
  1761. // focus iframe
  1762. $(target_iframe).get(0)?.focus({preventScroll:true});
  1763. // send file_opened event
  1764. const file_opened_event = new CustomEvent('file_opened', {detail: res});
  1765. // dispatch event to parent window
  1766. $(`.window[data-element_uuid="${parent_uuid}"]`).get(0)?.dispatchEvent(file_opened_event);
  1767. }
  1768. }catch(e){
  1769. console.log(e);
  1770. }
  1771. // done
  1772. let busy_duration = (Date.now() - busy_init_ts);
  1773. if( busy_duration >= window.busy_indicator_hide_delay){
  1774. $el_parent_window.close();
  1775. }else{
  1776. setTimeout(() => {
  1777. // close this dialog
  1778. $el_parent_window.close();
  1779. }, Math.abs(window.busy_indicator_hide_delay - busy_duration));
  1780. }
  1781. }
  1782. //----------------------------------------------------------------
  1783. // Does the user have a preference for this file type?
  1784. //----------------------------------------------------------------
  1785. else if(!associated_app_name && !is_dir && window.user_preferences[`default_apps${path.extname(item_path).toLowerCase()}`]) {
  1786. window.launch_app({
  1787. name: window.user_preferences[`default_apps${path.extname(item_path).toLowerCase()}`],
  1788. file_path: item_path,
  1789. window_title: path.basename(item_path),
  1790. maximized: options.maximized,
  1791. file_uid: file_uid,
  1792. });
  1793. }
  1794. //----------------------------------------------------------------
  1795. // Is there an app associated with this item?
  1796. //----------------------------------------------------------------
  1797. else if(associated_app_name !== ''){
  1798. window.launch_app({
  1799. name: associated_app_name,
  1800. })
  1801. }
  1802. //----------------------------------------------------------------
  1803. // Dir with no open windows: create a new window
  1804. //----------------------------------------------------------------
  1805. else if(is_dir && ($el_parent_window.length === 0 || options.new_window)){
  1806. UIWindow({
  1807. path: item_path,
  1808. title: path.basename(item_path),
  1809. icon: await window.item_icon({is_dir: true, path: item_path}),
  1810. uid: $(el_item).attr('data-uid'),
  1811. is_dir: is_dir,
  1812. app: 'explorer',
  1813. top: options.maximized ? 0 : undefined,
  1814. left: options.maximized ? 0 : undefined,
  1815. height: options.maximized ? `calc(100% - ${window.taskbar_height + window.toolbar_height + 1}px)` : undefined,
  1816. width: options.maximized ? `100%` : undefined,
  1817. });
  1818. }
  1819. //----------------------------------------------------------------
  1820. // Dir with an open window: change the path of the open window
  1821. //----------------------------------------------------------------
  1822. else if($el_parent_window.length > 0 && is_dir){
  1823. window.window_nav_history[parent_win_id] = window.window_nav_history[parent_win_id].slice(0, window.window_nav_history_current_position[parent_win_id]+1);
  1824. window.window_nav_history[parent_win_id].push(item_path);
  1825. window.window_nav_history_current_position[parent_win_id]++;
  1826. window.update_window_path($el_parent_window, item_path);
  1827. }
  1828. //----------------------------------------------------------------
  1829. // all other cases: try to open using an app
  1830. //----------------------------------------------------------------
  1831. else{
  1832. const fspath = item_path.toLowerCase();
  1833. const fsuid = uid.toLowerCase();
  1834. let open_item_meta;
  1835. // get all info needed to open an item
  1836. try{
  1837. open_item_meta = await $.ajax({
  1838. url: window.api_origin + "/open_item",
  1839. type: 'POST',
  1840. contentType: "application/json",
  1841. data: JSON.stringify({
  1842. uid: fsuid ?? undefined,
  1843. path: fspath ?? undefined,
  1844. }),
  1845. headers: {
  1846. "Authorization": "Bearer "+window.auth_token
  1847. },
  1848. statusCode: {
  1849. 401: function () {
  1850. window.logout();
  1851. },
  1852. },
  1853. });
  1854. }catch(err){
  1855. // Ignored
  1856. }
  1857. // get a list of suggested apps for this file type.
  1858. let suggested_apps = open_item_meta?.suggested_apps ?? await window.suggest_apps_for_fsentry({uid: fsuid, path: fspath});
  1859. //---------------------------------------------
  1860. // No suitable apps, ask if user would like to
  1861. // download
  1862. //---------------------------------------------
  1863. if(suggested_apps.length === 0){
  1864. //---------------------------------------------
  1865. // If .zip file, unzip it
  1866. //---------------------------------------------
  1867. if(path.extname(item_path) === '.zip'){
  1868. window.unzipItem(item_path);
  1869. return;
  1870. }
  1871. const alert_resp = await UIAlert(
  1872. 'Found no suitable apps to open this file with. Would you like to download it instead?',
  1873. [
  1874. {
  1875. label: i18n('download_file'),
  1876. value: 'download_file',
  1877. type: 'primary',
  1878. },
  1879. {
  1880. label: i18n('cancel')
  1881. }
  1882. ])
  1883. if(alert_resp === 'download_file'){
  1884. window.trigger_download([item_path]);
  1885. }
  1886. return;
  1887. }
  1888. //---------------------------------------------
  1889. // First suggested app is default app to open this item
  1890. //---------------------------------------------
  1891. else{
  1892. window.launch_app({
  1893. name: suggested_apps[0].name,
  1894. token: open_item_meta.token,
  1895. file_path: item_path,
  1896. app_obj: suggested_apps[0],
  1897. window_title: path.basename(item_path),
  1898. file_uid: fsuid,
  1899. maximized: options.maximized,
  1900. file_signature: open_item_meta.signature,
  1901. });
  1902. }
  1903. }
  1904. }
  1905. /**
  1906. * Moves the given items to the destination path.
  1907. *
  1908. * @param {HTMLElement[]} el_items - jQuery elements representing the items to move
  1909. * @param {string} dest_path - The destination path to move the items to
  1910. * @returns {Promise<void>}
  1911. */
  1912. window.move_items = async function(el_items, dest_path, is_undo = false){
  1913. let move_op_id = window.operation_id++;
  1914. window.operation_cancelled[move_op_id] = false;
  1915. // --------------------------------------------------------
  1916. // Optimization: in case all items being moved
  1917. // are immutable do not proceed
  1918. // --------------------------------------------------------
  1919. let all_items_are_immutable = true;
  1920. for(let i=0; i<el_items.length; i++){
  1921. if($(el_items[i]).attr('data-immutable') === '0'){
  1922. all_items_are_immutable = false;
  1923. break;
  1924. }
  1925. }
  1926. if(all_items_are_immutable)
  1927. return;
  1928. // --------------------------------------------------------
  1929. // good to go, proceed
  1930. // --------------------------------------------------------
  1931. // overwrite all items? default is false unless in a conflict case user asks for it
  1932. let overwrite_all = false;
  1933. // when did this operation start
  1934. let move_init_ts = Date.now();
  1935. // only show progress window if it takes longer than 2s to move
  1936. let progwin;
  1937. let progwin_timeout = setTimeout(async () => {
  1938. progwin = await UIWindowProgress({
  1939. operation_id: move_op_id,
  1940. on_cancel: () => {
  1941. window.operation_cancelled[move_op_id] = true;
  1942. },
  1943. });
  1944. }, 2000);
  1945. // storing moved items for undo ability
  1946. const moved_items = []
  1947. // Go through each item and try to move it
  1948. for(let i=0; i<el_items.length; i++){
  1949. // get current item
  1950. let el_item = el_items[i];
  1951. // if operation cancelled by user, stop
  1952. if(window.operation_cancelled[move_op_id])
  1953. return;
  1954. // cannot move an immutable item, skip it
  1955. if($(el_item).attr('data-immutable') === '1')
  1956. continue;
  1957. // cannot move item to its own path, skip it
  1958. if(path.dirname($(el_item).attr('data-path')) === dest_path){
  1959. await UIAlert(`<p>Moving <strong>${html_encode($(el_item).attr('data-name'))}</strong></p>Cannot move item to its current location.`)
  1960. continue;
  1961. }
  1962. // if an item with the same name already exists in the destination path
  1963. let item_with_same_name_already_exists = false;
  1964. let overwrite = overwrite_all;
  1965. let untrashed_at_least_one_item = false;
  1966. // --------------------------------------------------------
  1967. // Keep trying to move the item until it succeeds or is cancelled
  1968. // or user decides to overwrite or skip
  1969. // --------------------------------------------------------
  1970. do{
  1971. try{
  1972. let path_to_show_on_progwin = $(el_item).attr('data-path');
  1973. // parse metadata if any
  1974. let metadata = $(el_item).attr('data-metadata');
  1975. // no metadata?
  1976. if(metadata === '' || metadata === 'null' || metadata === null)
  1977. metadata = {}
  1978. // try to parse metadata as JSON
  1979. else{
  1980. try{
  1981. metadata = JSON.parse(metadata)
  1982. }catch(e){
  1983. // Ignored
  1984. }
  1985. }
  1986. let new_name;
  1987. // user cancelled?
  1988. if(window.operation_cancelled[move_op_id])
  1989. return;
  1990. // indicates whether this is a recycling operation
  1991. let recycling = false;
  1992. let status_i18n_string = 'moving_file';
  1993. // --------------------------------------------------------
  1994. // Trashing
  1995. // --------------------------------------------------------
  1996. if(dest_path === window.trash_path){
  1997. new_name = $(el_item).attr('data-uid');
  1998. metadata = {
  1999. original_name: $(el_item).attr('data-name'),
  2000. original_path: $(el_item).attr('data-path'),
  2001. trashed_ts: Math.round(Date.now() / 1000),
  2002. };
  2003. status_i18n_string = 'deleting_file';
  2004. // update other clients
  2005. if(window.socket)
  2006. window.socket.emit('trash.is_empty', {is_empty: false});
  2007. // change trash icons to 'trash-full.svg'
  2008. $(`[data-app="trash"]`).find('.taskbar-icon > img').attr('src', window.icons['trash-full.svg']);
  2009. $(`.item[data-path="${html_encode(window.trash_path)}" i], .item[data-shortcut_to_path="${html_encode(window.trash_path)}" i]`).find('.item-icon > img').attr('src', window.icons['trash-full.svg']);
  2010. $(`.window[data-path="${html_encode(window.trash_path)}" i]`).find('.window-head-icon').attr('src', window.icons['trash-full.svg']);
  2011. }
  2012. // moving an item into a trashed directory? deny.
  2013. else if(dest_path.startsWith(window.trash_path)){
  2014. progwin?.close();
  2015. UIAlert('Cannot move items into a deleted folder.');
  2016. return;
  2017. }
  2018. // --------------------------------------------------------
  2019. // If recycling an item, restore its original name
  2020. // --------------------------------------------------------
  2021. else if(metadata.trashed_ts !== undefined){
  2022. recycling = true;
  2023. new_name = metadata.original_name;
  2024. metadata = {};
  2025. untrashed_at_least_one_item = true;
  2026. path_to_show_on_progwin = window.trash_path + '/' + new_name;
  2027. }
  2028. // --------------------------------------------------------
  2029. // update progress window with current item being moved
  2030. // --------------------------------------------------------
  2031. progwin?.set_status(i18n(status_i18n_string, path_to_show_on_progwin));
  2032. // execute move
  2033. let resp = await puter.fs.move({
  2034. source: $(el_item).attr('data-uid'),
  2035. destination: dest_path,
  2036. overwrite: overwrite || overwrite_all,
  2037. newName: new_name,
  2038. // recycling requires making all missing dirs
  2039. createMissingParents: recycling,
  2040. newMetadata: metadata,
  2041. excludeSocketID: window.socket?.id,
  2042. });
  2043. let fsentry = resp.moved;
  2044. // path must use the real name from DB
  2045. fsentry.path = path.join(dest_path, fsentry.name);
  2046. // skip next loop iteration because this iteration was successful
  2047. item_with_same_name_already_exists = false;
  2048. // update all shortcut_to_path
  2049. $(`.item[data-shortcut_to_path="${html_encode($(el_item).attr('data-path'))}" i]`).attr(`data-shortcut_to_path`, fsentry.path);
  2050. // Remove all items with matching uids
  2051. $(`.item[data-uid='${$(el_item).attr('data-uid')}']`).fadeOut(150, function(){
  2052. // find all parent windows that contain this item
  2053. let parent_windows = $(`.item[data-uid='${$(el_item).attr('data-uid')}']`).closest('.window');
  2054. // remove this item
  2055. $(this).removeItems();
  2056. // update parent windows' item counts and selected item counts in their footers
  2057. $(parent_windows).each(function(){
  2058. window.update_explorer_footer_item_count(this);
  2059. window.update_explorer_footer_selected_items_count(this)
  2060. });
  2061. })
  2062. // if trashing, close windows of trashed items and its descendants
  2063. if(dest_path === window.trash_path){
  2064. $(`.window[data-path="${html_encode($(el_item).attr('data-path'))}" i]`).close();
  2065. // todo this has to be case-insensitive but the `i` selector doesn't work on ^=
  2066. $(`.window[data-path^="${html_encode($(el_item).attr('data-path'))}/"]`).close();
  2067. }
  2068. // update all paths of its and its descendants' open windows
  2069. else{
  2070. // todo this has to be case-insensitive but the `i` selector doesn't work on ^=
  2071. $(`.window[data-path^="${html_encode($(el_item).attr('data-path'))}/"], .window[data-path="${html_encode($(el_item).attr('data-path'))}" i]`).each(function(){
  2072. window.update_window_path(this, $(this).attr('data-path').replace($(el_item).attr('data-path'), path.join(dest_path, fsentry.name)));
  2073. })
  2074. }
  2075. if(dest_path === window.trash_path){
  2076. // if trashing dir...
  2077. if($(el_item).attr('data-is_dir') === '1'){
  2078. // disassociate all its websites
  2079. // todo, some client-side check to see if this dir has at least one associated website before sending ajax request
  2080. // FIXME: dir_uuid is not defined, is this the same as the data-uid attribute?
  2081. // puter.hosting.delete(dir_uuid)
  2082. $(`.mywebsites-dir-path[data-uuid="${$(el_item).attr('data-uid')}"]`).remove();
  2083. // remove the website badge from all instances of the dir
  2084. $(`.item[data-uid="${$(el_item).attr('data-uid')}"]`).find('.item-has-website-badge').fadeOut(300);
  2085. }
  2086. }
  2087. // if replacing an existing item, remove the old item that was just replaced
  2088. if(resp.overwritten?.id){
  2089. $(`.item[data-uid=${resp.overwritten.id}]`).removeItems();
  2090. }
  2091. // if this is trash, get original name from item metadata
  2092. fsentry.name = metadata?.original_name || fsentry.name;
  2093. // create new item on matching containers
  2094. const options = {
  2095. appendTo: $(`.item-container[data-path="${html_encode(dest_path)}" i]`),
  2096. immutable: fsentry.immutable,
  2097. associated_app_name: fsentry.associated_app?.name,
  2098. uid: fsentry.uid,
  2099. path: fsentry.path,
  2100. icon: await window.item_icon(fsentry),
  2101. name: (dest_path === window.trash_path) ? $(el_item).attr('data-name') : fsentry.name,
  2102. is_dir: fsentry.is_dir,
  2103. size: fsentry.size,
  2104. type: fsentry.type,
  2105. modified: fsentry.modified,
  2106. is_selected: false,
  2107. is_shared: (dest_path === window.trash_path) ? false : fsentry.is_shared,
  2108. is_shortcut: fsentry.is_shortcut,
  2109. shortcut_to: fsentry.shortcut_to,
  2110. shortcut_to_path: fsentry.shortcut_to_path,
  2111. has_website: $(el_item).attr('data-has_website') === '1',
  2112. metadata: fsentry.metadata ?? '',
  2113. suggested_apps: fsentry.suggested_apps,
  2114. }
  2115. UIItem(options);
  2116. moved_items.push({'options': options, 'original_path': $(el_item).attr('data-path')});
  2117. // this operation may have created some missing directories,
  2118. // see if any of the directories in the path of this file is new AND
  2119. // if these new path have any open parents that need to be updated
  2120. resp.parent_dirs_created?.forEach(async dir => {
  2121. let item_container = $(`.item-container[data-path="${html_encode(path.dirname(dir.path))}" i]`);
  2122. if(item_container.length > 0 && $(`.item[data-path="${html_encode(dir.path)}" i]`).length === 0){
  2123. UIItem({
  2124. appendTo: item_container,
  2125. immutable: false,
  2126. uid: dir.uid,
  2127. path: dir.path,
  2128. icon: await window.item_icon(dir),
  2129. name: dir.name,
  2130. size: dir.size,
  2131. type: dir.type,
  2132. modified: dir.modified,
  2133. is_dir: true,
  2134. is_selected: false,
  2135. is_shared: dir.is_shared,
  2136. has_website: false,
  2137. suggested_apps: dir.suggested_apps,
  2138. });
  2139. }
  2140. window.sort_items(item_container);
  2141. });
  2142. //sort each container
  2143. $(`.item-container[data-path="${html_encode(dest_path)}" i]`).each(function(){
  2144. window.sort_items(this, $(this).attr('data-sort_by'), $(this).attr('data-sort_order'))
  2145. })
  2146. }catch(err){
  2147. // -----------------------------------------------------------------------
  2148. // if item with same name already exists, ask user if they want to overwrite
  2149. // -----------------------------------------------------------------------
  2150. if(err.code==='item_with_same_name_exists'){
  2151. item_with_same_name_already_exists = true;
  2152. const alert_resp = await UIAlert({
  2153. message: `<strong>${html_encode(err.entry_name)}</strong> already exists.`,
  2154. buttons:[
  2155. { label: i18n('replace'), type: 'primary', value: 'replace' },
  2156. ... (el_items.length > 1) ? [{label: i18n('replace_all'), value: 'replace_all'}] : [],
  2157. ... (el_items.length > 1) ? [{label: i18n('skip'), value: 'skip'}] : [{label: i18n('cancel'), value: 'cancel'}],
  2158. ]
  2159. })
  2160. if(alert_resp === 'replace'){
  2161. overwrite = true;
  2162. }else if (alert_resp === 'replace_all'){
  2163. overwrite = true;
  2164. overwrite_all = true;
  2165. }else if(alert_resp === 'skip' || alert_resp === 'cancel'){
  2166. item_with_same_name_already_exists = false;
  2167. }
  2168. }
  2169. // -----------------------------------------------------------------------
  2170. // all other errors
  2171. // -----------------------------------------------------------------------
  2172. else{
  2173. item_with_same_name_already_exists = false;
  2174. // error message after source item has reappeared
  2175. $(el_item).show(0, function(){
  2176. UIAlert(`<p>Moving <strong>${html_encode($(el_item).attr('data-name'))}</strong></p>${err.message ?? ''}`)
  2177. });
  2178. break;
  2179. }
  2180. }
  2181. }while(item_with_same_name_already_exists);
  2182. // check if trash is empty
  2183. if(untrashed_at_least_one_item){
  2184. const trash = await puter.fs.stat(window.trash_path);
  2185. if(window.socket){
  2186. window.socket.emit('trash.is_empty', {is_empty: trash.is_empty});
  2187. }
  2188. if(trash.is_empty){
  2189. $(`[data-app="trash"]`).find('.taskbar-icon > img').attr('src', window.icons['trash.svg']);
  2190. $(`.item[data-path="${html_encode(window.trash_path)}" i]`).find('.item-icon > img').attr('src', window.icons['trash.svg']);
  2191. $(`.window[data-path="${html_encode(window.trash_path)}" i]`).find('.window-head-icon').attr('src', window.icons['trash.svg']);
  2192. }
  2193. }
  2194. }
  2195. clearTimeout(progwin_timeout);
  2196. // log stats to console
  2197. let move_duration = (Date.now() - move_init_ts);
  2198. console.log(`moved ${el_items.length} item${el_items.length > 1 ? 's':''} in ${move_duration}ms`);
  2199. // -----------------------------------------------------------------------
  2200. // DONE! close progress window with delay to allow user to see 100% progress
  2201. // -----------------------------------------------------------------------
  2202. // Add action to actions_history for undo ability
  2203. if(!is_undo && dest_path !== window.trash_path){
  2204. window.actions_history.push({
  2205. operation: 'move',
  2206. data: moved_items,
  2207. });
  2208. }else if(!is_undo && dest_path === window.trash_path){
  2209. window.actions_history.push({
  2210. operation: 'delete',
  2211. data: moved_items,
  2212. });
  2213. }
  2214. if(progwin){
  2215. setTimeout(() => {
  2216. progwin.close();
  2217. }, window.copy_progress_hide_delay);
  2218. }
  2219. }
  2220. /**
  2221. * Generates sharing URLs for various social media platforms and services based on the provided arguments.
  2222. *
  2223. * @global
  2224. * @function
  2225. * @param {Object} args - Configuration object for generating share URLs.
  2226. * @param {string} [args.url] - The URL to share.
  2227. * @param {string} [args.title] - The title or headline of the content to share.
  2228. * @param {string} [args.image] - Image URL associated with the content.
  2229. * @param {string} [args.desc] - A description of the content.
  2230. * @param {string} [args.appid] - App ID for certain platforms that require it.
  2231. * @param {string} [args.redirecturl] - Redirect URL for certain platforms.
  2232. * @param {string} [args.via] - Attribution source, e.g., a Twitter username.
  2233. * @param {string} [args.hashtags] - Comma-separated list of hashtags without '#'.
  2234. * @param {string} [args.provider] - Content provider.
  2235. * @param {string} [args.language] - Content's language.
  2236. * @param {string} [args.userid] - User ID for certain platforms.
  2237. * @param {string} [args.category] - Content's category.
  2238. * @param {string} [args.phonenumber] - Phone number for platforms like SMS or Telegram.
  2239. * @param {string} [args.emailaddress] - Email address to share content to.
  2240. * @param {string} [args.ccemailaddress] - CC email address for sharing content.
  2241. * @param {string} [args.bccemailaddress] - BCC email address for sharing content.
  2242. * @returns {Object} - An object containing key-value pairs where keys are platform names and values are constructed sharing URLs.
  2243. *
  2244. * @example
  2245. * const shareConfig = {
  2246. * url: 'https://example.com',
  2247. * title: 'Check this out!',
  2248. * desc: 'This is an amazing article on example.com',
  2249. * via: 'exampleUser'
  2250. * };
  2251. * const shareLinks = window.socialLink(shareConfig);
  2252. * console.log(shareLinks.twitter); // Outputs the constructed Twitter share link
  2253. */
  2254. window.socialLink = function (args) {
  2255. const validargs = [
  2256. 'url',
  2257. 'title',
  2258. 'image',
  2259. 'desc',
  2260. 'appid',
  2261. 'redirecturl',
  2262. 'via',
  2263. 'hashtags',
  2264. 'provider',
  2265. 'language',
  2266. 'userid',
  2267. 'category',
  2268. 'phonenumber',
  2269. 'emailaddress',
  2270. 'cemailaddress',
  2271. 'bccemailaddress',
  2272. ];
  2273. for(var i = 0; i < validargs.length; i++) {
  2274. const validarg = validargs[i];
  2275. if(!args[validarg]) {
  2276. args[validarg] = '';
  2277. }
  2278. }
  2279. const url = fixedEncodeURIComponent(args.url);
  2280. const title = fixedEncodeURIComponent(args.title);
  2281. const image = fixedEncodeURIComponent(args.image);
  2282. const desc = fixedEncodeURIComponent(args.desc);
  2283. const via = fixedEncodeURIComponent(args.via);
  2284. const hash_tags = fixedEncodeURIComponent(args.hashtags);
  2285. const language = fixedEncodeURIComponent(args.language);
  2286. const user_id = fixedEncodeURIComponent(args.userid);
  2287. const category = fixedEncodeURIComponent(args.category);
  2288. const phone_number = fixedEncodeURIComponent(args.phonenumber);
  2289. const email_address = fixedEncodeURIComponent(args.emailaddress);
  2290. const cc_email_address = fixedEncodeURIComponent(args.ccemailaddress);
  2291. const bcc_email_address = fixedEncodeURIComponent(args.bccemailaddress);
  2292. var text = title;
  2293. if(desc) {
  2294. text += '%20%3A%20'; // This is just this, " : "
  2295. text += desc;
  2296. }
  2297. return {
  2298. 'add.this':'http://www.addthis.com/bookmark.php?url=' + url,
  2299. 'blogger':'https://www.blogger.com/blog-this.g?u=' + url + '&n=' + title + '&t=' + desc,
  2300. 'buffer':'https://buffer.com/add?text=' + text + '&url=' + url,
  2301. 'diaspora':'https://share.diasporafoundation.org/?title=' + title + '&url=' + url,
  2302. 'douban':'http://www.douban.com/recommend/?url=' + url + '&title=' + text,
  2303. 'email':'mailto:' + email_address + '?subject=' + title + '&body=' + desc,
  2304. 'evernote':'https://www.evernote.com/clip.action?url=' + url + '&title=' + text,
  2305. 'getpocket':'https://getpocket.com/edit?url=' + url,
  2306. 'facebook':'http://www.facebook.com/sharer.php?u=' + url,
  2307. 'flattr':'https://flattr.com/submit/auto?user_id=' + user_id + '&url=' + url + '&title=' + title + '&description=' + text + '&language=' + language + '&tags=' + hash_tags + '&hidden=HIDDEN&category=' + category,
  2308. 'flipboard':'https://share.flipboard.com/bookmarklet/popout?v=2&title=' + text + '&url=' + url,
  2309. 'gmail':'https://mail.google.com/mail/?view=cm&to=' + email_address + '&su=' + title + '&body=' + url + '&bcc=' + bcc_email_address + '&cc=' + cc_email_address,
  2310. 'google.bookmarks':'https://www.google.com/bookmarks/mark?op=edit&bkmk=' + url + '&title=' + title + '&annotation=' + text + '&labels=' + hash_tags + '',
  2311. 'instapaper':'http://www.instapaper.com/edit?url=' + url + '&title=' + title + '&description=' + desc,
  2312. 'line.me':'https://lineit.line.me/share/ui?url=' + url + '&text=' + text,
  2313. 'linkedin':'https://www.linkedin.com/sharing/share-offsite/?url=' + url,
  2314. 'livejournal':'http://www.livejournal.com/update.bml?subject=' + text + '&event=' + url,
  2315. 'hacker.news':'https://news.ycombinator.com/submitlink?u=' + url + '&t=' + title,
  2316. 'ok.ru':'https://connect.ok.ru/dk?st.cmd=WidgetSharePreview&st.shareUrl=' + url,
  2317. 'pinterest':'http://pinterest.com/pin/create/button/?url=' + url ,
  2318. 'qzone':'http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=' + url,
  2319. 'reddit':'https://reddit.com/submit?url=' + url + '&title=' + title,
  2320. 'renren':'http://widget.renren.com/dialog/share?resourceUrl=' + url + '&srcUrl=' + url + '&title=' + text + '&description=' + desc,
  2321. 'skype':'https://web.skype.com/share?url=' + url + '&text=' + text,
  2322. 'sms':'sms:' + phone_number + '?body=' + text,
  2323. 'surfingbird.ru':'http://surfingbird.ru/share?url=' + url + '&description=' + desc + '&screenshot=' + image + '&title=' + title,
  2324. 'telegram.me':'https://t.me/share/url?url=' + url + '&text=' + text + '&to=' + phone_number,
  2325. 'threema':'threema://compose?text=' + text + '&id=' + user_id,
  2326. 'tumblr':'https://www.tumblr.com/widgets/share/tool?canonicalUrl=' + url + '&title=' + title + '&caption=' + desc + '&tags=' + hash_tags,
  2327. 'twitter':'https://twitter.com/intent/tweet?url=' + url + '&text=' + text + '&via=' + via + '&hashtags=' + hash_tags,
  2328. 'vk':'http://vk.com/share.php?url=' + url + '&title=' + title + '&comment=' + desc,
  2329. 'weibo':'http://service.weibo.com/share/share.php?url=' + url + '&appkey=&title=' + title + '&pic=&ralateUid=',
  2330. 'whatsapp':'https://api.whatsapp.com/send?text=' + text + '%20' + url,
  2331. 'xing':'https://www.xing.com/spi/shares/new?url=' + url,
  2332. 'yahoo':'http://compose.mail.yahoo.com/?to=' + email_address + '&subject=' + title + '&body=' + text,
  2333. };
  2334. }
  2335. /**
  2336. * Encodes a URI component with enhanced safety by replacing characters
  2337. * that are not typically encoded by the standard encodeURIComponent.
  2338. *
  2339. * @param {string} str - The string to be URI encoded.
  2340. * @returns {string} - Returns the URI encoded string.
  2341. *
  2342. * @example
  2343. * const str = "Hello, world!";
  2344. * const encodedStr = fixedEncodeURIComponent(str);
  2345. * console.log(encodedStr); // Expected output: "Hello%2C%20world%21"
  2346. */
  2347. function fixedEncodeURIComponent(str) {
  2348. return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
  2349. return '%' + c.charCodeAt(0).toString(16);
  2350. });
  2351. }
  2352. /**
  2353. * Refreshes the desktop background based on the user's settings.
  2354. * If the user has set a custom desktop background URL or color, it will use that.
  2355. * If not, it defaults to a specific wallpaper image.
  2356. *
  2357. * @global
  2358. * @function
  2359. * @fires set_desktop_background - Calls this global function to set the desktop background.
  2360. *
  2361. * @example
  2362. * // This will refresh the desktop background according to the user's preference or defaults.
  2363. * window.refresh_desktop_background();
  2364. */
  2365. window.refresh_desktop_background = function(){
  2366. if(window.user && (window.user.desktop_bg_url !== null || window.user.desktop_bg_color !== null)){
  2367. window.set_desktop_background({
  2368. url: window.user.desktop_bg_url,
  2369. fit: window.user.desktop_bg_fit,
  2370. color: window.user.desktop_bg_color,
  2371. })
  2372. }
  2373. // default background
  2374. else{
  2375. let wallpaper = (window.gui_env === 'prod') ? '/dist/images/wallpaper.webp' : '/src/images/wallpaper.webp';
  2376. window.set_desktop_background({
  2377. url: wallpaper,
  2378. fit: 'cover',
  2379. });
  2380. }
  2381. }
  2382. window.determine_website_url = function(fsentry_path){
  2383. // search window.sites and if any site has `dir_path` set and the fsentry_path starts with that dir_path + '/', return the site's url + path
  2384. for(let i=0; i<window.sites.length; i++){
  2385. if(window.sites[i].dir_path && fsentry_path.startsWith(window.sites[i].dir_path + '/')){
  2386. return window.sites[i].address + fsentry_path.replace(window.sites[i].dir_path, '');
  2387. }
  2388. }
  2389. return null;
  2390. }
  2391. window.update_sites_cache = function(){
  2392. return puter.hosting.list((sites)=>{
  2393. if(sites && sites.length > 0){
  2394. window.sites = sites;
  2395. }else{
  2396. window.sites = [];
  2397. }
  2398. })
  2399. }
  2400. /**
  2401. *
  2402. * @param {*} el_target_container
  2403. * @param {*} target_path
  2404. */
  2405. window.init_upload_using_dialog = function(el_target_container, target_path = null){
  2406. $("#upload-file-dialog").unbind('onchange');
  2407. $("#upload-file-dialog").unbind('change');
  2408. $("#upload-file-dialog").unbind('onChange');
  2409. target_path = target_path === null ? $(el_target_container).attr('data-path') : path.resolve(target_path);
  2410. $('#upload-file-dialog').trigger('click');
  2411. $("#upload-file-dialog").on('change', async function(e){
  2412. if($("#upload-file-dialog").val() !== ''){
  2413. const files = $('#upload-file-dialog')[0].files;
  2414. if(files.length > 0){
  2415. try{
  2416. window.upload_items(files, target_path);
  2417. }
  2418. catch(err){
  2419. UIAlert(err.message ?? err)
  2420. }
  2421. $('#upload-file-dialog').val('');
  2422. }
  2423. }
  2424. else{
  2425. return
  2426. }
  2427. })
  2428. }
  2429. window.upload_items = async function(items, dest_path){
  2430. let upload_progress_window;
  2431. let opid;
  2432. if(dest_path == window.trash_path){
  2433. UIAlert('Uploading to trash is not allowed!');
  2434. return;
  2435. }
  2436. puter.fs.upload(
  2437. // what to upload
  2438. items,
  2439. // where to upload
  2440. dest_path,
  2441. // options
  2442. {
  2443. // init
  2444. init: async(operation_id, xhr)=>{
  2445. opid = operation_id;
  2446. // create upload progress window
  2447. upload_progress_window = await UIWindowProgress({
  2448. title: i18n('upload'),
  2449. icon: window.icons[`app-icon-uploader.svg`],
  2450. operation_id: operation_id,
  2451. show_progress: true,
  2452. on_cancel: () => {
  2453. window.show_save_account_notice_if_needed();
  2454. xhr.abort();
  2455. },
  2456. });
  2457. // add to active_uploads
  2458. window.active_uploads[opid] = 0;
  2459. },
  2460. // start
  2461. start: async function(){
  2462. // change upload progress window message to uploading
  2463. upload_progress_window.set_status('Uploading');
  2464. upload_progress_window.set_progress(0);
  2465. },
  2466. // progress
  2467. progress: async function(operation_id, op_progress){
  2468. upload_progress_window.set_progress(op_progress);
  2469. // update active_uploads
  2470. window.active_uploads[opid] = op_progress;
  2471. // update title if window is not visible
  2472. if(document.visibilityState !== "visible"){
  2473. update_title_based_on_uploads();
  2474. }
  2475. },
  2476. // success
  2477. success: async function(items){
  2478. // DONE
  2479. // Add action to actions_history for undo ability
  2480. const files = []
  2481. if(typeof items[Symbol.iterator] === 'function'){
  2482. for(const item of items){
  2483. files.push(item.path)
  2484. }
  2485. }else{
  2486. files.push(items.path)
  2487. }
  2488. window.actions_history.push({
  2489. operation: 'upload',
  2490. data: files
  2491. });
  2492. // close progress window after a bit of delay for a better UX
  2493. setTimeout(() => {
  2494. setTimeout(() => {
  2495. upload_progress_window.close();
  2496. window.show_save_account_notice_if_needed();
  2497. }, Math.abs(window.upload_progress_hide_delay));
  2498. })
  2499. // remove from active_uploads
  2500. delete window.active_uploads[opid];
  2501. },
  2502. // error
  2503. error: async function(err){
  2504. upload_progress_window.show_error(i18n('error_uploading_files'), err.message);
  2505. // remove from active_uploads
  2506. delete window.active_uploads[opid];
  2507. },
  2508. // abort
  2509. abort: async function(operation_id){
  2510. // console.log('upload aborted');
  2511. // remove from active_uploads
  2512. delete window.active_uploads[opid];
  2513. }
  2514. }
  2515. );
  2516. }
  2517. window.empty_trash = async function(){
  2518. const alert_resp = await UIAlert({
  2519. message: i18n('empty_trash_confirmation'),
  2520. buttons:[
  2521. {
  2522. label: i18n('yes'),
  2523. value: 'yes',
  2524. type: 'primary',
  2525. },
  2526. {
  2527. label: i18n('no'),
  2528. value: 'no',
  2529. },
  2530. ]
  2531. })
  2532. if(alert_resp === 'no')
  2533. return;
  2534. // only show progress window if it takes longer than 500ms to create folder
  2535. let init_ts = Date.now();
  2536. let progwin;
  2537. let op_id = window.uuidv4();
  2538. let progwin_timeout = setTimeout(async () => {
  2539. progwin = await UIWindowProgress({operation_id: op_id});
  2540. progwin.set_status(i18n('emptying_trash'));
  2541. }, 500);
  2542. await puter.fs.delete({
  2543. paths: window.trash_path,
  2544. descendantsOnly: true,
  2545. recursive: true,
  2546. success: async function (resp){
  2547. // update other clients
  2548. if(window.socket){
  2549. window.socket.emit('trash.is_empty', {is_empty: true});
  2550. }
  2551. // use the 'empty trash' icon for Trash
  2552. $(`[data-app="trash"]`).find('.taskbar-icon > img').attr('src', window.icons['trash.svg']);
  2553. $(`.item[data-path="${html_encode(window.trash_path)}" i], .item[data-shortcut_to_path="${html_encode(window.trash_path)}" i]`).find('.item-icon > img').attr('src', window.icons['trash.svg']);
  2554. $(`.window[data-path="${window.trash_path}"]`).find('.window-head-icon').attr('src', window.icons['trash.svg']);
  2555. // remove all items with trash paths
  2556. // todo this has to be case-insensitive but the `i` selector doesn't work on ^=
  2557. $(`.item[data-path^="${window.trash_path}/"]`).removeItems();
  2558. // update the footer item count for Trash
  2559. window. update_explorer_footer_item_count($(`.window[data-path="${window.trash_path}"]`))
  2560. // close progress window
  2561. clearTimeout(progwin_timeout);
  2562. setTimeout(() => {
  2563. progwin?.close();
  2564. }, Math.max(0, window.copy_progress_hide_delay - (Date.now() - init_ts)));
  2565. },
  2566. error: async function (err){
  2567. clearTimeout(progwin_timeout);
  2568. setTimeout(() => {
  2569. progwin?.close();
  2570. }, Math.max(0, window.copy_progress_hide_delay - (Date.now() - init_ts)));
  2571. }
  2572. });
  2573. }
  2574. window.copy_to_clipboard = async function(text){
  2575. if (navigator.clipboard) {
  2576. // copy text to clipboard
  2577. await navigator.clipboard.writeText(text);
  2578. }
  2579. else{
  2580. document.execCommand('copy');
  2581. }
  2582. }
  2583. window.getUsage = () => {
  2584. return fetch(window.api_origin + "/drivers/usage", {
  2585. headers: {
  2586. "Content-Type": "application/json",
  2587. "Authorization": "Bearer " + window.auth_token
  2588. },
  2589. method: "GET"
  2590. })
  2591. .then(response => {
  2592. // Check if the response is ok (status code in the range 200-299)
  2593. if (!response.ok) {
  2594. throw new Error('Network response was not ok');
  2595. }
  2596. return response.json(); // Parse the response as JSON
  2597. })
  2598. .then(data => {
  2599. // Handle the JSON data
  2600. return data;
  2601. })
  2602. .catch(error => {
  2603. // Handle any errors
  2604. console.error('There has been a problem with your fetch operation:', error);
  2605. });
  2606. }
  2607. window.getAppUIDFromOrigin = async function(origin) {
  2608. try {
  2609. const response = await fetch(window.api_origin + "/auth/app-uid-from-origin", {
  2610. headers: {
  2611. "Content-Type": "application/json",
  2612. "Authorization": "Bearer " + window.auth_token,
  2613. },
  2614. body: JSON.stringify({ origin: origin }),
  2615. method: "POST",
  2616. });
  2617. const data = await response.json();
  2618. // Assuming the app_uid is in the data object, return it
  2619. return data.uid;
  2620. } catch (err) {
  2621. // Handle any errors here
  2622. console.error(err);
  2623. // You may choose to return something specific here in case of an error
  2624. return null;
  2625. }
  2626. }
  2627. window.getUserAppToken = async function(origin) {
  2628. try {
  2629. const response = await fetch(window.api_origin + "/auth/get-user-app-token", {
  2630. headers: {
  2631. "Content-Type": "application/json",
  2632. "Authorization": "Bearer " + window.auth_token,
  2633. },
  2634. body: JSON.stringify({ origin: origin }),
  2635. method: "POST",
  2636. });
  2637. const data = await response.json();
  2638. // return
  2639. return data;
  2640. } catch (err) {
  2641. // Handle any errors here
  2642. console.error(err);
  2643. // You may choose to return something specific here in case of an error
  2644. return null;
  2645. }
  2646. }
  2647. window.checkUserSiteRelationship = async function(origin) {
  2648. try {
  2649. const response = await fetch(window.api_origin + "/auth/check-app ", {
  2650. headers: {
  2651. "Content-Type": "application/json",
  2652. "Authorization": "Bearer " + window.auth_token,
  2653. },
  2654. body: JSON.stringify({ origin: origin }),
  2655. method: "POST",
  2656. });
  2657. const data = await response.json();
  2658. // return
  2659. return data;
  2660. } catch (err) {
  2661. // Handle any errors here
  2662. console.error(err);
  2663. // You may choose to return something specific here in case of an error
  2664. return null;
  2665. }
  2666. }
  2667. window.zipItems = async function(el_items, targetDirPath, download = true) {
  2668. const zip = new JSZip();
  2669. // if single item, convert to array
  2670. el_items = Array.isArray(el_items) ? el_items : [el_items];
  2671. // create progress window
  2672. let start_ts = Date.now();
  2673. let progwin, progwin_timeout;
  2674. // only show progress window if it takes longer than 500ms to download
  2675. progwin_timeout = setTimeout(async () => {
  2676. progwin = await UIWindowProgress();
  2677. }, 500);
  2678. for (const el_item of el_items) {
  2679. let targetPath = $(el_item).attr('data-path');
  2680. // if directory, zip the directory
  2681. if($(el_item).attr('data-is_dir') === '1'){
  2682. progwin?.set_status(i18n('reading_file', targetPath));
  2683. // Recursively read the directory
  2684. let children = await readDirectoryRecursive(targetPath);
  2685. // Add files to the zip
  2686. for (const child of children) {
  2687. let relativePath;
  2688. if(el_items.length === 1)
  2689. relativePath = child.relativePath;
  2690. else
  2691. relativePath = path.basename(targetPath) + '/' + child.relativePath;
  2692. // update progress window
  2693. progwin?.set_status(i18n('zipping_file', relativePath));
  2694. // read file content
  2695. let content = await puter.fs.read(child.path);
  2696. try{
  2697. zip.file(relativePath, content, {binary: true});
  2698. }catch(e){
  2699. console.error(e);
  2700. }
  2701. }
  2702. }
  2703. // if item is a file, zip the file
  2704. else{
  2705. let content = await puter.fs.read(targetPath);
  2706. zip.file(path.basename(targetPath), content, {binary: true});
  2707. }
  2708. }
  2709. // determine name of zip file
  2710. let zipName;
  2711. if(el_items.length === 1)
  2712. zipName = path.basename($(el_items[0]).attr('data-path'));
  2713. else
  2714. zipName = 'Archive';
  2715. // Generate the zip file
  2716. zip.generateAsync({ type: "blob" })
  2717. .then(async function (content) {
  2718. // Trigger the download
  2719. if(download){
  2720. const url = URL.createObjectURL(content);
  2721. const a = document.createElement("a");
  2722. a.href = url;
  2723. a.download = zipName;
  2724. document.body.appendChild(a);
  2725. a.click();
  2726. // Cleanup
  2727. document.body.removeChild(a);
  2728. URL.revokeObjectURL(url);
  2729. }
  2730. // save
  2731. else
  2732. await puter.fs.write(targetDirPath + '/' + zipName + ".zip", content, {overwrite: false, dedupeName: true})
  2733. // close progress window
  2734. clearTimeout(progwin_timeout);
  2735. setTimeout(() => {
  2736. progwin?.close();
  2737. }, Math.max(0, window.copy_progress_hide_delay - (Date.now() - start_ts)));
  2738. })
  2739. .catch(function (err) {
  2740. // close progress window
  2741. clearTimeout(progwin_timeout);
  2742. setTimeout(() => {
  2743. progwin?.close();
  2744. }, Math.max(0, window.copy_progress_hide_delay - (Date.now() - start_ts)));
  2745. // handle errors
  2746. // TODO: Display in progress dialog
  2747. console.error("Error in zipping files: ", err);
  2748. });
  2749. }
  2750. async function readDirectoryRecursive(path, baseDir = '') {
  2751. let allFiles = [];
  2752. // Read the directory
  2753. const entries = await puter.fs.readdir(path);
  2754. // Process each entry
  2755. for (const entry of entries) {
  2756. const fullPath = `${path}/${entry.name}`;
  2757. if (entry.is_dir) {
  2758. // If entry is a directory, recursively read it
  2759. const subDirFiles = await readDirectoryRecursive(fullPath, `${baseDir}${entry.name}/`);
  2760. allFiles = allFiles.concat(subDirFiles);
  2761. } else {
  2762. // If entry is a file, add it to the list
  2763. allFiles.push({ path: fullPath, relativePath: `${baseDir}${entry.name}` });
  2764. }
  2765. }
  2766. return allFiles;
  2767. }
  2768. window.extractSubdomain = function(url) {
  2769. var subdomain = url.split('://')[1].split('.')[0];
  2770. return subdomain;
  2771. }
  2772. window.sleep = function(ms){
  2773. return new Promise(resolve => setTimeout(resolve, ms));
  2774. }
  2775. window.unzipItem = async function(itemPath) {
  2776. // create progress window
  2777. let start_ts = Date.now();
  2778. let progwin, progwin_timeout;
  2779. // only show progress window if it takes longer than 500ms to download
  2780. progwin_timeout = setTimeout(async () => {
  2781. progwin = await UIWindowProgress();
  2782. }, 500);
  2783. const zip = new JSZip();
  2784. let filPath = itemPath;
  2785. let file = puter.fs.read(filPath);
  2786. zip.loadAsync(file).then(async function (zip) {
  2787. const rootdir = await puter.fs.mkdir(path.dirname(filPath) + '/' + path.basename(filPath, '.zip'), {dedupeName: true});
  2788. Object.keys(zip.files).forEach(async function (filename) {
  2789. console.log(filename);
  2790. if(filename.endsWith('/'))
  2791. await puter.fs.mkdir(rootdir.path +'/' + filename, {createMissingParents: true});
  2792. zip.files[filename].async('blob').then(async function (fileData) {
  2793. await puter.fs.write(rootdir.path +'/' + filename, fileData);
  2794. }).catch(function (e) {
  2795. // UIAlert(e.message);
  2796. })
  2797. })
  2798. // close progress window
  2799. clearTimeout(progwin_timeout);
  2800. setTimeout(() => {
  2801. progwin?.close();
  2802. }, Math.max(0, window.copy_progress_hide_delay - (Date.now() - start_ts)));
  2803. }).catch(function (e) {
  2804. // UIAlert(e.message);
  2805. // close progress window
  2806. clearTimeout(progwin_timeout);
  2807. setTimeout(() => {
  2808. progwin?.close();
  2809. }, Math.max(0, window.copy_progress_hide_delay - (Date.now() - start_ts)));
  2810. })
  2811. }
  2812. window.rename_file = async(options, new_name, old_name, old_path, el_item, el_item_name, el_item_icon, el_item_name_editor, website_url, is_undo = false)=>{
  2813. puter.fs.rename({
  2814. uid: options.uid === 'null' ? null : options.uid,
  2815. new_name: new_name,
  2816. excludeSocketID: window.socket.id,
  2817. success: async (fsentry)=>{
  2818. // Add action to actions_history for undo ability
  2819. if (!is_undo)
  2820. window.actions_history.push({
  2821. operation: 'rename',
  2822. data: {options, new_name, old_name, old_path, el_item, el_item_name, el_item_icon, el_item_name_editor, website_url}
  2823. });
  2824. // Has the extension changed? in that case update options.sugggested_apps
  2825. const old_extension = path.extname(old_name);
  2826. const new_extension = path.extname(new_name);
  2827. if(old_extension !== new_extension){
  2828. window.suggest_apps_for_fsentry({
  2829. uid: options.uid,
  2830. onSuccess: function(suggested_apps){
  2831. options.suggested_apps = suggested_apps;
  2832. }
  2833. });
  2834. }
  2835. // Set new item name
  2836. $(`.item[data-uid='${$(el_item).attr('data-uid')}'] .item-name`).html(html_encode(truncate_filename(new_name)).replaceAll(' ', '&nbsp;'));
  2837. $(el_item_name).show();
  2838. // Hide item name editor
  2839. $(el_item_name_editor).hide();
  2840. // Set new icon
  2841. const new_icon = (options.is_dir ? window.icons['folder.svg'] : (await window.item_icon(fsentry)).image);
  2842. $(el_item_icon).find('.item-icon-icon').attr('src', new_icon);
  2843. // Set new data-name
  2844. options.name = new_name;
  2845. $(el_item).attr('data-name', html_encode(new_name));
  2846. $(`.item[data-uid='${$(el_item).attr('data-uid')}']`).attr('data-name', html_encode(new_name));
  2847. $(`.window-${options.uid}`).attr('data-name', html_encode(new_name));
  2848. // Set new title attribute
  2849. $(`.item[data-uid='${$(el_item).attr('data-uid')}']`).attr('title', html_encode(new_name));
  2850. $(`.window-${options.uid}`).attr('title', html_encode(new_name));
  2851. // Set new value for item-name-editor
  2852. $(`.item[data-uid='${$(el_item).attr('data-uid')}'] .item-name-editor`).val(html_encode(new_name));
  2853. $(`.item[data-uid='${$(el_item).attr('data-uid')}'] .item-name`).attr('title', html_encode(new_name));
  2854. // Set new data-path
  2855. options.path = path.join( path.dirname(options.path), options.name);
  2856. const new_path = options.path;
  2857. $(el_item).attr('data-path', new_path);
  2858. $(`.item[data-uid='${$(el_item).attr('data-uid')}']`).attr('data-path', new_path);
  2859. $(`.window-${options.uid}`).attr('data-path', new_path);
  2860. // Update all elements that have matching paths
  2861. $(`[data-path="${html_encode(old_path)}" i]`).each(function(){
  2862. $(this).attr('data-path', new_path)
  2863. if($(this).hasClass('window-navbar-path-dirname'))
  2864. $(this).text(new_name);
  2865. });
  2866. // Update the paths of all elements whose paths start with old_path
  2867. $(`[data-path^="${html_encode(old_path) + '/'}"]`).each(function(){
  2868. const new_el_path = _.replace($(this).attr('data-path'), old_path + '/', new_path+'/');
  2869. $(this).attr('data-path', new_el_path);
  2870. });
  2871. // Update the 'Sites Cache'
  2872. if($(el_item).attr('data-has_website') === '1')
  2873. await window.update_sites_cache();
  2874. // Update website_url
  2875. website_url = window.determine_website_url(new_path);
  2876. $(el_item).attr('data-website_url', website_url);
  2877. // Update all exact-matching windows
  2878. $(`.window-${options.uid}`).each(function(){
  2879. window.update_window_path(this, options.path);
  2880. })
  2881. // Set new name for corresponding open windows
  2882. $(`.window-${options.uid} .window-head-title`).text(new_name);
  2883. // Re-sort all matching item containers
  2884. $(`.item[data-uid='${$(el_item).attr('data-uid')}']`).parent('.item-container').each(function(){
  2885. window.sort_items(this, $(el_item).closest('.item-container').attr('data-sort_by'), $(el_item).closest('.item-container').attr('data-sort_order'));
  2886. })
  2887. },
  2888. error: function (err){
  2889. // reset to old name
  2890. $(el_item_name).text(truncate_filename(options.name));
  2891. $(el_item_name).show();
  2892. // hide item name editor
  2893. $(el_item_name_editor).hide();
  2894. $(el_item_name_editor).val(html_encode($(el_item).attr('data-name')));
  2895. //show error
  2896. if(err.message){
  2897. UIAlert(err.message)
  2898. }
  2899. },
  2900. });
  2901. }
  2902. /**
  2903. * Deletes the given item with path.
  2904. *
  2905. * @param {string} path - path of the item to delete
  2906. * @returns {Promise<void>}
  2907. */
  2908. window.delete_item_with_path = async function(path){
  2909. try{
  2910. await puter.fs.delete({
  2911. paths: path,
  2912. descendantsOnly: false,
  2913. recursive: true,
  2914. });
  2915. }catch(err){
  2916. UIAlert(err.responseText);
  2917. }
  2918. }
  2919. window.undo_last_action = async()=>{
  2920. if (window.actions_history.length > 0) {
  2921. const last_action = window.actions_history.pop();
  2922. // Undo the create file action
  2923. if (last_action.operation === 'create_file' || last_action.operation === 'create_folder') {
  2924. const lastCreatedItem = last_action.data;
  2925. window.undo_create_file_or_folder(lastCreatedItem);
  2926. } else if(last_action.operation === 'rename') {
  2927. const {options, new_name, old_name, old_path, el_item, el_item_name, el_item_icon, el_item_name_editor, website_url} = last_action.data;
  2928. window.rename_file(options, old_name, new_name, old_path, el_item, el_item_name, el_item_icon, el_item_name_editor, website_url, true);
  2929. } else if(last_action.operation === 'upload') {
  2930. const files = last_action.data;
  2931. window.undo_upload(files);
  2932. } else if(last_action.operation === 'copy') {
  2933. const files = last_action.data;
  2934. window.undo_copy(files);
  2935. } else if(last_action.operation === 'move') {
  2936. const items = last_action.data;
  2937. window.undo_move(items);
  2938. } else if(last_action.operation === 'delete') {
  2939. const items = last_action.data;
  2940. window.undo_delete(items);
  2941. }
  2942. }
  2943. }
  2944. window.undo_create_file_or_folder = async(item)=>{
  2945. await window.delete_item(item);
  2946. }
  2947. window.undo_upload = async(files)=>{
  2948. for (const file of files) {
  2949. await window.delete_item_with_path(file);
  2950. }
  2951. }
  2952. window.undo_copy = async(files)=>{
  2953. for (const file of files) {
  2954. await window.delete_item_with_path(file);
  2955. }
  2956. }
  2957. window.undo_move = async(items)=>{
  2958. for (const item of items) {
  2959. const el = await window.get_html_element_from_options(item.options);
  2960. console.log(item.original_path)
  2961. window.move_items([el], path.dirname(item.original_path), true);
  2962. }
  2963. }
  2964. window.undo_delete = async(items)=>{
  2965. for (const item of items) {
  2966. const el = await window.get_html_element_from_options(item.options);
  2967. let metadata = $(el).attr('data-metadata') === '' ? {} : JSON.parse($(el).attr('data-metadata'))
  2968. window.move_items([el], path.dirname(metadata.original_path), true);
  2969. }
  2970. }
  2971. window.get_html_element_from_options = async function(options){
  2972. const item_id = window.global_element_id++;
  2973. options.disabled = options.disabled ?? false;
  2974. options.visible = options.visible ?? 'visible'; // one of 'visible', 'revealed', 'hidden'
  2975. options.is_dir = options.is_dir ?? false;
  2976. options.is_selected = options.is_selected ?? false;
  2977. options.is_shared = options.is_shared ?? false;
  2978. options.is_shortcut = options.is_shortcut ?? 0;
  2979. options.is_trash = options.is_trash ?? false;
  2980. options.metadata = options.metadata ?? '';
  2981. options.multiselectable = options.multiselectable ?? true;
  2982. options.shortcut_to = options.shortcut_to ?? '';
  2983. options.shortcut_to_path = options.shortcut_to_path ?? '';
  2984. options.immutable = (options.immutable === false || options.immutable === 0 || options.immutable === undefined ? 0 : 1);
  2985. options.sort_container_after_append = (options.sort_container_after_append !== undefined ? options.sort_container_after_append : false);
  2986. const is_shared_with_me = (options.path !== '/'+window.user.username && !options.path.startsWith('/'+window.user.username+'/'));
  2987. let website_url = window.determine_website_url(options.path);
  2988. // do a quick check to see if the target parent has any file type restrictions
  2989. const appendto_allowed_file_types = $(options.appendTo).attr('data-allowed_file_types')
  2990. if(!window.check_fsentry_against_allowed_file_types_string({is_dir: options.is_dir, name:options.name, type:options.type}, appendto_allowed_file_types))
  2991. options.disabled = true;
  2992. // --------------------------------------------------------
  2993. // HTML for Item
  2994. // --------------------------------------------------------
  2995. let h = '';
  2996. h += `<div id="item-${item_id}"
  2997. class="item${options.is_selected ? ' item-selected':''} ${options.disabled ? 'item-disabled':''} item-${options.visible}"
  2998. data-id="${item_id}"
  2999. data-name="${html_encode(options.name)}"
  3000. data-metadata="${html_encode(options.metadata)}"
  3001. data-uid="${options.uid}"
  3002. data-is_dir="${options.is_dir ? 1 : 0}"
  3003. data-is_trash="${options.is_trash ? 1 : 0}"
  3004. data-has_website="${options.has_website ? 1 : 0 }"
  3005. data-website_url = "${website_url ? html_encode(website_url) : ''}"
  3006. data-immutable="${options.immutable}"
  3007. data-is_shortcut = "${options.is_shortcut}"
  3008. data-shortcut_to = "${html_encode(options.shortcut_to)}"
  3009. data-shortcut_to_path = "${html_encode(options.shortcut_to_path)}"
  3010. data-sortable = "${options.sortable ?? 'true'}"
  3011. data-sort_by = "${html_encode(options.sort_by) ?? 'name'}"
  3012. data-size = "${options.size ?? ''}"
  3013. data-type = "${html_encode(options.type) ?? ''}"
  3014. data-modified = "${options.modified ?? ''}"
  3015. data-associated_app_name = "${html_encode(options.associated_app_name) ?? ''}"
  3016. data-path="${html_encode(options.path)}">`;
  3017. // spinner
  3018. h += `<div class="item-spinner">`;
  3019. h += `</div>`;
  3020. // modified
  3021. h += `<div class="item-attr item-attr--modified">`;
  3022. h += `<span>${options.modified === 0 ? '-' : timeago.format(options.modified*1000)}</span>`;
  3023. h += `</div>`;
  3024. // size
  3025. h += `<div class="item-attr item-attr--size">`;
  3026. h += `<span>${options.size ? window.byte_format(options.size) : '-'}</span>`;
  3027. h += `</div>`;
  3028. // type
  3029. h += `<div class="item-attr item-attr--type">`;
  3030. if(options.is_dir)
  3031. h += `<span>Folder</span>`;
  3032. else
  3033. h += `<span>${options.type ? html_encode(options.type) : '-'}</span>`;
  3034. h += `</div>`;
  3035. // icon
  3036. h += `<div class="item-icon">`;
  3037. h += `<img src="${html_encode(options.icon.image)}" class="item-icon-${options.icon.type}" data-item-id="${item_id}">`;
  3038. h += `</div>`;
  3039. // badges
  3040. h += `<div class="item-badges">`;
  3041. // website badge
  3042. h += `<img class="item-badge item-has-website-badge long-hover"
  3043. style="${options.has_website ? 'display:block;' : ''}"
  3044. src="${html_encode(window.icons['world.svg'])}"
  3045. data-item-id="${item_id}"
  3046. >`;
  3047. // link badge
  3048. h += `<img class="item-badge item-has-website-url-badge"
  3049. style="${website_url ? 'display:block;' : ''}"
  3050. src="${html_encode(window.icons['link.svg'])}"
  3051. data-item-id="${item_id}"
  3052. >`;
  3053. // shared badge
  3054. h += `<img class="item-badge item-badge-has-permission"
  3055. style="display: ${ is_shared_with_me ? 'block' : 'none'};
  3056. background-color: #ffffff;
  3057. padding: 2px;" src="${html_encode(window.icons['shared.svg'])}"
  3058. data-item-id="${item_id}"
  3059. title="A user has shared this item with you.">`;
  3060. // owner-shared badge
  3061. h += `<img class="item-badge item-is-shared"
  3062. style="background-color: #ffffff; padding: 2px; ${!is_shared_with_me && options.is_shared ? 'display:block;' : ''}"
  3063. src="${html_encode(window.icons['owner-shared.svg'])}"
  3064. data-item-id="${item_id}"
  3065. data-item-uid="${options.uid}"
  3066. data-item-path="${html_encode(options.path)}"
  3067. title="You have shared this item with at least one other user."
  3068. >`;
  3069. // shortcut badge
  3070. h += `<img class="item-badge item-shortcut"
  3071. style="background-color: #ffffff; padding: 2px; ${options.is_shortcut !== 0 ? 'display:block;' : ''}"
  3072. src="${html_encode(window.icons['shortcut.svg'])}"
  3073. data-item-id="${item_id}"
  3074. title="Shortcut"
  3075. >`;
  3076. h += `</div>`;
  3077. // name
  3078. h += `<span class="item-name" data-item-id="${item_id}" title="${html_encode(options.name)}">${html_encode(truncate_filename(options.name)).replaceAll(' ', '&nbsp;')}</span>`
  3079. // name editor
  3080. h += `<textarea class="item-name-editor hide-scrollbar" spellcheck="false" autocomplete="off" autocorrect="off" autocapitalize="off" data-gramm_editor="false">${html_encode(options.name)}</textarea>`
  3081. h += `</div>`;
  3082. return h;
  3083. }
  3084. window.store_auto_arrange_preference = (preference)=>{
  3085. puter.kv.set('user_preferences.auto_arrange_desktop', preference);
  3086. localStorage.setItem('auto_arrange', preference);
  3087. }
  3088. window.get_auto_arrange_data = async()=>{
  3089. const preferenceValue = await puter.kv.get('user_preferences.auto_arrange_desktop');
  3090. window.is_auto_arrange_enabled = preferenceValue === null ? true : preferenceValue;
  3091. const positions = await puter.kv.get('desktop_item_positions')
  3092. window.desktop_item_positions = (!positions || typeof positions !== 'object' || Array.isArray(positions)) ? {} : positions;
  3093. }
  3094. window.clear_desktop_item_positions = async(el_desktop)=>{
  3095. $(el_desktop).find('.item').each(function(){
  3096. const el_item = $(this)[0];
  3097. $(el_item).css('position', '');
  3098. $(el_item).css('left', '');
  3099. $(el_item).css('top', '');
  3100. });
  3101. if(window.reset_item_positions){
  3102. window.delete_desktop_item_positions()
  3103. }
  3104. }
  3105. window.set_desktop_item_positions = async(el_desktop)=>{
  3106. $(el_desktop).find('.item').each(async function(){
  3107. const position = window.desktop_item_positions[$(this).attr('data-uid')]
  3108. const el_item = $(this)[0];
  3109. if(position){
  3110. $(el_item).css('position', 'absolute');
  3111. $(el_item).css('left', position.left + 'px');
  3112. $(el_item).css('top', position.top + 'px');
  3113. }
  3114. });
  3115. }
  3116. window.save_desktop_item_positions = ()=>{
  3117. puter.kv.set('desktop_item_positions', window.desktop_item_positions);
  3118. }
  3119. window.delete_desktop_item_positions = ()=>{
  3120. window.desktop_item_positions = {}
  3121. puter.kv.del('desktop_item_positions');
  3122. }
  3123. window.change_clock_visible = (clock_visible) => {
  3124. let newValue = clock_visible || window.user_preferences.clock_visible;
  3125. newValue === 'auto' && window.is_fullscreen() ? $('#clock').show() : $('#clock').hide();
  3126. newValue === 'show' && $('#clock').show();
  3127. newValue === 'hide' && $('#clock').hide();
  3128. if(clock_visible) {
  3129. // save clock_visible to user preferences
  3130. window.mutate_user_preferences({
  3131. clock_visible: newValue
  3132. });
  3133. return;
  3134. }
  3135. $('select.change-clock-visible').val(window.user_preferences.clock_visible);
  3136. }
  3137. // Finds the `.window` element for the given app instance ID
  3138. window.window_for_app_instance = (instance_id) => {
  3139. return $(`.window[data-element_uuid="${instance_id}"]`).get(0);
  3140. };
  3141. // Finds the `iframe` element for the given app instance ID
  3142. window.iframe_for_app_instance = (instance_id) => {
  3143. return $(window.window_for_app_instance(instance_id)).find('.window-app-iframe').get(0);
  3144. };
  3145. // Run any callbacks to say that the app has launched
  3146. window.report_app_launched = (instance_id, { uses_sdk = true }) => {
  3147. const child_launch_callback = window.child_launch_callbacks[instance_id];
  3148. if (child_launch_callback) {
  3149. const parent_iframe = window.iframe_for_app_instance(child_launch_callback.parent_instance_id);
  3150. // send confirmation to requester window
  3151. parent_iframe.contentWindow.postMessage({
  3152. msg: 'childAppLaunched',
  3153. original_msg_id: child_launch_callback.launch_msg_id,
  3154. child_instance_id: instance_id,
  3155. uses_sdk: uses_sdk,
  3156. }, '*');
  3157. delete window.child_launch_callbacks[instance_id];
  3158. }
  3159. };
  3160. // Run any callbacks to say that the app has closed
  3161. window.report_app_closed = (instance_id, status_code) => {
  3162. const el_window = window.window_for_app_instance(instance_id);
  3163. // notify parent app, if we have one, that we're closing
  3164. const parent_id = el_window.dataset['parent_instance_id'];
  3165. const parent = $(`.window[data-element_uuid="${parent_id}"] .window-app-iframe`).get(0);
  3166. if (parent) {
  3167. parent.contentWindow.postMessage({
  3168. msg: 'appClosed',
  3169. appInstanceID: instance_id,
  3170. statusCode: status_code ?? 0,
  3171. }, '*');
  3172. }
  3173. // notify child apps, if we have them, that we're closing
  3174. const children = $(`.window[data-parent_instance_id="${instance_id}"] .window-app-iframe`);
  3175. children.each((_, child) => {
  3176. child.contentWindow.postMessage({
  3177. msg: 'appClosed',
  3178. appInstanceID: instance_id,
  3179. statusCode: status_code ?? 0,
  3180. }, '*');
  3181. });
  3182. // TODO: Once other AppConnections exist, those will need notifying too.
  3183. };
  3184. window.check_password_strength = (password) => {
  3185. // Define criteria for password strength
  3186. const criteria = {
  3187. minLength: 8,
  3188. hasUpperCase: /[A-Z]/.test(password),
  3189. hasLowerCase: /[a-z]/.test(password),
  3190. hasNumber: /\d/.test(password),
  3191. hasSpecialChar: /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/.test(password)
  3192. };
  3193. let overallPass = true;
  3194. // Initialize report object
  3195. let criteria_report = {
  3196. minLength: {
  3197. message: `Password must be at least ${criteria.minLength} characters long`,
  3198. pass: password.length >= criteria.minLength,
  3199. },
  3200. hasUpperCase: {
  3201. message: 'Password must contain at least one uppercase letter',
  3202. pass: criteria.hasUpperCase,
  3203. },
  3204. hasLowerCase: {
  3205. message: 'Password must contain at least one lowercase letter',
  3206. pass: criteria.hasLowerCase,
  3207. },
  3208. hasNumber: {
  3209. message: 'Password must contain at least one number',
  3210. pass: criteria.hasNumber,
  3211. },
  3212. hasSpecialChar: {
  3213. message: 'Password must contain at least one special character',
  3214. pass: criteria.hasSpecialChar,
  3215. },
  3216. };
  3217. // Check overall pass status and add messages
  3218. for (let criterion in criteria) {
  3219. if (!criteria_report[criterion].pass) {
  3220. overallPass = false;
  3221. break;
  3222. }
  3223. }
  3224. return {
  3225. overallPass: overallPass,
  3226. report: criteria_report,
  3227. };
  3228. }
  3229. window.set_menu_item_prop = (items, item_id, prop, val) => {
  3230. // iterate over items
  3231. for (const item of items) {
  3232. // find the item with the given item_id
  3233. if (item.id === item_id) {
  3234. // set the property value
  3235. item[prop] = val;
  3236. break;
  3237. }
  3238. else if(item.items){
  3239. set_menu_item_prop(item.items, item_id, prop, val);
  3240. }
  3241. }
  3242. };