helpers.js 143 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574
  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 utm_source=puter.com to the URL
  1658. iframe_url.searchParams.append('utm_source', 'puter.com');
  1659. el_win = UIWindow({
  1660. element_uuid: uuid,
  1661. title: title,
  1662. iframe_url: iframe_url.href,
  1663. params: options.params ?? undefined,
  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. $(el).on('remove', () => {
  1709. const svc_process = globalThis.services.get('process');
  1710. svc_process.unregister(process.uuid);
  1711. // If it's a non-sdk app, report that it launched and closed.
  1712. // FIXME: This is awkward. Really, we want some way of knowing when it's launched and reporting that immediately instead.
  1713. const $app_iframe = $(el).find('.window-app-iframe');
  1714. if ($app_iframe.attr('data-appUsesSdk') !== 'true') {
  1715. window.report_app_launched(process.uuid, { uses_sdk: false });
  1716. // We also have to report an extra close event because the real one was sent already
  1717. window.report_app_closed(process.uuid);
  1718. }
  1719. });
  1720. process.references.el_win = el;
  1721. process.chstatus(PROCESS_RUNNING);
  1722. })();
  1723. }
  1724. window.open_item = async function(options){
  1725. let el_item = options.item;
  1726. const $el_parent_window = $(el_item).closest('.window');
  1727. const parent_win_id = $($el_parent_window).attr('data-id');
  1728. const is_dir = $(el_item).attr('data-is_dir') === '1' ? true : false;
  1729. const uid = $(el_item).attr('data-shortcut_to') === '' ? $(el_item).attr('data-uid') : $(el_item).attr('data-shortcut_to');
  1730. const item_path = $(el_item).attr('data-shortcut_to_path') === '' ? $(el_item).attr('data-path') : $(el_item).attr('data-shortcut_to_path');
  1731. const is_shortcut = $(el_item).attr('data-is_shortcut') === '1';
  1732. const shortcut_to_path = $(el_item).attr('data-shortcut_to_path');
  1733. const associated_app_name = $(el_item).attr('data-associated_app_name');
  1734. const file_uid = $(el_item).attr('data-uid')
  1735. //----------------------------------------------------------------
  1736. // Is this a shortcut whose source is perma-deleted?
  1737. //----------------------------------------------------------------
  1738. if(is_shortcut && shortcut_to_path === ''){
  1739. UIAlert(`This shortcut can't be opened because its source has been deleted.`)
  1740. }
  1741. //----------------------------------------------------------------
  1742. // Is this a shortcut whose source is trashed?
  1743. //----------------------------------------------------------------
  1744. else if(is_shortcut && shortcut_to_path.startsWith(trash_path + '/')){
  1745. UIAlert(`This shortcut can't be opened because its source has been deleted.`)
  1746. }
  1747. //----------------------------------------------------------------
  1748. // Is this a trashed file?
  1749. //----------------------------------------------------------------
  1750. else if(item_path.startsWith(trash_path + '/')){
  1751. UIAlert(`This item can't be opened because it's in the trash. To use this item, first drag it out of the Trash.`)
  1752. }
  1753. //----------------------------------------------------------------
  1754. // Is this a file (no dir) on a SaveFileDialog?
  1755. //----------------------------------------------------------------
  1756. else if($el_parent_window.attr('data-is_saveFileDialog') === 'true' && !is_dir){
  1757. $el_parent_window.find('.savefiledialog-filename').val($(el_item).attr('data-name'));
  1758. $el_parent_window.find('.savefiledialog-save-btn').trigger('click');
  1759. }
  1760. //----------------------------------------------------------------
  1761. // Is this a file (no dir) on an OpenFileDialog?
  1762. //----------------------------------------------------------------
  1763. else if($el_parent_window.attr('data-is_openFileDialog') === 'true' && !is_dir){
  1764. $el_parent_window.find('.window-disable-mask, .busy-indicator').show();
  1765. let busy_init_ts = Date.now();
  1766. try{
  1767. let filedialog_parent_uid = $el_parent_window.attr('data-parent_uuid');
  1768. let $filedialog_parent_app_window = $(`.window[data-element_uuid="${filedialog_parent_uid}"]`);
  1769. let parent_window_app_uid = $filedialog_parent_app_window.attr('data-app_uuid');
  1770. const initiating_app_uuid = $el_parent_window.attr('data-initiating_app_uuid');
  1771. let res = await puter.fs.sign(window.host_app_uid ?? parent_window_app_uid, {uid: uid, action: 'write'});
  1772. res = res.items;
  1773. // todo split is buggy because there might be a slash in the filename
  1774. res.path = `~/` + item_path.split('/').slice(2).join('/');
  1775. const parent_uuid = $el_parent_window.attr('data-parent_uuid');
  1776. const return_to_parent_window = $el_parent_window.attr('data-return_to_parent_window') === 'true';
  1777. if(return_to_parent_window){
  1778. window.opener.postMessage({
  1779. msg: "fileOpenPicked",
  1780. original_msg_id: $el_parent_window.attr('data-iframe_msg_uid'),
  1781. items: Array.isArray(res) ? [...res] : [res],
  1782. // LEGACY SUPPORT, remove this in the future when Polotno uses the new SDK
  1783. // this is literally put in here to support Polotno's legacy code
  1784. ...(!Array.isArray(res) && res)
  1785. }, '*');
  1786. window.close();
  1787. }
  1788. else if(parent_uuid){
  1789. // send event to iframe
  1790. const target_iframe = $(`.window[data-element_uuid="${parent_uuid}"]`).find('.window-app-iframe').get(0);
  1791. if(target_iframe){
  1792. let retobj = {
  1793. msg: "fileOpenPicked",
  1794. original_msg_id: $el_parent_window.attr('data-iframe_msg_uid'),
  1795. items: Array.isArray(res) ? [...res] : [res],
  1796. // LEGACY SUPPORT, remove this in the future when Polotno uses the new SDK
  1797. // this is literally put in here to support Polotno's legacy code
  1798. ...(!Array.isArray(res) && res)
  1799. };
  1800. target_iframe.contentWindow.postMessage(retobj, '*');
  1801. }
  1802. // focus iframe
  1803. $(target_iframe).get(0)?.focus({preventScroll:true});
  1804. // send file_opened event
  1805. const file_opened_event = new CustomEvent('file_opened', {detail: res});
  1806. // dispatch event to parent window
  1807. $(`.window[data-element_uuid="${parent_uuid}"]`).get(0)?.dispatchEvent(file_opened_event);
  1808. }
  1809. }catch(e){
  1810. console.log(e);
  1811. }
  1812. // done
  1813. let busy_duration = (Date.now() - busy_init_ts);
  1814. if( busy_duration >= busy_indicator_hide_delay){
  1815. $el_parent_window.close();
  1816. }else{
  1817. setTimeout(() => {
  1818. // close this dialog
  1819. $el_parent_window.close();
  1820. }, Math.abs(busy_indicator_hide_delay - busy_duration));
  1821. }
  1822. }
  1823. //----------------------------------------------------------------
  1824. // Does the user have a preference for this file type?
  1825. //----------------------------------------------------------------
  1826. else if(user_preferences[`default_apps${path.extname(item_path).toLowerCase()}`]) {
  1827. launch_app({
  1828. name: user_preferences[`default_apps${path.extname(item_path).toLowerCase()}`],
  1829. file_path: item_path,
  1830. window_title: path.basename(item_path),
  1831. maximized: options.maximized,
  1832. file_uid: file_uid,
  1833. });
  1834. }
  1835. //----------------------------------------------------------------
  1836. // Is there an app associated with this item?
  1837. //----------------------------------------------------------------
  1838. else if(associated_app_name !== ''){
  1839. launch_app({
  1840. name: associated_app_name,
  1841. })
  1842. }
  1843. //----------------------------------------------------------------
  1844. // Dir with no open windows: create a new window
  1845. //----------------------------------------------------------------
  1846. else if(is_dir && ($el_parent_window.length === 0 || options.new_window)){
  1847. UIWindow({
  1848. path: item_path,
  1849. title: path.basename(item_path),
  1850. icon: await item_icon({is_dir: true, path: item_path}),
  1851. uid: $(el_item).attr('data-uid'),
  1852. is_dir: is_dir,
  1853. app: 'explorer',
  1854. top: options.maximized ? 0 : undefined,
  1855. left: options.maximized ? 0 : undefined,
  1856. height: options.maximized ? `calc(100% - ${window.taskbar_height + window.toolbar_height + 1}px)` : undefined,
  1857. width: options.maximized ? `100%` : undefined,
  1858. });
  1859. }
  1860. //----------------------------------------------------------------
  1861. // Dir with an open window: change the path of the open window
  1862. //----------------------------------------------------------------
  1863. else if($el_parent_window.length > 0 && is_dir){
  1864. window_nav_history[parent_win_id] = window_nav_history[parent_win_id].slice(0, window_nav_history_current_position[parent_win_id]+1);
  1865. window_nav_history[parent_win_id].push(item_path);
  1866. window_nav_history_current_position[parent_win_id]++;
  1867. update_window_path($el_parent_window, item_path);
  1868. }
  1869. //----------------------------------------------------------------
  1870. // all other cases: try to open using an app
  1871. //----------------------------------------------------------------
  1872. else{
  1873. const fspath = item_path.toLowerCase();
  1874. const fsuid = uid.toLowerCase();
  1875. let open_item_meta;
  1876. // get all info needed to open an item
  1877. try{
  1878. open_item_meta = await $.ajax({
  1879. url: api_origin + "/open_item",
  1880. type: 'POST',
  1881. contentType: "application/json",
  1882. data: JSON.stringify({
  1883. uid: fsuid ?? undefined,
  1884. path: fspath ?? undefined,
  1885. }),
  1886. headers: {
  1887. "Authorization": "Bearer "+auth_token
  1888. },
  1889. statusCode: {
  1890. 401: function () {
  1891. logout();
  1892. },
  1893. },
  1894. });
  1895. }catch(err){
  1896. }
  1897. // get a list of suggested apps for this file type.
  1898. let suggested_apps = open_item_meta?.suggested_apps ?? await suggest_apps_for_fsentry({uid: fsuid, path: fspath});
  1899. //---------------------------------------------
  1900. // No suitable apps, ask if user would like to
  1901. // download
  1902. //---------------------------------------------
  1903. if(suggested_apps.length === 0){
  1904. //---------------------------------------------
  1905. // If .zip file, unzip it
  1906. //---------------------------------------------
  1907. if(path.extname(item_path) === '.zip'){
  1908. unzipItem(item_path);
  1909. return;
  1910. }
  1911. const alert_resp = await UIAlert(
  1912. 'Found no suitable apps to open this file with. Would you like to download it instead?',
  1913. [
  1914. {
  1915. label: i18n('download_file'),
  1916. value: 'download_file',
  1917. type: 'primary',
  1918. },
  1919. {
  1920. label: i18n('cancel')
  1921. }
  1922. ])
  1923. if(alert_resp === 'download_file'){
  1924. trigger_download([item_path]);
  1925. }
  1926. return;
  1927. }
  1928. //---------------------------------------------
  1929. // First suggested app is default app to open this item
  1930. //---------------------------------------------
  1931. else{
  1932. launch_app({
  1933. name: suggested_apps[0].name,
  1934. token: open_item_meta.token,
  1935. file_path: item_path,
  1936. app_obj: suggested_apps[0],
  1937. window_title: path.basename(item_path),
  1938. file_uid: fsuid,
  1939. maximized: options.maximized,
  1940. file_signature: open_item_meta.signature,
  1941. });
  1942. }
  1943. }
  1944. }
  1945. /**
  1946. * Moves the given items to the destination path.
  1947. *
  1948. * @param {HTMLElement[]} el_items - jQuery elements representing the items to move
  1949. * @param {string} dest_path - The destination path to move the items to
  1950. * @returns {Promise<void>}
  1951. */
  1952. window.move_items = async function(el_items, dest_path, is_undo = false){
  1953. let move_op_id = operation_id++;
  1954. operation_cancelled[move_op_id] = false;
  1955. // --------------------------------------------------------
  1956. // Optimization: in case all items being moved
  1957. // are immutable do not proceed
  1958. // --------------------------------------------------------
  1959. let all_items_are_immutable = true;
  1960. for(let i=0; i<el_items.length; i++){
  1961. if($(el_items[i]).attr('data-immutable') === '0'){
  1962. all_items_are_immutable = false;
  1963. break;
  1964. }
  1965. }
  1966. if(all_items_are_immutable)
  1967. return;
  1968. // --------------------------------------------------------
  1969. // good to go, proceed
  1970. // --------------------------------------------------------
  1971. // overwrite all items? default is false unless in a conflict case user asks for it
  1972. let overwrite_all = false;
  1973. // when did this operation start
  1974. let move_init_ts = Date.now();
  1975. // only show progress window if it takes longer than 2s to move
  1976. let progwin;
  1977. let progwin_timeout = setTimeout(async () => {
  1978. progwin = await UIWindowMoveProgress({operation_id: move_op_id});
  1979. }, 2000);
  1980. // storing moved items for undo ability
  1981. const moved_items = []
  1982. // Go through each item and try to move it
  1983. for(let i=0; i<el_items.length; i++){
  1984. // get current item
  1985. let el_item = el_items[i];
  1986. // if operation cancelled by user, stop
  1987. if(operation_cancelled[move_op_id])
  1988. return;
  1989. // cannot move an immutable item, skip it
  1990. if($(el_item).attr('data-immutable') === '1')
  1991. continue;
  1992. // cannot move item to its own path, skip it
  1993. if(path.dirname($(el_item).attr('data-path')) === dest_path){
  1994. await UIAlert(`<p>Moving <strong>${html_encode($(el_item).attr('data-name'))}</strong></p>Cannot move item to its current location.`)
  1995. continue;
  1996. }
  1997. // if an item with the same name already exists in the destination path
  1998. let item_with_same_name_already_exists = false;
  1999. let overwrite = overwrite_all;
  2000. let untrashed_at_least_one_item = false;
  2001. // --------------------------------------------------------
  2002. // Keep trying to move the item until it succeeds or is cancelled
  2003. // or user decides to overwrite or skip
  2004. // --------------------------------------------------------
  2005. do{
  2006. try{
  2007. let path_to_show_on_progwin = $(el_item).attr('data-path');
  2008. // parse metadata if any
  2009. let metadata = $(el_item).attr('data-metadata');
  2010. // no metadata?
  2011. if(metadata === '' || metadata === 'null' || metadata === null)
  2012. metadata = {}
  2013. // try to parse metadata as JSON
  2014. else{
  2015. try{
  2016. metadata = JSON.parse(metadata)
  2017. }catch(e){
  2018. }
  2019. }
  2020. let new_name;
  2021. // user cancelled?
  2022. if(operation_cancelled[move_op_id])
  2023. return;
  2024. // indicates whether this is a recycling operation
  2025. let recycling = false;
  2026. // --------------------------------------------------------
  2027. // Trashing
  2028. // --------------------------------------------------------
  2029. if(dest_path === trash_path){
  2030. new_name = $(el_item).attr('data-uid');
  2031. metadata = {
  2032. original_name: $(el_item).attr('data-name'),
  2033. original_path: $(el_item).attr('data-path'),
  2034. trashed_ts: Math.round(Date.now() / 1000),
  2035. };
  2036. // update other clients
  2037. if(window.socket)
  2038. window.socket.emit('trash.is_empty', {is_empty: false});
  2039. // change trash icons to 'trash-full.svg'
  2040. $(`[data-app="trash"]`).find('.taskbar-icon > img').attr('src', window.icons['trash-full.svg']);
  2041. $(`.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']);
  2042. $(`.window[data-path="${html_encode(trash_path)}" i]`).find('.window-head-icon').attr('src', window.icons['trash-full.svg']);
  2043. }
  2044. // moving an item into a trashed directory? deny.
  2045. else if(dest_path.startsWith(trash_path)){
  2046. $(progwin).close();
  2047. UIAlert('Cannot move items into a deleted folder.');
  2048. return;
  2049. }
  2050. // --------------------------------------------------------
  2051. // If recycling an item, restore its original name
  2052. // --------------------------------------------------------
  2053. else if(metadata.trashed_ts !== undefined){
  2054. recycling = true;
  2055. new_name = metadata.original_name;
  2056. metadata = {};
  2057. untrashed_at_least_one_item = true;
  2058. path_to_show_on_progwin = trash_path + '/' + new_name;
  2059. }
  2060. // --------------------------------------------------------
  2061. // update progress window with current item being moved
  2062. // --------------------------------------------------------
  2063. $(progwin).find('.move-from').html(path_to_show_on_progwin);
  2064. // execute move
  2065. let resp = await puter.fs.move({
  2066. source: $(el_item).attr('data-uid'),
  2067. destination: dest_path,
  2068. overwrite: overwrite || overwrite_all,
  2069. newName: new_name,
  2070. // recycling requires making all missing dirs
  2071. createMissingParents: recycling,
  2072. newMetadata: metadata,
  2073. excludeSocketID: window.socket?.id,
  2074. });
  2075. let fsentry = resp.moved;
  2076. // path must use the real name from DB
  2077. fsentry.path = path.join(dest_path, fsentry.name);
  2078. // skip next loop iteration because this iteration was successful
  2079. item_with_same_name_already_exists = false;
  2080. // update all shortcut_to_path
  2081. $(`.item[data-shortcut_to_path="${html_encode($(el_item).attr('data-path'))}" i]`).attr(`data-shortcut_to_path`, fsentry.path);
  2082. // Remove all items with matching uids
  2083. $(`.item[data-uid='${$(el_item).attr('data-uid')}']`).fadeOut(150, function(){
  2084. // find all parent windows that contain this item
  2085. let parent_windows = $(`.item[data-uid='${$(el_item).attr('data-uid')}']`).closest('.window');
  2086. // remove this item
  2087. $(this).removeItems();
  2088. // update parent windows' item counts and selected item counts in their footers
  2089. $(parent_windows).each(function(){
  2090. update_explorer_footer_item_count(this);
  2091. update_explorer_footer_selected_items_count(this)
  2092. });
  2093. })
  2094. // if trashing, close windows of trashed items and its descendants
  2095. if(dest_path === trash_path){
  2096. $(`.window[data-path="${html_encode($(el_item).attr('data-path'))}" i]`).close();
  2097. // todo this has to be case-insensitive but the `i` selector doesn't work on ^=
  2098. $(`.window[data-path^="${html_encode($(el_item).attr('data-path'))}/"]`).close();
  2099. }
  2100. // update all paths of its and its descendants' open windows
  2101. else{
  2102. // todo this has to be case-insensitive but the `i` selector doesn't work on ^=
  2103. $(`.window[data-path^="${html_encode($(el_item).attr('data-path'))}/"], .window[data-path="${html_encode($(el_item).attr('data-path'))}" i]`).each(function(){
  2104. update_window_path(this, $(this).attr('data-path').replace($(el_item).attr('data-path'), path.join(dest_path, fsentry.name)));
  2105. })
  2106. }
  2107. if(dest_path === trash_path){
  2108. // if trashing dir...
  2109. if($(el_item).attr('data-is_dir') === '1'){
  2110. // disassociate all its websites
  2111. // todo, some client-side check to see if this dir has at least one associated website before sending ajax request
  2112. puter.hosting.delete(dir_uuid)
  2113. $(`.mywebsites-dir-path[data-uuid="${$(el_item).attr('data-uid')}"]`).remove();
  2114. // remove the website badge from all instances of the dir
  2115. $(`.item[data-uid="${$(el_item).attr('data-uid')}"]`).find('.item-has-website-badge').fadeOut(300);
  2116. }
  2117. }
  2118. // if replacing an existing item, remove the old item that was just replaced
  2119. if(resp.overwritten?.id){
  2120. $(`.item[data-uid=${resp.overwritten.id}]`).removeItems();
  2121. }
  2122. // if this is trash, get original name from item metadata
  2123. fsentry.name = metadata?.original_name || fsentry.name;
  2124. // create new item on matching containers
  2125. const options = {
  2126. appendTo: $(`.item-container[data-path="${html_encode(dest_path)}" i]`),
  2127. immutable: fsentry.immutable,
  2128. associated_app_name: fsentry.associated_app?.name,
  2129. uid: fsentry.uid,
  2130. path: fsentry.path,
  2131. icon: await item_icon(fsentry),
  2132. name: (dest_path === trash_path) ? $(el_item).attr('data-name') : fsentry.name,
  2133. is_dir: fsentry.is_dir,
  2134. size: fsentry.size,
  2135. type: fsentry.type,
  2136. modified: fsentry.modified,
  2137. is_selected: false,
  2138. is_shared: (dest_path === trash_path) ? false : fsentry.is_shared,
  2139. is_shortcut: fsentry.is_shortcut,
  2140. shortcut_to: fsentry.shortcut_to,
  2141. shortcut_to_path: fsentry.shortcut_to_path,
  2142. has_website: $(el_item).attr('data-has_website') === '1',
  2143. metadata: fsentry.metadata ?? '',
  2144. suggested_apps: fsentry.suggested_apps,
  2145. }
  2146. UIItem(options);
  2147. moved_items.push({'options': options, 'original_path': $(el_item).attr('data-path')});
  2148. // this operation may have created some missing directories,
  2149. // see if any of the directories in the path of this file is new AND
  2150. // if these new path have any open parents that need to be updated
  2151. resp.parent_dirs_created?.forEach(async dir => {
  2152. let item_container = $(`.item-container[data-path="${html_encode(path.dirname(dir.path))}" i]`);
  2153. if(item_container.length > 0 && $(`.item[data-path="${html_encode(dir.path)}" i]`).length === 0){
  2154. UIItem({
  2155. appendTo: item_container,
  2156. immutable: false,
  2157. uid: dir.uid,
  2158. path: dir.path,
  2159. icon: await item_icon(dir),
  2160. name: dir.name,
  2161. size: dir.size,
  2162. type: dir.type,
  2163. modified: dir.modified,
  2164. is_dir: true,
  2165. is_selected: false,
  2166. is_shared: dir.is_shared,
  2167. has_website: false,
  2168. suggested_apps: dir.suggested_apps,
  2169. });
  2170. }
  2171. sort_items(item_container);
  2172. });
  2173. //sort each container
  2174. $(`.item-container[data-path="${html_encode(dest_path)}" i]`).each(function(){
  2175. sort_items(this, $(this).attr('data-sort_by'), $(this).attr('data-sort_order'))
  2176. })
  2177. }catch(err){
  2178. // -----------------------------------------------------------------------
  2179. // if item with same name already exists, ask user if they want to overwrite
  2180. // -----------------------------------------------------------------------
  2181. if(err.code==='item_with_same_name_exists'){
  2182. item_with_same_name_already_exists = true;
  2183. const alert_resp = await UIAlert({
  2184. message: `<strong>${html_encode(err.entry_name)}</strong> already exists.`,
  2185. buttons:[
  2186. { label: i18n('replace'), type: 'primary', value: 'replace' },
  2187. ... (el_items.length > 1) ? [{label: i18n('replace_all'), value: 'replace_all'}] : [],
  2188. ... (el_items.length > 1) ? [{label: i18n('skip'), value: 'skip'}] : [{label: i18n('cancel'), value: 'cancel'}],
  2189. ]
  2190. })
  2191. if(alert_resp === 'replace'){
  2192. overwrite = true;
  2193. }else if (alert_resp === 'replace_all'){
  2194. overwrite = true;
  2195. overwrite_all = true;
  2196. }else if(alert_resp === 'skip' || alert_resp === 'cancel'){
  2197. item_with_same_name_already_exists = false;
  2198. }
  2199. }
  2200. // -----------------------------------------------------------------------
  2201. // all other errors
  2202. // -----------------------------------------------------------------------
  2203. else{
  2204. item_with_same_name_already_exists = false;
  2205. // error message after source item has reappeared
  2206. $(el_item).show(0, function(){
  2207. UIAlert(`<p>Moving <strong>${html_encode($(el_item).attr('data-name'))}</strong></p>${err.message ?? ''}`)
  2208. });
  2209. break;
  2210. }
  2211. }
  2212. }while(item_with_same_name_already_exists);
  2213. // check if trash is empty
  2214. if(untrashed_at_least_one_item){
  2215. const trash = await puter.fs.stat(trash_path);
  2216. if(window.socket){
  2217. window.socket.emit('trash.is_empty', {is_empty: trash.is_empty});
  2218. }
  2219. if(trash.is_empty){
  2220. $(`[data-app="trash"]`).find('.taskbar-icon > img').attr('src', window.icons['trash.svg']);
  2221. $(`.item[data-path="${html_encode(trash_path)}" i]`).find('.item-icon > img').attr('src', window.icons['trash.svg']);
  2222. $(`.window[data-path="${html_encode(trash_path)}" i]`).find('.window-head-icon').attr('src', window.icons['trash.svg']);
  2223. }
  2224. }
  2225. }
  2226. clearTimeout(progwin_timeout);
  2227. // log stats to console
  2228. let move_duration = (Date.now() - move_init_ts);
  2229. console.log(`moved ${el_items.length} item${el_items.length > 1 ? 's':''} in ${move_duration}ms`);
  2230. // -----------------------------------------------------------------------
  2231. // DONE! close progress window with delay to allow user to see 100% progress
  2232. // -----------------------------------------------------------------------
  2233. // Add action to actions_history for undo ability
  2234. if(!is_undo && dest_path !== trash_path){
  2235. actions_history.push({
  2236. operation: 'move',
  2237. data: moved_items,
  2238. });
  2239. }else if(!is_undo && dest_path === trash_path){
  2240. actions_history.push({
  2241. operation: 'delete',
  2242. data: moved_items,
  2243. });
  2244. }
  2245. if(progwin){
  2246. setTimeout(() => {
  2247. $(progwin).close();
  2248. }, copy_progress_hide_delay);
  2249. }
  2250. }
  2251. /**
  2252. * Generates sharing URLs for various social media platforms and services based on the provided arguments.
  2253. *
  2254. * @global
  2255. * @function
  2256. * @param {Object} args - Configuration object for generating share URLs.
  2257. * @param {string} [args.url] - The URL to share.
  2258. * @param {string} [args.title] - The title or headline of the content to share.
  2259. * @param {string} [args.image] - Image URL associated with the content.
  2260. * @param {string} [args.desc] - A description of the content.
  2261. * @param {string} [args.appid] - App ID for certain platforms that require it.
  2262. * @param {string} [args.redirecturl] - Redirect URL for certain platforms.
  2263. * @param {string} [args.via] - Attribution source, e.g., a Twitter username.
  2264. * @param {string} [args.hashtags] - Comma-separated list of hashtags without '#'.
  2265. * @param {string} [args.provider] - Content provider.
  2266. * @param {string} [args.language] - Content's language.
  2267. * @param {string} [args.userid] - User ID for certain platforms.
  2268. * @param {string} [args.category] - Content's category.
  2269. * @param {string} [args.phonenumber] - Phone number for platforms like SMS or Telegram.
  2270. * @param {string} [args.emailaddress] - Email address to share content to.
  2271. * @param {string} [args.ccemailaddress] - CC email address for sharing content.
  2272. * @param {string} [args.bccemailaddress] - BCC email address for sharing content.
  2273. * @returns {Object} - An object containing key-value pairs where keys are platform names and values are constructed sharing URLs.
  2274. *
  2275. * @example
  2276. * const shareConfig = {
  2277. * url: 'https://example.com',
  2278. * title: 'Check this out!',
  2279. * desc: 'This is an amazing article on example.com',
  2280. * via: 'exampleUser'
  2281. * };
  2282. * const shareLinks = window.socialLink(shareConfig);
  2283. * console.log(shareLinks.twitter); // Outputs the constructed Twitter share link
  2284. */
  2285. window.socialLink = function (args) {
  2286. const validargs = [
  2287. 'url',
  2288. 'title',
  2289. 'image',
  2290. 'desc',
  2291. 'appid',
  2292. 'redirecturl',
  2293. 'via',
  2294. 'hashtags',
  2295. 'provider',
  2296. 'language',
  2297. 'userid',
  2298. 'category',
  2299. 'phonenumber',
  2300. 'emailaddress',
  2301. 'cemailaddress',
  2302. 'bccemailaddress',
  2303. ];
  2304. for(var i = 0; i < validargs.length; i++) {
  2305. const validarg = validargs[i];
  2306. if(!args[validarg]) {
  2307. args[validarg] = '';
  2308. }
  2309. }
  2310. const url = fixedEncodeURIComponent(args.url);
  2311. const title = fixedEncodeURIComponent(args.title);
  2312. const image = fixedEncodeURIComponent(args.image);
  2313. const desc = fixedEncodeURIComponent(args.desc);
  2314. const via = fixedEncodeURIComponent(args.via);
  2315. const hash_tags = fixedEncodeURIComponent(args.hashtags);
  2316. const language = fixedEncodeURIComponent(args.language);
  2317. const user_id = fixedEncodeURIComponent(args.userid);
  2318. const category = fixedEncodeURIComponent(args.category);
  2319. const phone_number = fixedEncodeURIComponent(args.phonenumber);
  2320. const email_address = fixedEncodeURIComponent(args.emailaddress);
  2321. const cc_email_address = fixedEncodeURIComponent(args.ccemailaddress);
  2322. const bcc_email_address = fixedEncodeURIComponent(args.bccemailaddress);
  2323. var text = title;
  2324. if(desc) {
  2325. text += '%20%3A%20'; // This is just this, " : "
  2326. text += desc;
  2327. }
  2328. return {
  2329. 'add.this':'http://www.addthis.com/bookmark.php?url=' + url,
  2330. 'blogger':'https://www.blogger.com/blog-this.g?u=' + url + '&n=' + title + '&t=' + desc,
  2331. 'buffer':'https://buffer.com/add?text=' + text + '&url=' + url,
  2332. 'diaspora':'https://share.diasporafoundation.org/?title=' + title + '&url=' + url,
  2333. 'douban':'http://www.douban.com/recommend/?url=' + url + '&title=' + text,
  2334. 'email':'mailto:' + email_address + '?subject=' + title + '&body=' + desc,
  2335. 'evernote':'https://www.evernote.com/clip.action?url=' + url + '&title=' + text,
  2336. 'getpocket':'https://getpocket.com/edit?url=' + url,
  2337. 'facebook':'http://www.facebook.com/sharer.php?u=' + url,
  2338. '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,
  2339. 'flipboard':'https://share.flipboard.com/bookmarklet/popout?v=2&title=' + text + '&url=' + url,
  2340. 'gmail':'https://mail.google.com/mail/?view=cm&to=' + email_address + '&su=' + title + '&body=' + url + '&bcc=' + bcc_email_address + '&cc=' + cc_email_address,
  2341. 'google.bookmarks':'https://www.google.com/bookmarks/mark?op=edit&bkmk=' + url + '&title=' + title + '&annotation=' + text + '&labels=' + hash_tags + '',
  2342. 'instapaper':'http://www.instapaper.com/edit?url=' + url + '&title=' + title + '&description=' + desc,
  2343. 'line.me':'https://lineit.line.me/share/ui?url=' + url + '&text=' + text,
  2344. 'linkedin':'https://www.linkedin.com/sharing/share-offsite/?url=' + url,
  2345. 'livejournal':'http://www.livejournal.com/update.bml?subject=' + text + '&event=' + url,
  2346. 'hacker.news':'https://news.ycombinator.com/submitlink?u=' + url + '&t=' + title,
  2347. 'ok.ru':'https://connect.ok.ru/dk?st.cmd=WidgetSharePreview&st.shareUrl=' + url,
  2348. 'pinterest':'http://pinterest.com/pin/create/button/?url=' + url ,
  2349. 'qzone':'http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=' + url,
  2350. 'reddit':'https://reddit.com/submit?url=' + url + '&title=' + title,
  2351. 'renren':'http://widget.renren.com/dialog/share?resourceUrl=' + url + '&srcUrl=' + url + '&title=' + text + '&description=' + desc,
  2352. 'skype':'https://web.skype.com/share?url=' + url + '&text=' + text,
  2353. 'sms':'sms:' + phone_number + '?body=' + text,
  2354. 'surfingbird.ru':'http://surfingbird.ru/share?url=' + url + '&description=' + desc + '&screenshot=' + image + '&title=' + title,
  2355. 'telegram.me':'https://t.me/share/url?url=' + url + '&text=' + text + '&to=' + phone_number,
  2356. 'threema':'threema://compose?text=' + text + '&id=' + user_id,
  2357. 'tumblr':'https://www.tumblr.com/widgets/share/tool?canonicalUrl=' + url + '&title=' + title + '&caption=' + desc + '&tags=' + hash_tags,
  2358. 'twitter':'https://twitter.com/intent/tweet?url=' + url + '&text=' + text + '&via=' + via + '&hashtags=' + hash_tags,
  2359. 'vk':'http://vk.com/share.php?url=' + url + '&title=' + title + '&comment=' + desc,
  2360. 'weibo':'http://service.weibo.com/share/share.php?url=' + url + '&appkey=&title=' + title + '&pic=&ralateUid=',
  2361. 'whatsapp':'https://api.whatsapp.com/send?text=' + text + '%20' + url,
  2362. 'xing':'https://www.xing.com/spi/shares/new?url=' + url,
  2363. 'yahoo':'http://compose.mail.yahoo.com/?to=' + email_address + '&subject=' + title + '&body=' + text,
  2364. };
  2365. }
  2366. /**
  2367. * Encodes a URI component with enhanced safety by replacing characters
  2368. * that are not typically encoded by the standard encodeURIComponent.
  2369. *
  2370. * @param {string} str - The string to be URI encoded.
  2371. * @returns {string} - Returns the URI encoded string.
  2372. *
  2373. * @example
  2374. * const str = "Hello, world!";
  2375. * const encodedStr = fixedEncodeURIComponent(str);
  2376. * console.log(encodedStr); // Expected output: "Hello%2C%20world%21"
  2377. */
  2378. function fixedEncodeURIComponent(str) {
  2379. return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
  2380. return '%' + c.charCodeAt(0).toString(16);
  2381. });
  2382. }
  2383. /**
  2384. * Refreshes the desktop background based on the user's settings.
  2385. * If the user has set a custom desktop background URL or color, it will use that.
  2386. * If not, it defaults to a specific wallpaper image.
  2387. *
  2388. * @global
  2389. * @function
  2390. * @fires set_desktop_background - Calls this global function to set the desktop background.
  2391. *
  2392. * @example
  2393. * // This will refresh the desktop background according to the user's preference or defaults.
  2394. * window.refresh_desktop_background();
  2395. */
  2396. window.refresh_desktop_background = function(){
  2397. if(window.user && (window.user.desktop_bg_url !== null || window.user.desktop_bg_color !== null)){
  2398. window.set_desktop_background({
  2399. url: window.user.desktop_bg_url,
  2400. fit: window.user.desktop_bg_fit,
  2401. color: window.user.desktop_bg_color,
  2402. })
  2403. }
  2404. // default background
  2405. else{
  2406. let wallpaper = (window.gui_env === 'prod') ? '/dist/images/wallpaper.webp' : '/images/wallpaper.webp';
  2407. window.set_desktop_background({
  2408. url: wallpaper,
  2409. fit: 'cover',
  2410. });
  2411. }
  2412. }
  2413. window.determine_website_url = function(fsentry_path){
  2414. // 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
  2415. for(let i=0; i<window.sites.length; i++){
  2416. if(window.sites[i].dir_path && fsentry_path.startsWith(window.sites[i].dir_path + '/')){
  2417. return window.sites[i].address + fsentry_path.replace(window.sites[i].dir_path, '');
  2418. }
  2419. }
  2420. return null;
  2421. }
  2422. window.update_sites_cache = function(){
  2423. return puter.hosting.list((sites)=>{
  2424. if(sites && sites.length > 0){
  2425. window.sites = sites;
  2426. }else{
  2427. window.sites = [];
  2428. }
  2429. })
  2430. }
  2431. /**
  2432. *
  2433. * @param {*} el_target_container
  2434. * @param {*} target_path
  2435. */
  2436. window.init_upload_using_dialog = function(el_target_container, target_path = null){
  2437. $("#upload-file-dialog").unbind('onchange');
  2438. $("#upload-file-dialog").unbind('change');
  2439. $("#upload-file-dialog").unbind('onChange');
  2440. target_path = target_path === null ? $(el_target_container).attr('data-path') : path.resolve(target_path);
  2441. $('#upload-file-dialog').trigger('click');
  2442. $("#upload-file-dialog").on('change', async function(e){
  2443. if($("#upload-file-dialog").val() !== ''){
  2444. const files = $('#upload-file-dialog')[0].files;
  2445. if(files.length > 0){
  2446. try{
  2447. upload_items(files, target_path);
  2448. }
  2449. catch(err){
  2450. UIAlert(err.message ?? err)
  2451. }
  2452. $('#upload-file-dialog').val('');
  2453. }
  2454. }
  2455. else{
  2456. return
  2457. }
  2458. })
  2459. }
  2460. window.upload_items = async function(items, dest_path){
  2461. let upload_progress_window;
  2462. let opid;
  2463. if(dest_path == trash_path){
  2464. UIAlert('Uploading to trash is not allowed!');
  2465. return;
  2466. }
  2467. puter.fs.upload(
  2468. // what to upload
  2469. items,
  2470. // where to upload
  2471. dest_path,
  2472. // options
  2473. {
  2474. // init
  2475. init: async(operation_id, xhr)=>{
  2476. opid = operation_id;
  2477. // create upload progress window
  2478. upload_progress_window = await UIWindowUploadProgress({operation_id: operation_id});
  2479. // cancel btn
  2480. $(upload_progress_window).find('.upload-cancel-btn').on('click', function(e){
  2481. $(upload_progress_window).close();
  2482. show_save_account_notice_if_needed();
  2483. xhr.abort();
  2484. })
  2485. // add to active_uploads
  2486. active_uploads[opid] = 0;
  2487. },
  2488. // start
  2489. start: async function(){
  2490. // change upload progress window message to uploading
  2491. $(upload_progress_window).find('.upload-progress-msg').html(`Uploading (<span class="upload-progress-percent">0%</span>)`);
  2492. },
  2493. // progress
  2494. progress: async function(operation_id, op_progress){
  2495. $(`[data-upload-operation-id="${operation_id}"]`).find('.upload-progress-bar').css( 'width', op_progress+'%');
  2496. $(`[data-upload-operation-id="${operation_id}"]`).find('.upload-progress-percent').html(op_progress+'%');
  2497. // update active_uploads
  2498. active_uploads[opid] = op_progress;
  2499. // update title if window is not visible
  2500. if(document.visibilityState !== "visible"){
  2501. update_title_based_on_uploads();
  2502. }
  2503. },
  2504. // success
  2505. success: async function(items){
  2506. // DONE
  2507. // Add action to actions_history for undo ability
  2508. const files = []
  2509. if(typeof items[Symbol.iterator] === 'function'){
  2510. for(const item of items){
  2511. files.push(item.path)
  2512. }
  2513. }else{
  2514. files.push(items.path)
  2515. }
  2516. actions_history.push({
  2517. operation: 'upload',
  2518. data: files
  2519. });
  2520. // close progress window after a bit of delay for a better UX
  2521. setTimeout(() => {
  2522. setTimeout(() => {
  2523. $(upload_progress_window).close();
  2524. show_save_account_notice_if_needed();
  2525. }, Math.abs(upload_progress_hide_delay));
  2526. })
  2527. // remove from active_uploads
  2528. delete active_uploads[opid];
  2529. },
  2530. // error
  2531. error: async function(err){
  2532. $(upload_progress_window).close();
  2533. // UIAlert(err?.message ?? 'An error occurred while uploading.');
  2534. // remove from active_uploads
  2535. delete active_uploads[opid];
  2536. },
  2537. // abort
  2538. abort: async function(operation_id){
  2539. // console.log('upload aborted');
  2540. // remove from active_uploads
  2541. delete active_uploads[opid];
  2542. }
  2543. }
  2544. );
  2545. }
  2546. window.empty_trash = async function(){
  2547. const alert_resp = await UIAlert({
  2548. message: i18n('empty_trash_confirmation'),
  2549. buttons:[
  2550. {
  2551. label: i18n('yes'),
  2552. value: 'yes',
  2553. type: 'primary',
  2554. },
  2555. {
  2556. label: i18n('no'),
  2557. value: 'no',
  2558. },
  2559. ]
  2560. })
  2561. if(alert_resp === 'no')
  2562. return;
  2563. // only show progress window if it takes longer than 500ms to create folder
  2564. let init_ts = Date.now();
  2565. let progwin;
  2566. let op_id = uuidv4();
  2567. let progwin_timeout = setTimeout(async () => {
  2568. progwin = await UIWindowProgressEmptyTrash({operation_id: op_id});
  2569. }, 500);
  2570. await puter.fs.delete({
  2571. paths: trash_path,
  2572. descendantsOnly: true,
  2573. recursive: true,
  2574. success: async function (resp){
  2575. // update other clients
  2576. if(window.socket){
  2577. window.socket.emit('trash.is_empty', {is_empty: true});
  2578. }
  2579. // use the 'empty trash' icon for Trash
  2580. $(`[data-app="trash"]`).find('.taskbar-icon > img').attr('src', window.icons['trash.svg']);
  2581. $(`.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']);
  2582. $(`.window[data-path="${trash_path}"]`).find('.window-head-icon').attr('src', window.icons['trash.svg']);
  2583. // remove all items with trash paths
  2584. // todo this has to be case-insensitive but the `i` selector doesn't work on ^=
  2585. $(`.item[data-path^="${trash_path}/"]`).removeItems();
  2586. // update the footer item count for Trash
  2587. update_explorer_footer_item_count($(`.window[data-path="${trash_path}"]`))
  2588. // close progress window
  2589. clearTimeout(progwin_timeout);
  2590. setTimeout(() => {
  2591. $(progwin).close();
  2592. }, Math.max(0, copy_progress_hide_delay - (Date.now() - init_ts)));
  2593. },
  2594. error: async function (err){
  2595. clearTimeout(progwin_timeout);
  2596. setTimeout(() => {
  2597. $(progwin).close();
  2598. }, Math.max(0, copy_progress_hide_delay - (Date.now() - init_ts)));
  2599. }
  2600. });
  2601. }
  2602. window.copy_to_clipboard = async function(text){
  2603. if (navigator.clipboard) {
  2604. // copy text to clipboard
  2605. await navigator.clipboard.writeText(text);
  2606. }
  2607. else{
  2608. document.execCommand('copy');
  2609. }
  2610. }
  2611. window.getUsage = () => {
  2612. return fetch(api_origin + "/drivers/usage", {
  2613. headers: {
  2614. "Content-Type": "application/json",
  2615. "Authorization": "Bearer " + auth_token
  2616. },
  2617. method: "GET"
  2618. })
  2619. .then(response => {
  2620. // Check if the response is ok (status code in the range 200-299)
  2621. if (!response.ok) {
  2622. throw new Error('Network response was not ok');
  2623. }
  2624. return response.json(); // Parse the response as JSON
  2625. })
  2626. .then(data => {
  2627. // Handle the JSON data
  2628. return data;
  2629. })
  2630. .catch(error => {
  2631. // Handle any errors
  2632. console.error('There has been a problem with your fetch operation:', error);
  2633. });
  2634. }
  2635. window.getAppUIDFromOrigin = async function(origin) {
  2636. try {
  2637. const response = await fetch(window.api_origin + "/auth/app-uid-from-origin", {
  2638. headers: {
  2639. "Content-Type": "application/json",
  2640. "Authorization": "Bearer " + window.auth_token,
  2641. },
  2642. body: JSON.stringify({ origin: origin }),
  2643. method: "POST",
  2644. });
  2645. const data = await response.json();
  2646. // Assuming the app_uid is in the data object, return it
  2647. return data.uid;
  2648. } catch (err) {
  2649. // Handle any errors here
  2650. console.error(err);
  2651. // You may choose to return something specific here in case of an error
  2652. return null;
  2653. }
  2654. }
  2655. window.getUserAppToken = async function(origin) {
  2656. try {
  2657. const response = await fetch(window.api_origin + "/auth/get-user-app-token", {
  2658. headers: {
  2659. "Content-Type": "application/json",
  2660. "Authorization": "Bearer " + window.auth_token,
  2661. },
  2662. body: JSON.stringify({ origin: origin }),
  2663. method: "POST",
  2664. });
  2665. const data = await response.json();
  2666. // return
  2667. return data;
  2668. } catch (err) {
  2669. // Handle any errors here
  2670. console.error(err);
  2671. // You may choose to return something specific here in case of an error
  2672. return null;
  2673. }
  2674. }
  2675. window.checkUserSiteRelationship = async function(origin) {
  2676. try {
  2677. const response = await fetch(window.api_origin + "/auth/check-app ", {
  2678. headers: {
  2679. "Content-Type": "application/json",
  2680. "Authorization": "Bearer " + window.auth_token,
  2681. },
  2682. body: JSON.stringify({ origin: origin }),
  2683. method: "POST",
  2684. });
  2685. const data = await response.json();
  2686. // return
  2687. return data;
  2688. } catch (err) {
  2689. // Handle any errors here
  2690. console.error(err);
  2691. // You may choose to return something specific here in case of an error
  2692. return null;
  2693. }
  2694. }
  2695. window.zipItems = async function(el_items, targetDirPath, download = true) {
  2696. const zip = new JSZip();
  2697. // if single item, convert to array
  2698. el_items = Array.isArray(el_items) ? el_items : [el_items];
  2699. // create progress window
  2700. let start_ts = Date.now();
  2701. let progwin, progwin_timeout;
  2702. // only show progress window if it takes longer than 500ms to download
  2703. progwin_timeout = setTimeout(async () => {
  2704. progwin = await UIWindowDownloadDirProg();
  2705. }, 500);
  2706. for (const el_item of el_items) {
  2707. let targetPath = $(el_item).attr('data-path');
  2708. // if directory, zip the directory
  2709. if($(el_item).attr('data-is_dir') === '1'){
  2710. $(progwin).find('.dir-dl-status').html(`Reading <strong>${html_encode(targetPath)}</strong>`);
  2711. // Recursively read the directory
  2712. let children = await readDirectoryRecursive(targetPath);
  2713. // Add files to the zip
  2714. for (const child of children) {
  2715. let relativePath;
  2716. if(el_items.length === 1)
  2717. relativePath = child.relativePath;
  2718. else
  2719. relativePath = path.basename(targetPath) + '/' + child.relativePath;
  2720. // update progress window
  2721. $(progwin).find('.dir-dl-status').html(`Zipping <strong>${html_encode(relativePath)}</strong>`);
  2722. // read file content
  2723. let content = await puter.fs.read(child.path);
  2724. try{
  2725. zip.file(relativePath, content, {binary: true});
  2726. }catch(e){
  2727. console.error(e);
  2728. }
  2729. }
  2730. }
  2731. // if item is a file, zip the file
  2732. else{
  2733. let content = await puter.fs.read(targetPath);
  2734. zip.file(path.basename(targetPath), content, {binary: true});
  2735. }
  2736. }
  2737. // determine name of zip file
  2738. let zipName;
  2739. if(el_items.length === 1)
  2740. zipName = path.basename($(el_items[0]).attr('data-path'));
  2741. else
  2742. zipName = 'Archive';
  2743. // Generate the zip file
  2744. zip.generateAsync({ type: "blob" })
  2745. .then(async function (content) {
  2746. // Trigger the download
  2747. if(download){
  2748. const url = URL.createObjectURL(content);
  2749. const a = document.createElement("a");
  2750. a.href = url;
  2751. a.download = zipName;
  2752. document.body.appendChild(a);
  2753. a.click();
  2754. // Cleanup
  2755. document.body.removeChild(a);
  2756. URL.revokeObjectURL(url);
  2757. }
  2758. // save
  2759. else
  2760. await puter.fs.write(targetDirPath + '/' + zipName + ".zip", content, {overwrite: false, dedupeName: true})
  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. })
  2767. .catch(function (err) {
  2768. // close progress window
  2769. clearTimeout(progwin_timeout);
  2770. setTimeout(() => {
  2771. $(progwin).close();
  2772. }, Math.max(0, copy_progress_hide_delay - (Date.now() - start_ts)));
  2773. // handle errors
  2774. console.error("Error in zipping files: ", err);
  2775. });
  2776. }
  2777. async function readDirectoryRecursive(path, baseDir = '') {
  2778. let allFiles = [];
  2779. // Read the directory
  2780. const entries = await puter.fs.readdir(path);
  2781. // Process each entry
  2782. for (const entry of entries) {
  2783. const fullPath = `${path}/${entry.name}`;
  2784. if (entry.is_dir) {
  2785. // If entry is a directory, recursively read it
  2786. const subDirFiles = await readDirectoryRecursive(fullPath, `${baseDir}${entry.name}/`);
  2787. allFiles = allFiles.concat(subDirFiles);
  2788. } else {
  2789. // If entry is a file, add it to the list
  2790. allFiles.push({ path: fullPath, relativePath: `${baseDir}${entry.name}` });
  2791. }
  2792. }
  2793. return allFiles;
  2794. }
  2795. window.extractSubdomain = function(url) {
  2796. var subdomain = url.split('://')[1].split('.')[0];
  2797. return subdomain;
  2798. }
  2799. window.sleep = function(ms){
  2800. return new Promise(resolve => setTimeout(resolve, ms));
  2801. }
  2802. window.unzipItem = async function(itemPath) {
  2803. // create progress window
  2804. let start_ts = Date.now();
  2805. let progwin, progwin_timeout;
  2806. // only show progress window if it takes longer than 500ms to download
  2807. progwin_timeout = setTimeout(async () => {
  2808. progwin = await UIWindowDownloadDirProg();
  2809. }, 500);
  2810. const zip = new JSZip();
  2811. let filPath = itemPath;
  2812. let file = puter.fs.read(filPath);
  2813. zip.loadAsync(file).then(async function (zip) {
  2814. const rootdir = await puter.fs.mkdir(path.dirname(filPath) + '/' + path.basename(filPath, '.zip'), {dedupeName: true});
  2815. Object.keys(zip.files).forEach(async function (filename) {
  2816. console.log(filename);
  2817. if(filename.endsWith('/'))
  2818. await puter.fs.mkdir(rootdir.path +'/' + filename, {createMissingParents: true});
  2819. zip.files[filename].async('blob').then(async function (fileData) {
  2820. await puter.fs.write(rootdir.path +'/' + filename, fileData);
  2821. }).catch(function (e) {
  2822. // UIAlert(e.message);
  2823. })
  2824. })
  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. }).catch(function (e) {
  2831. // UIAlert(e.message);
  2832. // close progress window
  2833. clearTimeout(progwin_timeout);
  2834. setTimeout(() => {
  2835. $(progwin).close();
  2836. }, Math.max(0, copy_progress_hide_delay - (Date.now() - start_ts)));
  2837. })
  2838. }
  2839. 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)=>{
  2840. puter.fs.rename({
  2841. uid: options.uid === 'null' ? null : options.uid,
  2842. new_name: new_name,
  2843. excludeSocketID: window.socket.id,
  2844. success: async (fsentry)=>{
  2845. // Add action to actions_history for undo ability
  2846. if (!is_undo)
  2847. actions_history.push({
  2848. operation: 'rename',
  2849. data: {options, new_name, old_name, old_path, el_item, el_item_name, el_item_icon, el_item_name_editor, website_url}
  2850. });
  2851. // Has the extension changed? in that case update options.sugggested_apps
  2852. const old_extension = path.extname(old_name);
  2853. const new_extension = path.extname(new_name);
  2854. if(old_extension !== new_extension){
  2855. suggest_apps_for_fsentry({
  2856. uid: options.uid,
  2857. onSuccess: function(suggested_apps){
  2858. options.suggested_apps = suggested_apps;
  2859. }
  2860. });
  2861. }
  2862. // Set new item name
  2863. $(`.item[data-uid='${$(el_item).attr('data-uid')}'] .item-name`).html(html_encode(truncate_filename(new_name, TRUNCATE_LENGTH)).replaceAll(' ', '&nbsp;'));
  2864. $(el_item_name).show();
  2865. // Hide item name editor
  2866. $(el_item_name_editor).hide();
  2867. // Set new icon
  2868. const new_icon = (options.is_dir ? window.icons['folder.svg'] : (await item_icon(fsentry)).image);
  2869. $(el_item_icon).find('.item-icon-icon').attr('src', new_icon);
  2870. // Set new data-name
  2871. options.name = new_name;
  2872. $(el_item).attr('data-name', html_encode(new_name));
  2873. $(`.item[data-uid='${$(el_item).attr('data-uid')}']`).attr('data-name', html_encode(new_name));
  2874. $(`.window-${options.uid}`).attr('data-name', html_encode(new_name));
  2875. // Set new title attribute
  2876. $(`.item[data-uid='${$(el_item).attr('data-uid')}']`).attr('title', html_encode(new_name));
  2877. $(`.window-${options.uid}`).attr('title', html_encode(new_name));
  2878. // Set new value for item-name-editor
  2879. $(`.item[data-uid='${$(el_item).attr('data-uid')}'] .item-name-editor`).val(html_encode(new_name));
  2880. $(`.item[data-uid='${$(el_item).attr('data-uid')}'] .item-name`).attr('title', html_encode(new_name));
  2881. // Set new data-path
  2882. options.path = path.join( path.dirname(options.path), options.name);
  2883. const new_path = options.path;
  2884. $(el_item).attr('data-path', new_path);
  2885. $(`.item[data-uid='${$(el_item).attr('data-uid')}']`).attr('data-path', new_path);
  2886. $(`.window-${options.uid}`).attr('data-path', new_path);
  2887. // Update all elements that have matching paths
  2888. $(`[data-path="${html_encode(old_path)}" i]`).each(function(){
  2889. $(this).attr('data-path', new_path)
  2890. if($(this).hasClass('window-navbar-path-dirname'))
  2891. $(this).text(new_name);
  2892. });
  2893. // Update the paths of all elements whose paths start with old_path
  2894. $(`[data-path^="${html_encode(old_path) + '/'}"]`).each(function(){
  2895. const new_el_path = _.replace($(this).attr('data-path'), old_path + '/', new_path+'/');
  2896. $(this).attr('data-path', new_el_path);
  2897. });
  2898. // Update the 'Sites Cache'
  2899. if($(el_item).attr('data-has_website') === '1')
  2900. await update_sites_cache();
  2901. // Update website_url
  2902. website_url = determine_website_url(new_path);
  2903. $(el_item).attr('data-website_url', website_url);
  2904. // Update all exact-matching windows
  2905. $(`.window-${options.uid}`).each(function(){
  2906. update_window_path(this, options.path);
  2907. })
  2908. // Set new name for corresponding open windows
  2909. $(`.window-${options.uid} .window-head-title`).text(new_name);
  2910. // Re-sort all matching item containers
  2911. $(`.item[data-uid='${$(el_item).attr('data-uid')}']`).parent('.item-container').each(function(){
  2912. sort_items(this, $(el_item).closest('.item-container').attr('data-sort_by'), $(el_item).closest('.item-container').attr('data-sort_order'));
  2913. })
  2914. },
  2915. error: function (err){
  2916. // reset to old name
  2917. $(el_item_name).text(truncate_filename(options.name, TRUNCATE_LENGTH));
  2918. $(el_item_name).show();
  2919. // hide item name editor
  2920. $(el_item_name_editor).hide();
  2921. $(el_item_name_editor).val(html_encode($(el_item).attr('data-name')));
  2922. //show error
  2923. if(err.message){
  2924. UIAlert(err.message)
  2925. }
  2926. },
  2927. });
  2928. }
  2929. /**
  2930. * Deletes the given item with path.
  2931. *
  2932. * @param {string} path - path of the item to delete
  2933. * @returns {Promise<void>}
  2934. */
  2935. window.delete_item_with_path = async function(path){
  2936. try{
  2937. await puter.fs.delete({
  2938. paths: path,
  2939. descendantsOnly: false,
  2940. recursive: true,
  2941. });
  2942. }catch(err){
  2943. UIAlert(err.responseText);
  2944. }
  2945. }
  2946. window.undo_last_action = async()=>{
  2947. if (actions_history.length > 0) {
  2948. const last_action = actions_history.pop();
  2949. // Undo the create file action
  2950. if (last_action.operation === 'create_file' || last_action.operation === 'create_folder') {
  2951. const lastCreatedItem = last_action.data;
  2952. undo_create_file_or_folder(lastCreatedItem);
  2953. } else if(last_action.operation === 'rename') {
  2954. 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;
  2955. rename_file(options, old_name, new_name, old_path, el_item, el_item_name, el_item_icon, el_item_name_editor, website_url, true);
  2956. } else if(last_action.operation === 'upload') {
  2957. const files = last_action.data;
  2958. undo_upload(files);
  2959. } else if(last_action.operation === 'copy') {
  2960. const files = last_action.data;
  2961. undo_copy(files);
  2962. } else if(last_action.operation === 'move') {
  2963. const items = last_action.data;
  2964. undo_move(items);
  2965. } else if(last_action.operation === 'delete') {
  2966. const items = last_action.data;
  2967. undo_delete(items);
  2968. }
  2969. }
  2970. }
  2971. window.undo_create_file_or_folder = async(item)=>{
  2972. await window.delete_item(item);
  2973. }
  2974. window.undo_upload = async(files)=>{
  2975. for (const file of files) {
  2976. await window.delete_item_with_path(file);
  2977. }
  2978. }
  2979. window.undo_copy = async(files)=>{
  2980. for (const file of files) {
  2981. await window.delete_item_with_path(file);
  2982. }
  2983. }
  2984. window.undo_move = async(items)=>{
  2985. for (const item of items) {
  2986. const el = await get_html_element_from_options(item.options);
  2987. console.log(item.original_path)
  2988. move_items([el], path.dirname(item.original_path), true);
  2989. }
  2990. }
  2991. window.undo_delete = async(items)=>{
  2992. for (const item of items) {
  2993. const el = await get_html_element_from_options(item.options);
  2994. let metadata = $(el).attr('data-metadata') === '' ? {} : JSON.parse($(el).attr('data-metadata'))
  2995. move_items([el], path.dirname(metadata.original_path), true);
  2996. }
  2997. }
  2998. window.get_html_element_from_options = async function(options){
  2999. const item_id = global_element_id++;
  3000. options.disabled = options.disabled ?? false;
  3001. options.visible = options.visible ?? 'visible'; // one of 'visible', 'revealed', 'hidden'
  3002. options.is_dir = options.is_dir ?? false;
  3003. options.is_selected = options.is_selected ?? false;
  3004. options.is_shared = options.is_shared ?? false;
  3005. options.is_shortcut = options.is_shortcut ?? 0;
  3006. options.is_trash = options.is_trash ?? false;
  3007. options.metadata = options.metadata ?? '';
  3008. options.multiselectable = options.multiselectable ?? true;
  3009. options.shortcut_to = options.shortcut_to ?? '';
  3010. options.shortcut_to_path = options.shortcut_to_path ?? '';
  3011. options.immutable = (options.immutable === false || options.immutable === 0 || options.immutable === undefined ? 0 : 1);
  3012. options.sort_container_after_append = (options.sort_container_after_append !== undefined ? options.sort_container_after_append : false);
  3013. const is_shared_with_me = (options.path !== '/'+window.user.username && !options.path.startsWith('/'+window.user.username+'/'));
  3014. let website_url = determine_website_url(options.path);
  3015. // do a quick check to see if the target parent has any file type restrictions
  3016. const appendto_allowed_file_types = $(options.appendTo).attr('data-allowed_file_types')
  3017. if(!window.check_fsentry_against_allowed_file_types_string({is_dir: options.is_dir, name:options.name, type:options.type}, appendto_allowed_file_types))
  3018. options.disabled = true;
  3019. // --------------------------------------------------------
  3020. // HTML for Item
  3021. // --------------------------------------------------------
  3022. let h = '';
  3023. h += `<div id="item-${item_id}"
  3024. class="item${options.is_selected ? ' item-selected':''} ${options.disabled ? 'item-disabled':''} item-${options.visible}"
  3025. data-id="${item_id}"
  3026. data-name="${html_encode(options.name)}"
  3027. data-metadata="${html_encode(options.metadata)}"
  3028. data-uid="${options.uid}"
  3029. data-is_dir="${options.is_dir ? 1 : 0}"
  3030. data-is_trash="${options.is_trash ? 1 : 0}"
  3031. data-has_website="${options.has_website ? 1 : 0 }"
  3032. data-website_url = "${website_url ? html_encode(website_url) : ''}"
  3033. data-immutable="${options.immutable}"
  3034. data-is_shortcut = "${options.is_shortcut}"
  3035. data-shortcut_to = "${html_encode(options.shortcut_to)}"
  3036. data-shortcut_to_path = "${html_encode(options.shortcut_to_path)}"
  3037. data-sortable = "${options.sortable ?? 'true'}"
  3038. data-sort_by = "${html_encode(options.sort_by) ?? 'name'}"
  3039. data-size = "${options.size ?? ''}"
  3040. data-type = "${html_encode(options.type) ?? ''}"
  3041. data-modified = "${options.modified ?? ''}"
  3042. data-associated_app_name = "${html_encode(options.associated_app_name) ?? ''}"
  3043. data-path="${html_encode(options.path)}">`;
  3044. // spinner
  3045. h += `<div class="item-spinner">`;
  3046. h += `</div>`;
  3047. // modified
  3048. h += `<div class="item-attr item-attr--modified">`;
  3049. h += `<span>${options.modified === 0 ? '-' : timeago.format(options.modified*1000)}</span>`;
  3050. h += `</div>`;
  3051. // size
  3052. h += `<div class="item-attr item-attr--size">`;
  3053. h += `<span>${options.size ? byte_format(options.size) : '-'}</span>`;
  3054. h += `</div>`;
  3055. // type
  3056. h += `<div class="item-attr item-attr--type">`;
  3057. if(options.is_dir)
  3058. h += `<span>Folder</span>`;
  3059. else
  3060. h += `<span>${options.type ? html_encode(options.type) : '-'}</span>`;
  3061. h += `</div>`;
  3062. // icon
  3063. h += `<div class="item-icon">`;
  3064. h += `<img src="${html_encode(options.icon.image)}" class="item-icon-${options.icon.type}" data-item-id="${item_id}">`;
  3065. h += `</div>`;
  3066. // badges
  3067. h += `<div class="item-badges">`;
  3068. // website badge
  3069. h += `<img class="item-badge item-has-website-badge long-hover"
  3070. style="${options.has_website ? 'display:block;' : ''}"
  3071. src="${html_encode(window.icons['world.svg'])}"
  3072. data-item-id="${item_id}"
  3073. >`;
  3074. // link badge
  3075. h += `<img class="item-badge item-has-website-url-badge"
  3076. style="${website_url ? 'display:block;' : ''}"
  3077. src="${html_encode(window.icons['link.svg'])}"
  3078. data-item-id="${item_id}"
  3079. >`;
  3080. // shared badge
  3081. h += `<img class="item-badge item-badge-has-permission"
  3082. style="display: ${ is_shared_with_me ? 'block' : 'none'};
  3083. background-color: #ffffff;
  3084. padding: 2px;" src="${html_encode(window.icons['shared.svg'])}"
  3085. data-item-id="${item_id}"
  3086. title="A user has shared this item with you.">`;
  3087. // owner-shared badge
  3088. h += `<img class="item-badge item-is-shared"
  3089. style="background-color: #ffffff; padding: 2px; ${!is_shared_with_me && options.is_shared ? 'display:block;' : ''}"
  3090. src="${html_encode(window.icons['owner-shared.svg'])}"
  3091. data-item-id="${item_id}"
  3092. data-item-uid="${options.uid}"
  3093. data-item-path="${html_encode(options.path)}"
  3094. title="You have shared this item with at least one other user."
  3095. >`;
  3096. // shortcut badge
  3097. h += `<img class="item-badge item-shortcut"
  3098. style="background-color: #ffffff; padding: 2px; ${options.is_shortcut !== 0 ? 'display:block;' : ''}"
  3099. src="${html_encode(window.icons['shortcut.svg'])}"
  3100. data-item-id="${item_id}"
  3101. title="Shortcut"
  3102. >`;
  3103. h += `</div>`;
  3104. // name
  3105. 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>`
  3106. // name editor
  3107. 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>`
  3108. h += `</div>`;
  3109. return h;
  3110. }
  3111. window.store_auto_arrange_preference = (preference)=>{
  3112. puter.kv.set('user_preferences.auto_arrange_desktop', preference);
  3113. localStorage.setItem('auto_arrange', preference);
  3114. }
  3115. window.get_auto_arrange_data = async()=>{
  3116. const preferenceValue = await puter.kv.get('user_preferences.auto_arrange_desktop');
  3117. is_auto_arrange_enabled = preferenceValue === null ? true : preferenceValue;
  3118. const positions = await puter.kv.get('desktop_item_positions')
  3119. desktop_item_positions = (!positions || typeof positions !== 'object' || Array.isArray(positions)) ? {} : positions;
  3120. }
  3121. window.clear_desktop_item_positions = async(el_desktop)=>{
  3122. $(el_desktop).find('.item').each(function(){
  3123. const el_item = $(this)[0];
  3124. $(el_item).css('position', '');
  3125. $(el_item).css('left', '');
  3126. $(el_item).css('top', '');
  3127. });
  3128. if(reset_item_positions){
  3129. delete_desktop_item_positions()
  3130. }
  3131. }
  3132. window.set_desktop_item_positions = async(el_desktop)=>{
  3133. $(el_desktop).find('.item').each(async function(){
  3134. const position = desktop_item_positions[$(this).attr('data-uid')]
  3135. const el_item = $(this)[0];
  3136. if(position){
  3137. $(el_item).css('position', 'absolute');
  3138. $(el_item).css('left', position.left + 'px');
  3139. $(el_item).css('top', position.top + 'px');
  3140. }
  3141. });
  3142. }
  3143. window.save_desktop_item_positions = ()=>{
  3144. puter.kv.set('desktop_item_positions', desktop_item_positions);
  3145. }
  3146. window.delete_desktop_item_positions = ()=>{
  3147. desktop_item_positions = {}
  3148. puter.kv.del('desktop_item_positions');
  3149. }
  3150. window.change_clock_visible = (clock_visible) => {
  3151. let newValue = clock_visible || window.user_preferences.clock_visible;
  3152. newValue === 'auto' && is_fullscreen() ? $('#clock').show() : $('#clock').hide();
  3153. newValue === 'show' && $('#clock').show();
  3154. newValue === 'hide' && $('#clock').hide();
  3155. if(clock_visible) {
  3156. // save clock_visible to user preferences
  3157. window.mutate_user_preferences({
  3158. clock_visible: newValue
  3159. });
  3160. return;
  3161. }
  3162. $('select.change-clock-visible').val(window.user_preferences.clock_visible);
  3163. }
  3164. // Finds the `.window` element for the given app instance ID
  3165. window.window_for_app_instance = (instance_id) => {
  3166. return $(`.window[data-element_uuid="${instance_id}"]`).get(0);
  3167. };
  3168. // Finds the `iframe` element for the given app instance ID
  3169. window.iframe_for_app_instance = (instance_id) => {
  3170. return $(window_for_app_instance(instance_id)).find('.window-app-iframe').get(0);
  3171. };
  3172. // Run any callbacks to say that the app has launched
  3173. window.report_app_launched = (instance_id, { uses_sdk = true }) => {
  3174. const child_launch_callback = window.child_launch_callbacks[instance_id];
  3175. if (child_launch_callback) {
  3176. const parent_iframe = iframe_for_app_instance(child_launch_callback.parent_instance_id);
  3177. // send confirmation to requester window
  3178. parent_iframe.contentWindow.postMessage({
  3179. msg: 'childAppLaunched',
  3180. original_msg_id: child_launch_callback.launch_msg_id,
  3181. child_instance_id: instance_id,
  3182. uses_sdk: uses_sdk,
  3183. }, '*');
  3184. delete window.child_launch_callbacks[instance_id];
  3185. }
  3186. };
  3187. // Run any callbacks to say that the app has closed
  3188. window.report_app_closed = (instance_id) => {
  3189. const el_window = window_for_app_instance(instance_id);
  3190. // notify parent app, if we have one, that we're closing
  3191. const parent_id = el_window.dataset['parent_instance_id'];
  3192. const parent = $(`.window[data-element_uuid="${parent_id}"] .window-app-iframe`).get(0);
  3193. if (parent) {
  3194. parent.contentWindow.postMessage({
  3195. msg: 'appClosed',
  3196. appInstanceID: instance_id,
  3197. }, '*');
  3198. }
  3199. // notify child apps, if we have them, that we're closing
  3200. const children = $(`.window[data-parent_instance_id="${instance_id}"] .window-app-iframe`);
  3201. children.each((_, child) => {
  3202. child.contentWindow.postMessage({
  3203. msg: 'appClosed',
  3204. appInstanceID: instance_id,
  3205. }, '*');
  3206. });
  3207. // TODO: Once other AppConnections exist, those will need notifying too.
  3208. };