helpers.js 93 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415
  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 UIWindowLogin from './UI/UIWindowLogin.js';
  24. import UIWindowSaveAccount from './UI/UIWindowSaveAccount.js';
  25. import update_username_in_gui from './helpers/update_username_in_gui.js';
  26. import update_title_based_on_uploads from './helpers/update_title_based_on_uploads.js';
  27. import truncate_filename from './helpers/truncate_filename.js';
  28. import UIWindowProgress from './UI/UIWindowProgress.js';
  29. import globToRegExp from "./helpers/globToRegExp.js";
  30. import get_html_element_from_options from "./helpers/get_html_element_from_options.js";
  31. import item_icon from "./helpers/item_icon.js";
  32. window.is_auth = ()=>{
  33. if(localStorage.getItem("auth_token") === null || window.auth_token === null)
  34. return false;
  35. else
  36. return true;
  37. }
  38. window.suggest_apps_for_fsentry = async (options)=>{
  39. let res = await $.ajax({
  40. url: window.api_origin + "/suggest_apps",
  41. type: 'POST',
  42. contentType: "application/json",
  43. data: JSON.stringify({
  44. uid: options.uid ?? undefined,
  45. path: options.path ?? undefined,
  46. }),
  47. headers: {
  48. "Authorization": "Bearer "+window.auth_token
  49. },
  50. statusCode: {
  51. 401: function () {
  52. window.logout();
  53. },
  54. },
  55. success: function (res){
  56. if(options.onSuccess && typeof options.onSuccess == "function")
  57. options.onSuccess(res);
  58. }
  59. });
  60. return res;
  61. }
  62. /**
  63. * Formats a binary-byte integer into the human-readable form with units.
  64. *
  65. * @param {integer} bytes
  66. * @returns
  67. */
  68. window.byte_format = (bytes)=>{
  69. const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
  70. if (bytes === 0) return '0 Byte';
  71. const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
  72. return (bytes / Math.pow(1024, i)).toFixed(2) + ' ' + sizes[i];
  73. };
  74. /**
  75. * A function that generates a UUID (Universally Unique Identifier) using the version 4 format,
  76. * which are random UUIDs. It uses the cryptographic number generator available in modern browsers.
  77. *
  78. * The generated UUID is a 36 character string (32 alphanumeric characters separated by 4 hyphens).
  79. * It follows the pattern: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx, where x is any hexadecimal digit
  80. * and y is one of 8, 9, A, or B.
  81. *
  82. * @returns {string} Returns a new UUID v4 string.
  83. *
  84. * @example
  85. *
  86. * let id = window.uuidv4(); // Generate a new UUID
  87. *
  88. */
  89. window.uuidv4 = ()=>{
  90. return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
  91. (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
  92. );
  93. }
  94. /**
  95. * Checks if the provided string is a valid email format.
  96. *
  97. * @function
  98. * @global
  99. * @param {string} email - The email string to be validated.
  100. * @returns {boolean} `true` if the email is valid, otherwise `false`.
  101. * @example
  102. * window.is_email("test@example.com"); // true
  103. * window.is_email("invalid-email"); // false
  104. */
  105. window.is_email = (email) => {
  106. 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,}))$/;
  107. return re.test(String(email).toLowerCase());
  108. }
  109. /**
  110. * A function that scrolls the parent element so that the child element is in view.
  111. * If the child element is already in view, no scrolling occurs.
  112. * The function decides the best scroll direction based on which requires the smaller adjustment.
  113. *
  114. * @param {HTMLElement} parent - The parent HTML element that might be scrolled.
  115. * @param {HTMLElement} child - The child HTML element that should be made viewable.
  116. *
  117. * @returns {void}
  118. *
  119. * @example
  120. *
  121. * let parentElem = document.querySelector('#parent');
  122. * let childElem = document.querySelector('#child');
  123. * window.scrollParentToChild(parentElem, childElem);
  124. * // Scrolls parentElem so that childElem is in view
  125. *
  126. */
  127. window.scrollParentToChild = (parent, child)=>{
  128. // Where is the parent on page
  129. var parentRect = parent.getBoundingClientRect();
  130. // What can you see?
  131. var parentViewableArea = {
  132. height: parent.clientHeight,
  133. width: parent.clientWidth
  134. };
  135. // Where is the child
  136. var childRect = child.getBoundingClientRect();
  137. // Is the child viewable?
  138. var isViewable = (childRect.top >= parentRect.top) && (childRect.bottom <= parentRect.top + parentViewableArea.height);
  139. // if you can't see the child try to scroll parent
  140. if (!isViewable) {
  141. // Should we scroll using top or bottom? Find the smaller ABS adjustment
  142. const scrollTop = childRect.top - parentRect.top;
  143. const scrollBot = childRect.bottom - parentRect.bottom;
  144. if (Math.abs(scrollTop) < Math.abs(scrollBot)) {
  145. // we're near the top of the list
  146. parent.scrollTop += (scrollTop + 80);
  147. } else {
  148. // we're near the bottom of the list
  149. parent.scrollTop += (scrollBot + 80);
  150. }
  151. }
  152. }
  153. /**
  154. * Validates the provided file system entry name.
  155. *
  156. * @function validate_fsentry_name
  157. * @memberof window
  158. * @param {string} name - The name of the file system entry to validate.
  159. * @returns {boolean} Returns true if the name is valid.
  160. * @throws {Object} Throws an object with a `message` property indicating the specific validation error.
  161. *
  162. * @description
  163. * This function checks the provided name against a set of rules to determine its validity as a file system entry name:
  164. * 1. Name cannot be empty.
  165. * 2. Name must be a string.
  166. * 3. Name cannot contain the '/' character.
  167. * 4. Name cannot be the '.' character.
  168. * 5. Name cannot be the '..' character.
  169. * 6. Name cannot exceed the maximum allowed length (as defined in window.max_item_name_length).
  170. */
  171. window.validate_fsentry_name = function(name){
  172. if(!name)
  173. throw {message: i18n('name_cannot_be_empty')}
  174. else if(!window.isString(name))
  175. throw {message: i18n('name_must_be_string')}
  176. else if(name.includes('/'))
  177. throw {message: i18n('name_cannot_contain_slash')}
  178. else if(name === '.')
  179. throw {message: i18n('name_cannot_contain_period')};
  180. else if(name === '..')
  181. throw {message: i18n('name_cannot_contain_double_period')};
  182. else if(name.length > window.max_item_name_length)
  183. throw {message: i18n('name_too_long', window.max_item_name_length)}
  184. else
  185. return true
  186. }
  187. /**
  188. * A function that generates a unique identifier by combining a random adjective, a random noun, and a random number (between 0 and 9999).
  189. * The result is returned as a string with components separated by hyphens.
  190. * It is useful when you need to create unique identifiers that are also human-friendly.
  191. *
  192. * @returns {string} A unique, hyphen-separated string comprising of an adjective, a noun, and a number.
  193. *
  194. * @example
  195. *
  196. * let identifier = window.generate_identifier();
  197. * // identifier would be something like 'clever-idea-123'
  198. *
  199. */
  200. window.generate_identifier = function(){
  201. const first_adj = ['helpful','sensible', 'loyal', 'honest', 'clever', 'capable','calm', 'smart', 'genius', 'bright', 'charming', 'creative', 'diligent', 'elegant', 'fancy',
  202. 'colorful', 'avid', 'active', 'gentle', 'happy', 'intelligent', 'jolly', 'kind', 'lively', 'merry', 'nice', 'optimistic', 'polite',
  203. 'quiet', 'relaxed', 'silly', 'victorious', 'witty', 'young', 'zealous', 'strong', 'brave', 'agile', 'bold'];
  204. const nouns = ['street', 'roof', 'floor', 'tv', 'idea', 'morning', 'game', 'wheel', 'shoe', 'bag', 'clock', 'pencil', 'pen',
  205. 'magnet', 'chair', 'table', 'house', 'dog', 'room', 'book', 'car', 'cat', 'tree',
  206. 'flower', 'bird', 'fish', 'sun', 'moon', 'star', 'cloud', 'rain', 'snow', 'wind', 'mountain',
  207. 'river', 'lake', 'sea', 'ocean', 'island', 'bridge', 'road', 'train', 'plane', 'ship', 'bicycle',
  208. 'horse', 'elephant', 'lion', 'tiger', 'bear', 'zebra', 'giraffe', 'monkey', 'snake', 'rabbit', 'duck',
  209. 'goose', 'penguin', 'frog', 'crab', 'shrimp', 'whale', 'octopus', 'spider', 'ant', 'bee', 'butterfly', 'dragonfly',
  210. 'ladybug', 'snail', 'camel', 'kangaroo', 'koala', 'panda', 'piglet', 'sheep', 'wolf', 'fox', 'deer', 'mouse', 'seal',
  211. 'chicken', 'cow', 'dinosaur', 'puppy', 'kitten', 'circle', 'square', 'garden', 'otter', 'bunny', 'meerkat', 'harp']
  212. // return a random combination of first_adj + noun + number (between 0 and 9999)
  213. // e.g. clever-idea-123
  214. return first_adj[Math.floor(Math.random() * first_adj.length)] + '-' + nouns[Math.floor(Math.random() * nouns.length)] + '-' + Math.floor(Math.random() * 10000);
  215. }
  216. /**
  217. * Checks if the provided variable is a string or an instance of the String object.
  218. *
  219. * @param {*} variable - The variable to check.
  220. * @returns {boolean} True if the variable is a string or an instance of the String object, false otherwise.
  221. */
  222. window.isString = function (variable) {
  223. return typeof variable === 'string' || variable instanceof String;
  224. }
  225. /**
  226. * A function that checks whether a file system entry (fsentry) matches a list of allowed file types.
  227. * It handles both file extensions (like '.jpg') and MIME types (like 'text/plain').
  228. * If the allowed file types string is empty or not provided, the function always returns true.
  229. * It checks the file types only if the fsentry is a file, not a directory.
  230. *
  231. * @param {Object} fsentry - The file system entry to check. It must be an object with properties: 'is_dir', 'name', 'type'.
  232. * @param {string} allowed_file_types_string - The list of allowed file types, separated by commas. Can include extensions and MIME types.
  233. *
  234. * @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.
  235. *
  236. * @example
  237. *
  238. * let fsentry = {is_dir: false, name: 'example.jpg', type: 'image/jpeg'};
  239. * let allowedTypes = '.jpg, text/plain, image/*';
  240. * let result = window.check_fsentry_against_allowed_file_types_string(fsentry, allowedTypes);
  241. * // result would be true, as 'example.jpg' matches the '.jpg' in allowedTypes
  242. *
  243. */
  244. window.check_fsentry_against_allowed_file_types_string =function (fsentry, allowed_file_types_string) {
  245. // simple cases that are always a pass
  246. if(!allowed_file_types_string || allowed_file_types_string.trim() === '')
  247. return true;
  248. // parse allowed_file_types into an array of extensions and types
  249. let allowed_file_types = allowed_file_types_string.split(',');
  250. if(allowed_file_types.length > 0){
  251. // trim every entry
  252. for (let index = 0; index < allowed_file_types.length; index++) {
  253. allowed_file_types[index] = allowed_file_types[index].trim();
  254. }
  255. }
  256. let passes_allowed_file_type_filter = true;
  257. // check types, only if this fsentry is a file and not a directory
  258. if(!fsentry.is_dir && allowed_file_types.length > 0){
  259. passes_allowed_file_type_filter = false;
  260. for (let index = 0; index < allowed_file_types.length; index++) {
  261. const allowed_file_type = allowed_file_types[index].toLowerCase();
  262. // if type is not already set, try to set it based on the file name
  263. if(!fsentry.type)
  264. fsentry.type = mime.getType(fsentry.name);
  265. // extensions (e.g. .jpg)
  266. if(allowed_file_type.startsWith('.') && fsentry.name.toLowerCase().endsWith(allowed_file_type)){
  267. passes_allowed_file_type_filter = true;
  268. break;
  269. }
  270. // MIME types (e.g. text/plain)
  271. else if(globToRegExp(allowed_file_type).test(fsentry.type?.toLowerCase())){
  272. passes_allowed_file_type_filter = true;
  273. break;
  274. }
  275. }
  276. }
  277. return passes_allowed_file_type_filter;
  278. }
  279. // @author Rich Adams <rich@richadams.me>
  280. // Implements a tap and hold functionality. If you click/tap and release, it will trigger a normal
  281. // click event. But if you click/tap and hold for 1s (default), it will trigger a taphold event instead.
  282. ;(function($)
  283. {
  284. // Default options
  285. var defaults = {
  286. duration: 500, // ms
  287. clickHandler: null
  288. }
  289. // When start of a taphold event is triggered.
  290. function startHandler(event)
  291. {
  292. var $elem = jQuery(this);
  293. // Merge the defaults and any user defined settings.
  294. let settings = jQuery.extend({}, defaults, event.data);
  295. // If object also has click handler, store it and unbind. Taphold will trigger the
  296. // click itself, rather than normal propagation.
  297. if (typeof $elem.data("events") != "undefined"
  298. && typeof $elem.data("events").click != "undefined")
  299. {
  300. // Find the one without a namespace defined.
  301. for (var c in $elem.data("events").click)
  302. {
  303. if ($elem.data("events").click[c].namespace == "")
  304. {
  305. var handler = $elem.data("events").click[c].handler
  306. $elem.data("taphold_click_handler", handler);
  307. $elem.unbind("click", handler);
  308. break;
  309. }
  310. }
  311. }
  312. // Otherwise, if a custom click handler was explicitly defined, then store it instead.
  313. else if (typeof settings.clickHandler == "function")
  314. {
  315. $elem.data("taphold_click_handler", settings.clickHandler);
  316. }
  317. // Reset the flags
  318. $elem.data("taphold_triggered", false); // If a hold was triggered
  319. $elem.data("taphold_clicked", false); // If a click was triggered
  320. $elem.data("taphold_cancelled", false); // If event has been cancelled.
  321. // Set the timer for the hold event.
  322. $elem.data("taphold_timer",
  323. setTimeout(function()
  324. {
  325. // If event hasn't been cancelled/clicked already, then go ahead and trigger the hold.
  326. if (!$elem.data("taphold_cancelled")
  327. && !$elem.data("taphold_clicked"))
  328. {
  329. // Trigger the hold event, and set the flag to say it's been triggered.
  330. $elem.trigger(jQuery.extend(event, jQuery.Event("taphold")));
  331. $elem.data("taphold_triggered", true);
  332. }
  333. }, settings.duration));
  334. }
  335. // When user ends a tap or click, decide what we should do.
  336. function stopHandler(event)
  337. {
  338. var $elem = jQuery(this);
  339. // If taphold has been cancelled, then we're done.
  340. if ($elem.data("taphold_cancelled")) { return; }
  341. // Clear the hold timer. If it hasn't already triggered, then it's too late anyway.
  342. clearTimeout($elem.data("taphold_timer"));
  343. // If hold wasn't triggered and not already clicked, then was a click event.
  344. if (!$elem.data("taphold_triggered")
  345. && !$elem.data("taphold_clicked"))
  346. {
  347. // If click handler, trigger it.
  348. if (typeof $elem.data("taphold_click_handler") == "function")
  349. {
  350. $elem.data("taphold_click_handler")(jQuery.extend(event, jQuery.Event("click")));
  351. }
  352. // Set flag to say we've triggered the click event.
  353. $elem.data("taphold_clicked", true);
  354. }
  355. }
  356. // If a user prematurely leaves the boundary of the object we're working on.
  357. function leaveHandler(event)
  358. {
  359. // Cancel the event.
  360. $(this).data("taphold_cancelled", true);
  361. }
  362. // Determine if touch events are supported.
  363. var touchSupported = ("ontouchstart" in window) // Most browsers
  364. || ("onmsgesturechange" in window); // Microsoft
  365. var taphold = $.event.special.taphold =
  366. {
  367. setup: function(data)
  368. {
  369. $(this).bind((touchSupported ? "touchstart" : "mousedown"), data, startHandler)
  370. .bind((touchSupported ? "touchend" : "mouseup"), stopHandler)
  371. .bind((touchSupported ? "touchmove touchcancel" : "mouseleave"), leaveHandler);
  372. },
  373. teardown: function(namespaces)
  374. {
  375. $(this).unbind((touchSupported ? "touchstart" : "mousedown"), startHandler)
  376. .unbind((touchSupported ? "touchend" : "mouseup"), stopHandler)
  377. .unbind((touchSupported ? "touchmove touchcancel" : "mouseleave"), leaveHandler);
  378. }
  379. };
  380. })(jQuery);
  381. window.refresh_user_data = async (auth_token)=>{
  382. let whoami
  383. try{
  384. whoami = await puter.os.user();
  385. }catch(e){
  386. // Ignored
  387. }
  388. // update local user data
  389. if(whoami){
  390. window.update_auth_data(auth_token, whoami)
  391. }
  392. }
  393. window.update_auth_data = (auth_token, user)=>{
  394. window.auth_token = auth_token;
  395. localStorage.setItem('auth_token', auth_token);
  396. // Has username changed?
  397. if(window.user?.username !== user.username)
  398. update_username_in_gui(user.username);
  399. // Has email changed?
  400. if(window.user?.email !== user.email && user.email){
  401. $('.user-email').html(html_encode(user.email));
  402. }
  403. const to_storable_user = user => {
  404. const storable_user = {...user};
  405. delete storable_user.taskbar_items;
  406. return storable_user;
  407. };
  408. // update this session's user data
  409. window.user = user;
  410. localStorage.setItem('user', JSON.stringify(to_storable_user(user)));
  411. // re-initialize the Puter.js objects with the new auth token
  412. puter.setAuthToken(auth_token, window.api_origin)
  413. //update the logged_in_users array entry for this user
  414. if(window.user){
  415. let logged_in_users_updated = false;
  416. for (let i = 0; i < window.logged_in_users.length && !logged_in_users_updated; i++) {
  417. if(window.logged_in_users[i].uuid === window.user.uuid){
  418. window.logged_in_users[i] = window.user;
  419. window.logged_in_users[i].auth_token = window.auth_token;
  420. logged_in_users_updated = true;
  421. }
  422. }
  423. // no matching array elements, add one
  424. if(!logged_in_users_updated){
  425. let userobj = window.user;
  426. userobj.auth_token = window.auth_token;
  427. window.logged_in_users.push(userobj);
  428. }
  429. // update local storage
  430. localStorage.setItem('logged_in_users', JSON.stringify(
  431. window.logged_in_users.map(to_storable_user)));
  432. }
  433. window.desktop_path = '/' + window.user.username + '/Desktop';
  434. window.trash_path = '/' + window.user.username + '/Trash';
  435. window.appdata_path = '/' + window.user.username + '/AppData';
  436. window.docs_path = '/' + window.user.username + '/Documents';
  437. window.pictures_path = '/' + window.user.username + '/Pictures';
  438. window.videos_path = '/' + window.user.username + '/Videos';
  439. window.desktop_path = '/' + window.user.username + '/Desktop';
  440. window.home_path = '/' + window.user.username;
  441. if(window.user !== null && !window.user.is_temp){
  442. $('.user-options-login-btn, .user-options-create-account-btn').hide();
  443. $('.user-options-menu-btn').show();
  444. }
  445. }
  446. window.mutate_user_preferences = function(user_preferences_delta) {
  447. for (const [key, value] of Object.entries(user_preferences_delta)) {
  448. // Don't wait for set to be done for better efficiency
  449. puter.kv.set(`user_preferences.${key}`, value);
  450. }
  451. // There may be syncing issues across multiple devices
  452. window.update_user_preferences({ ...window.user_preferences, ...user_preferences_delta });
  453. }
  454. window.update_user_preferences = function(user_preferences) {
  455. window.user_preferences = user_preferences;
  456. localStorage.setItem('user_preferences', JSON.stringify(user_preferences));
  457. const language = user_preferences.language ?? 'en';
  458. window.locale = language;
  459. // Broadcast locale change to apps
  460. const broadcastService = globalThis.services.get('broadcast');
  461. broadcastService.sendBroadcast('localeChanged', {
  462. language: language,
  463. }, { sendToNewAppInstances: true });
  464. }
  465. window.sendWindowWillCloseMsg = function(iframe_element) {
  466. return new Promise(function(resolve){
  467. const msg_id = window.uuidv4();
  468. iframe_element.contentWindow.postMessage({
  469. msg: "windowWillClose",
  470. msg_id: msg_id
  471. }, '*');
  472. //register callback
  473. window.appCallbackFunctions[msg_id] = resolve;
  474. })
  475. }
  476. window.logout = ()=>{
  477. console.log('DISP LOGOUT EVENT');
  478. $(document).trigger('logout');
  479. // document.dispatchEvent(new Event("logout", { bubbles: true}));
  480. }
  481. /**
  482. * Checks if the current document is in fullscreen mode.
  483. *
  484. * @function is_fullscreen
  485. * @memberof window
  486. * @returns {boolean} Returns true if the document is in fullscreen mode, otherwise false.
  487. *
  488. * @example
  489. * // Checks if the document is currently in fullscreen mode
  490. * const inFullscreen = window.is_fullscreen();
  491. *
  492. * @description
  493. * This function checks various browser-specific properties to determine if the document
  494. * is currently being displayed in fullscreen mode. It covers standard as well as
  495. * some vendor-prefixed properties to ensure compatibility across different browsers.
  496. */
  497. window.is_fullscreen = ()=>{
  498. return (document.fullscreenElement && document.fullscreenElement !== null) ||
  499. (document.webkitIsFullScreen && document.webkitIsFullScreen !== null) ||
  500. (document.webkitFullscreenElement && document.webkitFullscreenElement !== null) ||
  501. (document.mozFullScreenElement && document.mozFullScreenElement !== null) ||
  502. (document.msFullscreenElement && document.msFullscreenElement !== null);
  503. }
  504. window.get_apps = async (app_names, callback)=>{
  505. if(Array.isArray(app_names))
  506. app_names = app_names.join('|');
  507. // 'explorer' is a special app, no metadata should be returned
  508. if(app_names === 'explorer')
  509. return [];
  510. let res = await $.ajax({
  511. url: window.api_origin + "/apps/"+app_names,
  512. type: 'GET',
  513. async: true,
  514. contentType: "application/json",
  515. headers: {
  516. "Authorization": "Bearer "+window.auth_token
  517. },
  518. success: function (res){
  519. }
  520. });
  521. if(res.length === 1)
  522. res = res[0];
  523. if(callback && typeof callback === 'function')
  524. callback(res);
  525. else
  526. return res;
  527. }
  528. /**
  529. * Sends an "itemChanged" event to all watching applications associated with a specific item.
  530. *
  531. * @function sendItemChangeEventToWatchingApps
  532. * @memberof window
  533. * @param {string} item_uid - Unique identifier of the item that experienced the change.
  534. * @param {Object} event_data - Additional data about the event to be passed to the watching applications.
  535. *
  536. * @description
  537. * This function sends an "itemChanged" message to all applications that are currently watching
  538. * the specified item. If an application's iframe is not found or no longer valid,
  539. * it is removed from the list of watchers.
  540. *
  541. * The function expects that `window.watchItems` contains a mapping of item UIDs to arrays of app instance IDs.
  542. *
  543. * @example
  544. * // Example usage to send a change event to watching applications of an item with UID "item123".
  545. * window.sendItemChangeEventToWatchingApps('item123', { property: 'value' });
  546. */
  547. window.sendItemChangeEventToWatchingApps = function(item_uid, event_data){
  548. if(window.watchItems[item_uid]){
  549. window.watchItems[item_uid].forEach(app_instance_id => {
  550. const iframe = $(`.window[data-element_uuid="${app_instance_id}"]`).find('.window-app-iframe')
  551. if(iframe && iframe.length > 0){
  552. iframe.get(0)?.contentWindow
  553. .postMessage({
  554. msg: 'itemChanged',
  555. data: event_data,
  556. }, '*');
  557. }else{
  558. window.watchItems[item_uid].splice(window.watchItems[item_uid].indexOf(app_instance_id), 1);
  559. }
  560. });
  561. }
  562. }
  563. /**
  564. * Asynchronously checks if a save account notice should be shown to the user, and if needed, displays the notice.
  565. *
  566. * This function first retrieves a key value pair from the cloud key-value storage to determine if the notice has been shown before.
  567. * 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,
  568. * the function updates the key-value storage indicating that the notice has been shown. The user can choose to save the session,
  569. * remind later or log in to an existing account.
  570. *
  571. * @param {string} [message] - The custom message to be displayed in the notice. If not provided, a default message will be used.
  572. * @global
  573. * @function window.show_save_account_notice_if_needed
  574. */
  575. window.show_save_account_notice_if_needed = function(message){
  576. puter.kv.get({
  577. key: "save_account_notice_shown",
  578. }).then(async function(value){
  579. if(!value && window.user?.is_temp){
  580. puter.kv.set({
  581. key: "save_account_notice_shown",
  582. value: true,
  583. });
  584. // Show the notice
  585. setTimeout(async () => {
  586. const alert_resp = await UIAlert({
  587. 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>`,
  588. body_icon: window.icons['reminder.svg'],
  589. buttons:[
  590. {
  591. label: i18n('save_session'),
  592. value: 'save-session',
  593. type: 'primary',
  594. },
  595. // {
  596. // label: 'Log into an existing account',
  597. // value: 'login',
  598. // },
  599. {
  600. label: `I'll do it later`,
  601. value: 'remind-later',
  602. },
  603. ],
  604. window_options: {
  605. backdrop: true,
  606. close_on_backdrop_click: false,
  607. }
  608. })
  609. if(alert_resp === 'remind-later'){
  610. // TODO
  611. }
  612. if(alert_resp === 'save-session'){
  613. let saved = await UIWindowSaveAccount({
  614. send_confirmation_code: false,
  615. });
  616. }else if (alert_resp === 'login'){
  617. let login_result = await UIWindowLogin({
  618. show_signup_button: false,
  619. reload_on_success: true,
  620. send_confirmation_code: false,
  621. window_options: {
  622. show_in_taskbar: false,
  623. backdrop: true,
  624. close_on_backdrop_click: false,
  625. }
  626. });
  627. // FIXME: Report login error.
  628. }
  629. }, window.desktop_loading_fade_delay + 1000);
  630. }
  631. });
  632. }
  633. window.onpopstate = (event) => {
  634. if(event.state !== null && event.state.window_id !== null){
  635. $(`.window[data-id="${event.state.window_id}"]`).focusWindow();
  636. }
  637. }
  638. window.sort_items = (item_container, sort_by, sort_order)=>{
  639. if(sort_order !== 'asc' && sort_order !== 'desc')
  640. sort_order = 'asc';
  641. $(item_container).find(`.item[data-sortable="true"]`).detach().sort(function(a,b) {
  642. // Name
  643. if(!sort_by || sort_by === 'name'){
  644. if(a.dataset.name.toLowerCase() < b.dataset.name.toLowerCase()) { return (sort_order === 'asc' ? -1 : 1); }
  645. if(a.dataset.name.toLowerCase() > b.dataset.name.toLowerCase()) { return (sort_order === 'asc' ? 1 : -1); }
  646. return 0;
  647. }
  648. // Size
  649. else if(sort_by === 'size'){
  650. if( parseInt(a.dataset.size) < parseInt(b.dataset.size)) { return (sort_order === 'asc' ? -1 : 1); }
  651. if( parseInt(a.dataset.size) > parseInt(b.dataset.size)) { return (sort_order === 'asc' ? 1 : -1); }
  652. return 0;
  653. }
  654. // Modified
  655. else if(sort_by === 'modified'){
  656. if( parseInt(a.dataset.modified) < parseInt(b.dataset.modified)) { return (sort_order === 'asc' ? -1 : 1); }
  657. if( parseInt(a.dataset.modified) > parseInt(b.dataset.modified)) { return (sort_order === 'asc' ? 1 : -1); }
  658. return 0;
  659. }
  660. // Type
  661. else if(sort_by === 'type'){
  662. if(path.extname(a.dataset.name.toLowerCase()) < path.extname(b.dataset.name.toLowerCase())) { return (sort_order === 'asc' ? -1 : 1); }
  663. if(path.extname(a.dataset.name.toLowerCase()) > path.extname(b.dataset.name.toLowerCase())) { return (sort_order === 'asc' ? 1 : -1); }
  664. return 0;
  665. }
  666. }).appendTo(item_container);
  667. }
  668. window.show_or_hide_files = (item_containers) => {
  669. const show_hidden_files = window.user_preferences.show_hidden_files;
  670. const class_to_add = show_hidden_files ? 'item-revealed' : 'item-hidden';
  671. const class_to_remove = show_hidden_files ? 'item-hidden' : 'item-revealed';
  672. $(item_containers)
  673. .find('.item')
  674. .filter((_, item) => item.dataset.name.startsWith('.'))
  675. .removeClass(class_to_remove).addClass(class_to_add);
  676. }
  677. window.create_folder = async(basedir, appendto_element)=>{
  678. let dirname = basedir;
  679. let folder_name = 'New Folder';
  680. let newfolder_op_id = window.operation_id++;
  681. window.operation_cancelled[newfolder_op_id] = false;
  682. let newfolder_progress_window_init_ts = Date.now();
  683. let progwin;
  684. // only show progress window if it takes longer than 500ms to create folder
  685. let progwin_timeout = setTimeout(async () => {
  686. progwin = await UIWindowProgress({
  687. operation_id: newfolder_op_id,
  688. // TODO: Implement cancellation.
  689. // on_cancel: () => {
  690. // window.operation_cancelled[newfolder_op_id] = true;
  691. // },
  692. });
  693. progwin.set_status(i18n('taking_longer_than_usual'));
  694. }, 500);
  695. // create folder
  696. try{
  697. await puter.fs.mkdir({
  698. path: dirname + '/'+folder_name,
  699. rename: true,
  700. overwrite: false,
  701. success: function (data){
  702. const el_created_dir = $(appendto_element).find('.item[data-path="'+html_encode(dirname)+'/'+html_encode(data.name)+'"]');
  703. if(el_created_dir.length > 0){
  704. window.activate_item_name_editor(el_created_dir);
  705. // Add action to actions_history for undo ability
  706. window.actions_history.push({
  707. operation: 'create_folder',
  708. data: el_created_dir
  709. });
  710. }
  711. clearTimeout(progwin_timeout);
  712. // done
  713. let newfolder_duration = (Date.now() - newfolder_progress_window_init_ts);
  714. if (progwin) {
  715. if (newfolder_duration >= window.copy_progress_hide_delay) {
  716. progwin.close();
  717. } else {
  718. setTimeout(() => {
  719. setTimeout(() => {
  720. progwin.close();
  721. }, Math.abs(window.copy_progress_hide_delay - newfolder_duration));
  722. });
  723. }
  724. }
  725. }
  726. });
  727. }catch(err){
  728. clearTimeout(progwin_timeout);
  729. }
  730. }
  731. window.create_file = async(options)=>{
  732. // args
  733. let dirname = options.dirname;
  734. let appendto_element = options.append_to_element;
  735. let filename = options.name;
  736. let content = options.content ? [options.content] : [];
  737. // create file
  738. try{
  739. puter.fs.upload(new File(content, filename), dirname,
  740. {
  741. success: async function (data){
  742. const created_file = $(appendto_element).find('.item[data-path="'+html_encode(dirname)+'/'+html_encode(data.name)+'"]');
  743. if(created_file.length > 0){
  744. window.activate_item_name_editor(created_file);
  745. // Add action to actions_history for undo ability
  746. window.actions_history.push({
  747. operation: 'create_file',
  748. data: created_file
  749. });
  750. }
  751. }
  752. });
  753. }catch(err){
  754. console.log(err);
  755. }
  756. }
  757. window.create_shortcut = async(filename, is_dir, basedir, appendto_element, shortcut_to, shortcut_to_path)=>{
  758. let dirname = basedir;
  759. const extname = path.extname(filename);
  760. const basename = path.basename(filename, extname) + ' - Shortcut';
  761. filename = basename + extname;
  762. // create file shortcut
  763. try{
  764. await puter.fs.upload(new File([], filename), dirname, {
  765. overwrite: false,
  766. shortcutTo: shortcut_to_path ?? shortcut_to,
  767. dedupeName: true,
  768. });
  769. }catch(err){
  770. console.log(err)
  771. }
  772. }
  773. window.copy_clipboard_items = async function(dest_path, dest_container_element){
  774. let copy_op_id = window.operation_id++;
  775. window.operation_cancelled[copy_op_id] = false;
  776. // unselect previously selected items in the target container
  777. $(dest_container_element).children('.item-selected').removeClass('item-selected');
  778. window.update_explorer_footer_selected_items_count($(dest_container_element).closest('.window'));
  779. let overwrite_all = false;
  780. (async()=>{
  781. let copy_progress_window_init_ts = Date.now();
  782. // only show progress window if it takes longer than 2s to copy
  783. let progwin;
  784. let progwin_timeout = setTimeout(async () => {
  785. progwin = await UIWindowProgress({
  786. operation_id: copy_op_id,
  787. on_cancel: () => {
  788. window.operation_cancelled[copy_op_id] = true;
  789. },
  790. });
  791. }, 0);
  792. const copied_item_paths = []
  793. for(let i=0; i<window.clipboard.length; i++){
  794. let copy_path = window.clipboard[i].path;
  795. let item_with_same_name_already_exists = true;
  796. let overwrite = overwrite_all;
  797. progwin?.set_status(i18n('copying_file', copy_path));
  798. do{
  799. if(overwrite)
  800. item_with_same_name_already_exists = false;
  801. // cancelled?
  802. if(window.operation_cancelled[copy_op_id])
  803. return;
  804. // perform copy
  805. try{
  806. let resp = await puter.fs.copy({
  807. source: copy_path,
  808. destination: dest_path,
  809. overwrite: overwrite || overwrite_all,
  810. // if user is copying an item to where its source is, change the name so there is no conflict
  811. dedupeName: dest_path === path.dirname(copy_path),
  812. });
  813. // remove overwritten item from the DOM
  814. if(resp[0].overwritten?.id){
  815. $(`.item[data-uid=${resp[0].overwritten.id}]`).removeItems();
  816. }
  817. // copy new path for undo copy
  818. copied_item_paths.push(resp[0].copied.path);
  819. // skips next loop iteration
  820. break;
  821. }catch(err){
  822. if(err.code==='item_with_same_name_exists'){
  823. const alert_resp = await UIAlert({
  824. message: `<strong>${html_encode(err.entry_name)}</strong> already exists.`,
  825. buttons:[
  826. {label: i18n('replace'), type: 'primary', value: 'replace'},
  827. ... (window.clipboard.length > 1) ? [{label: i18n('replace_all'), value: 'replace_all'}] : [],
  828. ... (window.clipboard.length > 1) ? [{label: i18n('skip'), value: 'skip'}] : [{label: i18n('cancel'), value: 'cancel'}],
  829. ]
  830. })
  831. if(alert_resp === 'replace'){
  832. overwrite = true;
  833. }else if (alert_resp === 'replace_all'){
  834. overwrite = true;
  835. overwrite_all = true;
  836. }else if(alert_resp === 'skip' || alert_resp === 'cancel'){
  837. item_with_same_name_already_exists = false;
  838. }
  839. }
  840. else{
  841. if(err.message){
  842. UIAlert(err.message)
  843. }
  844. item_with_same_name_already_exists = false;
  845. }
  846. }
  847. }while(item_with_same_name_already_exists)
  848. }
  849. // done
  850. // Add action to actions_history for undo ability
  851. window.actions_history.push({
  852. operation: 'copy',
  853. data: copied_item_paths
  854. });
  855. clearTimeout(progwin_timeout);
  856. let copy_duration = (Date.now() - copy_progress_window_init_ts);
  857. if (progwin) {
  858. if (copy_duration >= window.copy_progress_hide_delay) {
  859. progwin.close();
  860. } else {
  861. setTimeout(() => {
  862. setTimeout(() => {
  863. progwin.close();
  864. }, Math.abs(window.copy_progress_hide_delay - copy_duration));
  865. });
  866. }
  867. }
  868. })();
  869. }
  870. /**
  871. * Copies the given items to the destination path.
  872. *
  873. * @param {HTMLElement[]} el_items - HTML elements representing the items to copy
  874. * @param {string} dest_path - Destination path to copy items to
  875. */
  876. window.copy_items = function(el_items, dest_path){
  877. let copy_op_id = window.operation_id++;
  878. let overwrite_all = false;
  879. (async()=>{
  880. let copy_progress_window_init_ts = Date.now();
  881. // only show progress window if it takes longer than 2s to copy
  882. let progwin;
  883. let progwin_timeout = setTimeout(async () => {
  884. progwin = await UIWindowProgress({
  885. operation_id: copy_op_id,
  886. on_cancel: () => {
  887. window.operation_cancelled[copy_op_id] = true;
  888. },
  889. });
  890. }, 2000);
  891. const copied_item_paths = []
  892. for(let i=0; i < el_items.length; i++){
  893. let copy_path = $(el_items[i]).attr('data-path');
  894. let item_with_same_name_already_exists = true;
  895. let overwrite = overwrite_all;
  896. progwin?.set_status(i18n('copying_file', copy_path));
  897. do{
  898. if(overwrite)
  899. item_with_same_name_already_exists = false;
  900. // cancelled?
  901. if(window.operation_cancelled[copy_op_id])
  902. return;
  903. try{
  904. let resp = await puter.fs.copy({
  905. source: copy_path,
  906. destination: dest_path,
  907. overwrite: overwrite || overwrite_all,
  908. // if user is copying an item to where the source is, automatically change the name so there is no conflict
  909. dedupeName: dest_path === path.dirname(copy_path),
  910. })
  911. // remove overwritten item from the DOM
  912. if(resp[0].overwritten?.id){
  913. $(`.item[data-uid=${resp.overwritten.id}]`).removeItems();
  914. }
  915. // copy new path for undo copy
  916. copied_item_paths.push(resp[0].copied.path);
  917. // skips next loop iteration
  918. item_with_same_name_already_exists = false;
  919. }catch(err){
  920. if(err.code === 'item_with_same_name_exists'){
  921. const alert_resp = await UIAlert({
  922. message: `<strong>${html_encode(err.entry_name)}</strong> already exists.`,
  923. buttons:[
  924. { label: i18n('replace'), type: 'primary', value: 'replace' },
  925. ... (el_items.length > 1) ? [{label: i18n('replace_all'), value: 'replace_all'}] : [],
  926. ... (el_items.length > 1) ? [{label: i18n('skip'), value: 'skip'}] : [{label: i18n('cancel'), value: 'cancel'}],
  927. ]
  928. })
  929. if(alert_resp === 'replace'){
  930. overwrite = true;
  931. }else if (alert_resp === 'replace_all'){
  932. overwrite = true;
  933. overwrite_all = true;
  934. }else if(alert_resp === 'skip' || alert_resp === 'cancel'){
  935. item_with_same_name_already_exists = false;
  936. }
  937. }
  938. else{
  939. if(err.message){
  940. UIAlert(err.message)
  941. }
  942. else if(err){
  943. UIAlert(err)
  944. }
  945. item_with_same_name_already_exists = false;
  946. }
  947. }
  948. }while(item_with_same_name_already_exists)
  949. }
  950. // done
  951. // Add action to actions_history for undo ability
  952. window.actions_history.push({
  953. operation: 'copy',
  954. data: copied_item_paths
  955. });
  956. clearTimeout(progwin_timeout);
  957. let copy_duration = (Date.now() - copy_progress_window_init_ts);
  958. if (progwin) {
  959. if (copy_duration >= window.copy_progress_hide_delay) {
  960. progwin.close();
  961. } else {
  962. setTimeout(() => {
  963. setTimeout(() => {
  964. progwin.close();
  965. }, Math.abs(window.copy_progress_hide_delay - copy_duration));
  966. });
  967. }
  968. }
  969. })()
  970. }
  971. /**
  972. * Deletes the given item.
  973. *
  974. * @param {HTMLElement} el_item - HTML element representing the item to delete
  975. * @param {boolean} [descendants_only=false] - If true, only deletes descendant items under the given item
  976. * @returns {Promise<void>}
  977. */
  978. window.delete_item = async function(el_item, descendants_only = false){
  979. if($(el_item).attr('data-immutable') === '1')
  980. return;
  981. // hide all UIItems with matching uids
  982. $(`.item[data-uid='${$(el_item).attr('data-uid')}']`).fadeOut(150, function(){
  983. // close all windows with matching uids
  984. $('.window-' + $(el_item).attr('data-uid')).close();
  985. // close all windows that belong to a descendant of this item
  986. // todo this has to be case-insensitive but the `i` selector doesn't work on ^=
  987. $(`.window[data-path^="${$(el_item).attr('data-path')}/"]`).close();
  988. });
  989. try{
  990. await puter.fs.delete({
  991. paths: $(el_item).attr('data-path'),
  992. descendantsOnly: descendants_only,
  993. recursive: true,
  994. });
  995. // fade out item
  996. $(`.item[data-uid='${$(el_item).attr('data-uid')}']`).fadeOut(150, function(){
  997. // find all parent windows that contain this item
  998. let parent_windows = $(`.item[data-uid='${$(el_item).attr('data-uid')}']`).closest('.window');
  999. // remove item from DOM
  1000. $(`.item[data-uid='${$(el_item).attr('data-uid')}']`).removeItems();
  1001. // update parent windows' item counts
  1002. $(parent_windows).each(function(index){
  1003. window.update_explorer_footer_item_count(this);
  1004. window.update_explorer_footer_selected_items_count(this);
  1005. });
  1006. // update all shortcuts to this item
  1007. $(`.item[data-shortcut_to_path="${html_encode($(el_item).attr('data-path'))}" i]`).attr(`data-shortcut_to_path`, '');
  1008. });
  1009. }catch(err){
  1010. UIAlert(err.responseText);
  1011. }
  1012. }
  1013. window.move_clipboard_items = function (el_target_container, target_path){
  1014. let dest_path = target_path === undefined ? $(el_target_container).attr('data-path') : target_path;
  1015. let el_items = [];
  1016. if(window.clipboard.length > 0){
  1017. for(let i=0; i<window.clipboard.length; i++){
  1018. el_items.push($(`.item[data-path="${html_encode(window.clipboard[i])}" i]`));
  1019. }
  1020. if(el_items.length > 0)
  1021. window.move_items(el_items, dest_path);
  1022. }
  1023. window.clipboard = [];
  1024. }
  1025. /**
  1026. * Initiates a download for multiple files provided as an array of paths.
  1027. *
  1028. * This function triggers the download of files from given paths. It constructs the
  1029. * download URLs using an API base URL and the given paths, along with an authentication token.
  1030. * Each file is then fetched and prompted to the user for download using the `saveAs` function.
  1031. *
  1032. * Global dependencies:
  1033. * - `api_origin`: The base URL for the download API endpoint.
  1034. * - `auth_token`: The authentication token required for the download API.
  1035. * - `saveAs`: Function to save the fetched blob as a file.
  1036. * - `path.basename()`: Function to extract the filename from the provided path.
  1037. *
  1038. * @global
  1039. * @function trigger_download
  1040. * @param {string[]} paths - An array of file paths that are to be downloaded.
  1041. *
  1042. * @example
  1043. * let filePaths = ['/path/to/file1.txt', '/path/to/file2.png'];
  1044. * window.trigger_download(filePaths);
  1045. */
  1046. window.trigger_download = (paths)=>{
  1047. let urls = [];
  1048. for (let index = 0; index < paths.length; index++) {
  1049. urls.push({
  1050. download: window.api_origin + "/down?path=" + paths[index],
  1051. filename: path.basename(paths[index]),
  1052. });
  1053. }
  1054. urls.forEach(async function (e) {
  1055. const anti_csrf = await (async () => {
  1056. const resp = await fetch(`${window.gui_origin}/get-anticsrf-token`);
  1057. const { token } = await resp.json();
  1058. return token;
  1059. })();
  1060. fetch(e.download, {
  1061. method: 'POST',
  1062. headers: {
  1063. 'Content-Type': 'application/json',
  1064. 'Authorization': 'Bearer ' + puter.authToken,
  1065. },
  1066. body: JSON.stringify({
  1067. anti_csrf,
  1068. }),
  1069. })
  1070. .then(res => res.blob())
  1071. .then(blob => {
  1072. saveAs(blob, e.filename);
  1073. });
  1074. });
  1075. }
  1076. /**
  1077. * Moves the given items to the destination path.
  1078. *
  1079. * @param {HTMLElement[]} el_items - jQuery elements representing the items to move
  1080. * @param {string} dest_path - The destination path to move the items to
  1081. * @returns {Promise<void>}
  1082. */
  1083. window.move_items = async function(el_items, dest_path, is_undo = false){
  1084. let move_op_id = window.operation_id++;
  1085. window.operation_cancelled[move_op_id] = false;
  1086. // --------------------------------------------------------
  1087. // Optimization: in case all items being moved
  1088. // are immutable do not proceed
  1089. // --------------------------------------------------------
  1090. let all_items_are_immutable = true;
  1091. for(let i=0; i<el_items.length; i++){
  1092. if($(el_items[i]).attr('data-immutable') === '0'){
  1093. all_items_are_immutable = false;
  1094. break;
  1095. }
  1096. }
  1097. if(all_items_are_immutable)
  1098. return;
  1099. // --------------------------------------------------------
  1100. // good to go, proceed
  1101. // --------------------------------------------------------
  1102. // overwrite all items? default is false unless in a conflict case user asks for it
  1103. let overwrite_all = false;
  1104. // when did this operation start
  1105. let move_init_ts = Date.now();
  1106. // only show progress window if it takes longer than 2s to move
  1107. let progwin;
  1108. let progwin_timeout = setTimeout(async () => {
  1109. progwin = await UIWindowProgress({
  1110. operation_id: move_op_id,
  1111. on_cancel: () => {
  1112. window.operation_cancelled[move_op_id] = true;
  1113. },
  1114. });
  1115. }, 2000);
  1116. // storing moved items for undo ability
  1117. const moved_items = []
  1118. // Go through each item and try to move it
  1119. for(let i=0; i<el_items.length; i++){
  1120. // get current item
  1121. let el_item = el_items[i];
  1122. // if operation cancelled by user, stop
  1123. if(window.operation_cancelled[move_op_id])
  1124. return;
  1125. // cannot move an immutable item, skip it
  1126. if($(el_item).attr('data-immutable') === '1')
  1127. continue;
  1128. // cannot move item to its own path, skip it
  1129. if(path.dirname($(el_item).attr('data-path')) === dest_path){
  1130. await UIAlert(`<p>Moving <strong>${html_encode($(el_item).attr('data-name'))}</strong></p>Cannot move item to its current location.`)
  1131. continue;
  1132. }
  1133. // if an item with the same name already exists in the destination path
  1134. let item_with_same_name_already_exists = false;
  1135. let overwrite = overwrite_all;
  1136. let untrashed_at_least_one_item = false;
  1137. // --------------------------------------------------------
  1138. // Keep trying to move the item until it succeeds or is cancelled
  1139. // or user decides to overwrite or skip
  1140. // --------------------------------------------------------
  1141. do{
  1142. try{
  1143. let path_to_show_on_progwin = $(el_item).attr('data-path');
  1144. // parse metadata if any
  1145. let metadata = $(el_item).attr('data-metadata');
  1146. // no metadata?
  1147. if(metadata === '' || metadata === 'null' || metadata === null)
  1148. metadata = {}
  1149. // try to parse metadata as JSON
  1150. else{
  1151. try{
  1152. metadata = JSON.parse(metadata)
  1153. }catch(e){
  1154. // Ignored
  1155. }
  1156. }
  1157. let new_name;
  1158. // user cancelled?
  1159. if(window.operation_cancelled[move_op_id])
  1160. return;
  1161. // indicates whether this is a recycling operation
  1162. let recycling = false;
  1163. let status_i18n_string = 'moving_file';
  1164. // --------------------------------------------------------
  1165. // Trashing
  1166. // --------------------------------------------------------
  1167. if(dest_path === window.trash_path){
  1168. new_name = $(el_item).attr('data-uid');
  1169. metadata = {
  1170. original_name: $(el_item).attr('data-name'),
  1171. original_path: $(el_item).attr('data-path'),
  1172. trashed_ts: Math.round(Date.now() / 1000),
  1173. };
  1174. status_i18n_string = 'deleting_file';
  1175. // update other clients
  1176. if(window.socket)
  1177. window.socket.emit('trash.is_empty', {is_empty: false});
  1178. // change trash icons to 'trash-full.svg'
  1179. $(`[data-app="trash"]`).find('.taskbar-icon > img').attr('src', window.icons['trash-full.svg']);
  1180. $(`.item[data-path="${html_encode(window.trash_path)}" i], .item[data-shortcut_to_path="${html_encode(window.trash_path)}" i]`).find('.item-icon > img').attr('src', window.icons['trash-full.svg']);
  1181. $(`.window[data-path="${html_encode(window.trash_path)}" i]`).find('.window-head-icon').attr('src', window.icons['trash-full.svg']);
  1182. }
  1183. // moving an item into a trashed directory? deny.
  1184. else if(dest_path.startsWith(window.trash_path)){
  1185. progwin?.close();
  1186. UIAlert('Cannot move items into a deleted folder.');
  1187. return;
  1188. }
  1189. // --------------------------------------------------------
  1190. // If recycling an item, restore its original name
  1191. // --------------------------------------------------------
  1192. else if(metadata.trashed_ts !== undefined){
  1193. recycling = true;
  1194. new_name = metadata.original_name;
  1195. metadata = {};
  1196. untrashed_at_least_one_item = true;
  1197. path_to_show_on_progwin = window.trash_path + '/' + new_name;
  1198. }
  1199. // --------------------------------------------------------
  1200. // update progress window with current item being moved
  1201. // --------------------------------------------------------
  1202. progwin?.set_status(i18n(status_i18n_string, path_to_show_on_progwin));
  1203. // execute move
  1204. let resp = await puter.fs.move({
  1205. source: $(el_item).attr('data-uid'),
  1206. destination: dest_path,
  1207. overwrite: overwrite || overwrite_all,
  1208. newName: new_name,
  1209. // recycling requires making all missing dirs
  1210. createMissingParents: recycling,
  1211. newMetadata: metadata,
  1212. excludeSocketID: window.socket?.id,
  1213. });
  1214. let fsentry = resp.moved;
  1215. // path must use the real name from DB
  1216. fsentry.path = path.join(dest_path, fsentry.name);
  1217. // skip next loop iteration because this iteration was successful
  1218. item_with_same_name_already_exists = false;
  1219. // update all shortcut_to_path
  1220. $(`.item[data-shortcut_to_path="${html_encode($(el_item).attr('data-path'))}" i]`).attr(`data-shortcut_to_path`, fsentry.path);
  1221. // Remove all items with matching uids
  1222. $(`.item[data-uid='${$(el_item).attr('data-uid')}']`).fadeOut(150, function(){
  1223. // find all parent windows that contain this item
  1224. let parent_windows = $(`.item[data-uid='${$(el_item).attr('data-uid')}']`).closest('.window');
  1225. // remove this item
  1226. $(this).removeItems();
  1227. // update parent windows' item counts and selected item counts in their footers
  1228. $(parent_windows).each(function(){
  1229. window.update_explorer_footer_item_count(this);
  1230. window.update_explorer_footer_selected_items_count(this)
  1231. });
  1232. })
  1233. // if trashing, close windows of trashed items and its descendants
  1234. if(dest_path === window.trash_path){
  1235. $(`.window[data-path="${html_encode($(el_item).attr('data-path'))}" i]`).close();
  1236. // todo this has to be case-insensitive but the `i` selector doesn't work on ^=
  1237. $(`.window[data-path^="${html_encode($(el_item).attr('data-path'))}/"]`).close();
  1238. }
  1239. // update all paths of its and its descendants' open windows
  1240. else{
  1241. // todo this has to be case-insensitive but the `i` selector doesn't work on ^=
  1242. $(`.window[data-path^="${html_encode($(el_item).attr('data-path'))}/"], .window[data-path="${html_encode($(el_item).attr('data-path'))}" i]`).each(function(){
  1243. window.update_window_path(this, $(this).attr('data-path').replace($(el_item).attr('data-path'), path.join(dest_path, fsentry.name)));
  1244. })
  1245. }
  1246. if(dest_path === window.trash_path){
  1247. // if trashing dir...
  1248. if($(el_item).attr('data-is_dir') === '1'){
  1249. // disassociate all its websites
  1250. // todo, some client-side check to see if this dir has at least one associated website before sending ajax request
  1251. // FIXME: dir_uuid is not defined, is this the same as the data-uid attribute?
  1252. // puter.hosting.delete(dir_uuid)
  1253. $(`.mywebsites-dir-path[data-uuid="${$(el_item).attr('data-uid')}"]`).remove();
  1254. // remove the website badge from all instances of the dir
  1255. $(`.item[data-uid="${$(el_item).attr('data-uid')}"]`).find('.item-has-website-badge').fadeOut(300);
  1256. }
  1257. }
  1258. // if replacing an existing item, remove the old item that was just replaced
  1259. if(resp.overwritten?.id){
  1260. $(`.item[data-uid=${resp.overwritten.id}]`).removeItems();
  1261. }
  1262. // if this is trash, get original name from item metadata
  1263. fsentry.name = metadata?.original_name || fsentry.name;
  1264. // create new item on matching containers
  1265. const options = {
  1266. appendTo: $(`.item-container[data-path="${html_encode(dest_path)}" i]`),
  1267. immutable: fsentry.immutable,
  1268. associated_app_name: fsentry.associated_app?.name,
  1269. uid: fsentry.uid,
  1270. path: fsentry.path,
  1271. icon: await item_icon(fsentry),
  1272. name: (dest_path === window.trash_path) ? $(el_item).attr('data-name') : fsentry.name,
  1273. is_dir: fsentry.is_dir,
  1274. size: fsentry.size,
  1275. type: fsentry.type,
  1276. modified: fsentry.modified,
  1277. is_selected: false,
  1278. is_shared: (dest_path === window.trash_path) ? false : fsentry.is_shared,
  1279. is_shortcut: fsentry.is_shortcut,
  1280. shortcut_to: fsentry.shortcut_to,
  1281. shortcut_to_path: fsentry.shortcut_to_path,
  1282. has_website: $(el_item).attr('data-has_website') === '1',
  1283. metadata: fsentry.metadata ?? '',
  1284. suggested_apps: fsentry.suggested_apps,
  1285. }
  1286. UIItem(options);
  1287. moved_items.push({'options': options, 'original_path': $(el_item).attr('data-path')});
  1288. // this operation may have created some missing directories,
  1289. // see if any of the directories in the path of this file is new AND
  1290. // if these new path have any open parents that need to be updated
  1291. resp.parent_dirs_created?.forEach(async dir => {
  1292. let item_container = $(`.item-container[data-path="${html_encode(path.dirname(dir.path))}" i]`);
  1293. if(item_container.length > 0 && $(`.item[data-path="${html_encode(dir.path)}" i]`).length === 0){
  1294. UIItem({
  1295. appendTo: item_container,
  1296. immutable: false,
  1297. uid: dir.uid,
  1298. path: dir.path,
  1299. icon: await item_icon(dir),
  1300. name: dir.name,
  1301. size: dir.size,
  1302. type: dir.type,
  1303. modified: dir.modified,
  1304. is_dir: true,
  1305. is_selected: false,
  1306. is_shared: dir.is_shared,
  1307. has_website: false,
  1308. suggested_apps: dir.suggested_apps,
  1309. });
  1310. }
  1311. window.sort_items(item_container);
  1312. });
  1313. //sort each container
  1314. $(`.item-container[data-path="${html_encode(dest_path)}" i]`).each(function(){
  1315. window.sort_items(this, $(this).attr('data-sort_by'), $(this).attr('data-sort_order'))
  1316. })
  1317. }catch(err){
  1318. // -----------------------------------------------------------------------
  1319. // if item with same name already exists, ask user if they want to overwrite
  1320. // -----------------------------------------------------------------------
  1321. if(err.code==='item_with_same_name_exists'){
  1322. item_with_same_name_already_exists = true;
  1323. const alert_resp = await UIAlert({
  1324. message: `<strong>${html_encode(err.entry_name)}</strong> already exists.`,
  1325. buttons:[
  1326. { label: i18n('replace'), type: 'primary', value: 'replace' },
  1327. ... (el_items.length > 1) ? [{label: i18n('replace_all'), value: 'replace_all'}] : [],
  1328. ... (el_items.length > 1) ? [{label: i18n('skip'), value: 'skip'}] : [{label: i18n('cancel'), value: 'cancel'}],
  1329. ]
  1330. })
  1331. if(alert_resp === 'replace'){
  1332. overwrite = true;
  1333. }else if (alert_resp === 'replace_all'){
  1334. overwrite = true;
  1335. overwrite_all = true;
  1336. }else if(alert_resp === 'skip' || alert_resp === 'cancel'){
  1337. item_with_same_name_already_exists = false;
  1338. }
  1339. }
  1340. // -----------------------------------------------------------------------
  1341. // all other errors
  1342. // -----------------------------------------------------------------------
  1343. else{
  1344. item_with_same_name_already_exists = false;
  1345. // error message after source item has reappeared
  1346. $(el_item).show(0, function(){
  1347. UIAlert(`<p>Moving <strong>${html_encode($(el_item).attr('data-name'))}</strong></p>${err.message ?? ''}`)
  1348. });
  1349. break;
  1350. }
  1351. }
  1352. }while(item_with_same_name_already_exists);
  1353. // check if trash is empty
  1354. if(untrashed_at_least_one_item){
  1355. const trash = await puter.fs.stat(window.trash_path);
  1356. if(window.socket){
  1357. window.socket.emit('trash.is_empty', {is_empty: trash.is_empty});
  1358. }
  1359. if(trash.is_empty){
  1360. $(`[data-app="trash"]`).find('.taskbar-icon > img').attr('src', window.icons['trash.svg']);
  1361. $(`.item[data-path="${html_encode(window.trash_path)}" i]`).find('.item-icon > img').attr('src', window.icons['trash.svg']);
  1362. $(`.window[data-path="${html_encode(window.trash_path)}" i]`).find('.window-head-icon').attr('src', window.icons['trash.svg']);
  1363. }
  1364. }
  1365. }
  1366. clearTimeout(progwin_timeout);
  1367. // log stats to console
  1368. let move_duration = (Date.now() - move_init_ts);
  1369. console.log(`moved ${el_items.length} item${el_items.length > 1 ? 's':''} in ${move_duration}ms`);
  1370. // -----------------------------------------------------------------------
  1371. // DONE! close progress window with delay to allow user to see 100% progress
  1372. // -----------------------------------------------------------------------
  1373. // Add action to actions_history for undo ability
  1374. if(!is_undo && dest_path !== window.trash_path){
  1375. window.actions_history.push({
  1376. operation: 'move',
  1377. data: moved_items,
  1378. });
  1379. }else if(!is_undo && dest_path === window.trash_path){
  1380. window.actions_history.push({
  1381. operation: 'delete',
  1382. data: moved_items,
  1383. });
  1384. }
  1385. if(progwin){
  1386. setTimeout(() => {
  1387. progwin.close();
  1388. }, window.copy_progress_hide_delay);
  1389. }
  1390. }
  1391. /**
  1392. * Refreshes the desktop background based on the user's settings.
  1393. * If the user has set a custom desktop background URL or color, it will use that.
  1394. * If not, it defaults to a specific wallpaper image.
  1395. *
  1396. * @global
  1397. * @function
  1398. * @fires set_desktop_background - Calls this global function to set the desktop background.
  1399. *
  1400. * @example
  1401. * // This will refresh the desktop background according to the user's preference or defaults.
  1402. * window.refresh_desktop_background();
  1403. */
  1404. window.refresh_desktop_background = function(){
  1405. if(window.user && (window.user.desktop_bg_url !== null || window.user.desktop_bg_color !== null)){
  1406. window.set_desktop_background({
  1407. url: window.user.desktop_bg_url,
  1408. fit: window.user.desktop_bg_fit,
  1409. color: window.user.desktop_bg_color,
  1410. })
  1411. }
  1412. // default background
  1413. else{
  1414. let wallpaper = (window.gui_env === 'prod') ? '/dist/images/wallpaper.webp' : '/src/images/wallpaper.webp';
  1415. window.set_desktop_background({
  1416. url: wallpaper,
  1417. fit: 'cover',
  1418. });
  1419. }
  1420. }
  1421. window.determine_website_url = function(fsentry_path){
  1422. // 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
  1423. for(let i=0; i<window.sites.length; i++){
  1424. if(window.sites[i].dir_path && fsentry_path.startsWith(window.sites[i].dir_path + '/')){
  1425. return window.sites[i].address + fsentry_path.replace(window.sites[i].dir_path, '');
  1426. }
  1427. }
  1428. return null;
  1429. }
  1430. window.update_sites_cache = function(){
  1431. return puter.hosting.list((sites)=>{
  1432. if(sites && sites.length > 0){
  1433. window.sites = sites;
  1434. }else{
  1435. window.sites = [];
  1436. }
  1437. })
  1438. }
  1439. /**
  1440. *
  1441. * @param {*} el_target_container
  1442. * @param {*} target_path
  1443. */
  1444. window.init_upload_using_dialog = function(el_target_container, target_path = null){
  1445. $("#upload-file-dialog").unbind('onchange');
  1446. $("#upload-file-dialog").unbind('change');
  1447. $("#upload-file-dialog").unbind('onChange');
  1448. target_path = target_path === null ? $(el_target_container).attr('data-path') : path.resolve(target_path);
  1449. $('#upload-file-dialog').trigger('click');
  1450. $("#upload-file-dialog").on('change', async function(e){
  1451. if($("#upload-file-dialog").val() !== ''){
  1452. const files = $('#upload-file-dialog')[0].files;
  1453. if(files.length > 0){
  1454. try{
  1455. window.upload_items(files, target_path);
  1456. }
  1457. catch(err){
  1458. UIAlert(err.message ?? err)
  1459. }
  1460. $('#upload-file-dialog').val('');
  1461. }
  1462. }
  1463. else{
  1464. return
  1465. }
  1466. })
  1467. }
  1468. window.upload_items = async function(items, dest_path){
  1469. let upload_progress_window;
  1470. let opid;
  1471. if(dest_path == window.trash_path){
  1472. UIAlert('Uploading to trash is not allowed!');
  1473. return;
  1474. }
  1475. puter.fs.upload(
  1476. // what to upload
  1477. items,
  1478. // where to upload
  1479. dest_path,
  1480. // options
  1481. {
  1482. // init
  1483. init: async(operation_id, xhr)=>{
  1484. opid = operation_id;
  1485. // create upload progress window
  1486. upload_progress_window = await UIWindowProgress({
  1487. title: i18n('upload'),
  1488. icon: window.icons[`app-icon-uploader.svg`],
  1489. operation_id: operation_id,
  1490. show_progress: true,
  1491. on_cancel: () => {
  1492. window.show_save_account_notice_if_needed();
  1493. xhr.abort();
  1494. },
  1495. });
  1496. // add to active_uploads
  1497. window.active_uploads[opid] = 0;
  1498. },
  1499. // start
  1500. start: async function(){
  1501. // change upload progress window message to uploading
  1502. upload_progress_window.set_status('Uploading');
  1503. upload_progress_window.set_progress(0);
  1504. },
  1505. // progress
  1506. progress: async function(operation_id, op_progress){
  1507. upload_progress_window.set_progress(op_progress);
  1508. // update active_uploads
  1509. window.active_uploads[opid] = op_progress;
  1510. // update title if window is not visible
  1511. if(document.visibilityState !== "visible"){
  1512. update_title_based_on_uploads();
  1513. }
  1514. },
  1515. // success
  1516. success: async function(items){
  1517. // DONE
  1518. // Add action to actions_history for undo ability
  1519. const files = []
  1520. if(typeof items[Symbol.iterator] === 'function'){
  1521. for(const item of items){
  1522. files.push(item.path)
  1523. }
  1524. }else{
  1525. files.push(items.path)
  1526. }
  1527. window.actions_history.push({
  1528. operation: 'upload',
  1529. data: files
  1530. });
  1531. // close progress window after a bit of delay for a better UX
  1532. setTimeout(() => {
  1533. setTimeout(() => {
  1534. upload_progress_window.close();
  1535. window.show_save_account_notice_if_needed();
  1536. }, Math.abs(window.upload_progress_hide_delay));
  1537. })
  1538. // remove from active_uploads
  1539. delete window.active_uploads[opid];
  1540. },
  1541. // error
  1542. error: async function(err){
  1543. upload_progress_window.show_error(i18n('error_uploading_files'), err.message);
  1544. // remove from active_uploads
  1545. delete window.active_uploads[opid];
  1546. },
  1547. // abort
  1548. abort: async function(operation_id){
  1549. // remove from active_uploads
  1550. delete window.active_uploads[opid];
  1551. }
  1552. }
  1553. );
  1554. }
  1555. window.empty_trash = async function(){
  1556. const alert_resp = await UIAlert({
  1557. message: i18n('empty_trash_confirmation'),
  1558. buttons:[
  1559. {
  1560. label: i18n('yes'),
  1561. value: 'yes',
  1562. type: 'primary',
  1563. },
  1564. {
  1565. label: i18n('no'),
  1566. value: 'no',
  1567. },
  1568. ]
  1569. })
  1570. if(alert_resp === 'no')
  1571. return;
  1572. // only show progress window if it takes longer than 500ms to create folder
  1573. let init_ts = Date.now();
  1574. let progwin;
  1575. let op_id = window.uuidv4();
  1576. let progwin_timeout = setTimeout(async () => {
  1577. progwin = await UIWindowProgress({operation_id: op_id});
  1578. progwin.set_status(i18n('emptying_trash'));
  1579. }, 500);
  1580. await puter.fs.delete({
  1581. paths: window.trash_path,
  1582. descendantsOnly: true,
  1583. recursive: true,
  1584. success: async function (resp){
  1585. // update other clients
  1586. if(window.socket){
  1587. window.socket.emit('trash.is_empty', {is_empty: true});
  1588. }
  1589. // use the 'empty trash' icon for Trash
  1590. $(`[data-app="trash"]`).find('.taskbar-icon > img').attr('src', window.icons['trash.svg']);
  1591. $(`.item[data-path="${html_encode(window.trash_path)}" i], .item[data-shortcut_to_path="${html_encode(window.trash_path)}" i]`).find('.item-icon > img').attr('src', window.icons['trash.svg']);
  1592. $(`.window[data-path="${window.trash_path}"]`).find('.window-head-icon').attr('src', window.icons['trash.svg']);
  1593. // remove all items with trash paths
  1594. // todo this has to be case-insensitive but the `i` selector doesn't work on ^=
  1595. $(`.item[data-path^="${window.trash_path}/"]`).removeItems();
  1596. // update the footer item count for Trash
  1597. window. update_explorer_footer_item_count($(`.window[data-path="${window.trash_path}"]`))
  1598. // close progress window
  1599. clearTimeout(progwin_timeout);
  1600. setTimeout(() => {
  1601. progwin?.close();
  1602. }, Math.max(0, window.copy_progress_hide_delay - (Date.now() - init_ts)));
  1603. },
  1604. error: async function (err){
  1605. clearTimeout(progwin_timeout);
  1606. setTimeout(() => {
  1607. progwin?.close();
  1608. }, Math.max(0, window.copy_progress_hide_delay - (Date.now() - init_ts)));
  1609. }
  1610. });
  1611. }
  1612. window.copy_to_clipboard = async function(text){
  1613. if (navigator.clipboard) {
  1614. // copy text to clipboard
  1615. await navigator.clipboard.writeText(text);
  1616. }
  1617. else{
  1618. document.execCommand('copy');
  1619. }
  1620. }
  1621. window.getUsage = () => {
  1622. return fetch(window.api_origin + "/drivers/usage", {
  1623. headers: {
  1624. "Content-Type": "application/json",
  1625. "Authorization": "Bearer " + window.auth_token
  1626. },
  1627. method: "GET"
  1628. })
  1629. .then(response => {
  1630. // Check if the response is ok (status code in the range 200-299)
  1631. if (!response.ok) {
  1632. throw new Error('Network response was not ok');
  1633. }
  1634. return response.json(); // Parse the response as JSON
  1635. })
  1636. .then(data => {
  1637. // Handle the JSON data
  1638. return data;
  1639. })
  1640. .catch(error => {
  1641. // Handle any errors
  1642. console.error('There has been a problem with your fetch operation:', error);
  1643. });
  1644. }
  1645. window.getAppUIDFromOrigin = async function(origin) {
  1646. try {
  1647. const response = await fetch(window.api_origin + "/auth/app-uid-from-origin", {
  1648. headers: {
  1649. "Content-Type": "application/json",
  1650. "Authorization": "Bearer " + window.auth_token,
  1651. },
  1652. body: JSON.stringify({ origin: origin }),
  1653. method: "POST",
  1654. });
  1655. const data = await response.json();
  1656. // Assuming the app_uid is in the data object, return it
  1657. return data.uid;
  1658. } catch (err) {
  1659. // Handle any errors here
  1660. console.error(err);
  1661. // You may choose to return something specific here in case of an error
  1662. return null;
  1663. }
  1664. }
  1665. window.getUserAppToken = async function(origin) {
  1666. try {
  1667. const response = await fetch(window.api_origin + "/auth/get-user-app-token", {
  1668. headers: {
  1669. "Content-Type": "application/json",
  1670. "Authorization": "Bearer " + window.auth_token,
  1671. },
  1672. body: JSON.stringify({ origin: origin }),
  1673. method: "POST",
  1674. });
  1675. const data = await response.json();
  1676. // return
  1677. return data;
  1678. } catch (err) {
  1679. // Handle any errors here
  1680. console.error(err);
  1681. // You may choose to return something specific here in case of an error
  1682. return null;
  1683. }
  1684. }
  1685. window.checkUserSiteRelationship = async function(origin) {
  1686. try {
  1687. const response = await fetch(window.api_origin + "/auth/check-app ", {
  1688. headers: {
  1689. "Content-Type": "application/json",
  1690. "Authorization": "Bearer " + window.auth_token,
  1691. },
  1692. body: JSON.stringify({ origin: origin }),
  1693. method: "POST",
  1694. });
  1695. const data = await response.json();
  1696. // return
  1697. return data;
  1698. } catch (err) {
  1699. // Handle any errors here
  1700. console.error(err);
  1701. // You may choose to return something specific here in case of an error
  1702. return null;
  1703. }
  1704. }
  1705. window.zipItems = async function(el_items, targetDirPath, download = true) {
  1706. const zip = new JSZip();
  1707. // if single item, convert to array
  1708. el_items = Array.isArray(el_items) ? el_items : [el_items];
  1709. // create progress window
  1710. let start_ts = Date.now();
  1711. let progwin, progwin_timeout;
  1712. // only show progress window if it takes longer than 500ms to download
  1713. progwin_timeout = setTimeout(async () => {
  1714. progwin = await UIWindowProgress();
  1715. }, 500);
  1716. for (const el_item of el_items) {
  1717. let targetPath = $(el_item).attr('data-path');
  1718. // if directory, zip the directory
  1719. if($(el_item).attr('data-is_dir') === '1'){
  1720. progwin?.set_status(i18n('reading_file', targetPath));
  1721. // Recursively read the directory
  1722. let children = await readDirectoryRecursive(targetPath);
  1723. // Add files to the zip
  1724. for (const child of children) {
  1725. let relativePath;
  1726. if(el_items.length === 1)
  1727. relativePath = child.relativePath;
  1728. else
  1729. relativePath = path.basename(targetPath) + '/' + child.relativePath;
  1730. // update progress window
  1731. progwin?.set_status(i18n('zipping_file', relativePath));
  1732. // read file content
  1733. let content = await puter.fs.read(child.path);
  1734. try{
  1735. zip.file(relativePath, content, {binary: true});
  1736. }catch(e){
  1737. console.error(e);
  1738. }
  1739. }
  1740. }
  1741. // if item is a file, zip the file
  1742. else{
  1743. let content = await puter.fs.read(targetPath);
  1744. zip.file(path.basename(targetPath), content, {binary: true});
  1745. }
  1746. }
  1747. // determine name of zip file
  1748. let zipName;
  1749. if(el_items.length === 1)
  1750. zipName = path.basename($(el_items[0]).attr('data-path'));
  1751. else
  1752. zipName = 'Archive';
  1753. // Generate the zip file
  1754. zip.generateAsync({ type: "blob" })
  1755. .then(async function (content) {
  1756. // Trigger the download
  1757. if(download){
  1758. const url = URL.createObjectURL(content);
  1759. const a = document.createElement("a");
  1760. a.href = url;
  1761. a.download = zipName;
  1762. document.body.appendChild(a);
  1763. a.click();
  1764. // Cleanup
  1765. document.body.removeChild(a);
  1766. URL.revokeObjectURL(url);
  1767. }
  1768. // save
  1769. else
  1770. await puter.fs.write(targetDirPath + '/' + zipName + ".zip", content, {overwrite: false, dedupeName: true})
  1771. // close progress window
  1772. clearTimeout(progwin_timeout);
  1773. setTimeout(() => {
  1774. progwin?.close();
  1775. }, Math.max(0, window.copy_progress_hide_delay - (Date.now() - start_ts)));
  1776. })
  1777. .catch(function (err) {
  1778. // close progress window
  1779. clearTimeout(progwin_timeout);
  1780. setTimeout(() => {
  1781. progwin?.close();
  1782. }, Math.max(0, window.copy_progress_hide_delay - (Date.now() - start_ts)));
  1783. // handle errors
  1784. // TODO: Display in progress dialog
  1785. console.error("Error in zipping files: ", err);
  1786. });
  1787. }
  1788. async function readDirectoryRecursive(path, baseDir = '') {
  1789. let allFiles = [];
  1790. // Read the directory
  1791. const entries = await puter.fs.readdir(path);
  1792. // Process each entry
  1793. for (const entry of entries) {
  1794. const fullPath = `${path}/${entry.name}`;
  1795. if (entry.is_dir) {
  1796. // If entry is a directory, recursively read it
  1797. const subDirFiles = await readDirectoryRecursive(fullPath, `${baseDir}${entry.name}/`);
  1798. allFiles = allFiles.concat(subDirFiles);
  1799. } else {
  1800. // If entry is a file, add it to the list
  1801. allFiles.push({ path: fullPath, relativePath: `${baseDir}${entry.name}` });
  1802. }
  1803. }
  1804. return allFiles;
  1805. }
  1806. window.extractSubdomain = function(url) {
  1807. var subdomain = url.split('://')[1].split('.')[0];
  1808. return subdomain;
  1809. }
  1810. window.sleep = function(ms){
  1811. return new Promise(resolve => setTimeout(resolve, ms));
  1812. }
  1813. window.unzipItem = async function(itemPath) {
  1814. // create progress window
  1815. let start_ts = Date.now();
  1816. let progwin, progwin_timeout;
  1817. // only show progress window if it takes longer than 500ms to download
  1818. progwin_timeout = setTimeout(async () => {
  1819. progwin = await UIWindowProgress();
  1820. }, 500);
  1821. const zip = new JSZip();
  1822. let filPath = itemPath;
  1823. let file = puter.fs.read(filPath);
  1824. zip.loadAsync(file).then(async function (zip) {
  1825. const rootdir = await puter.fs.mkdir(path.dirname(filPath) + '/' + path.basename(filPath, '.zip'), {dedupeName: true});
  1826. Object.keys(zip.files).forEach(async function (filename) {
  1827. if(filename.endsWith('/'))
  1828. await puter.fs.mkdir(rootdir.path +'/' + filename, {createMissingParents: true});
  1829. zip.files[filename].async('blob').then(async function (fileData) {
  1830. await puter.fs.write(rootdir.path +'/' + filename, fileData);
  1831. }).catch(function (e) {
  1832. // UIAlert(e.message);
  1833. })
  1834. })
  1835. // close progress window
  1836. clearTimeout(progwin_timeout);
  1837. setTimeout(() => {
  1838. progwin?.close();
  1839. }, Math.max(0, window.copy_progress_hide_delay - (Date.now() - start_ts)));
  1840. }).catch(function (e) {
  1841. // UIAlert(e.message);
  1842. // close progress window
  1843. clearTimeout(progwin_timeout);
  1844. setTimeout(() => {
  1845. progwin?.close();
  1846. }, Math.max(0, window.copy_progress_hide_delay - (Date.now() - start_ts)));
  1847. })
  1848. }
  1849. 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)=>{
  1850. puter.fs.rename({
  1851. uid: options.uid === 'null' ? null : options.uid,
  1852. new_name: new_name,
  1853. excludeSocketID: window.socket.id,
  1854. success: async (fsentry)=>{
  1855. // Add action to actions_history for undo ability
  1856. if (!is_undo)
  1857. window.actions_history.push({
  1858. operation: 'rename',
  1859. data: {options, new_name, old_name, old_path, el_item, el_item_name, el_item_icon, el_item_name_editor, website_url}
  1860. });
  1861. // Has the extension changed? in that case update options.sugggested_apps
  1862. const old_extension = path.extname(old_name);
  1863. const new_extension = path.extname(new_name);
  1864. if(old_extension !== new_extension){
  1865. window.suggest_apps_for_fsentry({
  1866. uid: options.uid,
  1867. onSuccess: function(suggested_apps){
  1868. options.suggested_apps = suggested_apps;
  1869. }
  1870. });
  1871. }
  1872. // Set new item name
  1873. $(`.item[data-uid='${$(el_item).attr('data-uid')}'] .item-name`).html(html_encode(truncate_filename(new_name)).replaceAll(' ', '&nbsp;'));
  1874. $(el_item_name).show();
  1875. // Hide item name editor
  1876. $(el_item_name_editor).hide();
  1877. // Set new icon
  1878. const new_icon = (options.is_dir ? window.icons['folder.svg'] : (await item_icon(fsentry)).image);
  1879. $(el_item_icon).find('.item-icon-icon').attr('src', new_icon);
  1880. // Set new `data-name`
  1881. options.name = new_name;
  1882. $(el_item).attr('data-name', html_encode(new_name));
  1883. $(`.item[data-uid='${$(el_item).attr('data-uid')}']`).attr('data-name', html_encode(new_name));
  1884. $(`.window-${options.uid}`).attr('data-name', html_encode(new_name));
  1885. // Set new `title` attribute
  1886. $(`.item[data-uid='${$(el_item).attr('data-uid')}']`).attr('title', html_encode(new_name));
  1887. $(`.window-${options.uid}`).attr('title', html_encode(new_name));
  1888. // Set new value for `item-name-editor`
  1889. $(`.item[data-uid='${$(el_item).attr('data-uid')}'] .item-name-editor`).val(html_encode(new_name));
  1890. $(`.item[data-uid='${$(el_item).attr('data-uid')}'] .item-name`).attr('title', html_encode(new_name));
  1891. // Set new `data-path` attribute
  1892. options.path = path.join( path.dirname(options.path), options.name);
  1893. const new_path = options.path;
  1894. $(el_item).attr('data-path', new_path);
  1895. $(`.item[data-uid='${$(el_item).attr('data-uid')}']`).attr('data-path', new_path);
  1896. $(`.window-${options.uid}`).attr('data-path', new_path);
  1897. // Update all elements that have matching paths
  1898. $(`[data-path="${html_encode(old_path)}" i]`).each(function(){
  1899. $(this).attr('data-path', new_path)
  1900. if($(this).hasClass('window-navbar-path-dirname'))
  1901. $(this).text(new_name);
  1902. });
  1903. // Update the paths of all elements whose paths start with `old_path`
  1904. $(`[data-path^="${html_encode(old_path) + '/'}"]`).each(function(){
  1905. const new_el_path = _.replace($(this).attr('data-path'), old_path + '/', new_path+'/');
  1906. $(this).attr('data-path', new_el_path);
  1907. });
  1908. // Update the 'Sites Cache'
  1909. if($(el_item).attr('data-has_website') === '1')
  1910. await window.update_sites_cache();
  1911. // Update `website_url`
  1912. website_url = window.determine_website_url(new_path);
  1913. $(el_item).attr('data-website_url', website_url);
  1914. // Update all exact-matching windows
  1915. $(`.window-${options.uid}`).each(function(){
  1916. window.update_window_path(this, options.path);
  1917. })
  1918. // Set new name for corresponding open windows
  1919. $(`.window-${options.uid} .window-head-title`).text(new_name);
  1920. // Re-sort all matching item containers
  1921. $(`.item[data-uid='${$(el_item).attr('data-uid')}']`).parent('.item-container').each(function(){
  1922. window.sort_items(this, $(el_item).closest('.item-container').attr('data-sort_by'), $(el_item).closest('.item-container').attr('data-sort_order'));
  1923. })
  1924. },
  1925. error: function (err){
  1926. // reset to old name
  1927. $(el_item_name).text(truncate_filename(options.name));
  1928. $(el_item_name).show();
  1929. // hide item name editor
  1930. $(el_item_name_editor).hide();
  1931. $(el_item_name_editor).val(html_encode($(el_item).attr('data-name')));
  1932. //show error
  1933. if(err.message){
  1934. UIAlert(err.message)
  1935. }
  1936. },
  1937. });
  1938. }
  1939. /**
  1940. * Deletes the given item with path.
  1941. *
  1942. * @param {string} path - path of the item to delete
  1943. * @returns {Promise<void>}
  1944. */
  1945. window.delete_item_with_path = async function(path){
  1946. try{
  1947. await puter.fs.delete({
  1948. paths: path,
  1949. descendantsOnly: false,
  1950. recursive: true,
  1951. });
  1952. }catch(err){
  1953. UIAlert(err.responseText);
  1954. }
  1955. }
  1956. window.undo_last_action = async()=>{
  1957. if (window.actions_history.length > 0) {
  1958. const last_action = window.actions_history.pop();
  1959. // Undo the create file action
  1960. if (last_action.operation === 'create_file' || last_action.operation === 'create_folder') {
  1961. const lastCreatedItem = last_action.data;
  1962. window.undo_create_file_or_folder(lastCreatedItem);
  1963. } else if(last_action.operation === 'rename') {
  1964. 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;
  1965. window.rename_file(options, old_name, new_name, old_path, el_item, el_item_name, el_item_icon, el_item_name_editor, website_url, true);
  1966. } else if(last_action.operation === 'upload') {
  1967. const files = last_action.data;
  1968. window.undo_upload(files);
  1969. } else if(last_action.operation === 'copy') {
  1970. const files = last_action.data;
  1971. window.undo_copy(files);
  1972. } else if(last_action.operation === 'move') {
  1973. const items = last_action.data;
  1974. window.undo_move(items);
  1975. } else if(last_action.operation === 'delete') {
  1976. const items = last_action.data;
  1977. window.undo_delete(items);
  1978. }
  1979. }
  1980. }
  1981. window.undo_create_file_or_folder = async(item)=>{
  1982. await window.delete_item(item);
  1983. }
  1984. window.undo_upload = async(files)=>{
  1985. for (const file of files) {
  1986. await window.delete_item_with_path(file);
  1987. }
  1988. }
  1989. window.undo_copy = async(files)=>{
  1990. for (const file of files) {
  1991. await window.delete_item_with_path(file);
  1992. }
  1993. }
  1994. window.undo_move = async(items)=>{
  1995. for (const item of items) {
  1996. const el = await get_html_element_from_options(item.options);
  1997. window.move_items([el], path.dirname(item.original_path), true);
  1998. }
  1999. }
  2000. window.undo_delete = async(items)=>{
  2001. for (const item of items) {
  2002. const el = await get_html_element_from_options(item.options);
  2003. let metadata = $(el).attr('data-metadata') === '' ? {} : JSON.parse($(el).attr('data-metadata'))
  2004. window.move_items([el], path.dirname(metadata.original_path), true);
  2005. }
  2006. }
  2007. window.store_auto_arrange_preference = (preference)=>{
  2008. puter.kv.set('user_preferences.auto_arrange_desktop', preference);
  2009. localStorage.setItem('auto_arrange', preference);
  2010. }
  2011. window.get_auto_arrange_data = async()=>{
  2012. const preferenceValue = await puter.kv.get('user_preferences.auto_arrange_desktop');
  2013. window.is_auto_arrange_enabled = preferenceValue === null ? true : preferenceValue;
  2014. const positions = await puter.kv.get('desktop_item_positions')
  2015. window.desktop_item_positions = (!positions || typeof positions !== 'object' || Array.isArray(positions)) ? {} : positions;
  2016. }
  2017. window.clear_desktop_item_positions = async(el_desktop)=>{
  2018. $(el_desktop).find('.item').each(function(){
  2019. const el_item = $(this)[0];
  2020. $(el_item).css('position', '');
  2021. $(el_item).css('left', '');
  2022. $(el_item).css('top', '');
  2023. });
  2024. if(window.reset_item_positions){
  2025. window.delete_desktop_item_positions()
  2026. }
  2027. }
  2028. window.set_desktop_item_positions = async(el_desktop)=>{
  2029. $(el_desktop).find('.item').each(async function(){
  2030. const position = window.desktop_item_positions[$(this).attr('data-uid')]
  2031. const el_item = $(this)[0];
  2032. if(position){
  2033. $(el_item).css('position', 'absolute');
  2034. $(el_item).css('left', position.left + 'px');
  2035. $(el_item).css('top', position.top + 'px');
  2036. }
  2037. });
  2038. }
  2039. window.save_desktop_item_positions = ()=>{
  2040. puter.kv.set('desktop_item_positions', window.desktop_item_positions);
  2041. }
  2042. window.delete_desktop_item_positions = ()=>{
  2043. window.desktop_item_positions = {}
  2044. puter.kv.del('desktop_item_positions');
  2045. }
  2046. window.change_clock_visible = (clock_visible) => {
  2047. let newValue = clock_visible || window.user_preferences.clock_visible;
  2048. newValue === 'auto' && window.is_fullscreen() ? $('#clock').show() : $('#clock').hide();
  2049. newValue === 'show' && $('#clock').show();
  2050. newValue === 'hide' && $('#clock').hide();
  2051. if(clock_visible) {
  2052. // save clock_visible to user preferences
  2053. window.mutate_user_preferences({
  2054. clock_visible: newValue
  2055. });
  2056. return;
  2057. }
  2058. $('select.change-clock-visible').val(window.user_preferences.clock_visible);
  2059. }
  2060. // Finds the `.window` element for the given app instance ID
  2061. window.window_for_app_instance = (instance_id) => {
  2062. return $(`.window[data-element_uuid="${instance_id}"]`).get(0);
  2063. };
  2064. // Finds the `iframe` element for the given app instance ID
  2065. window.iframe_for_app_instance = (instance_id) => {
  2066. return $(window.window_for_app_instance(instance_id)).find('.window-app-iframe').get(0);
  2067. };
  2068. // Run any callbacks to say that the app has launched
  2069. window.report_app_launched = (instance_id, { uses_sdk = true }) => {
  2070. const child_launch_callback = window.child_launch_callbacks[instance_id];
  2071. if (child_launch_callback) {
  2072. const parent_iframe = window.iframe_for_app_instance(child_launch_callback.parent_instance_id);
  2073. // send confirmation to requester window
  2074. parent_iframe.contentWindow.postMessage({
  2075. msg: 'childAppLaunched',
  2076. original_msg_id: child_launch_callback.launch_msg_id,
  2077. child_instance_id: instance_id,
  2078. uses_sdk: uses_sdk,
  2079. }, '*');
  2080. delete window.child_launch_callbacks[instance_id];
  2081. }
  2082. };
  2083. // Run any callbacks to say that the app has closed
  2084. window.report_app_closed = (instance_id, status_code) => {
  2085. const el_window = window.window_for_app_instance(instance_id);
  2086. // notify parent app, if we have one, that we're closing
  2087. const parent_id = el_window.dataset['parent_instance_id'];
  2088. const parent = $(`.window[data-element_uuid="${parent_id}"] .window-app-iframe`).get(0);
  2089. if (parent) {
  2090. parent.contentWindow.postMessage({
  2091. msg: 'appClosed',
  2092. appInstanceID: instance_id,
  2093. statusCode: status_code ?? 0,
  2094. }, '*');
  2095. }
  2096. // notify child apps, if we have them, that we're closing
  2097. const children = $(`.window[data-parent_instance_id="${instance_id}"] .window-app-iframe`);
  2098. children.each((_, child) => {
  2099. child.contentWindow.postMessage({
  2100. msg: 'appClosed',
  2101. appInstanceID: instance_id,
  2102. statusCode: status_code ?? 0,
  2103. }, '*');
  2104. });
  2105. // TODO: Once other AppConnections exist, those will need notifying too.
  2106. };
  2107. window.set_menu_item_prop = (items, item_id, prop, val) => {
  2108. // iterate over items
  2109. for (const item of items) {
  2110. // find the item with the given item_id
  2111. if (item.id === item_id) {
  2112. // set the property value
  2113. item[prop] = val;
  2114. break;
  2115. }
  2116. else if(item.items){
  2117. set_menu_item_prop(item.items, item_id, prop, val);
  2118. }
  2119. }
  2120. };
  2121. window.countSubstr = (str, substring)=>{
  2122. if (substring.length === 0) {
  2123. return 0;
  2124. }
  2125. let count = 0;
  2126. let pos = str.indexOf(substring);
  2127. while (pos !== -1) {
  2128. count++;
  2129. pos = str.indexOf(substring, pos + 1);
  2130. }
  2131. return count;
  2132. }
  2133. window.detectHostOS = function(){
  2134. var userAgent = window.navigator.userAgent;
  2135. var platform = window.navigator.platform;
  2136. var macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'];
  2137. var windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'];
  2138. if (macosPlatforms.indexOf(platform) !== -1) {
  2139. return 'macos';
  2140. } else if (windowsPlatforms.indexOf(platform) !== -1) {
  2141. return 'windows';
  2142. } else {
  2143. return 'other';
  2144. }
  2145. }