helpers.js 144 KB

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