helpers.js 148 KB

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