helpers.js 142 KB

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