helpers.js 141 KB

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