├── .jscs.json ├── .jshintrc ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── init.js ├── lib ├── cherow │ └── cherow.js ├── esprima │ └── esprima.js ├── estraverse │ └── estraverse.js ├── jszip │ └── jszip.min.js ├── socket.io │ └── socket.io.js └── yaml │ └── js-yaml.js ├── modules ├── config │ └── filetypes ├── core │ ├── core.js │ └── merge.js ├── startup │ ├── loader.js │ └── startup.js ├── webapi │ └── webapi.js └── window_manager │ ├── bar │ ├── laskyawm-bar.js │ └── res │ │ ├── css │ │ └── laskyawm-bar.css │ │ ├── img │ │ └── power.png │ │ └── js │ │ ├── laskyawm-clock.js │ │ └── laskyawm-power.js │ ├── index.html │ ├── launcher │ └── launcher.js │ └── res │ ├── css │ ├── main.css │ └── mobile.css │ └── js │ └── laskyawm.js └── pre-commit /.jscs.json: -------------------------------------------------------------------------------- 1 | { 2 | "disallowSpaceAfterKeywords": [ 3 | "if", 4 | "for", 5 | "while", 6 | "switch", 7 | "catch" 8 | ], 9 | "requireSpaceBeforeBlockStatements": true, 10 | "disallowSpacesInFunction": { 11 | "beforeOpeningRoundBrace": true 12 | }, 13 | "requireSpacesInFunction": { 14 | "beforeOpeningCurlyBrace": true 15 | }, 16 | "disallowSpacesInsideObjectBrackets": "all", 17 | "disallowSpacesInsideArrayBrackets": "all", 18 | "disallowSpacesInsideParentheses": true, 19 | "disallowQuotedKeysInObjects": true, 20 | "disallowSpaceAfterObjectKeys": true, 21 | "requireCommaBeforeLineBreak": true, 22 | "validateLineBreaks": "LF", 23 | "validateQuoteMarks": { 24 | "mark": "'", 25 | "escape": true 26 | }, 27 | "validateIndentation": { 28 | "value": "\t", 29 | "allExcept": [] 30 | }, 31 | "disallowKeywordsOnNewLine": ["finally", "catch"], 32 | "disallowYodaConditions": true, 33 | "disallowNewlineBeforeBlockStatements": true 34 | } -------------------------------------------------------------------------------- /.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | "eqeqeq": true, 3 | "forin": true, 4 | "immed": true, 5 | "latedef": "nofunc", 6 | "newcap": true, 7 | "noarg": true, 8 | "undef": true, 9 | "unused": true, 10 | 11 | "eqnull": true, 12 | "evil": true, 13 | "sub": true, 14 | 15 | "browser": true, 16 | "devel": true, 17 | "esversion": 6 18 | } -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Before committing: 2 | 3 | sudo npm install -g jshint jscs # This globally installs jshint and jscs, 4 | # two JS code style checkers 5 | ln -s ../../pre-commit .git/hooks/pre-commit -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Airborn 2 | 3 | Airborn is a service that lets you create and store documents in the browser using [Open Web Apps](https://developer.mozilla.org/en/Apps/Quickstart/Build/Intro_to_open_web_apps). 4 | 5 | For a small amount of Developer Documentation, see the [wiki](https://github.com/twiss/airborn/wiki). 6 | -------------------------------------------------------------------------------- /init.js: -------------------------------------------------------------------------------- 1 | /* This file is licensed under the Affero General Public License. */ 2 | 3 | /*global GET, decryptAndMaybeUngzip, sjcl, files_hmac, files_key, getFile */ 4 | 5 | GET('/v2/live/Core/modules/core/core.js', function(response) { 6 | window.eval(response); 7 | 8 | getFile('/Core/modules/startup/startup.js', function(contents) { 9 | window.eval(contents); 10 | }); 11 | 12 | getFile('/Core/modules/startup/loader.js', function(contents) { 13 | window.eval(contents); 14 | 15 | var container = document.getElementById('container'); 16 | if(container) container.parentElement.removeChild(container); 17 | var iframe = document.getElementsByTagName('iframe')[0]; 18 | if(iframe && iframe.getAttribute('src') === 'content') iframe.parentElement.removeChild(iframe); 19 | }); 20 | }); 21 | 22 | var loginButton = document.getElementById('login'); 23 | if(loginButton) { 24 | loginButton.disabled = true; 25 | if(window.lang && window.lang.loggingIn) { 26 | loginButton.value = window.lang.loggingIn; 27 | } 28 | } 29 | 30 | [ 31 | '/Core/modules/window_manager/index.html', 32 | '/Core/modules/window_manager/res/css/main.css', 33 | '/settings', 34 | '/Apps/firetext/index.html', 35 | '/Apps/firetext/styles.css' 36 | ].forEach(function(url) { 37 | var link = document.createElement('link'); 38 | link.rel = 'prefetch'; 39 | link.href = 'object/' + sjcl.codec.hex.fromBits(files_hmac.mac(url)); 40 | document.body.appendChild(link); 41 | }); 42 | //# sourceURL=/Core/init.js -------------------------------------------------------------------------------- /lib/estraverse/estraverse.js: -------------------------------------------------------------------------------- 1 | (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.estraverse = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 4 | Copyright (C) 2012 Ariya Hidayat 5 | 6 | Redistribution and use in source and binary forms, with or without 7 | modification, are permitted provided that the following conditions are met: 8 | 9 | * Redistributions of source code must retain the above copyright 10 | notice, this list of conditions and the following disclaimer. 11 | * Redistributions in binary form must reproduce the above copyright 12 | notice, this list of conditions and the following disclaimer in the 13 | documentation and/or other materials provided with the distribution. 14 | 15 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 16 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 17 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 18 | ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY 19 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 20 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 21 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 22 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 23 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 24 | THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 | */ 26 | /*jslint vars:false, bitwise:true*/ 27 | /*jshint indent:4*/ 28 | /*global exports:true*/ 29 | (function clone(exports) { 30 | 'use strict'; 31 | 32 | var Syntax, 33 | isArray, 34 | VisitorOption, 35 | VisitorKeys, 36 | objectCreate, 37 | objectKeys, 38 | BREAK, 39 | SKIP, 40 | REMOVE; 41 | 42 | function ignoreJSHintError() { } 43 | 44 | isArray = Array.isArray; 45 | if (!isArray) { 46 | isArray = function isArray(array) { 47 | return Object.prototype.toString.call(array) === '[object Array]'; 48 | }; 49 | } 50 | 51 | function deepCopy(obj) { 52 | var ret = {}, key, val; 53 | for (key in obj) { 54 | if (obj.hasOwnProperty(key)) { 55 | val = obj[key]; 56 | if (typeof val === 'object' && val !== null) { 57 | ret[key] = deepCopy(val); 58 | } else { 59 | ret[key] = val; 60 | } 61 | } 62 | } 63 | return ret; 64 | } 65 | 66 | function shallowCopy(obj) { 67 | var ret = {}, key; 68 | for (key in obj) { 69 | if (obj.hasOwnProperty(key)) { 70 | ret[key] = obj[key]; 71 | } 72 | } 73 | return ret; 74 | } 75 | ignoreJSHintError(shallowCopy); 76 | 77 | // based on LLVM libc++ upper_bound / lower_bound 78 | // MIT License 79 | 80 | function upperBound(array, func) { 81 | var diff, len, i, current; 82 | 83 | len = array.length; 84 | i = 0; 85 | 86 | while (len) { 87 | diff = len >>> 1; 88 | current = i + diff; 89 | if (func(array[current])) { 90 | len = diff; 91 | } else { 92 | i = current + 1; 93 | len -= diff + 1; 94 | } 95 | } 96 | return i; 97 | } 98 | 99 | function lowerBound(array, func) { 100 | var diff, len, i, current; 101 | 102 | len = array.length; 103 | i = 0; 104 | 105 | while (len) { 106 | diff = len >>> 1; 107 | current = i + diff; 108 | if (func(array[current])) { 109 | i = current + 1; 110 | len -= diff + 1; 111 | } else { 112 | len = diff; 113 | } 114 | } 115 | return i; 116 | } 117 | ignoreJSHintError(lowerBound); 118 | 119 | objectCreate = Object.create || (function () { 120 | function F() { } 121 | 122 | return function (o) { 123 | F.prototype = o; 124 | return new F(); 125 | }; 126 | })(); 127 | 128 | objectKeys = Object.keys || function (o) { 129 | var keys = [], key; 130 | for (key in o) { 131 | keys.push(key); 132 | } 133 | return keys; 134 | }; 135 | 136 | function extend(to, from) { 137 | var keys = objectKeys(from), key, i, len; 138 | for (i = 0, len = keys.length; i < len; i += 1) { 139 | key = keys[i]; 140 | to[key] = from[key]; 141 | } 142 | return to; 143 | } 144 | 145 | Syntax = { 146 | AssignmentExpression: 'AssignmentExpression', 147 | AssignmentPattern: 'AssignmentPattern', 148 | ArrayExpression: 'ArrayExpression', 149 | ArrayPattern: 'ArrayPattern', 150 | ArrowFunctionExpression: 'ArrowFunctionExpression', 151 | AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7. 152 | BlockStatement: 'BlockStatement', 153 | BinaryExpression: 'BinaryExpression', 154 | BreakStatement: 'BreakStatement', 155 | CallExpression: 'CallExpression', 156 | CatchClause: 'CatchClause', 157 | ClassBody: 'ClassBody', 158 | ClassDeclaration: 'ClassDeclaration', 159 | ClassExpression: 'ClassExpression', 160 | ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7. 161 | ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7. 162 | ConditionalExpression: 'ConditionalExpression', 163 | ContinueStatement: 'ContinueStatement', 164 | DebuggerStatement: 'DebuggerStatement', 165 | DirectiveStatement: 'DirectiveStatement', 166 | DoWhileStatement: 'DoWhileStatement', 167 | EmptyStatement: 'EmptyStatement', 168 | ExportAllDeclaration: 'ExportAllDeclaration', 169 | ExportDefaultDeclaration: 'ExportDefaultDeclaration', 170 | ExportNamedDeclaration: 'ExportNamedDeclaration', 171 | ExportSpecifier: 'ExportSpecifier', 172 | ExpressionStatement: 'ExpressionStatement', 173 | ForStatement: 'ForStatement', 174 | ForInStatement: 'ForInStatement', 175 | ForOfStatement: 'ForOfStatement', 176 | FunctionDeclaration: 'FunctionDeclaration', 177 | FunctionExpression: 'FunctionExpression', 178 | GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7. 179 | Identifier: 'Identifier', 180 | IfStatement: 'IfStatement', 181 | ImportDeclaration: 'ImportDeclaration', 182 | ImportDefaultSpecifier: 'ImportDefaultSpecifier', 183 | ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', 184 | ImportSpecifier: 'ImportSpecifier', 185 | Literal: 'Literal', 186 | LabeledStatement: 'LabeledStatement', 187 | LogicalExpression: 'LogicalExpression', 188 | MemberExpression: 'MemberExpression', 189 | MetaProperty: 'MetaProperty', 190 | MethodDefinition: 'MethodDefinition', 191 | ModuleSpecifier: 'ModuleSpecifier', 192 | NewExpression: 'NewExpression', 193 | ObjectExpression: 'ObjectExpression', 194 | ObjectPattern: 'ObjectPattern', 195 | Program: 'Program', 196 | Property: 'Property', 197 | RestElement: 'RestElement', 198 | ReturnStatement: 'ReturnStatement', 199 | SequenceExpression: 'SequenceExpression', 200 | SpreadElement: 'SpreadElement', 201 | Super: 'Super', 202 | SwitchStatement: 'SwitchStatement', 203 | SwitchCase: 'SwitchCase', 204 | TaggedTemplateExpression: 'TaggedTemplateExpression', 205 | TemplateElement: 'TemplateElement', 206 | TemplateLiteral: 'TemplateLiteral', 207 | ThisExpression: 'ThisExpression', 208 | ThrowStatement: 'ThrowStatement', 209 | TryStatement: 'TryStatement', 210 | UnaryExpression: 'UnaryExpression', 211 | UpdateExpression: 'UpdateExpression', 212 | VariableDeclaration: 'VariableDeclaration', 213 | VariableDeclarator: 'VariableDeclarator', 214 | WhileStatement: 'WhileStatement', 215 | WithStatement: 'WithStatement', 216 | YieldExpression: 'YieldExpression' 217 | }; 218 | 219 | VisitorKeys = { 220 | AssignmentExpression: ['left', 'right'], 221 | AssignmentPattern: ['left', 'right'], 222 | ArrayExpression: ['elements'], 223 | ArrayPattern: ['elements'], 224 | ArrowFunctionExpression: ['params', 'body'], 225 | AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7. 226 | BlockStatement: ['body'], 227 | BinaryExpression: ['left', 'right'], 228 | BreakStatement: ['label'], 229 | CallExpression: ['callee', 'arguments'], 230 | CatchClause: ['param', 'body'], 231 | ClassBody: ['body'], 232 | ClassDeclaration: ['id', 'superClass', 'body'], 233 | ClassExpression: ['id', 'superClass', 'body'], 234 | ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7. 235 | ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. 236 | ConditionalExpression: ['test', 'consequent', 'alternate'], 237 | ContinueStatement: ['label'], 238 | DebuggerStatement: [], 239 | DirectiveStatement: [], 240 | DoWhileStatement: ['body', 'test'], 241 | EmptyStatement: [], 242 | ExportAllDeclaration: ['source'], 243 | ExportDefaultDeclaration: ['declaration'], 244 | ExportNamedDeclaration: ['declaration', 'specifiers', 'source'], 245 | ExportSpecifier: ['exported', 'local'], 246 | ExpressionStatement: ['expression'], 247 | ForStatement: ['init', 'test', 'update', 'body'], 248 | ForInStatement: ['left', 'right', 'body'], 249 | ForOfStatement: ['left', 'right', 'body'], 250 | FunctionDeclaration: ['id', 'params', 'body'], 251 | FunctionExpression: ['id', 'params', 'body'], 252 | GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. 253 | Identifier: [], 254 | IfStatement: ['test', 'consequent', 'alternate'], 255 | ImportDeclaration: ['specifiers', 'source'], 256 | ImportDefaultSpecifier: ['local'], 257 | ImportNamespaceSpecifier: ['local'], 258 | ImportSpecifier: ['imported', 'local'], 259 | Literal: [], 260 | LabeledStatement: ['label', 'body'], 261 | LogicalExpression: ['left', 'right'], 262 | MemberExpression: ['object', 'property'], 263 | MetaProperty: ['meta', 'property'], 264 | MethodDefinition: ['key', 'value'], 265 | ModuleSpecifier: [], 266 | NewExpression: ['callee', 'arguments'], 267 | ObjectExpression: ['properties'], 268 | ObjectPattern: ['properties'], 269 | Program: ['body'], 270 | Property: ['key', 'value'], 271 | RestElement: [ 'argument' ], 272 | ReturnStatement: ['argument'], 273 | SequenceExpression: ['expressions'], 274 | SpreadElement: ['argument'], 275 | Super: [], 276 | SwitchStatement: ['discriminant', 'cases'], 277 | SwitchCase: ['test', 'consequent'], 278 | TaggedTemplateExpression: ['tag', 'quasi'], 279 | TemplateElement: [], 280 | TemplateLiteral: ['quasis', 'expressions'], 281 | ThisExpression: [], 282 | ThrowStatement: ['argument'], 283 | TryStatement: ['block', 'handler', 'finalizer'], 284 | UnaryExpression: ['argument'], 285 | UpdateExpression: ['argument'], 286 | VariableDeclaration: ['declarations'], 287 | VariableDeclarator: ['id', 'init'], 288 | WhileStatement: ['test', 'body'], 289 | WithStatement: ['object', 'body'], 290 | YieldExpression: ['argument'] 291 | }; 292 | 293 | // unique id 294 | BREAK = {}; 295 | SKIP = {}; 296 | REMOVE = {}; 297 | 298 | VisitorOption = { 299 | Break: BREAK, 300 | Skip: SKIP, 301 | Remove: REMOVE 302 | }; 303 | 304 | function Reference(parent, key) { 305 | this.parent = parent; 306 | this.key = key; 307 | } 308 | 309 | Reference.prototype.replace = function replace(node) { 310 | this.parent[this.key] = node; 311 | }; 312 | 313 | Reference.prototype.remove = function remove() { 314 | if (isArray(this.parent)) { 315 | this.parent.splice(this.key, 1); 316 | return true; 317 | } else { 318 | this.replace(null); 319 | return false; 320 | } 321 | }; 322 | 323 | function Element(node, path, wrap, ref) { 324 | this.node = node; 325 | this.path = path; 326 | this.wrap = wrap; 327 | this.ref = ref; 328 | } 329 | 330 | function Controller() { } 331 | 332 | // API: 333 | // return property path array from root to current node 334 | Controller.prototype.path = function path() { 335 | var i, iz, j, jz, result, element; 336 | 337 | function addToPath(result, path) { 338 | if (isArray(path)) { 339 | for (j = 0, jz = path.length; j < jz; ++j) { 340 | result.push(path[j]); 341 | } 342 | } else { 343 | result.push(path); 344 | } 345 | } 346 | 347 | // root node 348 | if (!this.__current.path) { 349 | return null; 350 | } 351 | 352 | // first node is sentinel, second node is root element 353 | result = []; 354 | for (i = 2, iz = this.__leavelist.length; i < iz; ++i) { 355 | element = this.__leavelist[i]; 356 | addToPath(result, element.path); 357 | } 358 | addToPath(result, this.__current.path); 359 | return result; 360 | }; 361 | 362 | // API: 363 | // return type of current node 364 | Controller.prototype.type = function () { 365 | var node = this.current(); 366 | return node.type || this.__current.wrap; 367 | }; 368 | 369 | // API: 370 | // return array of parent elements 371 | Controller.prototype.parents = function parents() { 372 | var i, iz, result; 373 | 374 | // first node is sentinel 375 | result = []; 376 | for (i = 1, iz = this.__leavelist.length; i < iz; ++i) { 377 | result.push(this.__leavelist[i].node); 378 | } 379 | 380 | return result; 381 | }; 382 | 383 | // API: 384 | // return current node 385 | Controller.prototype.current = function current() { 386 | return this.__current.node; 387 | }; 388 | 389 | Controller.prototype.__execute = function __execute(callback, element) { 390 | var previous, result; 391 | 392 | result = undefined; 393 | 394 | previous = this.__current; 395 | this.__current = element; 396 | this.__state = null; 397 | if (callback) { 398 | result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node); 399 | } 400 | this.__current = previous; 401 | 402 | return result; 403 | }; 404 | 405 | // API: 406 | // notify control skip / break 407 | Controller.prototype.notify = function notify(flag) { 408 | this.__state = flag; 409 | }; 410 | 411 | // API: 412 | // skip child nodes of current node 413 | Controller.prototype.skip = function () { 414 | this.notify(SKIP); 415 | }; 416 | 417 | // API: 418 | // break traversals 419 | Controller.prototype['break'] = function () { 420 | this.notify(BREAK); 421 | }; 422 | 423 | // API: 424 | // remove node 425 | Controller.prototype.remove = function () { 426 | this.notify(REMOVE); 427 | }; 428 | 429 | Controller.prototype.__initialize = function(root, visitor) { 430 | this.visitor = visitor; 431 | this.root = root; 432 | this.__worklist = []; 433 | this.__leavelist = []; 434 | this.__current = null; 435 | this.__state = null; 436 | this.__fallback = null; 437 | if (visitor.fallback === 'iteration') { 438 | this.__fallback = objectKeys; 439 | } else if (typeof visitor.fallback === 'function') { 440 | this.__fallback = visitor.fallback; 441 | } 442 | 443 | this.__keys = VisitorKeys; 444 | if (visitor.keys) { 445 | this.__keys = extend(objectCreate(this.__keys), visitor.keys); 446 | } 447 | }; 448 | 449 | function isNode(node) { 450 | if (node == null) { 451 | return false; 452 | } 453 | return typeof node === 'object' && typeof node.type === 'string'; 454 | } 455 | 456 | function isProperty(nodeType, key) { 457 | return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key; 458 | } 459 | 460 | Controller.prototype.traverse = function traverse(root, visitor) { 461 | var worklist, 462 | leavelist, 463 | element, 464 | node, 465 | nodeType, 466 | ret, 467 | key, 468 | current, 469 | current2, 470 | candidates, 471 | candidate, 472 | sentinel; 473 | 474 | this.__initialize(root, visitor); 475 | 476 | sentinel = {}; 477 | 478 | // reference 479 | worklist = this.__worklist; 480 | leavelist = this.__leavelist; 481 | 482 | // initialize 483 | worklist.push(new Element(root, null, null, null)); 484 | leavelist.push(new Element(null, null, null, null)); 485 | 486 | while (worklist.length) { 487 | element = worklist.pop(); 488 | 489 | if (element === sentinel) { 490 | element = leavelist.pop(); 491 | 492 | ret = this.__execute(visitor.leave, element); 493 | 494 | if (this.__state === BREAK || ret === BREAK) { 495 | return; 496 | } 497 | continue; 498 | } 499 | 500 | if (element.node) { 501 | 502 | ret = this.__execute(visitor.enter, element); 503 | 504 | if (this.__state === BREAK || ret === BREAK) { 505 | return; 506 | } 507 | 508 | worklist.push(sentinel); 509 | leavelist.push(element); 510 | 511 | if (this.__state === SKIP || ret === SKIP) { 512 | continue; 513 | } 514 | 515 | node = element.node; 516 | nodeType = node.type || element.wrap; 517 | candidates = this.__keys[nodeType]; 518 | if (!candidates) { 519 | if (this.__fallback) { 520 | candidates = this.__fallback(node); 521 | } else { 522 | throw new Error('Unknown node type ' + nodeType + '.'); 523 | } 524 | } 525 | 526 | current = candidates.length; 527 | while ((current -= 1) >= 0) { 528 | key = candidates[current]; 529 | candidate = node[key]; 530 | if (!candidate) { 531 | continue; 532 | } 533 | 534 | if (isArray(candidate)) { 535 | current2 = candidate.length; 536 | while ((current2 -= 1) >= 0) { 537 | if (!candidate[current2]) { 538 | continue; 539 | } 540 | if (isProperty(nodeType, candidates[current])) { 541 | element = new Element(candidate[current2], [key, current2], 'Property', null); 542 | } else if (isNode(candidate[current2])) { 543 | element = new Element(candidate[current2], [key, current2], null, null); 544 | } else { 545 | continue; 546 | } 547 | worklist.push(element); 548 | } 549 | } else if (isNode(candidate)) { 550 | worklist.push(new Element(candidate, key, null, null)); 551 | } 552 | } 553 | } 554 | } 555 | }; 556 | 557 | Controller.prototype.replace = function replace(root, visitor) { 558 | var worklist, 559 | leavelist, 560 | node, 561 | nodeType, 562 | target, 563 | element, 564 | current, 565 | current2, 566 | candidates, 567 | candidate, 568 | sentinel, 569 | outer, 570 | key; 571 | 572 | function removeElem(element) { 573 | var i, 574 | key, 575 | nextElem, 576 | parent; 577 | 578 | if (element.ref.remove()) { 579 | // When the reference is an element of an array. 580 | key = element.ref.key; 581 | parent = element.ref.parent; 582 | 583 | // If removed from array, then decrease following items' keys. 584 | i = worklist.length; 585 | while (i--) { 586 | nextElem = worklist[i]; 587 | if (nextElem.ref && nextElem.ref.parent === parent) { 588 | if (nextElem.ref.key < key) { 589 | break; 590 | } 591 | --nextElem.ref.key; 592 | } 593 | } 594 | } 595 | } 596 | 597 | this.__initialize(root, visitor); 598 | 599 | sentinel = {}; 600 | 601 | // reference 602 | worklist = this.__worklist; 603 | leavelist = this.__leavelist; 604 | 605 | // initialize 606 | outer = { 607 | root: root 608 | }; 609 | element = new Element(root, null, null, new Reference(outer, 'root')); 610 | worklist.push(element); 611 | leavelist.push(element); 612 | 613 | while (worklist.length) { 614 | element = worklist.pop(); 615 | 616 | if (element === sentinel) { 617 | element = leavelist.pop(); 618 | 619 | target = this.__execute(visitor.leave, element); 620 | 621 | // node may be replaced with null, 622 | // so distinguish between undefined and null in this place 623 | if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { 624 | // replace 625 | element.ref.replace(target); 626 | } 627 | 628 | if (this.__state === REMOVE || target === REMOVE) { 629 | removeElem(element); 630 | } 631 | 632 | if (this.__state === BREAK || target === BREAK) { 633 | return outer.root; 634 | } 635 | continue; 636 | } 637 | 638 | target = this.__execute(visitor.enter, element); 639 | 640 | // node may be replaced with null, 641 | // so distinguish between undefined and null in this place 642 | if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { 643 | // replace 644 | element.ref.replace(target); 645 | element.node = target; 646 | } 647 | 648 | if (this.__state === REMOVE || target === REMOVE) { 649 | removeElem(element); 650 | element.node = null; 651 | } 652 | 653 | if (this.__state === BREAK || target === BREAK) { 654 | return outer.root; 655 | } 656 | 657 | // node may be null 658 | node = element.node; 659 | if (!node) { 660 | continue; 661 | } 662 | 663 | worklist.push(sentinel); 664 | leavelist.push(element); 665 | 666 | if (this.__state === SKIP || target === SKIP) { 667 | continue; 668 | } 669 | 670 | nodeType = node.type || element.wrap; 671 | candidates = this.__keys[nodeType]; 672 | if (!candidates) { 673 | if (this.__fallback) { 674 | candidates = this.__fallback(node); 675 | } else { 676 | throw new Error('Unknown node type ' + nodeType + '.'); 677 | } 678 | } 679 | 680 | current = candidates.length; 681 | while ((current -= 1) >= 0) { 682 | key = candidates[current]; 683 | candidate = node[key]; 684 | if (!candidate) { 685 | continue; 686 | } 687 | 688 | if (isArray(candidate)) { 689 | current2 = candidate.length; 690 | while ((current2 -= 1) >= 0) { 691 | if (!candidate[current2]) { 692 | continue; 693 | } 694 | if (isProperty(nodeType, candidates[current])) { 695 | element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2)); 696 | } else if (isNode(candidate[current2])) { 697 | element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2)); 698 | } else { 699 | continue; 700 | } 701 | worklist.push(element); 702 | } 703 | } else if (isNode(candidate)) { 704 | worklist.push(new Element(candidate, key, null, new Reference(node, key))); 705 | } 706 | } 707 | } 708 | 709 | return outer.root; 710 | }; 711 | 712 | function traverse(root, visitor) { 713 | var controller = new Controller(); 714 | return controller.traverse(root, visitor); 715 | } 716 | 717 | function replace(root, visitor) { 718 | var controller = new Controller(); 719 | return controller.replace(root, visitor); 720 | } 721 | 722 | function extendCommentRange(comment, tokens) { 723 | var target; 724 | 725 | target = upperBound(tokens, function search(token) { 726 | return token.range[0] > comment.range[0]; 727 | }); 728 | 729 | comment.extendedRange = [comment.range[0], comment.range[1]]; 730 | 731 | if (target !== tokens.length) { 732 | comment.extendedRange[1] = tokens[target].range[0]; 733 | } 734 | 735 | target -= 1; 736 | if (target >= 0) { 737 | comment.extendedRange[0] = tokens[target].range[1]; 738 | } 739 | 740 | return comment; 741 | } 742 | 743 | function attachComments(tree, providedComments, tokens) { 744 | // At first, we should calculate extended comment ranges. 745 | var comments = [], comment, len, i, cursor; 746 | 747 | if (!tree.range) { 748 | throw new Error('attachComments needs range information'); 749 | } 750 | 751 | // tokens array is empty, we attach comments to tree as 'leadingComments' 752 | if (!tokens.length) { 753 | if (providedComments.length) { 754 | for (i = 0, len = providedComments.length; i < len; i += 1) { 755 | comment = deepCopy(providedComments[i]); 756 | comment.extendedRange = [0, tree.range[0]]; 757 | comments.push(comment); 758 | } 759 | tree.leadingComments = comments; 760 | } 761 | return tree; 762 | } 763 | 764 | for (i = 0, len = providedComments.length; i < len; i += 1) { 765 | comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens)); 766 | } 767 | 768 | // This is based on John Freeman's implementation. 769 | cursor = 0; 770 | traverse(tree, { 771 | enter: function (node) { 772 | var comment; 773 | 774 | while (cursor < comments.length) { 775 | comment = comments[cursor]; 776 | if (comment.extendedRange[1] > node.range[0]) { 777 | break; 778 | } 779 | 780 | if (comment.extendedRange[1] === node.range[0]) { 781 | if (!node.leadingComments) { 782 | node.leadingComments = []; 783 | } 784 | node.leadingComments.push(comment); 785 | comments.splice(cursor, 1); 786 | } else { 787 | cursor += 1; 788 | } 789 | } 790 | 791 | // already out of owned node 792 | if (cursor === comments.length) { 793 | return VisitorOption.Break; 794 | } 795 | 796 | if (comments[cursor].extendedRange[0] > node.range[1]) { 797 | return VisitorOption.Skip; 798 | } 799 | } 800 | }); 801 | 802 | cursor = 0; 803 | traverse(tree, { 804 | leave: function (node) { 805 | var comment; 806 | 807 | while (cursor < comments.length) { 808 | comment = comments[cursor]; 809 | if (node.range[1] < comment.extendedRange[0]) { 810 | break; 811 | } 812 | 813 | if (node.range[1] === comment.extendedRange[0]) { 814 | if (!node.trailingComments) { 815 | node.trailingComments = []; 816 | } 817 | node.trailingComments.push(comment); 818 | comments.splice(cursor, 1); 819 | } else { 820 | cursor += 1; 821 | } 822 | } 823 | 824 | // already out of owned node 825 | if (cursor === comments.length) { 826 | return VisitorOption.Break; 827 | } 828 | 829 | if (comments[cursor].extendedRange[0] > node.range[1]) { 830 | return VisitorOption.Skip; 831 | } 832 | } 833 | }); 834 | 835 | return tree; 836 | } 837 | 838 | exports.version = require('./package.json').version; 839 | exports.Syntax = Syntax; 840 | exports.traverse = traverse; 841 | exports.replace = replace; 842 | exports.attachComments = attachComments; 843 | exports.VisitorKeys = VisitorKeys; 844 | exports.VisitorOption = VisitorOption; 845 | exports.Controller = Controller; 846 | exports.cloneEnvironment = function () { return clone({}); }; 847 | 848 | return exports; 849 | }(exports)); 850 | /* vim: set sw=4 ts=4 et tw=80 : */ 851 | 852 | },{"./package.json":2}],2:[function(require,module,exports){ 853 | module.exports={ 854 | "name": "estraverse", 855 | "description": "ECMAScript JS AST traversal functions", 856 | "homepage": "https://github.com/estools/estraverse", 857 | "main": "estraverse.js", 858 | "version": "4.2.0", 859 | "engines": { 860 | "node": ">=0.10.0" 861 | }, 862 | "maintainers": [ 863 | { 864 | "name": "Yusuke Suzuki", 865 | "email": "utatane.tea@gmail.com", 866 | "web": "http://github.com/Constellation" 867 | } 868 | ], 869 | "repository": { 870 | "type": "git", 871 | "url": "http://github.com/estools/estraverse.git" 872 | }, 873 | "devDependencies": { 874 | "babel-preset-es2015": "^6.3.13", 875 | "babel-register": "^6.3.13", 876 | "chai": "^2.1.1", 877 | "espree": "^1.11.0", 878 | "gulp": "^3.8.10", 879 | "gulp-bump": "^0.2.2", 880 | "gulp-filter": "^2.0.0", 881 | "gulp-git": "^1.0.1", 882 | "gulp-tag-version": "^1.2.1", 883 | "jshint": "^2.5.6", 884 | "mocha": "^2.1.0" 885 | }, 886 | "license": "BSD-2-Clause", 887 | "scripts": { 888 | "test": "npm run-script lint && npm run-script unit-test", 889 | "lint": "jshint estraverse.js", 890 | "unit-test": "mocha --compilers js:babel-register" 891 | } 892 | } 893 | 894 | },{}]},{},[1])(1) 895 | }); -------------------------------------------------------------------------------- /modules/config/filetypes: -------------------------------------------------------------------------------- 1 | * default=edit view,edit=editor 2 | / default=view view=files edit=editor 3 | txt view,edit=editor 4 | html edit=editor 5 | js edit=editor 6 | css edit=editor 7 | odt view,edit=writer 8 | laskyapkg default=install install=installer -------------------------------------------------------------------------------- /modules/core/core.js: -------------------------------------------------------------------------------- 1 | /* This file is licensed under the Affero General Public License. */ 2 | /*global jsyaml, cherow, estraverse, Promise, io, File, XDomainRequest, JSZip, getFile: true, putFile: true, prepareFile: true, prepareString: true, prepareUrl: true, startTransaction: true, endTransaction: true, deepEquals: true */ 3 | 4 | var core_version = 3; 5 | 6 | var settings = {}; 7 | 8 | var inTransaction = false; 9 | var transaction = null; 10 | var transactionDate; 11 | var transactionIdPrefix; 12 | var filesToPut; 13 | window.startTransaction = function() { 14 | inTransaction = true; 15 | if(!transaction) { 16 | transaction = {}; 17 | transactionDate = new Date(); 18 | transactionIdPrefix = Math.round(Math.random() * Date.now()).toString(16); 19 | filesToPut = 0; 20 | } 21 | }; 22 | window.endTransaction = function() { 23 | console.log(inTransaction, filesToPut, transaction); 24 | if(!transaction) return; 25 | inTransaction = false; 26 | if(filesToPut) return; 27 | var _transaction = transaction; 28 | transaction = null; 29 | var transactions = {}; 30 | var _transactionPaths = Object.keys(_transaction); 31 | _transactionPaths.forEach(function(path) { 32 | var transactionId = 33 | transactionIdPrefix + 34 | (_transaction[path][1].S3Prefix ? ':' + _transaction[path][1].S3Prefix : '') + 35 | (_transaction[path][1].transactionId ? ':' + _transaction[path][1].transactionId : ''); 36 | _transaction[path][1].fullTransactionId = transactionId; 37 | if(!transactions[transactionId]) { 38 | transactions[transactionId] = 0; 39 | } 40 | transactions[transactionId]++; 41 | }); 42 | Object.keys(transactions).forEach(function(transactionId) { 43 | if(transactions[transactionId] > 1) { 44 | var req = new XMLHttpRequest(); 45 | req.open('POST', '/transaction/add'); 46 | req.setRequestHeader('Content-Type', 'application/json'); 47 | req.send(JSON.stringify({ 48 | transactionId: transactionId, 49 | messageCount: transactions[transactionId] 50 | })); 51 | } 52 | }); 53 | var i = 0, len = _transactionPaths.length; 54 | const chunkSize = 50; 55 | (function transactionChunk() { 56 | var finished = 0; 57 | for(; i < len; i++) { 58 | let path = _transactionPaths[i]; 59 | _transaction[path][1].finishingTransaction = true; 60 | _transaction[path][1].messageCount = transactions[_transaction[path][1].fullTransactionId]; 61 | if(/\/\.history\//.test(_transaction[path][0])) { 62 | window.getFileCache[_transaction[path][0]] = {codec: _transaction[path][1].codec, contents: _transaction[path][2], ts: Date.now()}; 63 | } 64 | let callback = _transaction[path][4]; 65 | _transaction[path][4] = function(err) { // jshint ignore:line 66 | if(err && err.status === 403 && !_transaction[path][1].S3Prefix) { 67 | setTimeout(function() { 68 | putFile.apply(window, _transaction[path]); 69 | }, 5000); 70 | relogin(); 71 | return; 72 | } 73 | if(!err && ++finished === chunkSize) { 74 | transactionChunk(); 75 | } 76 | callback.apply(this, arguments); 77 | }; 78 | putFile.apply(window, _transaction[path]); 79 | if((i + 1) % chunkSize === 0) { 80 | i++; 81 | break; 82 | } 83 | } 84 | })(); 85 | }; 86 | 87 | var sjcl = parent.sjcl; 88 | var pako = parent.pako; 89 | var private_key = parent.private_key; 90 | var private_hmac = parent.private_hmac; 91 | var files_hmac = parent.files_hmac; 92 | var password = parent.password; 93 | var files_key = parent.files_key; 94 | var account_info = parent.account_info; 95 | var S3Prefix = parent.S3Prefix; 96 | 97 | var arrayBuffer_fromBits = sjcl.codec.arrayBuffer.fromBits; 98 | sjcl.codec.arrayBuffer.fromBits = function(bits, padding) { 99 | return arrayBuffer_fromBits(bits, !!padding); // Default to no padding. 100 | }; 101 | 102 | var codec = {}; 103 | 104 | codec.raw = codec.arrayBuffer = { 105 | fromAB: function(ab) { return ab; }, 106 | toAB: function(ab) { return ab; } 107 | }; 108 | 109 | if(!window.TextDecoder) { 110 | window.TextDecoder = function() {}; 111 | TextDecoder.prototype.decode = function(dataview) { return sjcl.codec.utf8String.fromBits(sjcl.codec.arrayBuffer.toBits(dataview.buffer)); }; 112 | } 113 | if(!window.TextEncoder) { 114 | window.TextEncoder = function() {}; 115 | TextEncoder.prototype.encode = function(str) { return {buffer: sjcl.codec.arrayBuffer.fromBits(sjcl.codec.utf8String.toBits(str))}; }; 116 | } 117 | var decoder = new TextDecoder('utf8'); 118 | var encoder = new TextEncoder('utf8'); 119 | codec.utf8String = { 120 | fromAB: function(ab) { return decoder.decode(new DataView(ab)); }, 121 | toAB: function(string) { return encoder.encode(string).buffer; } 122 | }; 123 | 124 | codec.json = { 125 | toAB: function(obj) { return codec.utf8String.toAB(JSON.stringify(obj)); } 126 | }; 127 | codec.prettyjson = { 128 | toAB: function(obj) { return codec.utf8String.toAB(JSON.stringify(obj, null, '\t')); } 129 | }; 130 | codec.json.fromAB = codec.prettyjson.fromAB = function(ab) { return JSON.parse(codec.utf8String.fromAB(ab)); }; 131 | 132 | var currentFilename; 133 | codec.dir = codec.yaml = { 134 | fromAB: function(ab) { return jsyaml.safeLoad(codec.utf8String.fromAB(ab), {filename: currentFilename}); }, 135 | toAB: function(obj) { return codec.utf8String.toAB(jsyaml.safeDump(obj, {flowLevel: 1})); } 136 | }; 137 | codec.dir.fromAB = function(ab) { 138 | var utf8 = codec.utf8String.fromAB(ab); 139 | if(utf8 !== '{}' && !/^.+: {.*}$/m.test(utf8)) { 140 | var obj = {}; 141 | utf8.split('\n').forEach(function(line) { 142 | if(line) obj[line] = {}; 143 | }); 144 | return obj; 145 | } 146 | return jsyaml.safeLoad(utf8, {filename: currentFilename}); 147 | }; 148 | 149 | codec.base64 = { 150 | fromAB: function(ab) { 151 | var bytes = new Uint8Array(ab); 152 | var len = bytes.byteLength; 153 | var binary = new Array(len); 154 | for(var i = 0; i < len; i++) { 155 | binary[i] = String.fromCharCode(bytes[i]); 156 | } 157 | return btoa(binary.join('')); 158 | }, 159 | toAB: function(string) { 160 | var binary = atob(string); 161 | var len = binary.length; 162 | var bytes = new Uint8Array(len); 163 | for(var i = 0; i < len; i++) { 164 | bytes[i] = binary.charCodeAt(i); 165 | } 166 | return bytes.buffer; 167 | } 168 | }; 169 | 170 | var subtle = window.crypto.subtle || window.crypto.webkitSubtle; 171 | var subtleKeys = {}; 172 | function encrypt(key, plaintext, params, callback) { 173 | try { 174 | if(!subtleKeys[key]) { 175 | subtleKeys[key] = subtle.importKey('raw', sjcl.codec.arrayBuffer.fromBits(key), {name: 'AES-CTR'}, false, ['encrypt', 'decrypt']); 176 | } 177 | subtleKeys[key].then(function(_key) { 178 | var iv = sjcl.codec.arrayBuffer.fromBits(sjcl.random.randomWords(4,0)); 179 | var ivLength = iv.byteLength; 180 | var plaintextLength = plaintext.byteLength; 181 | var L = _computeL(plaintextLength, ivLength); 182 | var ctr = new Uint8Array(16); 183 | ctr[0] = L - 1; 184 | ctr.set(new Uint8Array(iv, 0, 15 - L), 1); 185 | var ks = 128; 186 | var adata = codec.json.toAB(params.adata); 187 | var ts = 64; 188 | var tag = _computeTag(key, plaintext, iv, adata, ts, plaintextLength, L); 189 | return Promise.all([ 190 | subtle.encrypt({ 191 | name: 'AES-CTR', 192 | counter: ctr, 193 | length: ks, 194 | }, _key, sjcl.codec.arrayBuffer.fromBits(tag)), 195 | subtle.encrypt({ 196 | name: 'AES-CTR', 197 | counter: (ctr[15] = 1, ctr), 198 | length: ks, 199 | }, _key, plaintext) 200 | ]).then(function(result) { 201 | var tag = result[0]; 202 | var ct = result[1]; 203 | var concat = new Uint8Array(ct.byteLength + tag.byteLength); 204 | concat.set(new Uint8Array(ct), 0); 205 | concat.set(new Uint8Array(tag), ct.byteLength); 206 | return JSON.stringify({ 207 | adata: codec.base64.fromAB(adata), 208 | cipher: 'aes', 209 | ct: codec.base64.fromAB(concat), 210 | iter: params.iter != null ? params.iter : 1000, 211 | salt: params.salt, 212 | iv: codec.base64.fromAB(iv), 213 | ks: ks, 214 | ts: ts, 215 | v: 1 216 | }); 217 | }); 218 | }).then(callback, error); 219 | } catch(e) { 220 | error(e); 221 | } 222 | function error() { 223 | // Web Crypto or the algorithm may be unsupported, try sjcl. 224 | params.adata = params.adata ? sjcl.codec.arrayBuffer.toBits(codec.json.toAB(params.adata)) : []; 225 | callback(sjcl.encrypt(key, sjcl.codec.arrayBuffer.toBits(plaintext), params)); 226 | } 227 | } 228 | 229 | function decrypt(key, str, outparams, callback) { 230 | try { 231 | if(!subtleKeys[key]) { 232 | subtleKeys[key] = subtle.importKey('raw', sjcl.codec.arrayBuffer.fromBits(key), {name: 'AES-CTR'}, false, ['encrypt', 'decrypt']); 233 | } 234 | subtleKeys[key].then(function(_key) { 235 | var obj = JSON.parse(str); 236 | var ct = codec.base64.toAB(obj.ct); 237 | var iv = codec.base64.toAB(obj.iv); 238 | var ivLength = iv.byteLength; 239 | var ts = obj.ts; 240 | var plaintextLength = ct.byteLength - ts / 8; 241 | var L = _computeL(plaintextLength, ivLength); 242 | var ctr = new Uint8Array(16); 243 | ctr[0] = L - 1; 244 | ctr.set(new Uint8Array(iv, 0, 15 - L), 1); 245 | var ks = obj.ks; 246 | var adata = codec.base64.toAB(obj.adata); 247 | return Promise.all([ 248 | subtle.decrypt({ 249 | name: 'AES-CTR', 250 | counter: ctr, 251 | length: ks, 252 | }, _key, new DataView(ct, plaintextLength)), 253 | subtle.decrypt({ 254 | name: 'AES-CTR', 255 | counter: (ctr[15] = 1, ctr), 256 | length: ks, 257 | }, _key, new DataView(ct, 0, plaintextLength)) 258 | ]).then(function(result) { 259 | var tag = sjcl.codec.arrayBuffer.toBits(result[0]); 260 | var plaintext = result[1]; 261 | var tag2 = _computeTag(key, plaintext, iv, adata, ts, plaintextLength, L); 262 | if(sjcl.bitArray.equal(tag, tag2)) { 263 | return cont(); 264 | } 265 | if(plaintextLength % 16 === 0) { 266 | var paddedPlaintext = new Uint8Array(plaintextLength + 16); 267 | paddedPlaintext.set(new Uint8Array(plaintext), 0); 268 | var tag3 = _computeTag(key, paddedPlaintext.buffer, iv, adata, ts, plaintextLength, L); 269 | if(sjcl.bitArray.equal(tag, tag3)) { 270 | return cont(); 271 | } 272 | } 273 | throw new sjcl.exception.corrupt("ccm: tag doesn't match"); 274 | function cont() { 275 | if(obj.adata) outparams.adata = codec.json.fromAB(codec.base64.toAB(obj.adata)); 276 | return plaintext; 277 | } 278 | }); 279 | }).then(callback, error); 280 | } catch(e) { 281 | error(e); 282 | } 283 | function error(e) { 284 | // Web Crypto or the algorithm may be unsupported, try sjcl. 285 | var decrypted, error; 286 | try { 287 | decrypted = sjcl.decrypt(key, str, {raw: 1}, outparams); 288 | } catch(e2) { 289 | error = e; 290 | } 291 | if(error) { 292 | callback(null, error); 293 | } else { 294 | outparams.adata = outparams.adata.length ? codec.json.fromAB(sjcl.codec.arrayBuffer.fromBits(outparams.adata)) : undefined; 295 | callback(sjcl.codec.arrayBuffer.fromBits(decrypted)); 296 | } 297 | } 298 | } 299 | 300 | function _computeL(plaintextLength, ivLength) { 301 | var L; 302 | for(L = 2; L < 4 && plaintextLength >>> 8 * L; L++) {} 303 | if(L < 15 - ivLength) { 304 | L = 15 - ivLength; 305 | } 306 | return L; 307 | } 308 | 309 | function _computeTag(key, plaintext, iv, adata, ts, plaintextLength, L) { 310 | var _sjcl_computeTag = sjcl.arrayBuffer.ccm.r; // Minified name. 311 | if(plaintextLength % 16 !== 0) { 312 | var paddedPlaintext = new Uint8Array(plaintextLength + (16 - plaintextLength % 16)); 313 | paddedPlaintext.set(new Uint8Array(plaintext), 0); 314 | plaintext = paddedPlaintext.buffer; 315 | } 316 | var tag = _sjcl_computeTag(new sjcl.cipher.aes(key), plaintext, sjcl.codec.arrayBuffer.toBits(iv.slice(0, 15 - L)), sjcl.codec.arrayBuffer.toBits(adata), ts / 8, plaintextLength, L); 317 | return tag; 318 | } 319 | 320 | window.getFileCache = {}; 321 | window.getRequestCache = {}; 322 | window.getFile = function(file, options, callback) { 323 | if(typeof options === 'function' || options === undefined) { 324 | callback = options; 325 | options = {}; 326 | } 327 | if(callback === undefined) { 328 | callback = function() {}; 329 | } 330 | const fromlive = file.startsWith('/Core/') || file.startsWith('/Apps/firetext/') || file.startsWith('/Apps/strut/'); 331 | 332 | if((options.S3Prefix && options.S3Prefix !== window.S3Prefix) || options.object) { 333 | options.cache = false; 334 | } 335 | if(handleFromCache()) return; 336 | function handleFromCache() { 337 | if(options.cache === false) return; 338 | var cache = window.getFileCache[file]; 339 | if(cache) {// && Date.now() - cache.ts < 2000) { 340 | if((options.codec || 'utf8String') === (cache.codec || 'utf8String')) { 341 | callback(cache.contents); 342 | } else { 343 | currentFilename = file; 344 | var decrypted; 345 | try { 346 | decrypted = codec[options.codec || 'utf8String'].fromAB(codec[cache.codec || 'utf8String'].toAB(cache.contents)); 347 | } catch(e) { 348 | callback(null, {status: 0, statusText: e.message}); 349 | return true; 350 | } 351 | callback(decrypted); 352 | } 353 | return true; 354 | } 355 | } 356 | 357 | var requestCache = window.getRequestCache[file]; 358 | var req; 359 | if(requestCache) { 360 | req = requestCache; 361 | cb(); // For some reason browsers slightly delay firing readystatechange, so we check if it's already finished. 362 | } else { 363 | req = window.getRequestCache[file] = new XMLHttpRequest(); 364 | console.log('GET', file); 365 | } 366 | req.addEventListener('readystatechange', cb); 367 | if(!requestCache) { 368 | req.open('GET', fromlive ? '/v2/live' + file : getObjectUrl('GET', file, options)); 369 | if (fromlive) req.responseType = 'arraybuffer'; 370 | if(options.S3Prefix) { req.setRequestHeader('X-S3Prefix', options.S3Prefix); } 371 | req.send(null); 372 | } 373 | 374 | function cb() { 375 | if(req.readyState === 4) { 376 | window.getRequestCache[file] = null; 377 | if(handleFromCache()) return; // We might've PUT a newer version by now. 378 | if(req.status === 200) { 379 | currentFilename = file; 380 | var outparams = {}; 381 | new Promise(function(resolve, reject) { 382 | if (fromlive) { 383 | resolve(req.response); 384 | return; 385 | } 386 | decrypt(options.password != null ? options.password : files_key, req.response, outparams, function(decrypted, e) { 387 | if(e) { 388 | decrypt(password, req.response, outparams, function(decrypted, e2) { 389 | if(e2) { 390 | reject(e); 391 | } else { 392 | resolve(decrypted); 393 | } 394 | }); 395 | } else { 396 | resolve(decrypted); 397 | } 398 | }); 399 | }).then(function(decrypted) { 400 | if(outparams.adata && outparams.adata.gz) { 401 | if(outparams.adata.rel) { 402 | return new Promise(function(resolve, reject) { 403 | getFile(outparams.adata.rel, {rawObjectLocation: true, codec: 'arrayBuffer'}, function(contents, e) { 404 | if(e) { 405 | reject(e); 406 | return; 407 | } 408 | resolve(pako.inflate(new Uint8Array(decrypted), {dictionary: _getRelativeDictionary(contents)}).buffer); 409 | }); 410 | }); 411 | } 412 | return pako.ungzip(new Uint8Array(decrypted)).buffer; 413 | } 414 | return decrypted; 415 | }).then(function(decompressed) { 416 | var encoded = codec[options.codec || 'utf8String'].fromAB(decompressed); // Can throw 417 | if(options.cache !== false) window.getFileCache[file] = {codec: options.codec, contents: encoded, ts: Date.now()}; 418 | callback(encoded); 419 | }).catch(function(e) { 420 | callback(null, e.status ? e : {status: 0, statusText: e.message}); 421 | }); 422 | } else if(req.status === 403 && !options.S3Prefix) { 423 | relogin(function() { 424 | getFile(file, options, callback); 425 | }); 426 | } else { 427 | console.error('GET', file); 428 | callback(null, {status: req.status, statusText: req.statusText}); 429 | } 430 | } 431 | } 432 | }; 433 | 434 | var relogging = false; 435 | function relogin(callback) { 436 | if(relogging) { 437 | if(callback) setTimeout(callback, 100); 438 | return; 439 | } 440 | var creds = JSON.parse(localStorage.creds || sessionStorage.creds || '{}'); 441 | if(window.login && creds && creds.username === window.username) { 442 | relogging = true; 443 | window.login(creds, null, function() {}, function() { 444 | relogging = false; 445 | if(callback) callback(); 446 | }, function() { 447 | window.location.reload(); 448 | }); 449 | } else { 450 | window.location.reload(); 451 | } 452 | } 453 | 454 | var fileChangeListeners = []; 455 | window.listenForFileChanges = function(path, fn) { 456 | fileChangeListeners.push({ 457 | path: path, 458 | fn: fn 459 | }); 460 | }; 461 | function notifyFileChange(path, reason) { 462 | fileChangeListeners.forEach(function(listener) { 463 | if(startsWith(listener.path, path)) listener.fn(path, reason); 464 | }); 465 | } 466 | 467 | function getObjectUrl(method, file, options) { 468 | if(options.rawObjectLocation) { 469 | return '/object/' + file; 470 | } 471 | return '/object/' + (options.object || _getObjectLocation(file)) + 472 | // Chrome, when we prefetch a file and it returns a 404, caches 473 | // that 404 even for subsequent PUT requests (crbug.com/635350). 474 | // So we add a ? to the URL to make it actually request the PUT. 475 | (method === 'PUT' ? '?' : '') + 476 | '#' + (options.S3Prefix && options.S3Prefix !== S3Prefix && !options.demo ? '1' : '0') + '.' + file; 477 | } 478 | function _getObjectLocation(file) { 479 | var is_bootstrap_file = startsWith('/key', file) || startsWith('/hmac', file); 480 | return sjcl.codec.hex.fromBits((is_bootstrap_file ? private_hmac : files_hmac).mac(file)); 481 | } 482 | function _getUploadHistory(file) { 483 | return account_info.tier >= 5 && startsWith('/Documents/', file); 484 | } 485 | window.getObjectLocation = function(file, fn) { 486 | var upload_history = _getUploadHistory(file); 487 | fn({ 488 | S3Prefix: S3Prefix, 489 | object: _getObjectLocation(file), 490 | demo: location.pathname === '/demo' ? true : undefined, 491 | hist: upload_history ? true : undefined, 492 | }); 493 | }; 494 | 495 | /* https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript/#2117523 */ 496 | window.guid = function() { 497 | return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c => 498 | (c ^ window.crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16) 499 | ); 500 | }; 501 | 502 | function extend(target) { 503 | [].slice.call(arguments, 1).forEach(function(obj) { 504 | Object.keys(obj).forEach(function(key) { 505 | var value = obj[key]; 506 | if(value != null && value.constructor === Object) { 507 | if(target.hasOwnProperty(key)) extend(target[key], value); 508 | else target[key] = value; 509 | } 510 | else if(value === undefined) delete target[key]; 511 | else target[key] = value; 512 | }); 513 | }); 514 | return target; 515 | } 516 | 517 | /* jshint ignore:start *//* jscs: disable */ 518 | function deepEquals(a, b) { 519 | if (b == a) return true; 520 | 521 | var p; 522 | for (p in a) { 523 | if (typeof (b[p]) == 'undefined') { return false; } 524 | } 525 | 526 | for (p in a) { 527 | if (a[p]) { 528 | switch (typeof (a[p])) { 529 | case 'object': 530 | if (!deepEquals(a[p], b[p])) { return false; } break; 531 | default: 532 | if (a[p] !== b[p]) { return false; } 533 | } 534 | } else { 535 | if (b[p]) 536 | return false; 537 | } 538 | } 539 | 540 | for (p in b) { 541 | if (typeof (a[p]) == 'undefined') { return false; } 542 | } 543 | 544 | return true; 545 | } 546 | /* jshint ignore:end *//* jscs: enable */ 547 | 548 | function debounce(fn, time, obj) { 549 | if(obj.timeout) clearTimeout(obj.timeout); 550 | obj.timeout = setTimeout(function() { 551 | delete obj.timeout; 552 | fn(); 553 | }, time); 554 | } 555 | var debounceObj = {}; 556 | window.putFile = function(file, options, contents, attrs, callback, progress) { 557 | if(!options.finishingTransaction) { 558 | startTransaction(); 559 | debounce(endTransaction, 100, debounceObj); 560 | } 561 | 562 | if(typeof contents === 'function' || contents === undefined) { 563 | progress = attrs; 564 | callback = contents; 565 | contents = options; 566 | options = {}; 567 | attrs = {}; 568 | } else if(typeof attrs === 'function' || attrs === undefined) { 569 | if(options && typeof options === 'object') { // If contents is an object, you also need to pass options = {codec: 'dir'}. 570 | progress = callback; 571 | callback = attrs; 572 | attrs = {}; 573 | } else if(contents && typeof contents === 'object') { // 2nd argument is not an object, assume that's the contents. 574 | progress = callback; 575 | callback = attrs; 576 | attrs = contents; 577 | contents = options; 578 | options = {}; 579 | } 580 | } 581 | if(!callback) { 582 | callback = function() {}; 583 | } 584 | 585 | var upload_history = _getUploadHistory(file); 586 | var now = attrs.edited || transactionDate || new Date(); 587 | 588 | var size, is_new_file; 589 | if(!options.finishingTransaction && file !== '/' && !(options.S3Prefix && options.S3Prefix !== window.S3Prefix)) { 590 | // Add file to parent directories 591 | var slashindex = file.lastIndexOf('/', file.length - 2) + 1; 592 | var dirname = file.substr(0, slashindex); 593 | var basename = file.substr(slashindex); 594 | filesToPut++; 595 | getFile(dirname, {codec: 'dir'}, function(dircontents) { 596 | if(!dircontents) dircontents = {}; 597 | 598 | size = basename.substr(-1) === '/' ? undefined : codec[options.codec || 'utf8String'].toAB(contents).byteLength; 599 | is_new_file = !dircontents.hasOwnProperty(basename); 600 | var newattrs = extend({}, is_new_file ? {created: now} : dircontents[basename], {edited: upload_history ? now : undefined, size: upload_history ? size : undefined}, attrs); 601 | if(!dircontents.hasOwnProperty(basename) || !deepEquals(newattrs, dircontents[basename])) { 602 | var newdircontents = extend({}, dircontents); // Don't modify getFileCache entry. 603 | newdircontents[basename] = newattrs; 604 | putFile(dirname, {codec: 'dir', transactionId: options.transactionId}, newdircontents, {edited: upload_history ? now : undefined}); 605 | } 606 | filesToPut--; 607 | if(transaction && !inTransaction && !filesToPut) window.endTransaction(); 608 | }); 609 | } 610 | 611 | if((options.S3Prefix && options.S3Prefix !== window.S3Prefix) || options.object) { 612 | options.cache = false; 613 | } 614 | if(!/\/\.history\//.test(file)) { 615 | if(options.cache !== false) window.getFileCache[file] = {codec: options.codec, contents: contents, ts: Date.now()}; 616 | } 617 | 618 | if(!/\.history\//.test(file) && upload_history && !options.finishingTransaction) { 619 | // Add to file history 620 | filesToPut++; 621 | getFile(file + '.history/', {codec: 'dir'}, function(history) { 622 | if(!history && !is_new_file) { 623 | // User switched tier 624 | filesToPut++; 625 | getFile(file, {codec: 'raw', cache: false}, function(old, err) { 626 | if(!err) { 627 | putFile(file + '.history/v0' + file.match(/(\/|\.\w+)?$/)[0], {codec: 'raw', transactionId: options.transactionId}, old, {created: undefined, edited: undefined}); 628 | } 629 | filesToPut--; 630 | if(transaction && !inTransaction && !filesToPut) window.endTransaction(); 631 | }); 632 | } 633 | 634 | var histname = 635 | file + '.history/v' + 636 | (history ? Math.max.apply(Math, Object.keys(history).map(function(name) { return parseInt(name.substr(1), 10); })) + 1 : 1) + 637 | file.match(/(\/|\.\w+)?$/)[0]; 638 | putFile(histname, {codec: options.codec, transactionId: options.transactionId, histprevname: history && file + '.history/' + Object.keys(history).pop()}, contents, {edited: now}); 639 | filesToPut--; 640 | if(transaction && !inTransaction && !filesToPut) window.endTransaction(); 641 | }); 642 | } 643 | 644 | if(!options.finishingTransaction) { 645 | transaction[file] = [file, options, contents, attrs, callback, progress]; 646 | } else { 647 | // Upload file 648 | console.log('PUT', file); 649 | contents = codec[options.codec || 'utf8String'].toAB(contents); 650 | var compressed, adata, histprevcached; 651 | if(options.histprevname && (histprevcached = window.getFileCache[options.histprevname])) { 652 | var histprevcachedbuf = codec[histprevcached.codec || 'utf8String'].toAB(histprevcached.contents); 653 | compressed = pako.deflate(new Uint8Array(contents), {dictionary: _getRelativeDictionary(histprevcachedbuf)}).buffer; 654 | if(compressed.byteLength * (histprevcached.chainLength + 1 || 2) < (histprevcached.compressionRatio || 1) * contents.byteLength) { 655 | // We try to ensure that to download a particular history 656 | // entry, you never have to download more than 2x the data 657 | // that that entry compressed on its own would take (1x for 658 | // the original version, compressed, and at most 1x for the 659 | // chain of versions relative to that). This calculation 660 | // ignores metadata, headers and latency in the 661 | // consideration. 662 | // However, we don't know what the size of the entry 663 | // compressed on its own would be, so we estimate based on 664 | // the compression ratio of the first version in the chain. 665 | (window.getFileCache[file] || {}).compressionRatio = histprevcached.compressionRatio; 666 | (window.getFileCache[file] || {}).chainLength = (histprevcached.chainLength || 0) + 1; 667 | contents = compressed; 668 | adata = {gz: 1, rel: _getObjectLocation(options.histprevname)}; 669 | } 670 | } 671 | if(options.compress !== false && !adata) { 672 | compressed = pako.gzip(new Uint8Array(contents)).buffer; 673 | if(compressed.byteLength < contents.byteLength) { 674 | (window.getFileCache[file] || {}).compressionRatio = compressed.byteLength / contents.byteLength; 675 | contents = compressed; 676 | adata = {gz: 1}; 677 | } 678 | } 679 | encrypt(options.password != null ? options.password : startsWith('/key', file) || startsWith('/hmac', file) ? private_key : files_key, contents, extend({adata: adata}, options.password != null ? {iter: options.iter, salt: options.salt} : {}), function(encrypted) { 680 | var blob = new Blob([encrypted], {type: 'binary/octet-stream'}); 681 | var req = new XMLHttpRequest(); 682 | req.open('PUT', getObjectUrl('PUT', file, options) + '?'); 683 | var transactionId = options.fullTransactionId; 684 | var messageCount = options.messageCount; 685 | if(messageCount > 1) { req.setRequestHeader('X-Transaction-Id', transactionId); } 686 | if(options.ACL) { req.setRequestHeader('X-ACL', options.ACL); } 687 | if(options.S3Prefix) { req.setRequestHeader('X-S3Prefix', options.S3Prefix); } 688 | if(options.objectAuthkey) { req.setRequestHeader('X-Object-Authentication', options.objectAuthkey); } 689 | req.addEventListener('readystatechange', function() { 690 | if(this.readyState === 4) { 691 | if(this.status === 200) { 692 | callback(); 693 | notifyFileChange(file, is_new_file ? 'created' : 'modified'); 694 | } else { 695 | console.log('error', this); 696 | callback({status: this.status, statusText: this.statusText}); 697 | } 698 | } 699 | }); 700 | req.addEventListener('progress', function(evt) { 701 | if(evt.lengthComputable) { 702 | if(progress) progress(evt.loaded, evt.total); 703 | } 704 | }); 705 | req.send(blob); 706 | }); 707 | } 708 | }; 709 | 710 | function _getRelativeDictionary(contents) { 711 | // "The current implementation of deflate will use at most the window size 712 | // minus 262 bytes of the provided dictionary." (http://zlib.net/manual.html#Advanced) 713 | // Furthermore, deflate uses the end of the dictionary, while for us, the 714 | // beginning of the previous version is more likely to be useful. 715 | 716 | // It's a shame that we can't make the window size larger than 32kB (the 717 | // size of `contents`, for example). Also, zlib/pako searches for matches in 718 | // the dictionary backwards, which is in this case of course less efficient 719 | // than searching forwards. These two things are the downside of the hack 720 | // that is using zlib with a dictionary for delta compression. 721 | return new Uint8Array(contents, 0, Math.min(contents.byteLength, (1 << 15) - 262)); 722 | } 723 | 724 | var mimeTypes = { 725 | js: 'text/javascript', 726 | css: 'text/css', 727 | png: 'image/png', 728 | svg: 'image/svg+xml', 729 | woff: 'application/font-woff', 730 | html: 'text/html', 731 | htm: 'text/html', 732 | xhtml: 'text/html' 733 | }; 734 | 735 | function startsWith(start, path) { 736 | return path.substr(0, start.length) === start; 737 | } 738 | function resolve(from, to, rootParent) { 739 | if(to === '') return from; 740 | if(to[0] === '/') return resolve(rootParent, to.substr(1), rootParent); 741 | var resolved = from.replace(/[^/]*$/, '') + to; 742 | var rParentOrCurrent = /([^./]+\/\.\.\/|\/\.(?=\/))/g; 743 | while(rParentOrCurrent.test(resolved)) resolved = resolved.replace(rParentOrCurrent, ''); 744 | if(!startsWith(dirname(rootParent), resolved)) resolved = resolve(rootParent, resolved.substr(resolved.lastIndexOf('/', resolved.length - 2) + 1), rootParent); 745 | return resolved; 746 | } 747 | function dirname(path) { 748 | return path.substr(0, path.lastIndexOf('/') + 1); 749 | } 750 | function basename(path) { 751 | return path.substr(path.lastIndexOf('/') + 1); 752 | } 753 | 754 | function parallel(fns, callback) { 755 | var todo = fns.length, 756 | results = new Array(todo), 757 | error; 758 | fns.forEach(function(fn, i) { 759 | fns[i](function(data, err) { 760 | results[i] = data; 761 | error = err; 762 | if(!--todo) { 763 | callback.apply(this, results.concat(error)); 764 | } 765 | }); 766 | }); 767 | } 768 | 769 | function getTopLocation(urlArgs) { 770 | var url = new URL(top.location); 771 | if(url.hash && urlArgs !== true) { 772 | url.hash = '#' + url.hash.slice(1).split(';').filter(function(part) { 773 | return part.split(':')[0] === urlArgs; 774 | }).map(function(part) { 775 | return part.replace(urlArgs + ':', ''); 776 | }).join(';'); 777 | } 778 | return url.href; 779 | } 780 | 781 | function isHTML(extension) { 782 | return extension === 'html' || extension === 'htm' || extension === 'xhtml'; 783 | } 784 | 785 | window.prepareFile = function(file, options, callback, progress, createObjectURL) { 786 | var _options = {}; 787 | Object.keys(options).forEach(function(key) { 788 | _options[key] = options[key]; 789 | }); 790 | var extension = file.substr(file.lastIndexOf('.') + 1); 791 | if(isHTML(extension) && options.bootstrap !== false) { 792 | _options.bootstrap = false; 793 | delete _options.apikey; 794 | delete _options.permissions; 795 | delete _options.csp; 796 | var inline_linenr = +(new Error().stack.match(/[:@](\d+)/) || [])[1] + 2; 797 | var data = [ 798 | '', 799 | '', 800 | '', 801 | ' ', 802 | '', 803 | '', 804 | '', 836 | '', 837 | '', 838 | '' 839 | ].join('\n'); 840 | callback(data); 841 | } else if(isHTML(extension) && (options.compat !== false || options.csp)) { 842 | _options.compat = false; 843 | delete _options.csp; 844 | parallel([ 845 | function(cb) { 846 | prepareString('\n\n', {rootParent: '/', compat: false, selfContained: options.selfContained}, cb, function() {}, createObjectURL); 847 | }, 848 | function(cb) { 849 | prepareFile(file, _options, cb, progress, createObjectURL); 850 | }, 851 | function(cb) { 852 | getFile(options.appData + 'localStorage', function(localStorage) { 853 | cb(localStorage || '{}'); 854 | }); 855 | } 856 | ], function(compat, c, localStorage, err) { 857 | if(err) return callback(''); 858 | callback(c 859 | .replace(/^\uFEFF/, '') 860 | .replace(/(?=' + 862 | 'document.airborn_localStorage = ' + localStorage.replace(/<\/(script)/ig, '<\\\/$1') + ';' + 863 | (options.selfContained ? [ 864 | 'document.rootParent = ' + JSON.stringify(options.rootParent) + ';', 865 | 'document.relativeParent = ' + JSON.stringify(file) + ';', 866 | 'document.filenames = {};', 867 | 'document.apikey = null;', 868 | 'document.top_location = window.location;', 869 | ].join('\n') : '') + 870 | '' + 871 | (options.csp ? '' : '') + 872 | compat 873 | ) 874 | ); 875 | }); 876 | } else if(extension === 'js') { 877 | getFile(file, function(contents, err) { 878 | if(err) return callback(''); 879 | if(options.compat !== false && !options.webworker) { 880 | var renames = {}; 881 | renames.cookie = 'airborn_cookie'; 882 | renames.location = 'airborn_location'; 883 | renames.top = 'airborn_top'; 884 | renames.parent = 'airborn_parent'; 885 | if(navigator.userAgent.match(/Safari/)) { // Safari or Chrome 886 | renames.localStorage = 'airborn_localStorage'; 887 | renames.src = 'airborn_src'; 888 | renames.href = 'airborn_href'; 889 | renames.pathname = 'airborn_pathname'; 890 | renames.source = 'airborn_source'; 891 | renames.contentWindow = 'airborn_contentWindow'; 892 | if(!navigator.userAgent.match(/Chrome/)) { // Safari 893 | renames.indexedDB = 'airborn_indexedDB'; 894 | renames.responseType = 'airborn_responseType'; 895 | renames.readyState = 'airborn_readyState'; 896 | renames.status = 'airborn_status'; 897 | renames.response = 'airborn_response'; 898 | renames.responseText = 'airborn_responseText'; 899 | renames.innerHTML = 'airborn_innerHTML'; 900 | renames.result = 'airborn_result'; 901 | } 902 | } 903 | contents = renameGlobalVariables(file, contents, renames); 904 | } 905 | if(options.webworker) { 906 | _options.relativeParent = file; 907 | _options.rootParent = file.match(/\/Apps\/.+?\//)[0]; 908 | prepareString(contents, _options, callback, progress, createObjectURL); 909 | return; 910 | } 911 | callback(contents); 912 | }); 913 | } else { 914 | getFile(file, function(contents, err) { 915 | if(err) return callback(''); 916 | _options.rootParent = _options.rootParent || file; 917 | _options.relativeParent = file; 918 | delete _options.bootstrap; 919 | delete _options.compat; 920 | prepareString(contents, _options, callback, progress, createObjectURL); 921 | }); 922 | } 923 | }; 924 | 925 | window.prepareString = function(contents, options, callback, progress, createObjectURL) { 926 | var i = 0, 927 | match, matches = [], 928 | rURL, 929 | rSchema = /^(?!airbornstorage)[a-z]+:/i, 930 | filesDownloaded = 0; 931 | if(options.webworker) { 932 | var rImportScripts = /importScripts\s*\([\s\S]*?\)/; 933 | while((match = contents.substr(i).match(rImportScripts))) { 934 | var j = 0, 935 | subject = match[0]; 936 | rURL = /((["']))(.*?)(\2)()/; 937 | i += match.index; 938 | match.pos = i; 939 | while((match = subject.substr(j).match(rURL))) { 940 | if(!rSchema.test(match[3])) { 941 | matches.push(match); 942 | } 943 | 944 | j += match.index; 945 | match.pos = i + j; 946 | j++; 947 | } 948 | i++; 949 | } 950 | } else { 951 | rURL = /((?:\s(?:src|(?:xlink:)?href|icon|data)\s*=|[:,\s]url\()\s*(["']?))(.*?)(?=["') >])(\2\s*\)?)/; 952 | while((match = contents.substr(i).match(rURL))) { 953 | if(!rSchema.test(match[3])) { 954 | matches.push(match); 955 | } 956 | 957 | i += match.index; 958 | match.pos = i; 959 | i++; 960 | } 961 | } 962 | 963 | if(matches.length) { 964 | matches.forEach(function(match) { // We don't process matches immediately for when getFile calls callback immediately. 965 | prepareUrl(match[3], options, function(data, err) { 966 | if(!err) match[5] = data; 967 | filesDownloaded++; 968 | updateProgress(); 969 | if(filesDownloaded === matches.length) { 970 | matches.reverse().forEach(function(match) { 971 | if(match[5]) contents = contents.substr(0, match.pos + match[1].length) + match[5] + contents.substr(match.pos + match[0].length - match[4].length); 972 | }); 973 | callback(contents); 974 | } 975 | }, function(done, total) { 976 | match.progressDone = done; 977 | match.progressTotal = total; 978 | updateProgress(); 979 | }, createObjectURL); 980 | }); 981 | } else { 982 | callback(contents); 983 | } 984 | function updateProgress() { 985 | if(!progress) return; 986 | var done = filesDownloaded; 987 | var total = matches.length; 988 | matches.forEach(function(match) { 989 | if('progressDone' in match) { 990 | done += match.progressDone; 991 | total += match.progressTotal; 992 | } 993 | }); 994 | progress(done, total); 995 | } 996 | }; 997 | 998 | var rArgs = /[?#].*$/; 999 | var rHMAC = /([?&#])hmac=(\w+)&?/; 1000 | window.prepareUrl = function(url, options, callback, progress, createObjectURL) { 1001 | var args = (url.match(rArgs) || [''])[0]; 1002 | url = url.replace(rArgs, ''); 1003 | if(startsWith('//', url)) { 1004 | callback('https:' + url + args); 1005 | return; 1006 | } 1007 | if(url === '/') { 1008 | url = ''; // resolve to relativeParent 1009 | } 1010 | var path; 1011 | if(startsWith('airbornstorage:', url)) { 1012 | /* Note: we specifically calculate the HMAC including the 1013 | * "airbornstorage:" bit to make sure that this HMAC can't be 1014 | * observed on the network. 1015 | */ 1016 | if(_getObjectLocation(url) !== (args.match(rHMAC) || [])[2]) { 1017 | console.warn('Access denied: HMAC for airbornstorage: URL is incorrect:', url + args); 1018 | callback(url + args); 1019 | return; 1020 | } 1021 | path = url.substr(15); 1022 | } else { 1023 | path = resolve(options.relativeParent, url, options.rootParent); 1024 | } 1025 | if(args && path === options.relativeParent) { 1026 | callback(args); 1027 | return; 1028 | } 1029 | var extension = path.substr(path.lastIndexOf('.') + 1); 1030 | var _options = {}; 1031 | Object.keys(options).forEach(function(key) { 1032 | _options[key.replace(/^_/, '')] = options[key]; 1033 | }); 1034 | if(isHTML(extension) || extension === 'css' || extension === 'js' || extension === 'svg') prepareFile(path, _options, cb, progress, createObjectURL); 1035 | else getFile(path, {codec: 'arrayBuffer'}, cb); 1036 | 1037 | function cb(c, err) { 1038 | var data; 1039 | if(!err) { 1040 | if(options.selfContained || (navigator.userAgent.match(/Firefox\/(\d+)/) || [])[1] >= 51 || (navigator.userAgent.match(/Safari/) && !navigator.userAgent.match(/Chrome/))) { 1041 | if(extension === 'js') data = ',' + encodeURIComponent(c + '\n//# sourceURL=') + path; 1042 | else if(extension === 'css') data = ',' + encodeURIComponent(c + '\n/*# sourceURL=' + path + ' */'); 1043 | else if(isHTML(extension)) data = ',' + encodeURIComponent(c + '\n'); 1044 | else if(typeof c === 'string') data = ',' + encodeURIComponent(c); 1045 | else data = ';base64,' + codec.base64.fromAB(c); 1046 | data = 'data:' + mimeTypes[extension] + ';filename=' + encodeURIComponent(path) + ';charset=utf-8' + data; 1047 | callback(data.replace(/'/g, '%27')); 1048 | } else { 1049 | if(extension === 'js') data = c + '\n//# sourceURL=' + path; 1050 | else if(extension === 'css') data = c + '\n/*# sourceURL=' + path + ' */'; 1051 | else if(isHTML(extension)) data = c + '\n'; 1052 | else data = c; // string or arrayBuffer 1053 | createObjectURL({data: data, type: mimeTypes[extension], name: path + args}, callback); 1054 | } 1055 | } else { 1056 | callback(null, err); 1057 | } 1058 | } 1059 | }; 1060 | 1061 | getFile('/Core/lib/yaml/js-yaml.js', eval); 1062 | getFile('/Core/lib/cherow/cherow.js', eval); 1063 | getFile('/Core/lib/estraverse/estraverse.js', eval); 1064 | 1065 | var mainWindow; 1066 | 1067 | window.openWindow = function(path, callback) { 1068 | prepareUrl(path, {__compat: false, rootParent: '/Core/', appData: '/CoreData/', permissions: {urlArgs: true}}, function(url) { 1069 | var div = document.createElement('div'); 1070 | div.className = 'window'; 1071 | div.style.overflow = 'hidden'; 1072 | div.addEventListener('scroll', function() { 1073 | div.scrollLeft = div.scrollTop = 0; 1074 | }); 1075 | var iframe = document.createElement('iframe'); 1076 | iframe.sandbox = 'allow-scripts allow-forms allow-popups allow-modals allow-popups-to-escape-sandbox'; 1077 | iframe.setAttribute('allowfullscreen', 'true'); 1078 | iframe.src = url; 1079 | iframe.scrolling = 'no'; 1080 | iframe.name = 'LaskyaWM'; // Webkit Developer Tools hint. 1081 | div.appendChild(iframe); 1082 | document.body.appendChild(div); 1083 | mainWindow = iframe.contentWindow; 1084 | callback(iframe); 1085 | }, function() {}, function(arg, callback) { 1086 | var object; 1087 | try { 1088 | object = new File([arg.data], arg.name, {type: arg.type}); 1089 | } catch(e) { 1090 | object = new Blob([arg.data], {type: arg.type}); 1091 | } 1092 | callback(URL.createObjectURL(object)); 1093 | }); 1094 | }; 1095 | 1096 | window.setTitle = function(t) { 1097 | document.title = t ? t + ' - Airborn' : 'Airborn'; 1098 | }; 1099 | 1100 | window.setIcon = function() {}; 1101 | 1102 | window.openWindowTop = function(args, appName, callback) { 1103 | window.open.apply(window, args); 1104 | window.addEventListener('message', function(evt) { 1105 | if(evt.data.action === 'requestMessageChannel') { 1106 | var win = window.open('', args[1]); // Get reference to window by name. 1107 | if(evt.source === win) { 1108 | evt.stopImmediatePropagation(); 1109 | var channel = new MessageChannel(); 1110 | win.postMessage({ 1111 | action: 'setupMessageChannel', 1112 | appName: appName, 1113 | }, '*', [channel.port1]); 1114 | callback(channel.port2); 1115 | } 1116 | } 1117 | }); 1118 | }; 1119 | 1120 | var pushUrl, pushHandlers = {}; 1121 | function pushInit() { 1122 | return new Promise(function(resolve/*, reject*/) { 1123 | getFile('/Core/lib/socket.io/socket.io.js', function(contents) { 1124 | eval(contents); 1125 | var socket = io(); 1126 | var url; 1127 | socket.on('hello', function(path) { 1128 | url = new URL(path, location.href).href; 1129 | resolve(url); 1130 | }); 1131 | socket.on('push', function(data) { 1132 | if(pushHandlers[data.registrationId]) { 1133 | pushHandlers[data.registrationId].forEach(function(handler) { 1134 | handler({ 1135 | event: 'push', 1136 | result: { 1137 | pushEndpoint: url + '?registrationId=' + data.registrationId, 1138 | version: data.version 1139 | } 1140 | }); 1141 | }); 1142 | } 1143 | }); 1144 | function notifyPushRegister() { 1145 | Object.keys(pushHandlers).forEach(function(key) { 1146 | pushHandlers[key].forEach(function(handler) { 1147 | handler({ 1148 | event: 'push-register' 1149 | }); 1150 | }); 1151 | }); 1152 | pushHandlers = {}; 1153 | } 1154 | socket.on('reconnect', function() { 1155 | pushUrl = new Promise(function(_resolve) { 1156 | resolve = _resolve; 1157 | }); 1158 | notifyPushRegister(); 1159 | }); 1160 | socket.on('reconnect_failed', function() { 1161 | console.error('socket.io reconnect failed'); 1162 | pushUrl = null; 1163 | notifyPushRegister(); 1164 | }); 1165 | }); 1166 | }); 1167 | } 1168 | 1169 | window.pushRegister = function(callback) { 1170 | if(!pushUrl) { 1171 | pushUrl = pushInit(); 1172 | } 1173 | pushUrl.then(function(url) { 1174 | var registrationId = Math.round(Math.random() * Date.now()).toString(16); 1175 | var endpoint = url + '?registrationId=' + registrationId; 1176 | 1177 | if(!pushHandlers[registrationId]) { 1178 | pushHandlers[registrationId] = []; 1179 | } 1180 | pushHandlers[registrationId].push(callback); 1181 | 1182 | callback({ 1183 | event: 'registered', 1184 | result: endpoint 1185 | }); 1186 | }); 1187 | }; 1188 | 1189 | window.pushUnregister = function(endpoint, callback) { 1190 | delete pushHandlers[endpoint.split('?registrationId=')[1]]; 1191 | callback(); 1192 | }; 1193 | 1194 | function corsReq(url, callback, responseType) { 1195 | var req = new XMLHttpRequest(); 1196 | if('withCredentials' in req) { 1197 | req.open('GET', url, true); 1198 | } else if(typeof XDomainRequest !== 'undefined') { 1199 | req = new XDomainRequest(); 1200 | req.open('GET', url); 1201 | } else { 1202 | throw new Error('CORS not supported.'); 1203 | } 1204 | req.onload = callback; 1205 | if(responseType) req.responseType = responseType; 1206 | req.send(); 1207 | } 1208 | 1209 | function includeJSZip(callback) { 1210 | getFile('/Core/lib/jszip/jszip.min.js', function(contents) { 1211 | if(!window.JSZip) window.eval(contents); 1212 | if(callback) callback(); 1213 | }); 1214 | } 1215 | 1216 | window.installPackage = function(manifest_url, params, callback) { 1217 | if(typeof params === 'function') { 1218 | callback = params; 1219 | params = {}; 1220 | } 1221 | includeJSZip(); 1222 | corsReq(manifest_url, function() { 1223 | var manifest = JSON.parse(this.responseText); 1224 | corsReq(manifest.package_path, function() { 1225 | var response = this.response; 1226 | includeJSZip(function() { 1227 | var zip = new JSZip(response); 1228 | var keys = Object.keys(zip.files); 1229 | var uploaded = 0; 1230 | var total = 0; 1231 | var target = '/Apps/' + basename(manifest.package_path).replace('-' + manifest.version, '').replace('.zip', '') + '/'; 1232 | getFile(target, {codec: 'dir'}, function(contents) { 1233 | putFile(target, {codec: 'dir', transactionId: 'packageinstall'}, contents || {}, {x: {marketplace: extend({}, params, {manifest_url: manifest_url})}}); 1234 | }); 1235 | keys.forEach(function(path) { 1236 | var file = zip.files[path]; 1237 | if(!file.options.dir) { 1238 | total++; 1239 | putFile( 1240 | target + path, 1241 | {codec: 'arrayBuffer', transactionId: 'packageinstall'}, 1242 | file.asArrayBuffer(), 1243 | function() { 1244 | uploaded++; 1245 | if(uploaded === total) { 1246 | callback({installState: 'installed'}); 1247 | } 1248 | } 1249 | ); 1250 | } 1251 | }); 1252 | }); 1253 | }, 'arraybuffer'); 1254 | }); 1255 | }; 1256 | 1257 | window.update = function() { 1258 | corsReq('/v2/current-id', function() { 1259 | var currentId = this.response; 1260 | getFile('/Core/version-id', function(contents) { 1261 | if(currentId !== contents) { 1262 | if(!(settings.core && settings.core.notifyOfUpdates || account_info.tier >= 10) || (document.hasFocus() && confirm( 1263 | 'There is an update for Airborn. Do you want to install it now? You can continue using Aiborn while and after updating. The update will apply next time you open Airborn.\nIf you click Cancel, you will be asked again in 1 hour or next time you open Airborn.' 1264 | ))) { 1265 | includeJSZip(); 1266 | corsReq('/v2/current', function() { 1267 | var response = this.response; 1268 | includeJSZip(function() { 1269 | var zip = new JSZip(response); 1270 | var keys = Object.keys(zip.files); 1271 | var target = '/'; 1272 | window.showNotice('airbornupdating', "Updating… Please don't close this tab."); 1273 | keys.forEach(function(path, i) { 1274 | var file = zip.files[path]; 1275 | if(!file.options.dir) { 1276 | putFile(target + path, {codec: 'arrayBuffer', transactionId: 'airbornupdate'}, file.asArrayBuffer(), i === keys.length - 1 ? function() { 1277 | // Transaction finished; all files have been uploaded 1278 | setTimeout(function() { // Wait 10s to be sure 1279 | window.hideNotice('airbornupdating'); 1280 | }, 10000); 1281 | } : undefined); 1282 | } 1283 | }); 1284 | }); 1285 | }, 'arraybuffer'); 1286 | } 1287 | } 1288 | }); 1289 | }); 1290 | }; 1291 | 1292 | var notices; 1293 | window.showNotice = function(id, message, closeButton) { 1294 | if(!notices) { 1295 | notices = {}; 1296 | document.body.insertAdjacentHTML('beforeend', [ 1297 | '', 1353 | ].join('\n')); 1354 | } 1355 | 1356 | notices[id] = document.createElement('div'); 1357 | notices[id].className = 'airborn-notice'; 1358 | notices[id].innerHTML = message; 1359 | notices[id].style.opacity = 0; 1360 | if(closeButton) { 1361 | notices[id].insertAdjacentHTML('afterbegin', ''); 1362 | } 1363 | document.body.appendChild(notices[id]); 1364 | notices[id].style.setProperty('--height', notices[id].offsetHeight + 'px'); 1365 | var img = new Image(); 1366 | img.src = '/images/logo-hanger.svg'; 1367 | img.addEventListener('load', function() { 1368 | notices[id].style.opacity = 1; 1369 | }); 1370 | }; 1371 | 1372 | window.hideNotice = function(id) { 1373 | notices[id].style.opacity = 0; 1374 | notices[id].addEventListener('transitionend', function() { 1375 | notices[id].remove(); 1376 | delete notices[id]; 1377 | }); 1378 | }; 1379 | 1380 | window.getServerMessages = function() { 1381 | var req = new XMLHttpRequest(); 1382 | req.open('GET', '/messages'); 1383 | req.responseType = 'json'; 1384 | req.addEventListener('load', function() { 1385 | if(this.status === 200) { 1386 | this.response.forEach(function(message) { 1387 | if(message.min_core_version && message.min_core_version > core_version) return; 1388 | if(message.max_core_version && message.max_core_version < core_version) return; 1389 | alert(message.text); 1390 | }); 1391 | } 1392 | }); 1393 | req.send(); 1394 | }; 1395 | 1396 | window.loadSettings = function() { 1397 | getFile('/settings', {codec: 'json'}, function(_settings) { 1398 | settings = _settings; 1399 | }); 1400 | }; 1401 | 1402 | window.logout = function() { 1403 | sessionStorage.clear(); 1404 | localStorage.clear(); 1405 | document.cookie = document.cookie.split('=')[0] + '='; 1406 | window.location.reload(); 1407 | }; 1408 | 1409 | var APIKeys = []; 1410 | function getAPIKey(permissions) { 1411 | var array = new Uint32Array(10); 1412 | window.crypto.getRandomValues(array); 1413 | var key = Array.prototype.slice.call(array).toString(); 1414 | APIKeys[key] = permissions || {}; 1415 | return key; 1416 | } 1417 | window.isValidAPIKey = function(key) { 1418 | return APIKeys[key] !== undefined; 1419 | }; 1420 | function givesAccessToPath(permissions, path, type) { 1421 | return (permissions[type || 'read'] || []).some(function(allowed) { 1422 | return startsWith(allowed, path); 1423 | }); 1424 | } 1425 | window.hasPermission = function(key, action, args) { 1426 | var permissions = APIKeys[key]; 1427 | switch(action) { 1428 | case 'getFile': 1429 | return givesAccessToPath(permissions, args[0]); 1430 | case 'putFile': 1431 | return givesAccessToPath(permissions, args[0], 'write'); 1432 | case 'prepareFile': 1433 | return givesAccessToPath(permissions, args[1].rootParent) && givesAccessToPath(permissions, args[0]) && !Object.keys(args[1]).some(function(key) { 1434 | return key.replace(/^_+/, '') === 'permissions'; 1435 | }); 1436 | case 'prepareString': 1437 | case 'prepareUrl': 1438 | return givesAccessToPath(permissions, args[1].rootParent) && !Object.keys(args[1]).some(function(key) { 1439 | return key.replace(/^_+/, '') === 'permissions'; 1440 | }); 1441 | case 'startTransaction': 1442 | case 'endTransaction': 1443 | return false; 1444 | case 'listenForFileChanges': 1445 | return givesAccessToPath(permissions, args[0]); 1446 | case 'getObjectLocation': 1447 | return givesAccessToPath(permissions, args[0].replace(/^airbornstorage:/, '')) && permissions.getObjectLocations; 1448 | case 'pushRegister': 1449 | case 'pushUnregister': 1450 | case 'openWindowTop': 1451 | return true; 1452 | case 'installPackage': 1453 | return permissions.hasOwnProperty('manageApps'); 1454 | case 'setTitle': 1455 | case 'setIcon': 1456 | case 'logout': 1457 | return false; 1458 | default: 1459 | return false; 1460 | } 1461 | }; 1462 | 1463 | // From: http://tobyho.com/2013/12/02/fun-with-esprima/ 1464 | function renameGlobalVariables(file, source, variables) { 1465 | if(typeof cherow === 'undefined' || typeof estraverse === 'undefined') return source; 1466 | if(source.substr(-22) === '//# airbornos:prepared') { 1467 | return source; 1468 | } 1469 | var variablesContained = Object.keys(variables).filter(function(variable) { 1470 | return new RegExp('(?:^|[^"\'])\\b' + variable + '\\b').test(source); 1471 | }); 1472 | if(!variablesContained.length) { 1473 | return source; 1474 | } 1475 | console.log('Parsing', file, 'because it appears to contain the following variables:', variablesContained.join(', ')); 1476 | var ast; 1477 | if(window.parseTime === undefined) window.parseTime = 0; 1478 | window.startTime = performance.now(); 1479 | try { 1480 | ast = cherow.parseScript(source, {ranges: true}); 1481 | } catch(e) { 1482 | console.log(e); 1483 | return source; 1484 | } 1485 | window.parseTime += performance.now() - window.startTime; 1486 | console.log('parse ' + file, performance.now() - window.startTime, 'cumulative:', window.parseTime); 1487 | var scopeChain = []; 1488 | var identifiers = []; 1489 | var replaces = []; 1490 | estraverse.traverse(ast, { 1491 | enter: enter, 1492 | leave: leave 1493 | }); 1494 | replaces.sort(function(a, b) { 1495 | return a.start - b.start; 1496 | }); 1497 | var replaced = []; 1498 | var lastEnd = 0; 1499 | for(var i = 0; i < replaces.length; i++) { 1500 | replaced.push(source.substring(lastEnd, replaces[i].start), variables[replaces[i].name]); 1501 | lastEnd = replaces[i].end; 1502 | } 1503 | return replaced.join('') + source.substr(lastEnd) + '\n//# airbornos:prepared'; 1504 | 1505 | function enter(node) { 1506 | if(createsNewScope(node)) { 1507 | if(node.type === 'FunctionDeclaration') { 1508 | scopeChain[scopeChain.length - 1].push(node.id.name); 1509 | } 1510 | if(node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression') { 1511 | scopeChain.push(node.params.map(function(node) { return node.name; })); 1512 | if(node.rest) { 1513 | scopeChain[scopeChain.length - 1].push(node.rest.name); 1514 | } 1515 | } else { 1516 | scopeChain.push([]); 1517 | } 1518 | } 1519 | if(node.type === 'VariableDeclarator') { 1520 | var currentScope = scopeChain[scopeChain.length - 1]; 1521 | currentScope.push(node.id.name); 1522 | } 1523 | if(node.type === 'Identifier') { 1524 | identifiers.push(node); 1525 | } 1526 | if(node.type === 'ObjectExpression') { 1527 | node.properties.forEach(function(property) { 1528 | property.key.isObjectKey = true; 1529 | }); 1530 | return node; 1531 | } 1532 | if(node.type === 'MemberExpression') { 1533 | if(!node.computed) { 1534 | node.property.isProperty = true; 1535 | return node; 1536 | } 1537 | } 1538 | } 1539 | function leave(node) { 1540 | if(createsNewScope(node)) { 1541 | renameGlobals(identifiers, scopeChain); 1542 | scopeChain.pop(); 1543 | identifiers = []; 1544 | } 1545 | } 1546 | function isVarDefined(varname, scopeChain) { 1547 | for(var i = 0; i < scopeChain.length; i++) { 1548 | var scope = scopeChain[i]; 1549 | if(scope.indexOf(varname) !== -1) { 1550 | return true; 1551 | } 1552 | } 1553 | return false; 1554 | } 1555 | function renameGlobals(identifiers, scopeChain) { 1556 | for(var i = 0; i < identifiers.length; i++) { 1557 | var identifier = identifiers[i]; 1558 | var varname = identifier.name; 1559 | if(!identifier.isObjectKey && variables.hasOwnProperty(varname) && (identifier.isProperty || !isVarDefined(varname, scopeChain))) { 1560 | replaces.push(identifier); 1561 | } 1562 | } 1563 | } 1564 | function createsNewScope(node) { 1565 | return node.type === 'FunctionDeclaration' || 1566 | node.type === 'FunctionExpression' || 1567 | node.type === 'Program'; 1568 | } 1569 | } 1570 | //# sourceURL=/Core/core.js -------------------------------------------------------------------------------- /modules/core/merge.js: -------------------------------------------------------------------------------- 1 | /* This file is licensed under the Affero General Public License. */ 2 | 3 | var set = {}; 4 | var string = {}; 5 | 6 | 7 | set.equal = function(a, b) { 8 | return a === b || (a && b && ((a.__id__ && a.__id__ === b.__id__) || (a.text && a.text === b.text))); 9 | }; 10 | 11 | 12 | set.diff = function(a, b) { 13 | var i = 0, j = 0, patches = []; 14 | while(i <= a.length || j <= b.length) { 15 | if(set.equal(a[i], b[j])) { 16 | i++; 17 | j++; 18 | continue; 19 | } 20 | 21 | // Detect insert 22 | var k; 23 | for(k = j + 1; k <= b.length; k++) { 24 | if(set.equal(a[i], b[k])) { 25 | patches.push([i, 0].concat(b.slice(j, k))); 26 | i++; 27 | j = k + 1; 28 | break; 29 | } 30 | } 31 | if(k !== b.length + 1) continue; 32 | 33 | // Detect remove 34 | for(k = i + 1; k <= a.length; k++) { 35 | if(set.equal(a[k], b[j])) { 36 | patches.push([i, k - i]); 37 | j++; 38 | i = k + 1; 39 | break; 40 | } 41 | } 42 | if(k !== a.length + 1) continue; 43 | 44 | // Replace one 45 | patches.push([i, 1].concat([b[j]])); 46 | i++; 47 | j++; 48 | } 49 | return patches.reverse(); 50 | }; 51 | 52 | set.merge = function(first, second, resolve) { 53 | second.forEach(function(item) { 54 | item.fromSecond = true; 55 | }); 56 | var result = first.concat(second); 57 | result.sort(function(a, b) { 58 | return b[0] - a[0]; 59 | }); 60 | function patches_equal(a, b) { 61 | return a.length === b.length && a[0] === b[0] && a[1] === b[1] && a.slice(2).every(function(item, i) { 62 | return set.equal(item, b[i + 2]); 63 | }); 64 | } 65 | function patches_overlap(a, b) { 66 | return a.fromSecond !== b.fromSecond && b[0] <= a[0] + a[1]; // Less strict would be < 67 | } 68 | for(var i = 1; i < result.length; i++) { 69 | if(patches_equal(result[i], result[i - 1])) { 70 | result.splice(i, 1); 71 | } else if(patches_overlap(result[i], result[i - 1])) { 72 | console.log('merge conflict:', result[i - 1], result[i]); 73 | result.splice.apply(result, [i - 1, 2].concat(resolve(result[i - 1], result[i]))); 74 | } 75 | } 76 | return result; 77 | }; 78 | 79 | set.patch = function(parent, patches) { 80 | parent = parent.slice(); 81 | for(var i = 0; i < patches.length; i++) { 82 | parent.splice.apply(parent, patches[i]); 83 | } 84 | return parent; 85 | }; 86 | 87 | set.merge3 = function(parent, first, second, resolve) { 88 | return set.patch(parent, set.merge(set.diff(parent, first), set.diff(parent, second), resolve)); 89 | }; 90 | 91 | 92 | string.merge3 = function(parent, first, second, resolve) { 93 | // Source: https://en.wikipedia.org/wiki/Levenshtein_distance 94 | function levenshteinDistance(s, t) { 95 | // degenerate cases 96 | if(s === t) return 0; 97 | if(s.length === 0) return t.length; 98 | if(t.length === 0) return s.length; 99 | 100 | // create two work vectors of integer distances 101 | var v0 = new Array(t.length + 1); 102 | var v1 = new Array(t.length + 1); 103 | 104 | // initialize v0 (the previous row of distances) 105 | // this row is A[0][i]: edit distance for an empty s 106 | // the distance is just the number of characters to delete from t 107 | var i, j; 108 | for(i = 0; i < v0.length; i++) { 109 | v0[i] = i; 110 | } 111 | 112 | for(i = 0; i < s.length; i++) { 113 | // calculate v1 (current row distances) from the previous row v0 114 | 115 | // first element of v1 is A[i+1][0] 116 | // edit distance is delete (i+1) chars from s to match empty t 117 | v1[0] = i + 1; 118 | 119 | // use formula to fill in the rest of the row 120 | for(j = 0; j < t.length; j++) { 121 | var cost = (s[i] === t[j]) ? 0 : 1; 122 | v1[j + 1] = Math.min(v1[j] + 1, v0[j + 1] + 1, v0[j] + cost); 123 | } 124 | 125 | // copy v1 (current row) to v0 (previous row) for next iteration 126 | for(j = 0; j < v0.length; j++) { 127 | v0[j] = v1[j]; 128 | } 129 | } 130 | 131 | return v1[t.length]; 132 | } 133 | 134 | function split(str, by, equal, similar, comparedTo) { 135 | var ctr = comparedTo.length; 136 | var prev; 137 | var taken = {}; 138 | return str.split(by).map(function(line) { 139 | var obj = { 140 | text: line 141 | }; 142 | var id; 143 | var _prev = prev; 144 | prev = null; 145 | if(comparedTo[_prev + 1] && !taken[comparedTo[_prev + 1].__id__] && (equal(obj.text, comparedTo[_prev + 1].text) || similar(obj.text, comparedTo[_prev + 1].text))) { 146 | id = comparedTo[_prev + 1].__id__; 147 | taken[comparedTo[_prev + 1].__id__] = true; 148 | prev = _prev + 1; 149 | } else { 150 | comparedTo.some(function(otherObj, i) { 151 | if(!taken[otherObj.__id__] && equal(obj.text, otherObj.text)) { 152 | id = otherObj.__id__; 153 | taken[otherObj.__id__] = true; 154 | prev = i; 155 | return true; 156 | } 157 | }); 158 | } 159 | obj.__id__ = id; 160 | return obj; 161 | }).map(function(obj) { 162 | if(!obj.__id__) { 163 | var id; 164 | comparedTo.some(function(otherObj, i) { 165 | if(!taken[otherObj.__id__] && similar(obj.text, otherObj.text)) { 166 | id = otherObj.__id__; 167 | taken[otherObj.__id__] = true; 168 | prev = i; 169 | return true; 170 | } 171 | }); 172 | if(!id) { 173 | id = ++ctr; 174 | } 175 | obj.__id__ = id; 176 | } 177 | return obj; 178 | }); 179 | } 180 | function join(objs, by) { 181 | return objs.filter(function(obj) { return obj; }).map(function(obj) { 182 | return obj.text; 183 | }).join(by); 184 | } 185 | function extend(target) { 186 | [].slice.call(arguments, 1).forEach(function(obj) { 187 | Object.keys(obj).forEach(function(key) { 188 | var value = obj[key]; 189 | if(value != null && value.constructor === Object) { 190 | if(target.hasOwnProperty(key)) extend(target[key], value); 191 | else target[key] = extend({}, value); 192 | } 193 | else if(value === undefined) delete target[key]; 194 | else target[key] = value; 195 | }); 196 | }); 197 | return target; 198 | } 199 | function clone(objs) { return objs.map(function(obj) { return extend({}, obj); }); } 200 | function _equal(first, second) { 201 | return first === second; 202 | } 203 | function _similar(first, second) { 204 | return first.length > 100 && levenshteinDistance(first, second) / first.length < 0.2; 205 | } 206 | parent = split(parent, '\n', _equal, _similar, []); 207 | first = split(first, '\n', _equal, _similar, clone(parent)); 208 | second = split(second, '\n', _equal, _similar, clone(parent).concat(clone(first))); 209 | 210 | var parent_lines = {}; 211 | parent.forEach(function(line) { 212 | parent_lines[line.__id__] = line.text; 213 | }); 214 | var first_lines = {}; 215 | first.forEach(function(line) { 216 | first_lines[line.__id__] = line.text; 217 | }); 218 | var second_lines = {}; 219 | second.forEach(function(line) { 220 | second_lines[line.__id__] = line.text; 221 | }); 222 | var all = parent.concat(first).concat(second); 223 | var merged_lines = {}; 224 | 225 | all.forEach(function(line) { 226 | if(merged_lines.hasOwnProperty(line.__id__)) return; 227 | 228 | if(parent_lines[line.__id__] === first_lines[line.__id__]) { 229 | merged_lines[line.__id__] = second_lines[line.__id__]; 230 | return; 231 | } else if(parent_lines[line.__id__] === second_lines[line.__id__]) { 232 | merged_lines[line.__id__] = first_lines[line.__id__]; 233 | return; 234 | } else if(first_lines[line.__id__] === second_lines[line.__id__]) { 235 | merged_lines[line.__id__] = first_lines[line.__id__]; 236 | return; 237 | } 238 | 239 | function _equal(first, second) { 240 | return first === second; 241 | } 242 | function _similar() { 243 | return false; 244 | } 245 | 246 | var parent = split(parent_lines[line.__id__] || '', /\b/, _equal, _similar, []); 247 | var first = split(first_lines[line.__id__] || '', /\b/, _equal, _similar, clone(parent)); 248 | var second = split(second_lines[line.__id__] || '', /\b/, _equal, _similar, clone(parent).concat(clone(first))); 249 | 250 | merged_lines[line.__id__] = join(set.merge3(parent, first, second, resolve), ''); 251 | }); 252 | 253 | var merged = set.merge3(parent, first, second, resolve).map(function(obj) { 254 | return merged_lines[obj.__id__]; 255 | }).join('\n'); 256 | 257 | return merged; 258 | }; -------------------------------------------------------------------------------- /modules/startup/loader.js: -------------------------------------------------------------------------------- 1 | (function() { 2 | if(window.wmLoaded) { 3 | console.log('wmLoaded was true, not showing loader'); 4 | return; 5 | } 6 | 7 | var loaderNode = document.createElement('div'); 8 | loaderNode.id = 'loading'; 9 | loaderNode.innerHTML = [ 10 | '
', 11 | '', 12 | '', 13 | '

Loading…

', 14 | '', 51 | ].join('\n'); 52 | document.body.appendChild(loaderNode); 53 | 54 | var dpr = window.devicePixelRatio || 1; 55 | var canvas = document.getElementById('loading-canvas'); 56 | canvas.width = canvas.height = 240 * dpr; 57 | var ctx = canvas.getContext('2d'); 58 | ctx.scale(dpr, dpr); 59 | var circ = Math.PI * 2; 60 | var quart = Math.PI / 2; 61 | 62 | ctx.strokeStyle = 'rgba(255, 255, 255, .2)'; 63 | ctx.lineWidth = 4; 64 | ctx.lineCap = 'square'; 65 | ctx.beginPath(); 66 | ctx.arc(120, 120, 70, 0, circ, false); 67 | ctx.closePath(); 68 | ctx.stroke(); 69 | ctx.strokeStyle = '#fff'; 70 | 71 | var imd = ctx.getImageData(0, 0, canvas.width, canvas.height); 72 | 73 | var last; 74 | function updateLoader(current) { 75 | if(last >= current) { 76 | return; 77 | } 78 | last = current; 79 | ctx.putImageData(imd, 0, 0); 80 | ctx.beginPath(); 81 | ctx.arc(120, 120, 70, -quart, Math.max(0.05, current) * circ - quart, false); 82 | ctx.stroke(); 83 | canvas.className = current ? '' : 'spinning'; 84 | } 85 | 86 | updateLoader(0); 87 | 88 | window.addEventListener('message', function(evt) { 89 | if(evt.data.action === 'wm.setProgress') { 90 | updateLoader(evt.data.args[0]); 91 | } else if(evt.data.action === 'wm.hideProgress') { 92 | loaderNode.style.opacity = 0; 93 | loaderNode.style.pointerEvents = 'none'; 94 | loaderNode.addEventListener('transitionend', function() { 95 | document.body.removeChild(loaderNode); 96 | }); 97 | } 98 | }); 99 | })(); 100 | //# sourceURL=/Core/loader.js -------------------------------------------------------------------------------- /modules/startup/startup.js: -------------------------------------------------------------------------------- 1 | /* This file is licensed under the Affero General Public License. */ 2 | 3 | /*globals setTitle, openWindow, getServerMessages, update, mainWindow, loadSettings, isValidAPIKey, hasPermission, APIKeys, guid */ 4 | 5 | if(navigator.userAgent.indexOf('Edge') !== -1) { 6 | alert('Sorry, Edge is not supported. Please use Chrome or Firefox.'); 7 | } 8 | 9 | setTitle(''); 10 | 11 | openWindow('/modules/window_manager/index.html', function(iframe) { 12 | iframe.addEventListener('load', function firstLoad() { 13 | iframe.removeEventListener('load', firstLoad); 14 | iframe.addEventListener('load', function secondLoad() { 15 | iframe.removeEventListener('load', secondLoad); 16 | 17 | getServerMessages(); 18 | 19 | update(); 20 | setInterval(update, 3600000); // Each hour 21 | }); 22 | }); 23 | }); 24 | 25 | var messageCallbacks = {}; 26 | window.addEventListener('message', function(message) { 27 | if(message.data.inReplyTo) { 28 | messageCallbacks[message.data.inReplyTo].apply(this, message.data.result); 29 | } else if(message.source === mainWindow || (message.data.apikey && isValidAPIKey(message.data.apikey))) { 30 | if(message.source !== mainWindow && !hasPermission(message.data.apikey, message.data.action.split('.')[1], message.data.args)) { 31 | if(message.data.action === 'fs.getFile') { 32 | message.source.postMessage({inReplyTo: message.data.messageID, result: [null, {status: 0, statusText: 'Permission denied.'}]}, '*'); 33 | } else if(message.data.action === 'fs.putFile') { 34 | message.source.postMessage({inReplyTo: message.data.messageID, result: [{status: 0, statusText: 'Permission denied.'}]}, '*'); 35 | } else if(message.data.action === 'fs.prepareFile' || message.data.action === 'fs.prepareString') { 36 | message.source.postMessage({inReplyTo: message.data.messageID, result: ['']}, '*'); 37 | } else if(message.data.action === 'fs.prepareUrl') { 38 | message.source.postMessage({inReplyTo: message.data.messageID, result: [message.data.args[0]]}, '*'); 39 | } 40 | throw new Error('Permission denied: ' + message.data.action + '(' + message.data.args.map(JSON.stringify).join(', ') + ')'); 41 | } 42 | if(['fs.getFile', 'fs.putFile', 'fs.prepareFile', 'fs.prepareString', 'fs.prepareUrl', 'fs.startTransaction', 'fs.endTransaction', 'fs.listenForFileChanges', 'fs.getObjectLocation', 'fs.pushRegister', 'fs.pushUnregister', 'apps.installPackage', 'core.setTitle', 'core.setIcon', 'core.logout'].indexOf(message.data.action) !== -1) { 43 | window[message.data.action.split('.')[1]].apply(window, message.data.args.concat(function() { 44 | message.source.postMessage({inReplyTo: message.data.messageID, result: [].slice.call(arguments)}, '*'); 45 | }, function() { 46 | message.source.postMessage({inReplyTo: message.data.messageID, result: [].slice.call(arguments), progress: true}, '*'); 47 | }, function(data, callback) { 48 | var messageID = guid(); 49 | message.source.postMessage({action: 'createObjectURL', args: [data], messageID: messageID}, '*'); 50 | messageCallbacks[messageID] = callback; 51 | })); 52 | } else if(message.data.action === 'core.openWindowTop') { 53 | window.openWindowTop(message.data.args, APIKeys[message.data.apikey].appName, function(port) { 54 | message.source.postMessage({inReplyTo: message.data.messageID, result: [port]}, '*', [port]); 55 | }); 56 | } else if(message.data.action.substr(0, 3) === 'wm.') { 57 | if(message.data.action === 'wm.hideProgress') { 58 | window.wmLoaded = true; 59 | } 60 | } else { 61 | throw new TypeError('Unknown action: ' + message.data.action); 62 | } 63 | }/* else { 64 | console.info('Forwarding message.'); 65 | var src = message.source; 66 | var parent = src.parent; 67 | while(parent !== mainWindow) { 68 | src = parent; 69 | parent = src.parent; 70 | } 71 | src.postMessage({data: message.data, forwardedFrom: message.origin}, '*'); 72 | }*/ 73 | }); 74 | 75 | loadSettings(); 76 | //# sourceURL=/Core/startup.js -------------------------------------------------------------------------------- /modules/webapi/webapi.js: -------------------------------------------------------------------------------- 1 | /* This file is licensed under the Affero General Public License. */ 2 | 3 | /*global File, History, DOMError, HTMLAudioElement, airborn: true, laskya: true */ 4 | 5 | (function() { 6 | var rootParent = document.rootParent; 7 | delete document.rootParent; 8 | var relativeParent = document.relativeParent; 9 | delete document.relativeParent; 10 | var appData = rootParent.replace('Apps', 'AppData').replace('Core', 'CoreData'); 11 | var rootParentWithoutSlash = rootParent.substr(0, rootParent.length - 1); 12 | Object.defineProperty(document, 'baseURI', {get: function() { return relativeParent.replace(rootParentWithoutSlash, ''); }}); 13 | var filenames = document.filenames; 14 | delete document.filenames; 15 | 16 | var messageCallbacks = {}; 17 | var apikey = document.apikey; 18 | delete document.apikey; 19 | var action = function(action, args, callback, progress, transfer) { 20 | var messageID = guid(); 21 | (action.substr(0, 3) === 'wm.' ? window.parent : window.top).postMessage({messageID: messageID, action: action, args: args, apikey: apikey}, '*', transfer); 22 | messageCallbacks[messageID] = callback; 23 | if(messageCallbacks[messageID]) { 24 | messageCallbacks[messageID].progress = progress; 25 | messageCallbacks[messageID].listener = action === 'fs.listenForFileChanges' || action === 'fs.pushRegister' || action.substr(0, 10) === 'fs.prepare' || action === 'core.openWindowTop'; 26 | } 27 | }; 28 | window.addEventListener('message', function(message) { 29 | if(message.airborn_source === windowProxy(window.top) || message.airborn_source === windowProxy(window.parent)) { 30 | if(message.data.inReplyTo) { 31 | var callback = messageCallbacks[message.data.inReplyTo]; 32 | if(callback !== undefined && message.data.progress) callback = callback.progress; 33 | if(callback === undefined) return; 34 | callback.apply(window, message.data.result); 35 | if(!message.data.progress && !callback.listener) messageCallbacks[message.data.inReplyTo] = null; 36 | } else if(message.data.action) { 37 | if(message.data.action === 'createObjectURL') { 38 | var arg = message.data.args[0], object; 39 | try { 40 | object = new File([arg.data], arg.name, {type: arg.type}); 41 | } catch(e) { 42 | object = new Blob([arg.data], {type: arg.type}); 43 | } 44 | var url = URL.createObjectURL(object); 45 | filenames[url] = arg.name; 46 | message.source.postMessage({inReplyTo: message.data.messageID, result: [url]}, '*'); 47 | return; 48 | } 49 | airborn.listeners[message.data.action + 'Request'].forEach(function(listener) { 50 | listener.apply(airborn, message.data.args); 51 | }); 52 | } 53 | } else if(window.parent === window.top) { 54 | return; 55 | } else if([].map.call(document.getElementsByTagName('iframe'), function(iframe) { return iframe.contentWindow; }).indexOf(message.source) !== -1) { 56 | if(message.data.action) { 57 | action(message.data.action, message.data.args, function() { 58 | message.source.postMessage({inReplyTo: message.data.messageID, result: [].slice.call(arguments)}, '*'); 59 | }, function() { 60 | message.source.postMessage({inReplyTo: message.data.messageID, result: [].slice.call(arguments), progress: true}, '*'); 61 | }, message.data.args.filter(function(arg) { 62 | return arg instanceof ArrayBuffer; 63 | })); 64 | } 65 | } else { 66 | console.info('unknown source'); 67 | } 68 | }, false); 69 | function guid() { 70 | return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c => 71 | (c ^ window.crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16) 72 | ); 73 | } 74 | airborn = laskya = { 75 | listeners: { 76 | openFileRequest: [] 77 | }, 78 | addEventListener: function(eventName, listener) { 79 | airborn.listeners[eventName].push(listener); 80 | } 81 | }; 82 | function addAction(name) { 83 | var parts = name.split('.'); 84 | var target = airborn; 85 | parts.slice(0, -1).forEach(function(part) { 86 | if(!target[part]) target[part] = {}; 87 | target = target[part]; 88 | }); 89 | target[parts[parts.length - 1]] = function() { 90 | var args = [].slice.call(arguments); 91 | var firstfunction = args.map(function(arg) { return Object.prototype.toString.call(arg); }).indexOf('[object Function]'); 92 | if(firstfunction === -1) firstfunction = args.length; 93 | action(name, args.slice(0, firstfunction), args[firstfunction], args[firstfunction + 1]); 94 | }; 95 | } 96 | addAction('wm.focus'); 97 | addAction('wm.reportClicked'); 98 | addAction('wm.setTitle'); 99 | addAction('wm.setIcon'); 100 | addAction('wm.openFile'); 101 | addAction('wm.openWindow'); 102 | addAction('wm.showProgress'); 103 | addAction('wm.setProgress'); 104 | addAction('wm.hideProgress'); 105 | 106 | addAction('fs.getFile'); 107 | addAction('fs.putFile'); 108 | addAction('fs.prepareFile'); 109 | addAction('fs.prepareString'); 110 | addAction('fs.prepareUrl'); 111 | addAction('fs.startTransaction'); 112 | addAction('fs.endTransaction'); 113 | addAction('fs.listenForFileChanges'); 114 | addAction('fs.getObjectLocation'); 115 | addAction('fs.pushRegister'); 116 | addAction('fs.pushUnregister'); 117 | 118 | addAction('core.openWindowTop'); 119 | 120 | if(window.parent === window.top) { 121 | addAction('core.setTitle'); 122 | addAction('core.setIcon'); 123 | addAction('core.logout'); 124 | airborn.wm = airborn.core; 125 | } 126 | 127 | var getFileCache = {}; 128 | var listeningForDirectory = {}; 129 | var _getFile = airborn.fs.getFile; 130 | airborn.fs.getFile = function(file, options, callback) { 131 | if(typeof options === 'function' || options === undefined) { 132 | callback = options; 133 | options = {}; 134 | } 135 | if(callback === undefined) { 136 | callback = function() {}; 137 | } 138 | 139 | var JSON_options = JSON.stringify(options); 140 | if(!getFileCache[file]) { 141 | getFileCache[file] = {}; 142 | } 143 | if(getFileCache[file][JSON_options]) { 144 | callback.apply(this, getFileCache[file][JSON_options]); 145 | return; 146 | } 147 | var mainDirectory = file.substr(0, rootParent.length) === rootParent ? rootParent : (file.match(/\/[^\/]*\//) || ['/'])[0]; 148 | if(!listeningForDirectory[mainDirectory]) { 149 | listeningForDirectory[mainDirectory] = true; 150 | airborn.fs.listenForFileChanges(mainDirectory, function(path) { 151 | getFileCache[path] = {}; 152 | }); 153 | } 154 | _getFile(file, options, function() { 155 | if(!getFileCache[file][JSON_options]) { 156 | getFileCache[file][JSON_options] = arguments; 157 | } 158 | callback.apply(this, getFileCache[file][JSON_options]); 159 | }); 160 | }; 161 | 162 | var _putFile = airborn.fs.putFile; 163 | airborn.fs.putFile = function() { 164 | var args = [].slice.call(arguments); 165 | if(args[1] instanceof Blob) { 166 | throw new TypeError('You have to pass putFile(name, {codec: "blob"}, blob).'); 167 | } 168 | if(args[2] instanceof Blob) { 169 | if(!args[1] || args[1].codec !== 'blob') { 170 | throw new TypeError('You have to pass putFile(name, {codec: "blob"}, blob).'); 171 | } 172 | var blob = args[2]; 173 | if(typeof args[3] === 'function' || args[3] === undefined) { 174 | args[5] = args[4]; 175 | args[4] = args[3]; 176 | args[3] = {}; 177 | } 178 | args[3].type = blob.type; 179 | var reader = new FileReader(); 180 | reader.onload = function() { 181 | var arrayBuffer = this.result; 182 | args[2] = arrayBuffer; 183 | args[1].codec = 'arrayBuffer'; 184 | if(navigator.userAgent.match(/Safari/) && !navigator.userAgent.match(/Chrome/)) { // Safari 185 | action('fs.putFile', args.slice(0, 4), args[4], args[5]); 186 | } else { 187 | action('fs.putFile', args.slice(0, 4), args[4], args[5], [arrayBuffer]); 188 | } 189 | }; 190 | reader.readAsArrayBuffer(blob); 191 | return; 192 | } 193 | _putFile.apply(this, arguments); 194 | }; 195 | 196 | navigator.mozApps = {}; 197 | navigator.mozApps.installPackage = function() { 198 | var args = [].slice.call(arguments); 199 | var request = new DOMRequest(); 200 | action('apps.installPackage', args, function(result, err) { 201 | if(err) { 202 | request.error = err; 203 | request.dispatchEvent(new Event('error')); 204 | } else { 205 | request.result = result; 206 | request.dispatchEvent(new Event('success')); 207 | } 208 | }); 209 | return request; 210 | }; 211 | 212 | window.addEventListener('mousedown', function() { 213 | if(window.parent !== window.top) { 214 | airborn.wm.focus(); 215 | airborn.wm.reportClicked(); 216 | } 217 | }, true); 218 | 219 | var rArgs = /[?#].*$/; 220 | var rSchema = /^(?!airbornstorage)[a-z]+:/i; 221 | var rAnySchema = /^[a-z]+:/i; 222 | function getURLFilename(url, relativeTo) { 223 | var args = (url.match(rArgs) || [''])[0]; 224 | url = url.replace(rArgs, ''); 225 | var filename; 226 | if(filenames.hasOwnProperty(url)) { 227 | filename = filenames[url]; 228 | } else { 229 | var startIndex = url.indexOf('filename='); 230 | if(startIndex === -1) { 231 | if(rAnySchema.test(url)) { 232 | return url + args; 233 | } 234 | return airborn.path.resolve(relativeTo, url) + args; 235 | } else { 236 | filename = url.substr(startIndex + 9); // 'filename='.length == 9 237 | filename = decodeURIComponent(filename.substr(0, filename.indexOf(';'))); 238 | } 239 | } 240 | if(filename[0] !== '/' || filename.substr(0, rootParent.length) === rootParent) { 241 | return airborn.path.resolve(relativeTo, filename.replace(rootParentWithoutSlash, '')) + args; 242 | } else { 243 | return 'airbornstorage:' + filename + args; 244 | } 245 | } 246 | 247 | function defineWithPrefixed(obj, prop, rewrittenProp, descriptor) { 248 | try { 249 | Object.defineProperty(obj, prop, descriptor); 250 | } catch(e) {} 251 | Object.defineProperty(obj, rewrittenProp, descriptor); 252 | } 253 | function redefineWithPrefixed(obj, prop, rewrittenProp, getDescriptor) { 254 | var realDescriptor = Object.getOwnPropertyDescriptor(obj, prop); 255 | var realGet = realDescriptor && realDescriptor.get || function() { return this[prop]; }; 256 | var realSet = realDescriptor && realDescriptor.set || function(value) { this[prop] = value; }; 257 | defineWithPrefixed(obj, prop, rewrittenProp, getDescriptor(realGet, realSet)); 258 | } 259 | var AirbornObjectPrototype = Object.create(null); 260 | function defineDummy(prop, rewrittenProp) { 261 | Object.defineProperty(Object.prototype, rewrittenProp, {get: function() { return this[prop]; }, set: function(value) { this[prop] = value; }}); 262 | Object.defineProperty(AirbornObjectPrototype, rewrittenProp, {get: function() { return this[prop]; }, set: function(value) { this[prop] = value; }}); 263 | } 264 | var _Object_create = Object.create; 265 | Object.create = function(O) { 266 | if(O === null) { 267 | O = AirbornObjectPrototype; 268 | } 269 | return _Object_create.apply(this, arguments); 270 | }; 271 | 272 | var requestOpen = XMLHttpRequest.prototype.open; 273 | XMLHttpRequest.prototype.open = function(_method, url) { 274 | var method = _method.toUpperCase(); 275 | var responseType; 276 | if((url.substr(0, 7) === 'data://' && url.indexOf(',') === -1) || url.substr(0, 7) === 'blob://') url = url.substr(7); // Workaround for URI.js in Firetext 277 | if(method === 'GET' && !rSchema.test(url)) { 278 | this.airbornFile = true; 279 | this.setRequestHeader = function() { console.log(this, arguments); }; 280 | var codec; 281 | this.overrideMimeType = function(mimeType) { 282 | console.log(this, arguments); 283 | // mimeType is of the form mime/type; charset=utf-8 284 | if(mimeType.split('/')[0] === 'text') return; 285 | console.log("codec = 'arrayBuffer';"); 286 | codec = 'arrayBuffer'; 287 | }; 288 | defineWithPrefixed(this, 'responseType', 'airborn_responseType', { 289 | set: function(_responseType) { 290 | console.log(this, arguments); 291 | console.log("codec = '" + _responseType + "';"); 292 | if(_responseType === 'arraybuffer') { 293 | codec = 'arrayBuffer'; 294 | } else if(_responseType === 'json') { 295 | codec = 'json'; 296 | } else { 297 | responseType = _responseType; 298 | } 299 | }, 300 | }); 301 | this.send = function() { 302 | var req = this; 303 | url = url.replace(/^file:(?:\/\/)?/, ''); 304 | url = url.replace(rArgs, ''); 305 | url = rootParent + airborn.path.resolve('/', url).substr(1).replace(/^(\.\.\/)+/, ''); 306 | if(url.substr(-1) === '/') url += 'index.html'; 307 | airborn.fs.getFile(url, {codec: codec}, function(contents, err) { 308 | defineWithPrefixed(req, 'readyState', 'airborn_readyState', {get: function() { return 4; }}); 309 | defineWithPrefixed(req, 'status', 'airborn_status', {get: function() { return !err && 200; }}); 310 | defineWithPrefixed(req, 'response', 'airborn_response', { 311 | get: function() { 312 | if(responseType === 'document') { 313 | var doc = document.implementation.createHTMLDocument(''); 314 | Object.defineProperty(doc, 'baseURI', {get: function() { return url.replace(rootParentWithoutSlash, ''); }}); 315 | doc.documentElement.innerHTML = contents; 316 | return doc; 317 | } 318 | return contents; 319 | }, 320 | }); 321 | if(!codec) defineWithPrefixed(req, 'responseText', 'airborn_responseText', {get: function() { return contents; }}); 322 | setTimeout(function() { 323 | req.dispatchEvent(new Event('readystatechange')); 324 | req.dispatchEvent(new Event('load')); 325 | }); 326 | }); 327 | }; 328 | } else if(method === 'HEAD' && !rSchema.test(url)) { 329 | this.airbornFile = true; 330 | this.setRequestHeader = function() { console.log(this, arguments); }; 331 | this.overrideMimeType = function() { console.log(this, arguments); }; 332 | this.send = function() { 333 | var req = this; 334 | url = url.replace(/^file:(?:\/\/)?/, ''); 335 | url = url.replace(rArgs, ''); 336 | url = rootParent + airborn.path.resolve('/', url).substr(1).replace(/^(\.\.\/)+/, ''); 337 | if(url.substr(-1) === '/') url += 'index.html'; 338 | airborn.fs.getFile(airborn.path.dirname(url), {codec: 'dir'}, function(contents, err) { 339 | var getResponseHeader = req.getResponseHeader; 340 | req.getResponseHeader = function(header) { 341 | if(header === 'Content-Length') return contents[airborn.path.basename(url)].size; 342 | return getResponseHeader.apply(this, arguments); 343 | }; 344 | defineWithPrefixed(req, 'readyState', 'airborn_readyState', {get: function() { return 4; }}); 345 | defineWithPrefixed(req, 'status', 'airborn_status', {get: function() { return !err && 200; }}); 346 | setTimeout(function() { 347 | req.dispatchEvent(new Event('readystatechange')); 348 | req.dispatchEvent(new Event('load')); 349 | }); 350 | }); 351 | }; 352 | } else if(method === 'HEAD' && url.substr(0, 5) === 'data:') { 353 | this.setRequestHeader = function() { console.log(this, arguments); }; 354 | this.overrideMimeType = function() { console.log(this, arguments); }; 355 | this.send = function() { 356 | var req = this; 357 | var parts = url.substr(5).split(','); 358 | var contents = parts[0].indexOf('base64') === -1 ? decodeURIComponent(parts[1]) : atob(parts[1].replace(/-/g, '+').replace(/_/g, '/')); 359 | var getResponseHeader = req.getResponseHeader; 360 | req.getResponseHeader = function(header) { 361 | if(header === 'Content-Length') return contents.length; 362 | return getResponseHeader.apply(this, arguments); 363 | }; 364 | defineWithPrefixed(req, 'readyState', 'airborn_readyState', {get: function() { return 4; }}); 365 | defineWithPrefixed(req, 'status', 'airborn_status', {get: function() { return 200; }}); 366 | setTimeout(function() { 367 | req.dispatchEvent(new Event('readystatechange')); 368 | req.dispatchEvent(new Event('load')); 369 | }); 370 | }; 371 | } else { 372 | if(url.substr(0, 5) === 'data:') console.log(method, url); 373 | requestOpen.apply(this, arguments); 374 | } 375 | }; 376 | defineDummy('responseType', 'airborn_responseType'); 377 | defineDummy('readyState', 'airborn_readyState'); 378 | defineDummy('status', 'airborn_status'); 379 | defineDummy('response', 'airborn_response'); 380 | defineDummy('responseText', 'airborn_responseText'); 381 | 382 | var prepareUrlRequestCache = {}; 383 | function prepareUrl(url, callback) { 384 | if(prepareUrlRequestCache[url]) { 385 | if(prepareUrlRequestCache[url].result) { 386 | callback.apply(this, prepareUrlRequestCache[url].result); 387 | } else { 388 | prepareUrlRequestCache[url].push(callback); 389 | } 390 | } else { 391 | prepareUrlRequestCache[url] = [callback]; 392 | airborn.fs.prepareUrl(url, {rootParent: rootParent, relativeParent: relativeParent, appData: appData, apikey: apikey}, function() { 393 | var args = arguments; 394 | prepareUrlRequestCache[url].forEach(function(cb) { 395 | cb.apply(this, args); 396 | }); 397 | prepareUrlRequestCache[url].result = args; 398 | }); 399 | } 400 | } 401 | airborn.fs.listenForFileChanges(rootParent, function() { 402 | Object.keys(prepareUrlRequestCache).forEach(function(url) { 403 | if(prepareUrlRequestCache[url].result) { 404 | delete prepareUrlRequestCache[url]; 405 | } 406 | }); 407 | }); 408 | 409 | airborn.path = { 410 | dirname: function(path) { 411 | return path.substr(0, path.replace(/\/+$/, '').lastIndexOf('/') + 1); 412 | }, 413 | basename: function(path, ext) { 414 | var basename = path.substr(path.replace(/\/+$/, '').lastIndexOf('/') + 1); 415 | if(ext && basename.substr(-ext.length) === ext) return basename.substr(0, basename.length - ext.length); 416 | return basename; 417 | }, 418 | split: function(path) { 419 | return path.split('/').map(function(part, i, parts) { 420 | return part + (i + 1 === parts.length ? '' : '/'); 421 | }); 422 | }, 423 | join: function() { 424 | return [].join.call(arguments, ''); 425 | }, 426 | resolve: function(from, to) { 427 | if(to === '') return from; 428 | if(to[0] === '/') return airborn.path.resolve('/', to.substr(1)); 429 | var resolved = from.replace(/[^/]*$/, '') + to; 430 | var rParentOrCurrent = /([^./]+\/\.\.\/|\/\.(?=\/))/g; 431 | while(rParentOrCurrent.test(resolved)) resolved = resolved.replace(rParentOrCurrent, ''); 432 | return resolved; 433 | } 434 | }; 435 | 436 | var preventWindowLoad = 0, windowLoadPrevented = 0; 437 | window.addEventListener('load', function(evt) { 438 | if(preventWindowLoad) { 439 | evt.stopImmediatePropagation(); 440 | preventWindowLoad--; 441 | windowLoadPrevented++; 442 | } 443 | }); 444 | [ 445 | [HTMLAnchorElement, 'href', 'airborn_href', function() {}, function() {}], 446 | [HTMLLinkElement, 'href', 'airborn_href', function() {}, function() {}], 447 | [HTMLAudioElement, 'src', 'airborn_src', function() {}, function() {}], 448 | [HTMLScriptElement, 'src', 'airborn_src', 449 | function() { 450 | preventWindowLoad++; 451 | }, 452 | function() { 453 | this.addEventListener('load', function() { 454 | if(windowLoadPrevented--) window.dispatchEvent(new Event('load')); 455 | }); 456 | } 457 | ], 458 | [HTMLImageElement, 'src', 'airborn_src', 459 | function() { 460 | var imgCompleteDescriptor = Object.getOwnPropertyDescriptor(this, 'complete'); 461 | Object.defineProperty(this, 'complete', {get: function() { return false; }, configurable: true}); 462 | function onError(evt) { 463 | evt.stopImmediatePropagation(); 464 | } 465 | this.addEventListener('error', onError); 466 | 467 | return function() { 468 | if(imgCompleteDescriptor) { 469 | Object.defineProperty(this, 'complete', imgCompleteDescriptor); 470 | } else { 471 | delete this.complete; 472 | } 473 | this.removeEventListener('error', onError); 474 | }; 475 | } 476 | ], 477 | [HTMLIFrameElement, 'src', 'airborn_src', 478 | function() { 479 | this.addEventListener('load', function onLoad(evt) { 480 | evt.stopImmediatePropagation(); 481 | this.removeEventListener('load', onLoad); 482 | }); 483 | }, 484 | function() {} 485 | ] 486 | ].forEach(function(element) { 487 | var HTMLElm = element[0]; 488 | var attr = element[1]; 489 | var rewrittenAttr = element[2]; 490 | var onStart = element[3]; 491 | var onEnd = element[4]; 492 | 493 | var descriptor = (get, set) => ({ 494 | get: function() { 495 | // this.src is sometimes empty: https://crbug.com/291791 496 | return this.getAttribute(attr) || ''; 497 | }, 498 | set: function(url) { 499 | var _this = this; 500 | if(rSchema.test(url)) return set.call(_this, url); 501 | var absoluteUrl = airborn.path.resolve(rootParent, url); 502 | if(Object.keys(filenames).some(function(objectURL) { 503 | if(filenames[objectURL] === absoluteUrl) { 504 | set.call(_this, objectURL); 505 | return true; 506 | } 507 | })) return; 508 | onEnd = onStart.call(_this) || onEnd; 509 | prepareUrl(url, function(url) { 510 | set.call(_this, url); 511 | onEnd.call(_this); 512 | }); 513 | } 514 | }); 515 | redefineWithPrefixed(HTMLElm.prototype, attr, rewrittenAttr, descriptor); 516 | var realGetAttribute = HTMLElm.prototype.getAttribute; 517 | HTMLElm.prototype.getAttribute = function(attrName) { 518 | var realAttr = realGetAttribute.call(this, attrName); 519 | if(realAttr && attrName === attr) { 520 | return getURLFilename(realAttr, this.ownerDocument.baseURI); 521 | } 522 | return realAttr; 523 | }; 524 | }); 525 | defineDummy('src', 'airborn_src'); 526 | defineDummy('href', 'airborn_href'); 527 | defineWithPrefixed(HTMLAnchorElement.prototype, 'pathname', 'airborn_pathname', { 528 | get: function() { 529 | return this.airborn_href && new URL(this.airborn_href, 'file://').pathname; 530 | } 531 | }); 532 | defineDummy('pathname', 'airborn_pathname'); 533 | redefineWithPrefixed(Element.prototype, 'innerHTML', 'airborn_innerHTML', (get, set) => ({ 534 | get: get, 535 | set: function(html) { 536 | set.call(this, html); 537 | findNewElements(this); 538 | } 539 | })); 540 | defineDummy('innerHTML', 'airborn_innerHTML'); 541 | function findNewElements(context) { 542 | ['src', 'href', 'icon'].forEach(function(attrName) { 543 | Array.prototype.forEach.call(context.querySelectorAll( 544 | '[' + attrName + ']:not([' + attrName + '^="blob:"]):not([' + attrName + '^="data:"]):not([' + attrName + '^="http:"]):not([' + attrName + '^="https:"])' 545 | ), function(elm) { 546 | var attr = elm.getAttribute(attrName); 547 | if(attr && !rSchema.test(attr)) elm['airborn_' + attrName] = attr; 548 | }); 549 | }); 550 | } 551 | 552 | var windowOpen = window.open; 553 | window.open = function(url) { 554 | if(!rSchema.test(url)) { 555 | airborn.wm.openWindow(rootParent, {path: url}, null); 556 | return; 557 | } 558 | var win = windowOpen.apply(this, arguments); 559 | /* maybeWindowProxy(win) doesn't work in this case because at this point, 560 | * win contains about:blank. So we guess whether the window will be 561 | * same-origin with ours based on the url instead. 562 | */ 563 | if(url.substr(0, 9) === 'blob:null' || url.substr(0, 5) === 'data:') { 564 | return win; 565 | } else { 566 | return windowProxy(win); 567 | } 568 | }; 569 | 570 | var storageLocations = { 571 | apps: '/Apps/', 572 | music: '/Music/', 573 | pictures: '/Pictures/', 574 | sdcard: '/Documents/', 575 | system: '/Core/', 576 | videos: '/Videos/' 577 | }; 578 | function EventTarget() { 579 | var listeners = {}; 580 | this.addEventListener = function(eventName, fn) { 581 | if(!listeners[eventName]) listeners[eventName] = []; 582 | listeners[eventName].push(fn); 583 | }; 584 | this.removeEventListener = function(eventName, fn) { 585 | if(!listeners[eventName]) return; 586 | if(fn) { 587 | listeners[eventName] = listeners[eventName].filter(function(elm) { return elm !== fn; }); 588 | } else { 589 | listeners[eventName] = []; 590 | } 591 | }; 592 | this.dispatchEvent = function(event) { 593 | var _this = this; 594 | setTimeout(function() { 595 | Object.defineProperty(event, 'target', {get: function() { return _this; }}); 596 | if(listeners[event.type]) { 597 | listeners[event.type].forEach(function(fn) { 598 | fn.call(_this, event); 599 | }); 600 | } 601 | if(_this['on' + event.type]) { 602 | _this['on' + event.type](event); 603 | } 604 | }); 605 | return true; 606 | }; 607 | } 608 | function DOMRequest() { 609 | EventTarget.call(this); 610 | this.readyState = 'pending'; 611 | } 612 | DOMRequest.prototype = new EventTarget(); 613 | function DOMCursor() { 614 | DOMRequest.call(this); 615 | } 616 | DOMCursor.prototype = new DOMRequest(); 617 | if(!window.DOMError) { 618 | window.DOMError = function DOMError(name, message) { 619 | Object.defineProperty(this, 'name', {value: name}); 620 | Object.defineProperty(this, 'message', {value: message}); 621 | }; 622 | } 623 | function DeviceStorage(storageName) { 624 | EventTarget.call(this); 625 | Object.defineProperty(this, 'storageName', {value: storageName}); 626 | Object.defineProperty(this, 'default', {value: true}); 627 | var prefix = storageLocations[storageName]; 628 | var deviceStorage = this; 629 | airborn.fs.listenForFileChanges(prefix, function(path, reason) { 630 | if(path.substr(-1) !== '/' && !/\.history\//.test(path)) { 631 | var evt = new Event('change'); 632 | Object.defineProperty(evt, 'path', {value: toDeviceStoragePath(path)}); 633 | Object.defineProperty(evt, 'reason', {value: reason}); 634 | deviceStorage.dispatchEvent(evt); 635 | } 636 | }); 637 | } 638 | DeviceStorage.prototype = new EventTarget(); 639 | function toAirbornPath(deviceStorage, path) { 640 | if(path[0] === '/') { 641 | var parts = path.split('/'); 642 | if(storageLocations[parts[1]]) { 643 | return storageLocations[parts[1]] + parts.slice(2).join('/'); 644 | } 645 | return path; 646 | } 647 | return storageLocations[deviceStorage.storageName] + path; 648 | } 649 | function toDeviceStoragePath(path) { 650 | var parts = path.split('/'); 651 | Object.keys(storageLocations).forEach(function(deviceStorage) { 652 | if(storageLocations[deviceStorage] === '/' + parts[1] + '/') { 653 | parts[1] = deviceStorage; 654 | } 655 | }); 656 | return parts.join('/'); 657 | } 658 | DeviceStorage.prototype.onchange = null; 659 | DeviceStorage.prototype.available = function() { 660 | var request = new DOMRequest(); 661 | request.result = 'available'; 662 | request.dispatchEvent(new Event('success')); 663 | return request; 664 | }; 665 | DeviceStorage.prototype.addNamed = function(file, name) { 666 | var path = toAirbornPath(this, name); 667 | var request = new DOMRequest(); 668 | airborn.fs.getFile(airborn.path.dirname(path), {codec: 'dir'}, function(contents) { 669 | if(contents && contents.hasOwnProperty(airborn.path.basename(path))) { 670 | request.error = new DOMError('NoModificationAllowedError', 'The file already exists.'); 671 | request.dispatchEvent(new Event('error')); 672 | } else { 673 | airborn.fs.putFile(path, {codec: 'blob'}, file, function(err) { 674 | request.readyState = 'done'; 675 | if(err) { 676 | request.dispatchEvent(new Event('error')); 677 | } else { 678 | request.dispatchEvent(new Event('success')); 679 | } 680 | }); 681 | } 682 | }); 683 | return request; 684 | }; 685 | DeviceStorage.prototype.get = function(name) { 686 | var path = toAirbornPath(this, name); 687 | var request = new DOMRequest(); 688 | var dirname = airborn.path.dirname(path); 689 | var basename = airborn.path.basename(path); 690 | airborn.fs.getFile(dirname, {codec: 'dir'}, function(contents) { 691 | if(!contents || !contents.hasOwnProperty(basename)) { 692 | request.error = new DOMError('NotFoundError', "The file doesn't exist."); 693 | request.dispatchEvent(new Event('error')); 694 | } else { 695 | request.result = new AsyncFile({name: toDeviceStoragePath(path), type: contents[basename].type, path: path, lastModifiedDate: contents[basename].edited || new Date()}); 696 | request.dispatchEvent(new Event('success')); 697 | } 698 | }); 699 | return request; 700 | }; 701 | DeviceStorage.prototype.delete = function(name) { 702 | var path = toAirbornPath(this, name); 703 | var request = new DOMRequest(); 704 | var dirname = airborn.path.dirname(path); 705 | var basename = airborn.path.basename(path); 706 | airborn.fs.getFile(dirname, {codec: 'dir'}, function(contents) { 707 | delete contents[basename]; 708 | airborn.fs.putFile(dirname, {codec: 'dir'}, contents, function() { 709 | request.dispatchEvent(new Event('success')); 710 | }); 711 | }); 712 | return request; 713 | }; 714 | DeviceStorage.prototype.enumerate = function(_prefix) { 715 | var prefix = toAirbornPath(this, _prefix == null ? '' : _prefix); 716 | var prefixLen = prefix.length; 717 | var lastDir = prefix.split('/').slice(0, -1).join('/') + '/'; 718 | var cursor = new DOMCursor(); 719 | var files = []; 720 | (function add(path, done) { 721 | airborn.fs.getFile(path, {codec: 'dir'}, function(contents) { 722 | var dirs = 0, dirsdone = -1; 723 | if(contents) Object.keys(contents).forEach(function(name) { 724 | if(name.substr(-9) === '.history/') return; 725 | var filePath = path + name; 726 | if(_prefix && filePath.substr(0, prefixLen) !== prefix) return; 727 | if(name.substr(-1) === '/') { 728 | dirs++; 729 | add(filePath, dirdone); 730 | } else { 731 | files.push({name: toDeviceStoragePath(filePath), type: contents[name].type, path: filePath, lastModifiedDate: contents[name].edited || new Date()}); 732 | } 733 | }); 734 | function dirdone() { 735 | if(++dirsdone === dirs) done(); 736 | } 737 | dirdone(); 738 | }); 739 | })(lastDir, function() { 740 | cursor.readyState = 'done'; 741 | var next = 0; 742 | (cursor.continue = function() { 743 | this.result = files[next] && new AsyncFile(files[next]); 744 | this.done = !files[next]; 745 | next++; 746 | cursor.dispatchEvent(new Event('success')); 747 | }).call(cursor); 748 | }); 749 | return cursor; 750 | }; 751 | function AsyncFile(options) { 752 | var _this = this; 753 | Object.keys(options).forEach(function(key) { 754 | _this[key] = options[key]; 755 | }); 756 | } 757 | function extendFileReader(methodName, readerFn) { 758 | var origMethod = FileReader.prototype[methodName]; 759 | FileReader.prototype[methodName] = function(file) { 760 | if(file instanceof AsyncFile) { 761 | var reader = this; 762 | readerFn(file, function(result) { 763 | defineWithPrefixed(reader, 'result', 'airborn_result', {get: function() { return result; }}); 764 | setTimeout(function() { 765 | reader.dispatchEvent(new Event('load')); 766 | }); 767 | }); 768 | } else { 769 | origMethod.apply(this, arguments); 770 | } 771 | }; 772 | } 773 | defineDummy('result', 'airborn_result'); 774 | extendFileReader('readAsText', function(file, callback) { 775 | airborn.fs.getFile(file.path, callback); 776 | }); 777 | extendFileReader('readAsArrayBuffer', function(file, callback) { 778 | airborn.fs.getFile(file.path, {codec: 'arrayBuffer'}, callback); 779 | }); 780 | extendFileReader('readAsDataURL', function(file, callback) { 781 | airborn.fs.getFile(file.path, {codec: 'base64'}, function(contents) { 782 | callback('data:' + file.type + ';base64,' + contents); 783 | }); 784 | }); 785 | 786 | navigator.getDeviceStorage = function(storageName) { 787 | if(arguments.length !== 1) throw new TypeError('navigator.getDeviceStorage takes exactly one argument: storageName.'); 788 | if(!storageLocations[storageName]) return null; 789 | return new DeviceStorage(storageName); 790 | }; 791 | 792 | function Storage_(data) { 793 | var _this = this; 794 | Object.keys(data).forEach(function(key) { 795 | _this[key] = data[key]; 796 | }); 797 | } 798 | Storage_.prototype.getItem = function(name) { 799 | return this.hasOwnProperty(name) ? this[name] : null; 800 | }; 801 | Storage_.prototype.setItem = function(name, value) { 802 | this[name] = value + ''; 803 | flushStorage(); 804 | }; 805 | Storage_.prototype.removeItem = function(name) { 806 | delete this[name]; 807 | flushStorage(); 808 | }; 809 | Storage_.prototype.clear = function() { 810 | var _this = this; 811 | Object.keys(_this).forEach(function(key) { 812 | delete _this[key]; 813 | }); 814 | flushStorage(); 815 | }; 816 | Storage_.prototype.key = function(i) { 817 | return Object.keys(this)[i]; 818 | }; 819 | Object.defineProperty(Storage_.prototype, 'length', { 820 | get: function() { 821 | return Object.keys(this).length; 822 | } 823 | }); 824 | var localStorage = new Storage_(document.airborn_localStorage); 825 | var localStorageDescr; 826 | if(window.Proxy) { 827 | localStorageDescr = { 828 | value: new Proxy(localStorage, { 829 | set: function(target, name, value) { 830 | target.setItem(name, value); 831 | return true; 832 | }, 833 | deleteProperty: function(target, name) { 834 | target.removeItem(name); 835 | return true; 836 | }, 837 | }) 838 | }; 839 | } else { 840 | var stringifyStorageValues = function() { 841 | Object.keys(localStorage).forEach(function(key) { 842 | localStorage[key] += ''; 843 | }); 844 | }; 845 | var stringifyAndFlush = function() { 846 | stringifyStorageValues(); 847 | flushStorage(); 848 | }; 849 | localStorageDescr = { 850 | get: function() { 851 | stringifyStorageValues(); 852 | return localStorage; 853 | } 854 | }; 855 | setInterval(stringifyAndFlush, 300); 856 | window.addEventListener('unload', stringifyAndFlush); // Doesn't work on browser tab close or in Firefox 857 | } 858 | 859 | delete document.airborn_localStorage; 860 | defineWithPrefixed(window, 'localStorage', 'airborn_localStorage', localStorageDescr); 861 | var localStorageJSON = JSON.stringify(localStorage); 862 | function flushStorage() { 863 | var json = JSON.stringify(localStorage); 864 | if(json !== localStorageJSON) { 865 | airborn.fs.putFile(appData + 'localStorage', json); 866 | localStorageJSON = json; 867 | } 868 | } 869 | 870 | Object.defineProperty(document, 'airborn_cookie', {value: ''}); 871 | defineDummy('cookie', 'airborn_cookie'); 872 | 873 | function createLocationUrl(url, base) { 874 | var urlobj = new URL(url, 'file://' + (base || '')); 875 | var obj = { 876 | host: '', 877 | hostname: '', 878 | href: urlobj.href.substr(7), 879 | origin: 'null', 880 | pathname: urlobj.pathname, 881 | port: '', 882 | protocol: 'file:', 883 | search: urlobj.search 884 | }; 885 | Object.defineProperty(obj, 'hash', { 886 | get: function() { 887 | return window.location.hash; 888 | }, 889 | set: function(hash) { 890 | window.location.hash = hash; 891 | } 892 | }); 893 | obj.reload = window.location.reload.bind(window.location); 894 | return obj; 895 | } 896 | var locationurl = createLocationUrl(relativeParent.replace(rootParentWithoutSlash, '')); 897 | Object.defineProperty(window, 'airborn_location', { 898 | get: function() { 899 | return locationurl; 900 | }, 901 | }); 902 | defineDummy('location', 'airborn_location'); 903 | 904 | function setState(state, url) { 905 | locationurl = createLocationUrl(url, locationurl.href); 906 | Object.defineProperty(History.prototype, 'state', {value: state, enumerable: true, configurable: true}); 907 | } 908 | if(navigator.userAgent.match(/Safari/) && !navigator.userAgent.match(/Chrome/)) { 909 | var _history = window.history; 910 | window.History = function() {}; 911 | try { 912 | Object.defineProperty(window, 'history', {value: new window.History(), enumerable: true, configurable: true}); // Safari 10 913 | } catch(e) { 914 | window.history = new window.History(); // Safari 9 915 | } 916 | ['go', 'back', 'forward'].forEach(function(name) { 917 | window.History.prototype[name] = function() { 918 | _history[name].apply(_history, arguments); 919 | }; 920 | }); 921 | var hist = [{href: locationurl.href, state: null}]; 922 | var curr = 0; 923 | History.prototype.replaceState = function(state, title, url) { 924 | setState(state, url); 925 | hist[curr] = {href: locationurl.href, state: state}; 926 | window.location.hash = '#_airborn_state_' + curr; 927 | }; 928 | History.prototype.pushState = function(state, title, url) { // jshint ignore:line 929 | curr++; 930 | History.prototype.replaceState.apply(this, arguments); 931 | }; 932 | window.addEventListener('hashchange', function(evt) { 933 | if(window.location.hash.substr(0, 16) === '#_airborn_state_') { 934 | evt.stopImmediatePropagation(); 935 | if(curr === +window.location.hash.substr(16)) { 936 | return; 937 | } 938 | curr = +window.location.hash.substr(16); 939 | var state = hist[curr]; 940 | setState(state.state, state.href); 941 | var popstateevt = new Event('popstate'); 942 | Object.defineProperty(popstateevt, 'state', {value: state.state, enumerable: true, configurable: true}); 943 | window.dispatchEvent(popstateevt); 944 | } 945 | }, true); 946 | } else { 947 | var history_replaceState = History.prototype.replaceState; 948 | History.prototype.replaceState = function(state, title, url) { 949 | setState(state, url); 950 | history_replaceState.call(this, {href: locationurl.href, state: state, _airborn: true}, '', ''); 951 | }; 952 | var history_pushState = History.prototype.pushState; 953 | History.prototype.pushState = function(state, title, url) { 954 | setState(state, url); 955 | history_pushState.call(this, {href: locationurl.href, state: state, _airborn: true}, '', ''); 956 | }; 957 | window.addEventListener('popstate', function(evt) { 958 | if(evt.state && evt.state._airborn) { 959 | setState(evt.state.state, evt.state.href); 960 | Object.defineProperty(evt, 'state', {value: evt.state.state, enumerable: true, configurable: true}); 961 | } 962 | }, true); 963 | } 964 | 965 | function WindowProxy(window) { 966 | Object.defineProperty(this, 'airborn_top', { 967 | value: (function() { 968 | var top = window; 969 | while(top.parent.parent.parent !== top.parent.parent) top = top.parent; 970 | return top === window ? this : maybeWindowProxy(top); 971 | })() 972 | }); 973 | Object.defineProperty(this, 'airborn_parent', {value: this === this.airborn_top || window.parent === window ? this : maybeWindowProxy(window.parent)}); 974 | this.postMessage = function() { 975 | window.postMessage.apply(window, arguments); 976 | }; 977 | this.focus = function() { 978 | window.focus.apply(window, arguments); 979 | }; 980 | Object.defineProperty(this, 'location', {get: function() { return window.location; }, set: function(value) { window.location = value; }}); 981 | } 982 | var windowProxies = new Map(); 983 | function windowProxy(window) { 984 | if(windowProxies.has(window)) { 985 | return windowProxies.get(window); 986 | } 987 | var proxy = new WindowProxy(window); 988 | windowProxies.set(window, proxy); 989 | return proxy; 990 | } 991 | function maybeWindowProxy(window) { 992 | try { 993 | if(window.location.href === undefined) throw 0; 994 | } catch(e) { 995 | return windowProxy(window); 996 | } 997 | return window; 998 | } 999 | 1000 | Object.defineProperty(window, 'airborn_top', { 1001 | value: (function() { 1002 | var top = window; 1003 | while(top.parent.parent.parent !== top.parent.parent) top = top.parent; 1004 | return maybeWindowProxy(top); 1005 | })() 1006 | }); 1007 | defineDummy('top', 'airborn_top'); 1008 | 1009 | Object.defineProperty(window, 'airborn_parent', {value: window === window.airborn_top ? window : maybeWindowProxy(window.parent)}); 1010 | defineDummy('parent', 'airborn_parent'); 1011 | 1012 | redefineWithPrefixed(MessageEvent.prototype, 'source', 'airborn_source', get => ({get: function() { return maybeWindowProxy(get.call(this)); }})); 1013 | defineDummy('source', 'airborn_source'); 1014 | 1015 | redefineWithPrefixed(HTMLIFrameElement.prototype, 'contentWindow', 'airborn_contentWindow', get => ({get: function() { return maybeWindowProxy(get.call(this)); }})); 1016 | defineDummy('contentWindow', 'airborn_contentWindow'); 1017 | 1018 | if(window === window.airborn_top) { 1019 | var title = document.querySelector('head > title'); 1020 | airborn.wm.setTitle(title && title.textContent); 1021 | document.addEventListener('DOMContentLoaded', function() { 1022 | title = document.querySelector('head > title'); 1023 | if(title) { 1024 | airborn.wm.setTitle(title.textContent); 1025 | var observer = new window[window.MutationObserver ? 'MutationObserver' : 'WebKitMutationObserver'](function(mutations) { 1026 | mutations.forEach(function(mutation) { 1027 | airborn.wm.setTitle(mutation.target.textContent); 1028 | }); 1029 | }); 1030 | observer.observe(title, {subtree: true, characterData: true, childList: true}); 1031 | } 1032 | }); 1033 | } 1034 | 1035 | airborn.top_location = new URL(document.top_location); 1036 | delete document.top_location; 1037 | 1038 | window.MozActivity = function(options) { 1039 | var request = new DOMRequest(); 1040 | if(options.name === 'pick') { 1041 | var input = document.createElement('input'); 1042 | input.type = 'file'; 1043 | input.accept = options.data.type; 1044 | input.style.display = 'none'; 1045 | input.addEventListener('change', function() { 1046 | request.result = { 1047 | blob: input.files[0], 1048 | }; 1049 | request.dispatchEvent(new Event('success')); 1050 | }); 1051 | document.body.appendChild(input); 1052 | input.click(); 1053 | document.body.removeChild(input); 1054 | // Neither Chrome nor Firefox seems to mind sending change 1055 | // events to a file input that is not in the document, and 1056 | // there is no cancel event, so we wanna clean up after 1057 | // ourselves. We should listen to focus events to detect 1058 | // cancel to send an error event to the MozActivity, but 1059 | // Firetext doesn't need it and it's a bit of a hassle 1060 | // (Chrome doesn't seem to fire a blur event) so we 1061 | // currently don't. An additional benefit of immediately 1062 | // removing the element might be that it reduces the 1063 | // potential disruption of adding an element into a web app 1064 | // that doesn't expect it. 1065 | } else { 1066 | request.error = new DOMError('NotSupportedError', 'That activity is not supported.'); 1067 | request.dispatchEvent(new Event('error')); 1068 | } 1069 | return request; 1070 | }; 1071 | 1072 | function MockWorker() { 1073 | EventTarget.call(this); 1074 | } 1075 | MockWorker.prototype = new EventTarget(); 1076 | var RealWorker = window.Worker; 1077 | window.Worker = function(url) { 1078 | var mockWorker = new MockWorker(); 1079 | var messages = []; 1080 | mockWorker.postMessage = function() { 1081 | messages.push(arguments); 1082 | }; 1083 | airborn.fs.prepareUrl(url, {rootParent: rootParent, relativeParent: relativeParent, webworker: true}, function(url) { 1084 | var realWorker = new RealWorker(url); 1085 | realWorker.addEventListener('message', mockWorker.dispatchEvent.bind(mockWorker)); 1086 | mockWorker.postMessage = function() { 1087 | realWorker.postMessage.apply(realWorker, arguments); 1088 | }; 1089 | messages.forEach(function(message) { 1090 | mockWorker.postMessage.apply(mockWorker, message); 1091 | }); 1092 | }); 1093 | return mockWorker; 1094 | }; 1095 | 1096 | var messageHandlers = {}; 1097 | navigator.mozSetMessageHandler = function(event, handler) { 1098 | if(!messageHandlers[event]) { 1099 | messageHandlers[event] = []; 1100 | } 1101 | messageHandlers[event].push(handler); 1102 | }; 1103 | function mozCallMessageHandlers(event, data) { 1104 | if(messageHandlers[event]) { 1105 | messageHandlers[event].forEach(function(handler) { 1106 | handler(data); 1107 | }); 1108 | } 1109 | } 1110 | 1111 | var endpoints = {}; 1112 | var pushManager = { 1113 | register: function() { 1114 | var req = new DOMRequest(); 1115 | airborn.fs.pushRegister(function(data) { 1116 | switch(data.event) { 1117 | case 'registered': 1118 | endpoints[data.result] = { 1119 | pushEndpoint: data.result, 1120 | version: undefined 1121 | }; 1122 | req.result = data.result; 1123 | req.dispatchEvent(new Event('success')); 1124 | break; 1125 | case 'push': 1126 | if(!endpoints[data.result.pushEndpoint] || data.result.version <= endpoints[data.result.pushEndpoint].version) { 1127 | return; 1128 | } 1129 | endpoints[data.result.pushEndpoint] = { 1130 | pushEndpoint: data.result.pushEndpoint, 1131 | version: data.result.version 1132 | }; 1133 | mozCallMessageHandlers('push', data.result); 1134 | break; 1135 | case 'push-register': 1136 | endpoints = {}; 1137 | mozCallMessageHandlers('push-register', {}); 1138 | break; 1139 | } 1140 | }); 1141 | return req; 1142 | }, 1143 | unregister: function(endpoint) { 1144 | var req = new DOMRequest(); 1145 | airborn.fs.pushUnregister(endpoint, function() { 1146 | delete endpoints[endpoint]; 1147 | req.dispatchEvent(new Event('success')); 1148 | }); 1149 | return req; 1150 | }, 1151 | registrations: function() { 1152 | var req = new DOMRequest(); 1153 | req.result = Object.keys(endpoints).map(function(key) { return endpoints[key]; }); 1154 | req.dispatchEvent(new Event('success')); 1155 | return req; 1156 | } 1157 | }; 1158 | Object.defineProperty(navigator, 'push', {get: function() { return pushManager; }}); 1159 | })(); -------------------------------------------------------------------------------- /modules/window_manager/bar/laskyawm-bar.js: -------------------------------------------------------------------------------- 1 | /* This file is licensed under the Affero General Public License. */ 2 | 3 | (function() { 4 | // Add namespace 5 | var bar = window.bar = {}; 6 | 7 | // Add bar 8 | var barElement = document.createElement('div'); 9 | barElement.id = 'bar'; 10 | document.body.appendChild(barElement); 11 | 12 | // Add icon panel 13 | var barIcons = window.barIcons = document.createElement('div'); 14 | barIcons.id = 'barIcons'; 15 | barElement.appendChild(barIcons); 16 | 17 | bar.addItem = function(node) { 18 | barIcons.appendChild(node); 19 | bar.updateWidth(); 20 | }; 21 | 22 | bar.removeItem = function(node) { 23 | barIcons.removeChild(node); 24 | bar.updateWidth(); 25 | }; 26 | 27 | bar.updateWidth = function() { 28 | document.body.style.setProperty('--bar-icons-width', barIcons.offsetWidth + 'px'); 29 | }; 30 | 31 | bar.updateWidth(); 32 | })(window); -------------------------------------------------------------------------------- /modules/window_manager/bar/res/css/laskyawm-bar.css: -------------------------------------------------------------------------------- 1 | #bar { 2 | background-color: rgba(255, 255, 255, .5); 3 | z-index: -1000; 4 | position: absolute; 5 | width: 100%; 6 | height: 25px; 7 | color: white; 8 | text-shadow: 1px 1px 1px black; 9 | } 10 | .barButton { 11 | color: white; 12 | text-shadow: 1px 1px 1px black; 13 | cursor: pointer; 14 | font-weight: bold; 15 | } 16 | #toggleApps { 17 | padding: 3px 0; 18 | height: 25px; 19 | width: 100px; 20 | text-align: center; 21 | display: inline-block; 22 | } 23 | #barIcons { 24 | float: right; 25 | } 26 | #barIcons > * { 27 | padding: 3px 0; 28 | font-size: 15px; 29 | float: right; 30 | } 31 | #togglePowerMenu { 32 | padding: 4px 10px; 33 | margin: 0; 34 | line-height: 17px; 35 | } 36 | .barMenu { 37 | z-index: 1000; 38 | position: absolute; 39 | background: white; 40 | padding: 10px; 41 | border-radius: 7px; 42 | filter: drop-shadow(0 0 3px #888); 43 | top: 34px; 44 | } 45 | .barMenu:not(.shown) { 46 | display: none; 47 | } 48 | #apps { 49 | left: 20px; 50 | } 51 | #powerMenu { 52 | right: 5px; 53 | } 54 | .barMenu:after { 55 | content: ' '; 56 | height: 0; 57 | position: absolute; 58 | width: 0; 59 | border: 11px solid transparent; 60 | border-bottom-color: white; 61 | top: -22px; 62 | pointer-events: none; 63 | } 64 | #apps:after { 65 | left: 12px; 66 | } 67 | #powerMenu:after { 68 | right: 7px; 69 | } 70 | .barMenu > div { 71 | cursor: pointer; 72 | } 73 | .barMenu > div > img { 74 | width: 16px; 75 | height: 16px; 76 | margin-right: 5px; 77 | } -------------------------------------------------------------------------------- /modules/window_manager/bar/res/img/power.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/airbornio/airborn/2bb4685212c9a9da63940cea789a1a9fe2ac39ed/modules/window_manager/bar/res/img/power.png -------------------------------------------------------------------------------- /modules/window_manager/bar/res/js/laskyawm-clock.js: -------------------------------------------------------------------------------- 1 | /* This file is licensed under the Affero General Public License. */ 2 | 3 | /*global deviceType */ 4 | 5 | (function() { 6 | // Don't show clock on mobile 7 | if(deviceType === 'mobile') { 8 | return; 9 | } 10 | 11 | // Create clock widget 12 | var clock = document.createElement('span'); 13 | clock.id = 'barClock'; 14 | updateTime(); 15 | 16 | // Add to bar 17 | window.bar.addItem(clock); 18 | 19 | // Prevent freeze 20 | var updateTimeout; 21 | 22 | function updateTime() { 23 | // Clear timeout 24 | clearTimeout(updateTimeout); 25 | 26 | // Get time 27 | var currentTime = new Date(); 28 | clock.textContent = currentTime.toLocaleTimeString(navigator.languages || navigator.language, {hour: 'numeric', minute: 'numeric'}).replace(/(:..):../, '$1'); 29 | 30 | // Keep up-to-date 31 | updateTimeout = setTimeout(updateTime, 60000 - (currentTime.getSeconds() * 1000) - currentTime.getMilliseconds()); 32 | } 33 | })(); -------------------------------------------------------------------------------- /modules/window_manager/bar/res/js/laskyawm-power.js: -------------------------------------------------------------------------------- 1 | /* This file is licensed under the Affero General Public License. */ 2 | 3 | /*global airborn, deviceType, bar */ 4 | 5 | var powerMenu; 6 | 7 | var togglePowerMenu = document.createElement('input'); 8 | togglePowerMenu.id = 'togglePowerMenu'; 9 | togglePowerMenu.className = 'barButton'; 10 | togglePowerMenu.type = 'image'; 11 | togglePowerMenu.alt = 'Log Out…'; 12 | airborn.fs.prepareUrl('/Core/modules/window_manager/bar/res/img/power.png', {rootParent: '/'}, function(url) { 13 | togglePowerMenu.src = url; 14 | togglePowerMenu.addEventListener('load', function() { 15 | bar.updateWidth(); 16 | }); 17 | }); 18 | togglePowerMenu.addEventListener('click', function() { 19 | powerMenu.classList.toggle('shown'); 20 | }); 21 | bar.addItem(togglePowerMenu); 22 | 23 | powerMenu = document.createElement('div'); 24 | powerMenu.id = 'powerMenu'; 25 | powerMenu.className = 'barMenu'; 26 | ['Plans', 'Feedback'].forEach(function(page) { 27 | var link = document.createElement('div'); 28 | link.tabIndex = '0'; 29 | link.textContent = page; 30 | if(deviceType === 'desktop') { 31 | link.style.borderBottom = '1px solid #aaa'; 32 | link.style.paddingBottom = '5px'; 33 | link.style.marginBottom = '6px'; 34 | } 35 | link.addEventListener('click', function() { 36 | window.open(airborn.top_location.origin + '/' + page.toLowerCase()); 37 | }); 38 | powerMenu.appendChild(link); 39 | }); 40 | var logout = document.createElement('div'); 41 | logout.tabIndex = '0'; 42 | logout.textContent = 'Log Out'; 43 | logout.addEventListener('click', function() { 44 | airborn.core.logout(); 45 | }); 46 | powerMenu.appendChild(logout); 47 | document.body.appendChild(powerMenu); 48 | 49 | document.documentElement.addEventListener('click', function(evt) { 50 | if(evt.target !== powerMenu && evt.target !== togglePowerMenu) powerMenu.classList.remove('shown'); 51 | }); -------------------------------------------------------------------------------- /modules/window_manager/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /modules/window_manager/launcher/launcher.js: -------------------------------------------------------------------------------- 1 | /* This file is licensed under the Affero General Public License. */ 2 | 3 | /*global airborn, openTab, getName, getIconUrl */ 4 | 5 | var apps; 6 | 7 | var toggleApps = document.createElement('div'); 8 | toggleApps.id = 'toggleApps'; 9 | toggleApps.className = 'barButton'; 10 | toggleApps.textContent = 'Apps'; 11 | toggleApps.tabIndex = '0'; 12 | toggleApps.addEventListener('click', function() { 13 | apps.classList.toggle('shown'); 14 | }); 15 | toggleApps.addEventListener('keypress', function(evt) { 16 | if(evt.which === 13 || evt.which === 32) { 17 | apps.classList.toggle('shown'); 18 | } 19 | }); 20 | document.body.appendChild(toggleApps); 21 | 22 | apps = document.createElement('div'); 23 | apps.id = 'apps'; 24 | apps.className = 'barMenu'; 25 | apps.textContent = 'Loading…'; 26 | document.body.appendChild(apps); 27 | 28 | loadApps(); 29 | 30 | document.body.addEventListener('click', function(evt) { 31 | var app = evt.target; 32 | if(!app) return; 33 | while(app.className !== 'app') { 34 | app = app.parentElement; 35 | if(!app || app.parentElement === app) return; 36 | } 37 | openTab(app.dataset.path); 38 | }); 39 | document.body.addEventListener('keypress', function(evt) { 40 | if(evt.which !== 13) return; 41 | var app = evt.target; 42 | if(!app) return; 43 | while(app.className !== 'app') { 44 | app = app.parentElement; 45 | if(!app || app.parentElement === app) return; 46 | } 47 | app.click(); 48 | apps.classList.remove('shown'); 49 | }); 50 | 51 | function loadApps() { 52 | var fragment = document.createDocumentFragment(); 53 | airborn.fs.getFile('/Apps/', {codec: 'dir'}, function(contents) { 54 | var total = 0, done = 0, allApps = {}; 55 | Object.keys(contents).forEach(function(line) { 56 | if(line.substr(-9) !== '.history/') { 57 | total++; 58 | airborn.fs.getFile('/Apps/' + line + 'manifest.webapp', function(manifest) { 59 | manifest = manifest ? JSON.parse(manifest.replace(/^\uFEFF/, '')) : {}; 60 | var name = getName(manifest); 61 | var icon = getIconUrl(manifest.icons); 62 | if(icon) { 63 | airborn.fs.prepareUrl(icon, {relativeParent: '/Apps/' + line, rootParent: '/Apps/' + line}, function(url) { 64 | allApps[line] = {name: name, path: line, iconUrl: url}; 65 | maybeCont(); 66 | }); 67 | } else { 68 | allApps[line] = {name: name, path: line}; 69 | maybeCont(); 70 | } 71 | }); 72 | } 73 | }); 74 | function maybeCont() { 75 | if(++done === total) cont(); 76 | } 77 | function cont() { 78 | Object.keys(allApps).sort().forEach(function(key) { 79 | var props = allApps[key]; 80 | var app = document.createElement('div'); 81 | app.className = 'app'; 82 | app.textContent = props.name.replace(/ /g, '\u00a0'); 83 | var icon = document.createElement('img'); 84 | icon.src = props.iconUrl || ''; 85 | app.insertBefore(icon, app.firstChild); 86 | app.tabIndex = '0'; 87 | app.title = props.name; 88 | app.dataset.path = '/Apps/' + props.path; 89 | fragment.appendChild(app); 90 | }); 91 | apps.innerHTML = ''; 92 | apps.appendChild(fragment); 93 | } 94 | }); 95 | } 96 | 97 | airborn.fs.listenForFileChanges('/Apps/', function(path) { 98 | if(path === '/Apps/') loadApps(); 99 | }); 100 | 101 | document.documentElement.addEventListener('click', function(evt) { 102 | if(evt.target !== apps && evt.target !== toggleApps) apps.classList.remove('shown'); 103 | }); -------------------------------------------------------------------------------- /modules/window_manager/res/css/main.css: -------------------------------------------------------------------------------- 1 | * { 2 | box-sizing: border-box; 3 | } 4 | html { 5 | height: 100%; 6 | } 7 | body { 8 | margin: 0; 9 | cursor: default; 10 | font-family: Calibri, Lato, Ubuntu, sans-serif; 11 | height: 0; 12 | } 13 | .window { 14 | top: 0; 15 | left: 0; 16 | width: 100%; 17 | height: 100%; 18 | position: absolute !important; 19 | pointer-events: none; 20 | } 21 | .window .titlebar > *, 22 | .window .tabs { 23 | pointer-events: all; 24 | } 25 | .window .titlebar { 26 | height: 25px; 27 | padding-left: 100px; 28 | } 29 | .window .titlebar .tabbar { 30 | display: inline-block; 31 | white-space: nowrap; 32 | max-width: calc(100% - 38px - var(--bar-icons-width)); 33 | overflow: hidden; 34 | z-index: 1; 35 | position: relative; 36 | } 37 | .window .titlebar .tabbar:hover { 38 | overflow-x: auto; 39 | } 40 | .window .titlebar .tabbar .tabtitlebar, .window .titlebar .addtab { 41 | background-color: #DDD; 42 | display: inline-block; 43 | height: 25px; 44 | margin-right: 6px; 45 | line-height: 27px; 46 | padding: 0 10px; 47 | cursor: default; 48 | overflow: hidden; 49 | position: relative; 50 | vertical-align: top; 51 | } 52 | .window .titlebar .tabbar .tabtitlebar:last-child { 53 | margin-right: 0; 54 | } 55 | .window .titlebar .tabbar .tabtitlebar.focused { 56 | background-color: white; 57 | } 58 | .window .titlebar .addtab { 59 | margin-left: 6px; 60 | } 61 | .window .titlebar .icon { 62 | margin-right: 6px; 63 | height: 16px; 64 | vertical-align: -3px; 65 | } 66 | .window .tabs { 67 | height: calc(100% - 25px); 68 | } 69 | .window .tab { 70 | width: 100%; 71 | height: 100%; 72 | left: -100000px; 73 | position: absolute; 74 | 75 | /* Safari Mobile: allow scrolling in apps. 76 | * By default, Safari Mobile resizes iframes to fit their contents. 77 | * To "counteract" this, we make the iframe's container scrollable. 78 | * (http://stackoverflow.com/questions/23083462#23123845) 79 | */ 80 | overflow: auto; 81 | -webkit-overflow-scrolling: touch; 82 | } 83 | .window .tab.focused { 84 | left: 0; 85 | position: relative; 86 | } 87 | .window iframe { 88 | width: 100%; 89 | height: 100%; 90 | border: 0; 91 | background-color: white; 92 | position: absolute; 93 | left: 0; 94 | } 95 | .loader { 96 | position: absolute; 97 | top: 0; 98 | left: 0; 99 | height: 100%; 100 | pointer-events: none; 101 | } -------------------------------------------------------------------------------- /modules/window_manager/res/css/mobile.css: -------------------------------------------------------------------------------- 1 | #bar, 2 | #toggleApps, 3 | .window .titlebar, 4 | .window .titlebar .tabbar .tabtitlebar, 5 | .window .titlebar .addtab { 6 | height: 40px !important; 7 | line-height: 40px; 8 | } 9 | #toggleApps { 10 | padding: 0; 11 | } 12 | #togglePowerMenu { 13 | padding: 12px 17px; 14 | } 15 | .barMenu { 16 | top: 44px; 17 | } 18 | .barMenu > div { 19 | line-height: 32px; 20 | height: 32px; 21 | margin: 2px; 22 | } 23 | .barMenu > div > img { 24 | width: 32px; 25 | height: 32px; 26 | vertical-align: -9px; 27 | } 28 | .window .tabs { 29 | height: calc(100% - 40px); 30 | } 31 | .window .titlebar .tabbar { 32 | overflow-x: auto; 33 | } 34 | @media (max-width: 480px) { 35 | #toggleApps { 36 | display: none; 37 | } 38 | .window .titlebar { 39 | padding-left: 0; 40 | } 41 | } -------------------------------------------------------------------------------- /modules/window_manager/res/js/laskyawm.js: -------------------------------------------------------------------------------- 1 | /* This file is licensed under the Affero General Public License. */ 2 | 3 | /*global apps, getName: true, getIconUrl: true, powerMenu, airborn, airborn_localStorage, showProgress: true, setProgress: true, hideProgress: true, openWindow: true, openTab: true */ 4 | 5 | var deviceType = window.matchMedia('only screen and (max-device-width: 640px)').matches ? 'mobile' : 'desktop'; 6 | 7 | var childDiv; 8 | var childTabs = []; 9 | var childWindows = []; 10 | var childWindowsTabs = new Map(); 11 | 12 | 13 | window.addEventListener('message', function(message) { 14 | var tab = childWindowsTabs.get(message.source); 15 | if(tab) { 16 | if(message.data.action.substr(0, 3) === 'wm.') { 17 | var options; 18 | if(message.data.action === 'wm.focus') { 19 | } else if(message.data.action === 'wm.reportClicked') { 20 | apps.classList.remove('shown'); 21 | powerMenu.classList.remove('shown'); 22 | } else if(message.data.action === 'wm.setTitle') { 23 | var title = message.data.args[0] || getName(tab.manifest); 24 | tab.tabtitlebar.querySelector('.title').textContent = tab.title = title; 25 | tab.querySelector('iframe').name = title; // Webkit Developer Tools hint. 26 | if(tab.classList.contains('focused')) airborn.core.setTitle(title); 27 | updateDummyTabs(); 28 | } else if(message.data.action === 'wm.setIcon') { 29 | } else if(message.data.action === 'wm.openFile') { 30 | } else if(message.data.action === 'wm.openWindow') { 31 | window.openTab.apply(window, message.data.args); 32 | } else if(message.data.action === 'wm.showProgress' || message.data.action === 'wm.setProgress' || message.data.action === 'wm.hideProgress') { 33 | options = { 34 | loaderElm: tab.tabtitlebar.querySelector('.loader') 35 | }; 36 | window[message.data.action.substr(3)].apply(window, message.data.args.concat(options)); 37 | } else { 38 | throw 'unknown action'; 39 | } 40 | } else { 41 | throw 'unknown action'; 42 | } 43 | } 44 | }, false); 45 | 46 | showProgress = function(options) { 47 | if(!options.loaderElm) return; 48 | options.loaderElm.progressFrac = 0; 49 | setProgress(0.1, options); 50 | }; 51 | setProgress = function(frac, options) { 52 | if(!options.loaderElm) return; 53 | if(options.loaderElm.progressFrac >= frac) return; 54 | options.loaderElm.style.backgroundColor = 'rgba(77, 164, 213, .5)'; 55 | options.loaderElm.style.width = frac * 100 + '%'; 56 | options.loaderElm.progressFrac = frac; 57 | }; 58 | hideProgress = function(options) { 59 | if(!options.loaderElm) return; 60 | options.loaderElm.style.width = ''; 61 | }; 62 | 63 | getName = function(manifest) { 64 | var name; 65 | if(manifest.locales) { 66 | (navigator.languages || [navigator.language]).some(function(lang) { 67 | return (name = manifest.locales[lang] && manifest.locales[lang].name || lang === manifest.default_locale && manifest.name); 68 | }); 69 | } 70 | return name || manifest.name; 71 | }; 72 | 73 | var appIconSize = (deviceType === 'mobile' ? 32 : 64) * (window.devicePixelRatio || 1); 74 | getIconUrl = function(icons) { 75 | if(!icons) return; 76 | return icons[Object.keys(icons).sort(function(a, b) { 77 | if(a >= appIconSize && b >= appIconSize) return a - b; 78 | return b - a; 79 | })[0]]; 80 | }; 81 | 82 | openWindow = function() { 83 | var div = document.createElement('div'); 84 | div.className = 'window'; 85 | 86 | var titlebarDiv = document.createElement('div'); 87 | titlebarDiv.className = 'titlebar'; 88 | div.appendChild(titlebarDiv); 89 | 90 | var tabs = document.createElement('div'); 91 | tabs.className = 'tabs'; 92 | div.appendChild(tabs); 93 | 94 | var tabbar = document.createElement('div'); 95 | tabbar.className = 'tabbar'; 96 | tabbar.addEventListener('mousedown', function(evt) { 97 | evt.stopPropagation(); 98 | }); 99 | titlebarDiv.appendChild(tabbar); 100 | 101 | var addtab = document.createElement('div'); 102 | addtab.textContent = '+'; 103 | addtab.className = 'addtab'; 104 | addtab.addEventListener('click', function() { 105 | openTab(div.querySelector('.tab.focused').path); 106 | }); 107 | titlebarDiv.appendChild(addtab); 108 | 109 | document.body.appendChild(div); 110 | 111 | childDiv = div; 112 | }; 113 | 114 | openTab = function(path, options) { 115 | if(!options) options = {}; 116 | 117 | var div = childDiv; 118 | 119 | var tabs = div.querySelector('.tabs'); 120 | 121 | var tab = document.createElement('div'); 122 | tab.className = 'tab'; 123 | tabs.appendChild(tab); 124 | 125 | tab.path = path; 126 | 127 | var tabbar = div.querySelector('.tabbar'); 128 | 129 | var tabtitlebar = document.createElement('div'); 130 | tabtitlebar.className = 'tabtitlebar'; 131 | tabtitlebar.addEventListener('mousedown', function() { 132 | switchTab(tabtitlebar.tab); 133 | }); 134 | tabtitlebar.addEventListener(navigator.userAgent.includes('Firefox') ? 'click' : 'mousedown', function(evt) { 135 | focusTab(tabtitlebar.tab); 136 | evt.preventDefault(); // Prevent focus from leaving iframe. 137 | }); 138 | tabtitlebar.tab = tab; 139 | tab.tabtitlebar = tabtitlebar; 140 | tabbar.insertBefore(tabtitlebar, options.after && options.after.tabtitlebar.nextSibling); 141 | 142 | childTabs.splice(options.after ? childTabs.indexOf(options.after) + 1 : childTabs.length, 0, tab); 143 | 144 | airborn.fs.getFile(path + 'manifest.webapp', function(manifest) { 145 | 146 | manifest = manifest ? JSON.parse(manifest.replace(/^\uFEFF/, '')) : {}; 147 | 148 | var icon = document.createElement('img'); 149 | icon.className = 'icon'; 150 | var iconUrl = getIconUrl(manifest.icons); 151 | if(iconUrl) { 152 | airborn.fs.prepareUrl(iconUrl, {relativeParent: path, rootParent: path}, function(url) { 153 | icon.src = url; 154 | }); 155 | } 156 | tabtitlebar.appendChild(icon); 157 | 158 | var title = document.createElement('span'); 159 | title.className = 'title'; 160 | title.textContent = tab.title = getName(manifest); // This element needs at least a nbsp 161 | tabtitlebar.appendChild(title); 162 | 163 | var titleloader = document.createElement('div'); 164 | titleloader.className = 'loader'; 165 | tabtitlebar.appendChild(titleloader); 166 | 167 | tab.manifest = manifest; 168 | 169 | tab.dummy = options.dummy; 170 | updateDummyTabs(); 171 | 172 | if(options.dummy) { 173 | tabtitlebar.addEventListener('mousedown', function() { 174 | tab.tabtitlebar.style.display = 'none'; 175 | openTab(path, {after: tab}); 176 | }); 177 | } else { 178 | loadTab(path, options, tab); 179 | 180 | switchTab(tab); 181 | 182 | if(!options.after) { 183 | tabbar.scrollLeft = tabbar.scrollWidth; 184 | 185 | icon.addEventListener('load', function() { 186 | tabbar.scrollLeft = tabbar.scrollWidth; 187 | }); 188 | } 189 | 190 | airborn_localStorage.lastApp = path; 191 | } 192 | }); 193 | }; 194 | 195 | function loadTab(path, options, tab) { 196 | var manifest = tab.manifest; 197 | 198 | var launch_path = manifest.launch_path ? manifest.launch_path.replace(/^\//, '') : path.match(/[^/]+(?=\/$)/)[0] + '.html'; 199 | var _path = path + launch_path; 200 | var appData = path.replace('Apps', 'AppData'); 201 | 202 | var csp = manifest.csp || "default-src *; script-src 'self'; object-src 'none'; style-src 'self' 'unsafe-inline'"; 203 | if(csp.indexOf('-src ') !== -1) csp = csp.replace(/-src /g, '-src data: '); 204 | else csp = 'default-src data:; ' + csp; 205 | var storageLocations = { 206 | apps: '/Apps/', 207 | music: '/Music/', 208 | pictures: '/Pictures/', 209 | sdcard: '/Documents/', 210 | system: '/Core/', 211 | videos: '/Videos/' 212 | }; 213 | var appName = (_path.match('/Apps/(.+?)/') || [])[1]; 214 | var permissions = { 215 | read: [path, appData].concat(Object.keys(manifest.permissions || {}).filter(function(permission) { 216 | return storageLocations[permission.replace('device-storage:', '')] && ['readonly', 'readwrite', 'readcreate'].indexOf(manifest.permissions[permission].access) !== -1; 217 | }).map(function(permission) { 218 | return storageLocations[permission.replace('device-storage:', '')]; 219 | })), 220 | write: [appData].concat(Object.keys(manifest.permissions || {}).filter(function(permission) { 221 | return storageLocations[permission.replace('device-storage:', '')] && ['readwrite', 'readcreate', 'createonly'].indexOf(manifest.permissions[permission].access) !== -1; 222 | }).map(function(permission) { 223 | return storageLocations[permission.replace('device-storage:', '')]; 224 | })), 225 | manageApps: (manifest.permissions || {})['webapps-manage'], 226 | appName: appName, 227 | urlArgs: appName, 228 | getObjectLocations: (manifest.permissions || {})['get-object-locations'], 229 | }; 230 | airborn.fs.prepareUrl(options.path || '/', {rootParent: path, relativeParent: _path, permissions: permissions, csp: csp, appData: appData}, function(url) { 231 | var iframe = document.createElement('iframe'); 232 | iframe.sandbox = 'allow-scripts allow-forms allow-popups allow-modals allow-popups-to-escape-sandbox'; 233 | iframe.setAttribute('allowfullscreen', 'true'); 234 | iframe.src = url; 235 | iframe.name = path; // Webkit Developer Tools hint. 236 | tab.appendChild(iframe); 237 | 238 | childWindows.push(iframe.contentWindow); 239 | childWindowsTabs.set(iframe.contentWindow, tab); 240 | 241 | focusTab(tab); 242 | }); 243 | } 244 | 245 | function updateDummyTabs() { 246 | childTabs.forEach(function(tab, i) { 247 | if(tab.dummy) { 248 | var nextTab = childTabs[i + 1]; 249 | tab.tabtitlebar.style.display = nextTab && nextTab.path === tab.path && nextTab.title === tab.title ? 'none' : ''; 250 | } 251 | }); 252 | } 253 | 254 | 255 | openWindow(); 256 | 257 | openTab('/Apps/firetext/', {dummy: true}); 258 | openTab('/Apps/strut/', {dummy: true}); 259 | 260 | var hashArgumentOpenApp = airborn.top_location.hash.match(/[#&;]open=([^&;]+)/); 261 | var firstApp = 262 | hashArgumentOpenApp ? '/Apps/' + hashArgumentOpenApp[1].replace(/[./]/g, '') + '/' : 263 | airborn_localStorage.lastApp || 264 | '/Apps/firetext/'; 265 | openTab(firstApp, {after: firstApp === '/Apps/firetext/' ? childTabs[0] : null}); 266 | 267 | 268 | function switchTab(tab) { 269 | childDiv.querySelectorAll('.tabs .tab.focused, .tabtitlebar.focused').forEach(elm => elm.classList.remove('focused')); 270 | tab.classList.add('focused'); 271 | tab.tabtitlebar.classList.add('focused'); 272 | airborn.core.setTitle(tab.tabtitlebar.textContent.replace('\u00a0', '')); 273 | } 274 | 275 | function focusTab(tab) { 276 | tab.querySelector('iframe').focus(); 277 | } 278 | 279 | window.addEventListener('scroll', function() { 280 | window.scrollTo(0, 0); 281 | }); -------------------------------------------------------------------------------- /pre-commit: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | jshint $(git diff --cached --name-only --diff-filter=AM | egrep '.js$' | grep -v compat.js) --verbose && 4 | jscs $(git diff --cached --name-only --diff-filter=AM | egrep '.js$' | grep -v compat.js) && 5 | exit 0 6 | 7 | exit 1 --------------------------------------------------------------------------------