├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── LICENSE ├── README.md ├── app ├── build.gradle ├── icons │ ├── .gitignore │ ├── convert.sh │ └── lws_ic.svg ├── proguard-rules.txt └── src │ ├── betta │ └── res │ │ └── mipmap-xxxhdpi │ │ └── lws_ic.png │ ├── main │ ├── AndroidManifest.xml │ ├── assets │ │ ├── 403.html │ │ ├── 404.html │ │ ├── 416.html │ │ └── 500.html │ ├── java │ │ └── net │ │ │ └── basov │ │ │ └── lws │ │ │ ├── Constants.java │ │ │ ├── PreferencesActivity.java │ │ │ ├── Server.java │ │ │ ├── ServerHandler.java │ │ │ ├── ServerService.java │ │ │ └── StartActivity.java │ └── res │ │ ├── layout │ │ └── main.xml │ │ ├── mipmap-xxxhdpi │ │ └── lws_ic.png │ │ ├── values-v21 │ │ └── styles.xml │ │ ├── values │ │ ├── strings.xml │ │ └── styles.xml │ │ └── xml │ │ └── preferences.xml │ ├── release │ └── res │ │ └── mipmap-xxxhdpi │ │ └── lws_ic.png │ └── test │ └── java │ └── net │ └── basov │ └── lws │ └── ServerHandlerTest.java ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── ic_launcher-web.png └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | # Built application files 2 | build/ 3 | app/apk/ 4 | app/debug/ 5 | app/release/ 6 | app/beta/ 7 | 8 | # Crashlytics configuations 9 | /*/com_crashlytics_export_strings.xml 10 | 11 | # Local configuration file (sdk path, etc) 12 | local.properties 13 | /*/local.properties 14 | 15 | # Gradle generated files 16 | .gradle/ 17 | gradlew.bat 18 | 19 | # Signing files 20 | /*/.signing/ 21 | 22 | .idea/ 23 | 24 | *.iml 25 | 26 | # built application files 27 | *.apk 28 | *.ap_ 29 | 30 | # files for the dex VM 31 | *.dex 32 | 33 | # Java class files 34 | *.class 35 | 36 | # built native files 37 | *.o 38 | *.so 39 | 40 | # ProGuard mapping files 41 | *_mapping.txt 42 | 43 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: android 2 | android: 3 | components: 4 | - tools 5 | - platform-tools 6 | # The BuildTools version used by your project 7 | - build-tools-28.0.3 8 | # The SDK version used to compile your project 9 | - android-28 10 | before_script: 11 | - chmod ug+x ./gradlew 12 | #- sed -i -e '/signingConfigs.debug/d' app/build.gradle 13 | before_install: 14 | - yes | sdkmanager "platforms;android-28" 15 | 16 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | #### v07.00.00 (g) 2 | * Support Android O/P 3 | * Fallback bind to loopback 4 | * Several fixes 5 | 6 | #### v06.03.00b (g1b3161b) 7 | * Fix get AP IP address 8 | * Fix screen state after switcing off service from notification 9 | 10 | #### v06.02.00b (g521f4fb) 11 | * Request permission if need 12 | * FOREGROUND_SERVICE permission if need 13 | * Fix UTF-8 encoded document root 14 | 15 | #### v06.01.00b (g728324c) 16 | * Fix notification for Android 9 (P) (API 28) 17 | * Bind to loopback as fallback 18 | * minSdk is 10 19 | 20 | #### v06.00.00f (gbf50d54) 21 | #### v05.01.02f (g64632fd) 22 | #### v05.01.01f (g9538229) 23 | * Fake versions to trigger F-Driod publish 24 | 25 | #### v05.01.00b (g462fd90) 26 | * Update gradle configuration for Android Studio 3.2 27 | 28 | #### v05.00.00 (g2145b67) 29 | * Change lWS.QR call according to new API 30 | 31 | #### v04.02.00 (g7a05764) 32 | * Increase target API from 21 to 26 33 | 34 | #### v04.01.00 (g1bda4e4) 35 | * Change lWS.QR call according to new API 36 | 37 | ### v04.00.00 (gd747f64) 38 | * HEAD request and Last modified (incremental download) 39 | * Multipart range (video seek) 40 | * Directory index sort by name, date and size. New icons. 41 | * Add MIME types for audio files 42 | * Several fixes. 43 | 44 | #### v03.06.00b (g372ca97) 45 | * Default favicon.ico 46 | * Prepare code for release 47 | 48 | #### v03.05.00b (g4ccb846) 49 | * New design of directory index page 50 | * Fix bug with non ASCII file names v03.04.00b (g0efab1b) 51 | * Tweak directory listing design 52 | 53 | #### v03.03.00b (g6897fe2) 54 | * Directory listing sort 55 | 56 | #### v03.02.00b (g13af687) 57 | Since this version incremental download is possible. 58 | * Support Last-Modified 59 | * Support HEAD request 60 | 61 | #### v03.01.00b (g6141abe) 62 | * Support partial content (allow to seek video). 63 | 64 | ### v03.00.00 (g579b06e) 65 | * Add share URL by QR code. 66 | * Offer to install external program if need 67 | * Click on main screen variable values call corresponding settings. 68 | 69 | #### v02.03.00b (g7fb3791) 70 | * Offer to install OI File manager in attempt to use and it is not installed. 71 | 72 | #### v02.02.00b (ge329d5f) 73 | * support [QR code plugin](http://play.google.com/store/apps/details?id=net.basov.lws.qr.gpm") 74 | * Interface tweaks 75 | 76 | #### v02.01.00b (ga2077c8) 77 | * Add QR Code URL function 78 | * Fix service restart if configuration changed 79 | 80 | ### v02.00.00 (g36b7530) 81 | * Another service model to stable run in background 82 | * New 'Send URL' button 83 | * Add button to stop service from notification 84 | * More informative logging 85 | * Minimal Android version is 4.1 now 86 | * Check and fix wrong configuration values 87 | * Fix several NPE, ANR and other bugs 88 | 89 | #### v01.11.00b (g63a4a2d) 90 | * Add tethering AP switch off detection 91 | * More informative logging 92 | 93 | #### v01.10.00b (g8c53bf8) 94 | * Fix 'Use OI File Manager' preference issue 95 | * Several build system tweaks 96 | 97 | #### v01.09.00b (g5b9da2a) 98 | * New 'Send URL' button 99 | 100 | #### v01.08.00b (g6a995d3) 101 | * Fix issue with return from preferences 102 | 103 | #### v01.07.00b (g68e6e24) 104 | * Beta release to test ProGuard settings 105 | 106 | #### v01.06.00b (ca00cdb) 107 | * Display connection diagnostic on log screen 108 | * Fix default document root creation on legacy devices 109 | * Fix restart on configuration changed on legacy devices 110 | 111 | #### v01.05.00b (8fcb81b) 112 | * Improve stop service from notification issue 113 | * Make log selectable 114 | * Fix several bugs 115 | 116 | #### v01.04.00b (g7bf53e8) 117 | * Display application version at start 118 | * Fix configuration check and reset to default 119 | 120 | #### v01.03.00b (g722356c) 121 | * Fix NumberFormatException exception 122 | 123 | #### v01.02.00b (g86e678b) 124 | * Improve service stability 125 | * Add button to stop service from notification 126 | * Fix several NPE 127 | 128 | #### v01.01.00b (ga889b46) 129 | * Another service model to stable run in background 130 | * Check and fix configuration values 131 | * More informative logging 132 | * Fix several bugs 133 | 134 | ### v00.01.01b (g9efcd5f) 135 | * Fix 0 content length 136 | 137 | ### v01.00.00 (g06f4f90) 138 | * 1-st public release. 139 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 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 General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | lightweight Web Server (lWS) for Android. 635 | Copyright (C) 2017,2018 Mikhail Basov 636 | Copyright (C) 2009-2014 Markus Bode 637 | 638 | This program is free software: you can redistribute it and/or modify 639 | it under the terms of the GNU General Public License as published by 640 | the Free Software Foundation, either version 3 of the License, or 641 | (at your option) any later version. 642 | 643 | This program is distributed in the hope that it will be useful, 644 | but WITHOUT ANY WARRANTY; without even the implied warranty of 645 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 646 | GNU General Public License for more details. 647 | 648 | You should have received a copy of the GNU General Public License 649 | along with this program. If not, see . 650 | 651 | Also add information on how to contact you by electronic and paper mail. 652 | 653 | If the program does terminal interaction, make it output a short 654 | notice like this when it starts in an interactive mode: 655 | 656 | lWS Copyright (C) 2017,2018 Mikhail Basov 657 | androidwebserver Copyright (C) 2009-2014 Markus Bode 658 | 659 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 660 | This is free software, and you are welcome to redistribute it 661 | under certain conditions; type `show c' for details. 662 | 663 | The hypothetical commands `show w' and `show c' should show the appropriate 664 | parts of the General Public License. Of course, your program's commands 665 | might be different; for a GUI interface, you would use an "about box". 666 | 667 | You should also get your employer (if you work as a programmer) or school, 668 | if any, to sign a "copyright disclaimer" for the program, if necessary. 669 | For more information on this, and how to apply and follow the GNU GPL, see 670 | . 671 | 672 | The GNU General Public License does not permit incorporating your program 673 | into proprietary programs. If your program is a subroutine library, you 674 | may consider it more useful to permit linking proprietary applications with 675 | the library. If this is what you want to do, use the GNU Lesser General 676 | Public License instead of this License. But first, please read 677 | . 678 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## lightweight Web Server (lWS) for Android 2 | 3 | Available on Google Play 4 | Tavis CI Build Status 5 | Available on F-Droid 6 | 7 | 8 | 9 | 10 | 22 | 23 |
lWS

lWS

11 |

It is ...

12 |
    13 |
  • ... Web Server for static content.
  • 14 |
  • ... lightweight. APK size less then 100 Kb.
  • 15 |
  • ... as simple as possible. Only essential features implemented.
  • 16 |
  • ... open. Source code released under GPL-3.0.
  • 17 |
  • ... personal solution. It is not optimized/tested for many parallel connections and large file transfer.
  • 18 |
  • ... network state responsive. Require WiFi connected or tethering enabled. Service stop automatically if network disconnected.
  • 19 |
  • ... connect to lopback interface if no other available.
  • 20 |
21 |
24 | 25 | ### Derivate from 26 | This project based on [another open source project](https://github.com/bodeme/androidwebserver) 27 | Unfortunately, original project didn't maintained for 3 years. 28 | 29 | ### What is configurable 30 | * Document root. Path may be entered as text or optional elected using OI File Manager. 31 | * Port. May be from 1024 to 65535. Default is 8080 32 | In attempt to set wrong value parameter automatically set to default. 33 | 34 | ### Document root 35 | Document root by default set to application private directory. Example index file automatically created. It is safe configuration. You can place your pages in this directory. But be carefully! If you use Android 5.0 or above and deinstall the application this directory and it's content will be removed. 36 | 37 | ### "Open in browser" and "Send URL" 38 | After server starts you can press "Open in browser" button for check. 39 | You can send working server URL to another device by Bluetooth, Android Beam, E-Mail and other way available on your device. 40 | 41 | ### On screen log 42 | The application has no permanent logging. I treat this as redundant functionality. I doing my best to make notification actual all time. On screen log actual only then application visible. Log screen may be cleared after returning from background. 43 | 44 | ### Security warning 45 | You can change document root to any readable point of file system, but you need to understand what are you doing. 46 | Be careful: you could (suddenly?) create the configuration so way, than anyone on the same WiFi network could access to the data on your device either you don't like it. 47 | All files from document root and below available for reading without any restrictions to anyone who connected to network and known URL of the server. 48 | 49 | ### License 50 | lWS is licensed under the [GPLv3 License](LICENSE) because [original project](https://github.com/bodeme/androidwebserver) 51 | Directory listing sort based on [this project](https://github.com/wmentzel/table-sort) licensed under GPL-3.0 52 | 53 | ### Artwork 54 | * File listing icons from [Feather project](https://feathericons.com/) released under MIT license. 55 | * Application icon designed specially for this application. 56 | 57 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | 5 | namespace "net.basov.lws" 6 | 7 | def last_tag = getGitRevParseInfo("describe --tags --abbrev=0") 8 | def commit_count = getGitRevParseInfo("rev-list --count ${last_tag}..") 9 | def current_commit = getGitRevParseInfo("rev-parse --short") 10 | 11 | applicationVariants.all { variant -> 12 | variant.outputs.all { output -> 13 | outputFileName = "lWS.${variant.versionName}.apk" 14 | if (variant.getBuildType().isMinifyEnabled()) { 15 | variant.assemble.doLast{ 16 | copy { 17 | from variant.mappingFile 18 | into output.outputFile.parent 19 | rename { String fileName -> 20 | "lWS." + versionName + "_mapping.txt" 21 | } 22 | } 23 | } 24 | } 25 | } 26 | 27 | } 28 | 29 | compileSdkVersion 34 30 | 31 | defaultConfig { 32 | // Keep two lines around applicationId unchanged to allow use patch for F-Droid build 33 | 34 | 35 | applicationId "net.basov.lws" 36 | 37 | 38 | // End of strings reserved for F-Droid patch 39 | minSdkVersion 10 40 | targetSdkVersion 34 41 | 42 | versionCode 70000 43 | versionName "07.00.00" 44 | } 45 | 46 | buildTypes { 47 | release { 48 | minifyEnabled true 49 | shrinkResources true 50 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' 51 | zipAlignEnabled true 52 | applicationIdSuffix '.r' 53 | versionNameSuffix "r-g" + current_commit 54 | resValue "string", "git_describe", getGitRevParseInfo("describe --tags --abbrev=1") 55 | } 56 | beta { 57 | minifyEnabled true 58 | shrinkResources true 59 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' 60 | applicationIdSuffix '.b' 61 | versionNameSuffix "b-g" + current_commit 62 | debuggable false 63 | resValue "string", "git_describe", getGitRevParseInfo("describe --tags --abbrev=1") 64 | } 65 | debug { 66 | debuggable true 67 | versionNameSuffix 'a-' + commit_count + "-g" + current_commit 68 | resValue "string", "git_describe", getGitRevParseInfo("describe --tags --abbrev=1") 69 | } 70 | } 71 | } 72 | 73 | dependencies { 74 | testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2' 75 | } 76 | 77 | static def getGitRevParseInfo (what) { 78 | def cmd = "git " + what + " HEAD" 79 | def proc = cmd.execute () 80 | proc.text.trim () 81 | } 82 | -------------------------------------------------------------------------------- /app/icons/.gitignore: -------------------------------------------------------------------------------- 1 | ./res 2 | *.png 3 | 4 | -------------------------------------------------------------------------------- /app/icons/convert.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | icon="lws_ic" 4 | 5 | for size in 24 36 48 72 96 144 192 512; do 6 | inkscape -z --export-background=#000000 --export-background-opacity=0 --export-png=${icon}_${size}.png --export-width=${size} --export-height=${size} $icon.svg 7 | done 8 | 9 | for res in ldpi mdpi hdpi xhdpi xxhdpi xxxhdpi; do 10 | mkdir -p ./res/mipmap-$res 11 | done 12 | 13 | pngcrush -q ${icon}_36.png ./res/mipmap-ldpi/${icon}.png; rm ${icon}_36.png 14 | pngcrush -q ${icon}_48.png ./res/mipmap-mdpi/${icon}.png; rm ${icon}_48.png 15 | pngcrush -q ${icon}_72.png ./res/mipmap-hdpi/${icon}.png; rm ${icon}_72.png 16 | pngcrush -q ${icon}_96.png ./res/mipmap-xhdpi/${icon}.png; rm ${icon}_96.png 17 | pngcrush -q ${icon}_144.png ./res/mipmap-xxhdpi/${icon}.png; rm ${icon}_144.png 18 | pngcrush -q ${icon}_192.png ./res/mipmap-xxxhdpi/${icon}.png; rm ${icon}_192.png 19 | 20 | pngcrush -q ${icon}_24.png ./res/${icon}_24.png; rm ${icon}_24.png; mv ./res/${icon}_24.png ./ 21 | pngcrush -q ${icon}_512.png ./res/${icon}_512.png; rm ${icon}_512.png; mv ./res/${icon}_512.png ./ 22 | -------------------------------------------------------------------------------- /app/icons/lws_ic.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | image/svg+xml -------------------------------------------------------------------------------- /app/proguard-rules.txt: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /app/src/betta/res/mipmap-xxxhdpi/lws_ic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mvbasov/lWS/2927de4656826631a8bf13d48c7ccc8c489f2286/app/src/betta/res/mipmap-xxxhdpi/lws_ic.png -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 8 | 10 | 12 | 14 | 17 | 18 | 22 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /app/src/main/assets/403.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Error 403 6 | 7 | 8 | 9 | 10 | 403 - Forbidden 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /app/src/main/assets/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Error 404 6 | 7 | 8 | 9 | 10 | 404 - File or directory not found 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /app/src/main/assets/416.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Error 416 6 | 7 | 8 | 9 | 10 | 416 - Range Not Satisfiable 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /app/src/main/assets/500.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Error 500 6 | 7 | 8 | 9 | 10 | 500 - Internal server error 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /app/src/main/java/net/basov/lws/Constants.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017-2019 Mikhail Basov 3 | * 4 | * Licensed under the GNU General Public License v3 5 | * 6 | * This program is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | * 19 | */ 20 | package net.basov.lws; 21 | 22 | import java.util.HashMap; 23 | import java.util.Map; 24 | 25 | /** 26 | * Created by mvb on 12/18/17. 27 | */ 28 | 29 | final class Constants { 30 | public static final String LOG_TAG = "lWS"; 31 | public static final String ACTION_STOP = "net.basov.lws.stop_service"; 32 | public static final int NOTIFICATION_ID = 690927; 33 | public static final int DIRECTORY_REQUEST = 170; 34 | public static final int MAIN_SCREEN_REQUEST = 171; 35 | public static final int STOP_SERVICE_REQUEST = 172; 36 | public static final int GRANT_WRITE_EXTERNAL_STORAGE = 173; 37 | public static final MimeType MIME_OCTAL = new MimeType("application/octet-stream", "file"); 38 | public static final Map MIME = new HashMap(30, 1.0F) { 39 | { 40 | put("html", new MimeType("text/html; charset=utf-8", "web")); 41 | put("css", new MimeType("text/css; charset=utf-8", "code")); 42 | put("js", new MimeType("text/javascript; charset=utf-8", "code")); 43 | put("txt", new MimeType("text/plain; charset=utf-8", "file-text")); 44 | put("md", new MimeType("text/markdown; charset=utf-8", "file-text")); 45 | put("gif", new MimeType("image/gif", "image")); 46 | put("png", new MimeType("image/png", "image")); 47 | put("jpg", new MimeType("image/jpeg", "image")); 48 | put("bmp", new MimeType("image/bmp", "image")); 49 | put("svg", new MimeType("image/svg+xml", "image")); 50 | put("ico", new MimeType("image/x-icon", "image")); 51 | put("zip", new MimeType("application/zip", "package")); 52 | put("gz", new MimeType("application/gzip", "package")); 53 | put("tgz", new MimeType("application/gzip", "package")); 54 | put("pdf", new MimeType("application/pdf", "file-text")); 55 | put("mp4", new MimeType("video/mp4", "video")); 56 | put("avi", new MimeType("video/x-msvideo", "video")); 57 | put("3gp", new MimeType("video/3gpp", "video")); 58 | put("mp3", new MimeType("audio/mpeg", "music")); 59 | put("ogg", new MimeType("audio/ogg", "music")); 60 | put("wav", new MimeType("audio/wav", "music")); 61 | put("flac", new MimeType("audio/flac", "music")); 62 | put("java", new MimeType("text/plain", "code")); 63 | put(".c", new MimeType("text/plain", "code")); 64 | put(".cpp", new MimeType("text/plain", "code")); 65 | put(".sh", new MimeType("text/plain", "code")); 66 | put(".py", new MimeType("text/plain", "code")); 67 | } 68 | }; 69 | 70 | static class MimeType { 71 | final String contentType; 72 | final String kind; 73 | 74 | public MimeType(String contentType, String kind) { 75 | this.contentType = contentType; 76 | this.kind = kind; 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /app/src/main/java/net/basov/lws/PreferencesActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017-2019 Mikhail Basov 3 | * 4 | * Licensed under the GNU General Public License v3 5 | * 6 | * This program is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation, either version 3 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License 17 | * along with this program. If not, see . 18 | * 19 | */ 20 | package net.basov.lws; 21 | 22 | /** 23 | * Created by mvb on 6/22/17. 24 | */ 25 | 26 | import android.content.ActivityNotFoundException; 27 | import android.content.Intent; 28 | import android.content.SharedPreferences; 29 | import android.net.Uri; 30 | import android.os.Bundle; 31 | import android.preference.EditTextPreference; 32 | import android.preference.Preference; 33 | import android.preference.PreferenceActivity; 34 | import android.preference.PreferenceManager; 35 | import android.preference.PreferenceScreen; 36 | import android.util.Log; 37 | import android.widget.Toast; 38 | 39 | import java.io.File; 40 | import java.io.UnsupportedEncodingException; 41 | import java.net.URLDecoder; 42 | 43 | import static net.basov.lws.Constants.*; 44 | 45 | public class PreferencesActivity extends PreferenceActivity implements 46 | SharedPreferences.OnSharedPreferenceChangeListener { 47 | 48 | @Override 49 | protected void onCreate(Bundle savedInstanceState) { 50 | super.onCreate(savedInstanceState); 51 | 52 | addPreferencesFromResource(R.xml.preferences); 53 | 54 | SharedPreferences defSharedPref = 55 | PreferenceManager.getDefaultSharedPreferences(this); 56 | 57 | Preference prefDocumentRoot = findPreference(getString(R.string.pk_document_root)); 58 | prefDocumentRoot.setSummary(defSharedPref.getString(getString(R.string.pk_document_root), "")); 59 | enableDirPicker( 60 | prefDocumentRoot, 61 | defSharedPref.getBoolean(getString(R.string.pk_use_directory_pick), false) 62 | ); 63 | 64 | Preference prefPort = findPreference(getString(R.string.pk_port)); 65 | prefPort.setSummary(defSharedPref.getString(getString(R.string.pk_port), "8080")); 66 | 67 | Intent incomingIntent = getIntent(); 68 | Bundle incomingExtras = incomingIntent.getExtras(); 69 | if (incomingExtras != null) { 70 | int incomingIndex = incomingExtras.getInt("item"); 71 | if (incomingIndex >= 0 && incomingIndex <= 2 ) { 72 | PreferenceScreen screen = getPreferenceScreen(); 73 | screen.onItemClick(null, null, incomingIndex , 0); 74 | } 75 | } 76 | 77 | } 78 | 79 | private void enableDirPicker(Preference p, Boolean enable) { 80 | if (enable) { 81 | p.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { 82 | @Override 83 | public boolean onPreferenceClick(Preference preference) { 84 | ((EditTextPreference) preference).getDialog().dismiss(); 85 | Intent intent = new Intent("org.openintents.action.PICK_DIRECTORY"); 86 | intent.putExtra("org.openintents.extra.BUTTON_TEXT", "Select document root"); 87 | try { 88 | startActivityForResult(intent, DIRECTORY_REQUEST); 89 | } catch (ActivityNotFoundException e) { 90 | Toast.makeText(PreferencesActivity.this, 91 | "OI File Manager not installed. Install or disable using.", 92 | Toast.LENGTH_LONG 93 | ).show(); 94 | Intent i = new Intent(Intent.ACTION_VIEW); 95 | i.setData(Uri.parse("market://details?id=org.openintents.filemanager")); 96 | startActivity(i); 97 | Log.w("lWS", "OI File Manager not found", e); 98 | } 99 | return true; 100 | } 101 | }); 102 | } else { 103 | p.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { 104 | @Override 105 | public boolean onPreferenceClick(Preference preference) { 106 | return false; 107 | } 108 | }); 109 | } 110 | 111 | } 112 | @Override 113 | protected void onActivityResult(int requestCode, int resultCode, Intent data) { 114 | if (requestCode == DIRECTORY_REQUEST && data != null) { 115 | String newValue = null; 116 | Uri uri = data.getData(); 117 | if (uri != null) { 118 | String path = uri.toString(); 119 | if (path.toLowerCase().startsWith("file://")) { 120 | newValue = path.replace("file://","") + "/"; 121 | } 122 | } 123 | try { 124 | newValue = URLDecoder.decode(newValue, "UTF-8"); 125 | } catch (UnsupportedEncodingException e) { 126 | Log.e("lWS", "Invalid document root picked up (URLDecoder)", e); 127 | } 128 | SharedPreferences sharedPreferences = 129 | PreferenceManager.getDefaultSharedPreferences(this); 130 | SharedPreferences.Editor editor = sharedPreferences.edit(); 131 | editor.putString(getString(R.string.pk_document_root), newValue); 132 | editor.putBoolean(getString(R.string.pk_pref_changed), true); 133 | editor.commit(); 134 | findPreference(getString(R.string.pk_document_root)).setSummary(newValue); 135 | } 136 | } 137 | 138 | @Override 139 | protected void onResume() { 140 | super.onResume(); 141 | getPreferenceScreen().getSharedPreferences() 142 | .registerOnSharedPreferenceChangeListener(this); 143 | } 144 | 145 | @Override 146 | protected void onPause() { 147 | super.onPause(); 148 | getPreferenceScreen().getSharedPreferences() 149 | .unregisterOnSharedPreferenceChangeListener(this); 150 | } 151 | 152 | @Override 153 | public void onDestroy(){ 154 | super.onDestroy(); 155 | } 156 | 157 | @Override 158 | public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, 159 | String key) { 160 | Preference pref = findPreference(key); 161 | SharedPreferences.Editor prefEdit = sharedPreferences.edit(); 162 | 163 | String pref_document_root = getString(R.string.pk_document_root); 164 | if (pref_document_root.equals(key)) { 165 | String defaultDocumentRoot = StartActivity.getFilesDir(this).getPath() + "/html/"; 166 | String documentRoot = sharedPreferences.getString(pref_document_root, defaultDocumentRoot); 167 | int docRootLength = documentRoot.length(); 168 | if (! new File(documentRoot).canRead() || docRootLength == 0){ 169 | documentRoot = defaultDocumentRoot; 170 | docRootLength = documentRoot.length(); 171 | Toast.makeText(PreferencesActivity.this, 172 | "Document root doesn't exists. Set to default.", 173 | Toast.LENGTH_LONG 174 | ).show(); 175 | Log.w("lWS", "Document root doesn't exists. Set to default."); 176 | prefEdit.putString(getString(R.string.pk_document_root), defaultDocumentRoot).commit(); 177 | } else if (documentRoot.charAt(docRootLength - 1) != '/') { 178 | // existing directory readable with and without trailing slash 179 | // but slash need for correct filename forming 180 | documentRoot = documentRoot + "/"; 181 | prefEdit.putString(getString(R.string.pk_document_root), documentRoot).commit(); 182 | } 183 | prefEdit.putBoolean(getString(R.string.pk_pref_changed), true).commit(); 184 | pref.setSummary(documentRoot); 185 | } 186 | 187 | String pref_port = getString(R.string.pk_port); 188 | if (pref_port.equals(key)) { 189 | Integer port; 190 | String portAsString = sharedPreferences.getString(pref_port,"8080"); 191 | try { 192 | port = Integer.valueOf(portAsString); 193 | } catch (NumberFormatException e) { 194 | port = 8080; 195 | Log.w(Constants.LOG_TAG, "Port preferences may be empty"); 196 | } 197 | if (port < 1024 || port > 65535 || portAsString.length() == 0) { 198 | port = 8080; 199 | portAsString = Integer.toString(port); 200 | Toast.makeText(PreferencesActivity.this, 201 | "Port less then 1024 or grate then 65535. Set to default.", 202 | Toast.LENGTH_LONG 203 | ).show(); 204 | Log.w("lWS", "Port less then 1024 or grate then 65535. Set to default."); 205 | prefEdit.putString(getString(R.string.pk_port), portAsString).commit(); 206 | } 207 | prefEdit.putBoolean(getString(R.string.pk_pref_changed), true).commit(); 208 | pref.setSummary(portAsString); 209 | } 210 | 211 | String pref_use_directory_pick = getString(R.string.pk_use_directory_pick); 212 | if (pref_use_directory_pick.equals(key)) { 213 | // don't set preferences changed flag if only use directory pick changed 214 | Preference prefDocumentRoot = findPreference(getString(R.string.pk_document_root)); 215 | enableDirPicker( 216 | prefDocumentRoot, 217 | sharedPreferences.getBoolean(pref_use_directory_pick, false) 218 | ); 219 | } 220 | 221 | } 222 | } 223 | -------------------------------------------------------------------------------- /app/src/main/java/net/basov/lws/Server.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017-2019 Mikhail Basov 3 | * Copyright (C) 2009-2014 Markus Bode 4 | * 5 | * Licensed under the GNU General Public License v3 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | * 20 | */ 21 | 22 | package net.basov.lws; 23 | 24 | import java.io.IOException; 25 | import java.net.InetAddress; 26 | import java.net.ServerSocket; 27 | import java.net.Socket; 28 | import java.util.LinkedList; 29 | 30 | import android.content.Context; 31 | import android.os.Handler; 32 | import android.util.Log; 33 | 34 | import static net.basov.lws.Constants.*; 35 | 36 | class Server extends Thread { 37 | private ServerSocket listener = null; 38 | private boolean running = true; 39 | private final String documentRoot; 40 | private static Handler mHandler; 41 | private final Context context; 42 | 43 | private static final LinkedList clientList = new LinkedList<>(); 44 | 45 | public Server(Handler handler, String documentRoot, String ip, int port, Context context) throws IOException { 46 | super(); 47 | this.documentRoot = documentRoot; 48 | this.context = context; 49 | Server.mHandler = handler; 50 | InetAddress ipAddress = InetAddress.getByName(ip); 51 | listener = new ServerSocket(port,0,ipAddress); 52 | } 53 | 54 | @Override 55 | public void run() { 56 | while( running ) { 57 | try { 58 | Socket client = listener.accept(); 59 | new ServerHandler(documentRoot, context, client, Server.mHandler).start(); 60 | clientList.add(client); 61 | } catch (IOException e) { 62 | // Don't set running=false at this point! 63 | // Give the server chance to create new socket if it is temporary problem 64 | // This lead repeating message 'Socket closed' message many (more then 100) times 65 | // but they suppressed by '... previous string repeated x times' logging functionality. 66 | StartActivity.putToLogScreen("I: " + e.getMessage(), mHandler); 67 | Log.e(LOG_TAG, e.getMessage()); 68 | } 69 | } 70 | } 71 | 72 | public void stopServer() { 73 | running = false; 74 | try { 75 | listener.close(); 76 | } catch (IOException e) { 77 | StartActivity.putToLogScreen("E: " + e.getMessage(), mHandler); 78 | Log.e("lWS", e.getMessage()); 79 | } 80 | } 81 | 82 | public synchronized static void remove(Socket s) { 83 | clientList.remove(s); 84 | } 85 | 86 | } 87 | -------------------------------------------------------------------------------- /app/src/main/java/net/basov/lws/ServerHandler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017-2019 Mikhail Basov 3 | * Copyright (C) 2009-2014 Markus Bode 4 | * 5 | * Licensed under the GNU General Public License v3 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | * 20 | */ 21 | 22 | package net.basov.lws; 23 | 24 | import android.annotation.SuppressLint; 25 | import android.content.Context; 26 | import android.content.res.AssetFileDescriptor; 27 | import android.content.res.AssetManager; 28 | import android.os.Handler; 29 | import android.util.Log; 30 | 31 | import java.io.BufferedInputStream; 32 | import java.io.BufferedOutputStream; 33 | import java.io.BufferedReader; 34 | import java.io.File; 35 | import java.io.FileInputStream; 36 | import java.io.IOException; 37 | import java.io.InputStreamReader; 38 | import java.io.PrintWriter; 39 | import java.io.UnsupportedEncodingException; 40 | import java.net.Socket; 41 | import java.net.URLEncoder; 42 | import java.net.URLDecoder; 43 | import java.text.DateFormat; 44 | import java.text.SimpleDateFormat; 45 | import java.util.ArrayList; 46 | import java.util.Arrays; 47 | import java.util.Collections; 48 | import java.util.Comparator; 49 | import java.util.Date; 50 | import java.util.TimeZone; 51 | import java.util.regex.Pattern; 52 | 53 | import static net.basov.lws.Constants.*; 54 | 55 | class ServerHandler extends Thread { 56 | private static final Pattern LINE_ENDINGS = Pattern.compile("\\n|\\r|\\n\\r"); 57 | private static final Pattern FOLDERS = Pattern.compile("[/]+"); 58 | private final Socket toClient; 59 | private final String documentRoot; 60 | private final Context context; 61 | private final Handler msgHandler; 62 | private final DateFormat DF; 63 | private final DateFormat FLDF; 64 | private Boolean requestHEAD = false; 65 | 66 | public ServerHandler(String documentRoot, Context context, Socket toClient, Handler msgHandler) { 67 | this.toClient = toClient; 68 | this.documentRoot = documentRoot; 69 | this.context = context; 70 | this.msgHandler = msgHandler; 71 | DF = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss"); 72 | DF.setTimeZone(TimeZone.getTimeZone("GMT")); 73 | FLDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 74 | } 75 | 76 | public void run() { 77 | String document = ""; 78 | String[] rangesArray = {}; 79 | requestHEAD = false; 80 | 81 | try { 82 | BufferedReader in = new BufferedReader(new InputStreamReader(toClient.getInputStream())); 83 | // Receive data 84 | while (true) { 85 | String s = in.readLine().trim(); 86 | if (s.equals("")) { 87 | break; 88 | } 89 | 90 | if (s.startsWith("HEAD")) 91 | requestHEAD = true; 92 | if (s.startsWith("GET") || s.startsWith("HEAD")) { 93 | int leerstelle = s.indexOf(" HTTP/"); 94 | document = s.substring(5,leerstelle); 95 | document = FOLDERS.matcher(document).replaceAll("/"); 96 | document = URLDecoder.decode(document, "UTF-8"); 97 | } 98 | if (s.startsWith("Range:")) { 99 | rangesArray = s 100 | .split("=", 2)[1] 101 | .split(","); 102 | } 103 | } 104 | } catch (Exception e) { 105 | Server.remove(toClient); 106 | try { 107 | toClient.close(); 108 | } 109 | catch (Exception ignored){} 110 | } 111 | showHtml(document, rangesArray); 112 | } 113 | 114 | private void send(String text) { 115 | String header = context.getString(R.string.header, 116 | context.getString(R.string.rc200), 117 | text.getBytes().length, 118 | DF.format(new Date()) + " GMT", // workaround to avoid +00:00 119 | "text/html" 120 | ); 121 | try { 122 | PrintWriter out = new PrintWriter(toClient.getOutputStream(), true); 123 | out.print(header); 124 | out.print(text); 125 | out.flush(); 126 | Server.remove(toClient); 127 | toClient.close(); 128 | } catch (Exception ignored) { 129 | } 130 | } 131 | 132 | private void showHtml(String document, String[] ranges) { 133 | int rc = 200; 134 | long fileSize = 0L; 135 | String fileModified = ""; 136 | String clientIP = ""; 137 | if(toClient != null 138 | && toClient.getRemoteSocketAddress() != null 139 | && toClient.getRemoteSocketAddress().toString() != null 140 | && toClient.getRemoteSocketAddress().toString().length() > 2 141 | ) { 142 | clientIP = toClient.getRemoteSocketAddress().toString().substring(1); 143 | int clientIPColon = clientIP.indexOf(':'); 144 | if (clientIPColon > 0) 145 | clientIP = clientIP.substring(0, clientIPColon); 146 | } 147 | 148 | // Standard-Doc 149 | if (document.equals("")) { 150 | document = "/"; 151 | } 152 | 153 | // Don't allow directory traversal 154 | if (document.contains("..")) { 155 | rc = 403; 156 | } 157 | 158 | // Search for files in document root 159 | document = documentRoot + document; 160 | document = FOLDERS.matcher(document).replaceAll("/"); 161 | 162 | try { 163 | if (!new File(document).exists()) { 164 | if (document.replace(documentRoot, "").equals("favicon.ico")) { 165 | // set fake rc for default favicon.ico 166 | rc = -2; 167 | } else { 168 | rc = 404; 169 | } 170 | } else if(document.charAt(document.length()-1) == '/') { 171 | // This is directory 172 | if (new File(document+"index.html").exists()) { 173 | document = document + "index.html"; 174 | } else { 175 | send(directoryHtmlIndex(document)); 176 | StartActivity.putToLogScreen( 177 | "rc: " 178 | + rc 179 | + ", " 180 | + clientIP 181 | + ", /" 182 | + document.replace(documentRoot, "") 183 | + " (dir. index)", 184 | msgHandler 185 | ); 186 | return; 187 | } 188 | } 189 | 190 | } catch (Exception e) { 191 | e.printStackTrace(); 192 | return; 193 | } 194 | 195 | try { 196 | String rcStr; 197 | String header; 198 | String contType; 199 | BufferedOutputStream outStream = new BufferedOutputStream(toClient.getOutputStream()); 200 | BufferedInputStream in; 201 | 202 | if (rc == 200) { 203 | in = new BufferedInputStream(new FileInputStream(document)); 204 | rcStr = context.getString(R.string.rc200); 205 | contType = getMimeTypeForDocument(document).contentType; 206 | } else if (rc == -2) { 207 | // favicon.ico doesn't exist. Send application icon instead. 208 | @SuppressLint("ResourceType") 209 | final AssetFileDescriptor raw = context 210 | .getResources() 211 | .openRawResourceFd(R.mipmap.lws_ic); 212 | in = new BufferedInputStream(raw.createInputStream()); 213 | fileSize = (long) in.available(); 214 | // mipmap resource modification time difficult to obtain 215 | // and has no meaning. Set current date instead. 216 | fileModified = DF.format(new Date()); 217 | rcStr = context.getString(R.string.rc200); 218 | contType = getMimeTypeForDocument(document).contentType; 219 | rc = 200; 220 | } else { 221 | String errAsset; 222 | AssetManager am = context.getAssets(); 223 | switch (rc) { 224 | case 404: 225 | rcStr = context.getString(R.string.rc404); 226 | errAsset = "404.html"; 227 | break; 228 | case 403: 229 | rcStr = context.getString(R.string.rc403); 230 | errAsset = "403.html"; 231 | break; 232 | case 416: 233 | errAsset = "416.html"; 234 | rcStr = context.getString(R.string.rc416); 235 | break; 236 | default: 237 | errAsset = "500.html"; 238 | rcStr = context.getString(R.string.rc500); 239 | break; 240 | } 241 | 242 | contType = "text/html"; 243 | in = new BufferedInputStream(am.open(errAsset)); 244 | fileSize = (long) in.available(); 245 | fileModified = DF.format(new File("file:///android_asset/"+errAsset).lastModified()) + " GMT"; // workaround to avoid +00:00 246 | 247 | } 248 | // If fileSize not 0 some error detected and fileSize already set 249 | // to assets file length 250 | File documentFile = new File(document); 251 | if (fileSize == 0L) fileSize = documentFile.length(); 252 | if (fileModified.length() == 0) fileModified = DF.format(documentFile.lastModified()) + " GMT"; // workaround to avoid +00:00 253 | if(ranges.length == 0 || rc != 200) { 254 | header = context.getString(R.string.header, 255 | rcStr, 256 | fileSize, 257 | fileModified, 258 | contType 259 | ); 260 | 261 | header = normalizeLineEnd(header); 262 | outStream.write(header.getBytes()); 263 | if (!requestHEAD) { 264 | byte[] fileBuffer = new byte[8192]; 265 | int bytesCount; 266 | while ((bytesCount = in.read(fileBuffer)) != -1) { 267 | outStream.write(fileBuffer, 0, bytesCount); 268 | } 269 | } 270 | String headMark = requestHEAD ? "(HEAD)":""; 271 | StartActivity.putToLogScreen( 272 | "rc: " 273 | + rc 274 | + ", " 275 | + clientIP 276 | + ", /" 277 | + document.replace(documentRoot, "") 278 | + headMark, 279 | msgHandler 280 | ); 281 | } else { 282 | // TODO: range error processing 283 | // TODO: number conversion error processing 284 | rc = 206; 285 | long partialHeaderLength = 0L; 286 | PartialRange[] boundaries = new PartialRange[ranges.length]; 287 | 288 | for (int i = 0; i < ranges.length; i++) { 289 | String strRangeBegin = ranges[i].split("-",2)[0]; 290 | String strRangeEnd = ranges[i].split("-",2)[1]; 291 | boundaries[i] = new PartialRange(); 292 | try { 293 | if (strRangeBegin.length() != 0 && strRangeEnd.length() != 0) { 294 | boundaries[i].begin = Long.parseLong(strRangeBegin); 295 | boundaries[i].end = Long.parseLong(strRangeEnd); 296 | } else if (strRangeBegin.length() != 0 && strRangeEnd.length() == 0) { 297 | boundaries[i].begin = Long.parseLong(strRangeBegin); 298 | boundaries[i].end = fileSize - 1; 299 | } else if (strRangeBegin.length() == 0 && strRangeEnd.length() != 0) { 300 | boundaries[i].begin = fileSize - Long.parseLong(strRangeEnd); 301 | boundaries[i].end = fileSize - 1; 302 | } 303 | } catch (NumberFormatException e ) { 304 | e.printStackTrace(); 305 | handleError416(outStream); 306 | return; 307 | } 308 | boundaries[i].size = boundaries[i].end - boundaries[i].begin + 1; 309 | if (boundaries[i].size <= 0 310 | || boundaries[i].end > fileSize 311 | || boundaries[i].begin > fileSize) { 312 | handleError416(outStream); 313 | return; 314 | } 315 | boundaries[i].header = ""; 316 | if (i != 0) boundaries[i].header += "\n"; 317 | boundaries[i].header += context.getString(R.string.range_header, 318 | context.getString(R.string.boundary_string), 319 | contType, 320 | boundaries[i].begin, // begin 321 | boundaries[i].end, // end 322 | fileSize // length 323 | ); 324 | boundaries[i].header = normalizeLineEnd(boundaries[i].header); 325 | 326 | partialHeaderLength += boundaries[i].size + boundaries[i].header.length(); 327 | } 328 | if (ranges.length > 1) partialHeaderLength += context.getString(R.string.boundary_string).length() + 2 + 4; // I don't know why + 4 329 | 330 | String headMark = requestHEAD ? "(HEAD)":""; 331 | StartActivity.putToLogScreen( 332 | "rc: " 333 | + rc 334 | + ", " 335 | + clientIP 336 | + ", /" 337 | + document.replace(documentRoot, "") 338 | + ", Range: " 339 | + Arrays.toString(ranges) 340 | + headMark, 341 | msgHandler 342 | ); 343 | 344 | header = context.getString(R.string.header_partial, 345 | context.getString(R.string.rc206), 346 | ranges.length > 1 ? "" : "\nContent-Range: bytes " + boundaries[0].begin+"-"+boundaries[0].end+"/" + fileSize, 347 | ranges.length > 1 ? partialHeaderLength : boundaries[0].size, 348 | ranges.length > 1 ? "multipart/byteranges; boundary=" + context.getString(R.string.boundary_string) : contType 349 | ); 350 | header = normalizeLineEnd(header); 351 | outStream.write(header.getBytes()); 352 | 353 | if (!requestHEAD) { 354 | for (PartialRange b : boundaries) { 355 | if (boundaries.length > 1) { 356 | outStream.write(b.header.getBytes()); 357 | } 358 | byte[] fileBuffer = new byte[8192]; 359 | int bytesCount; 360 | long currentPosition = b.begin; 361 | in = new BufferedInputStream(new FileInputStream(document)); 362 | in.skip(currentPosition); 363 | while ((bytesCount = in.read(fileBuffer)) != -1) { 364 | if (currentPosition + bytesCount <= b.end) 365 | currentPosition += bytesCount; 366 | else { 367 | outStream.write(fileBuffer, 0, (int) (b.end - currentPosition + 1)); 368 | break; 369 | } 370 | outStream.write(fileBuffer, 0, bytesCount); 371 | } 372 | } 373 | if (boundaries.length > 1) 374 | outStream.write(("\r\n--" + context.getString(R.string.boundary_string) + "\r\n").getBytes()); 375 | } 376 | 377 | } 378 | outStream.flush(); 379 | 380 | Server.remove(toClient); 381 | toClient.close(); 382 | } catch (Exception e) { 383 | e.printStackTrace(); 384 | Log.e(Constants.LOG_TAG, "showHtml() very complex and need to be written simpler ... "); 385 | } 386 | } 387 | 388 | private String directoryHtmlIndex(String dir) { 389 | StringBuilder html = new StringBuilder(context.getString( 390 | R.string.dir_list_top_html, 391 | dir.replace(documentRoot, ""), 392 | dir.replace(documentRoot, ""), 393 | dir.equals(documentRoot) ? "" : context.getString(R.string.dir_list_parent_dir) 394 | )); 395 | 396 | File[] allFiles = new File(dir).listFiles(); 397 | ArrayList dirs = new ArrayList(allFiles.length); 398 | ArrayList files = new ArrayList(allFiles.length); 399 | 400 | for (File i : allFiles) { 401 | if (i.isDirectory()) { 402 | dirs.add(new FileInfo()); 403 | dirs.get(dirs.size() - 1).name = i.getName(); 404 | dirs.get(dirs.size() - 1).date = FLDF.format(i.lastModified()); 405 | } else if (i.isFile()) { 406 | files.add(new FileInfo()); 407 | files.get(files.size() - 1).name = i.getName(); 408 | files.get(files.size() - 1).size = i.length(); 409 | files.get(files.size() - 1).date = FLDF.format(i.lastModified()); 410 | } 411 | } 412 | 413 | Comparator fileNameCmp = new Comparator(){ 414 | @Override 415 | public int compare(FileInfo f1, FileInfo f2) { 416 | return f1.name.compareToIgnoreCase(f2.name); 417 | } 418 | }; 419 | Collections.sort(dirs, fileNameCmp); 420 | Collections.sort(files, fileNameCmp); 421 | 422 | for (FileInfo d : dirs) { 423 | html.append(context.getString( 424 | R.string.dir_list_item, 425 | "folder", 426 | "folder", 427 | fileName2URL(d.name) + "/", 428 | d.name, 429 | d.date, 430 | 0, 431 | "-" 432 | )); 433 | } 434 | for (FileInfo f : files) { 435 | html.append(context.getString( 436 | R.string.dir_list_item, 437 | "file", 438 | getMimeTypeForDocument(f.name).kind, 439 | fileName2URL(f.name), 440 | f.name, 441 | f.date, 442 | f.size, 443 | bytesToKMGT(f.size) 444 | )); 445 | } 446 | 447 | html.append(context.getString(R.string.dir_list_bottom_html)); 448 | 449 | return html.toString(); 450 | } 451 | 452 | static MimeType getMimeTypeForDocument(String document) { 453 | String fileExt = document.substring( 454 | document.lastIndexOf('.')+1 455 | ).toLowerCase(); 456 | MimeType mimeType = MIME.get(fileExt); 457 | if (mimeType == null) { 458 | return mimeType; 459 | } else 460 | return MIME_OCTAL; 461 | } 462 | 463 | static String fileName2URL(String fn) { 464 | String ref = ""; 465 | try { 466 | ref = URLEncoder.encode(fn, "UTF-8").replace("+", "%20"); 467 | } catch (UnsupportedEncodingException ignored) { 468 | } 469 | return ref; 470 | } 471 | 472 | private void handleError416(BufferedOutputStream outStream) { 473 | try { 474 | AssetManager am = context.getAssets(); 475 | BufferedInputStream in = new BufferedInputStream(am.open("416.html")); 476 | 477 | String header = context.getString(R.string.header, 478 | context.getString(R.string.rc500), 479 | (long) in.available(), 480 | DF.format(new Date()) + " GMT", // workaround to avoid +00:00 481 | "text/html" 482 | ); 483 | outStream.write(header.getBytes()); 484 | 485 | byte[] fileBuffer = new byte[8192]; 486 | int bytesCount; 487 | while ((bytesCount = in.read(fileBuffer)) != -1) { 488 | outStream.write(fileBuffer, 0, bytesCount); 489 | } 490 | outStream.flush(); 491 | Server.remove(toClient); 492 | toClient.close(); 493 | } catch (NumberFormatException e) { 494 | e.printStackTrace(); 495 | } catch (IOException e) { 496 | e.printStackTrace(); 497 | } 498 | 499 | } 500 | private String bytesToKMGT(Long size) { 501 | String ret; 502 | if (size <= 1024) 503 | ret = String.format("%d b", size); 504 | else if (size > 1024 && size <= 1024*1024) 505 | ret = String.format("%.2f Kb", (float) size/1024.0); 506 | else if (size > 1024.0*1024.0 && size <= 1024.0*1024.0*1024.0) 507 | ret = String.format("%.2f Mb", (float) size/(1024*1024)); 508 | else if (size > 1024.0*1024.0*1024.0 && size <= 1024.0*1024.0*1024.0*1024.0) 509 | ret = String.format("%.2f Gb", (float) size/(1024.0*1024.0*1024.0)); 510 | else // Yes. I am optimist :) 511 | ret = String.format("%.2f Tb", (float) size/(1024.0*1024.0*1024.0*1024.0)); 512 | return ret; 513 | } 514 | 515 | private String normalizeLineEnd (String src) { 516 | return LINE_ENDINGS.matcher(src).replaceAll("\r\n"); 517 | } 518 | 519 | static class PartialRange { 520 | long begin; 521 | long end; 522 | long size; 523 | String header; 524 | } 525 | 526 | static class FileInfo { 527 | String name; 528 | long size; 529 | String date; 530 | } 531 | } 532 | -------------------------------------------------------------------------------- /app/src/main/java/net/basov/lws/ServerService.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017-2019 Mikhail Basov 3 | * Copyright (C) 2009-2014 Markus Bode 4 | * 5 | * Licensed under the GNU General Public License v3 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | * 20 | */ 21 | 22 | package net.basov.lws; 23 | 24 | import android.app.Notification; 25 | import android.app.NotificationChannel; 26 | import android.app.NotificationManager; 27 | import android.app.PendingIntent; 28 | import android.app.Service; 29 | import android.content.BroadcastReceiver; 30 | import android.content.Context; 31 | import android.content.Intent; 32 | import android.content.IntentFilter; 33 | import android.content.SharedPreferences; 34 | import android.graphics.BitmapFactory; 35 | import android.net.ConnectivityManager; 36 | import android.net.NetworkInfo; 37 | import android.net.wifi.SupplicantState; 38 | import android.net.wifi.WifiInfo; 39 | import android.net.wifi.WifiManager; 40 | import android.os.Binder; 41 | import android.os.Build; 42 | import android.os.Handler; 43 | import android.os.IBinder; 44 | import android.preference.PreferenceManager; 45 | import android.util.Log; 46 | 47 | import java.lang.reflect.Method; 48 | import java.net.InetAddress; 49 | import java.net.NetworkInterface; 50 | import java.net.SocketException; 51 | import java.util.Enumeration; 52 | 53 | import static net.basov.lws.Constants.*; 54 | 55 | public class ServerService extends Service { 56 | private NotificationManager mNM; 57 | private Server server; 58 | private boolean isRunning = false; 59 | private String ipAddress = ""; 60 | private static Handler gHandler; 61 | private static BroadcastReceiver mReceiver = null; 62 | 63 | @Override 64 | public int onStartCommand(Intent intent, int flags, int startId) { 65 | 66 | if (intent != null 67 | && intent.getAction() != null 68 | && intent.getAction().equals(ACTION_STOP) 69 | ) stopServer(); 70 | 71 | return super.onStartCommand(intent, flags, startId); 72 | } 73 | 74 | @Override 75 | public void onCreate() { 76 | mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); 77 | } 78 | 79 | public void startServer(Handler handler) { 80 | ServerService.gHandler = handler; 81 | try { 82 | WifiManager wifiManager = 83 | (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE); 84 | // Check Tethering AP state 85 | Boolean isWifiAPEnabled = isSharingWiFi(wifiManager); 86 | // Check WiFi state 87 | WifiInfo wifiInfo = wifiManager.getConnectionInfo(); 88 | 89 | final SharedPreferences sharedPreferences = 90 | PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); 91 | 92 | // Start server 93 | isRunning = true; 94 | if (isWifiAPEnabled) { 95 | ipAddress = getAPIpAddress(); 96 | } else { 97 | ipAddress = intToIp(wifiInfo.getIpAddress()); 98 | } 99 | int port = Integer.valueOf( 100 | sharedPreferences.getString( 101 | getString(R.string.pk_port), 102 | "8080" 103 | ) 104 | ); 105 | 106 | if ( 107 | ( 108 | (!wifiManager.isWifiEnabled()) 109 | || (wifiInfo.getSupplicantState() != SupplicantState.COMPLETED) 110 | || (wifiInfo.getIpAddress() == 0) 111 | ) 112 | && !isWifiAPEnabled 113 | ) { 114 | ipAddress="127.0.0.1"; 115 | StartActivity.putToLogScreen( 116 | "Connected to loopback interface (127.0.0.1)\nTo change it connect to a WiFi-network or start Tethering, then restart server.", 117 | gHandler, 118 | true 119 | ); 120 | } 121 | 122 | server = new Server( 123 | gHandler, 124 | sharedPreferences.getString(getString(R.string.pk_document_root), ""), 125 | ipAddress, 126 | port, 127 | getApplicationContext() 128 | ); 129 | server.start(); 130 | 131 | startForegroundService("Running on " + ipAddress + ":" + port); 132 | 133 | StartActivity.putToLogScreen( 134 | "I: Web server address http://" 135 | + ipAddress 136 | + ":" 137 | + port, 138 | gHandler 139 | ); 140 | 141 | // register broadcast receiver to monitor WiFi state 142 | if (mReceiver == null) { 143 | mReceiver = new BroadcastReceiver() { 144 | @Override 145 | public void onReceive(Context context, Intent intent) { 146 | 147 | if (getIpAddress().equals("127.0.0.1")) return; 148 | 149 | NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); 150 | if (info != null && info.getState() == NetworkInfo.State.DISCONNECTED) { 151 | StartActivity.putToLogScreen( 152 | "I: Web server stopped because WiFi disconnected.", 153 | gHandler 154 | ); 155 | stopServer(); 156 | } 157 | 158 | Integer tetheringState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0); 159 | if (tetheringState > 10) tetheringState -= 10; // Old android fix 160 | if (tetheringState == 10) { 161 | StartActivity.putToLogScreen( 162 | "I: Web server stopped because AP switched off.", 163 | gHandler 164 | ); 165 | stopServer(); 166 | } 167 | } 168 | }; 169 | IntentFilter filter = new IntentFilter(); 170 | filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); 171 | filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION); 172 | filter.addAction("android.net.wifi.WIFI_AP_STATE_CHANGED"); 173 | registerReceiver(mReceiver, filter); 174 | } 175 | 176 | } catch (Exception e) { 177 | isRunning = false; 178 | mNM.cancel(NOTIFICATION_ID); 179 | Log.e(LOG_TAG, e.getMessage()+ "(from ServerService.startServer())"); 180 | StartActivity.putToLogScreen("E: " + e.getMessage(), gHandler); 181 | } 182 | } 183 | 184 | private static String intToIp(int i) { 185 | return ((i ) & 0xFF) + "." + 186 | ((i >> 8 ) & 0xFF) + "." + 187 | ((i >> 16 ) & 0xFF) + "." + 188 | ( i >> 24 & 0xFF); 189 | } 190 | 191 | public void stopServer() { 192 | isRunning = false; 193 | ipAddress = ""; 194 | mNM.cancel(NOTIFICATION_ID); 195 | try { 196 | //TODO: Exception when unregister receiver which is new... 197 | if (mReceiver != null) { 198 | unregisterReceiver(mReceiver); 199 | mReceiver = null; 200 | } 201 | } catch (IllegalArgumentException e) { 202 | StartActivity.putToLogScreen( 203 | "E: Receiver unregister error again :( (stopServer())", 204 | gHandler 205 | ); 206 | Log.e(LOG_TAG, e.getMessage() + "on ServerService.stopServer()"); 207 | } 208 | if (null != server) { 209 | server.stopServer(); 210 | server.interrupt(); 211 | } 212 | stopForeground(true); 213 | stopSelf(); 214 | } 215 | 216 | private void startForegroundService(String message) { 217 | if (null == message || message.length()==0) return; 218 | 219 | PendingIntent contentIntent = PendingIntent.getActivity( 220 | this, 221 | Constants.MAIN_SCREEN_REQUEST, 222 | new Intent(this, StartActivity.class), 223 | PendingIntent.FLAG_UPDATE_CURRENT 224 | ); 225 | Intent stopIntent = new Intent(this,ServerService.class); 226 | stopIntent.setAction(Constants.ACTION_STOP); 227 | PendingIntent stopPendingIntent = PendingIntent.getService( 228 | this, 229 | Constants.STOP_SERVICE_REQUEST, 230 | stopIntent, 231 | PendingIntent.FLAG_UPDATE_CURRENT 232 | ); 233 | if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { 234 | Notification.Builder notificationBuilder = new Notification.Builder(this) 235 | .setSmallIcon(R.mipmap.lws_ic) 236 | .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.lws_ic)) 237 | .setContentTitle(getString(R.string.app_name)) 238 | .setContentText(message) 239 | .setWhen(System.currentTimeMillis()) 240 | .setContentIntent(contentIntent) 241 | .addAction(0, "Stop service", stopPendingIntent) 242 | .setOngoing(true); 243 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { 244 | notificationBuilder.setChannelId(this.getString(R.string.notif_ch_id)); 245 | } 246 | startForeground(NOTIFICATION_ID, notificationBuilder.build()); 247 | } 248 | } 249 | 250 | @Override 251 | public IBinder onBind(Intent intent) { 252 | if (!isRunning) mNM.cancel(NOTIFICATION_ID); 253 | return mBinder; 254 | } 255 | 256 | private final IBinder mBinder = new LocalBinder(); 257 | 258 | public class LocalBinder extends Binder { 259 | ServerService getService() { 260 | return ServerService.this; 261 | } 262 | } 263 | 264 | public boolean isRunning() { 265 | return isRunning; 266 | } 267 | 268 | @Override 269 | public void onDestroy() { 270 | stopServer(); 271 | stopSelf(); 272 | super.onDestroy(); 273 | } 274 | 275 | @Override 276 | public void onTaskRemoved(Intent rootIntent) { 277 | stopServer(); 278 | stopSelf(); 279 | super.onTaskRemoved(rootIntent); 280 | } 281 | 282 | public String getIpAddress() { return ipAddress; } 283 | 284 | // Code from https://stackoverflow.com/a/20432036 285 | // Check Tethering AP enabled 286 | private static boolean isSharingWiFi(final WifiManager manager) { 287 | try { 288 | final Method method = manager.getClass().getDeclaredMethod("isWifiApEnabled"); 289 | method.setAccessible(true); //in the case of visibility change in future APIs 290 | return (Boolean) method.invoke(manager); 291 | } 292 | catch (final Throwable ignored) { } 293 | return false; 294 | } 295 | 296 | // Code from https://stackoverflow.com/questions/17302220/android-get-ip-address-of-a-hotspot-providing-device 297 | // Get IP address in WiFi hotspot (tethering) mode 298 | private String getAPIpAddress() { 299 | String ip = ""; 300 | try { 301 | Enumeration enumNetworkInterfaces = NetworkInterface 302 | .getNetworkInterfaces(); 303 | while (enumNetworkInterfaces.hasMoreElements()) { 304 | NetworkInterface networkInterface = enumNetworkInterfaces 305 | .nextElement(); 306 | Enumeration enumInetAddress = networkInterface 307 | .getInetAddresses(); 308 | while (enumInetAddress.hasMoreElements()) { 309 | InetAddress inetAddress = enumInetAddress.nextElement(); 310 | 311 | if (inetAddress.isSiteLocalAddress() 312 | && ( 313 | networkInterface.getName().toLowerCase().contains("wlan") 314 | || networkInterface.getName().toLowerCase().contains("ap") 315 | ) 316 | ) { 317 | ip = inetAddress.getHostAddress(); 318 | } 319 | } 320 | } 321 | 322 | } catch (SocketException e) { 323 | Log.e(LOG_TAG, e.getMessage()); 324 | } 325 | return ip; 326 | } 327 | } 328 | -------------------------------------------------------------------------------- /app/src/main/java/net/basov/lws/StartActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2017-2019 Mikhail Basov 3 | * Copyright (C) 2009-2014 Markus Bode 4 | * 5 | * Licensed under the GNU General Public License v3 6 | * 7 | * This program is free software: you can redistribute it and/or modify 8 | * it under the terms of the GNU General Public License as published by 9 | * the Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, 13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | * GNU General Public License for more details. 16 | * 17 | * You should have received a copy of the GNU General Public License 18 | * along with this program. If not, see . 19 | * 20 | */ 21 | 22 | package net.basov.lws; 23 | 24 | import java.io.BufferedWriter; 25 | import java.io.File; 26 | import java.io.FileWriter; 27 | 28 | import android.Manifest; 29 | import android.app.Activity; 30 | import android.app.NotificationManager; 31 | import android.app.NotificationChannel; 32 | import android.content.ComponentName; 33 | import android.content.Context; 34 | import android.content.Intent; 35 | import android.content.ServiceConnection; 36 | import android.content.SharedPreferences; 37 | import android.content.pm.PackageManager; 38 | import android.net.Uri; 39 | import android.os.Build; 40 | import android.os.Bundle; 41 | import android.os.Environment; 42 | import android.os.Handler; 43 | import android.os.IBinder; 44 | import android.os.Message; 45 | import android.preference.PreferenceManager; 46 | import android.util.Log; 47 | import android.view.View; 48 | import android.view.View.OnClickListener; 49 | import android.widget.Button; 50 | import android.widget.LinearLayout; 51 | import android.widget.ScrollView; 52 | import android.widget.TextView; 53 | import android.widget.Toast; 54 | import android.widget.ToggleButton; 55 | 56 | import static net.basov.lws.Constants.*; 57 | 58 | public class StartActivity extends Activity { 59 | private static int prevMsgCount; 60 | private static String prevMsg; 61 | private ToggleButton btnStartStop; 62 | private static TextView viewLog; 63 | private static ScrollView viewScroll; 64 | private String documentRoot; 65 | 66 | private ServerService mBoundService; 67 | private ServiceConnection mConnection; 68 | 69 | 70 | @Override 71 | public void onCreate(Bundle savedInstanceState) { 72 | StartActivity.prevMsg = ""; 73 | StartActivity.prevMsgCount = 0; 74 | super.onCreate(savedInstanceState); 75 | setContentView(R.layout.main); 76 | setTitle(R.string.hello); 77 | 78 | btnStartStop = (ToggleButton) findViewById(R.id.buttonStartStop); 79 | viewLog = (TextView) findViewById(R.id.log); 80 | viewScroll = (ScrollView) findViewById(R.id.ScrollView); 81 | 82 | findViewById(R.id.buttonSettings) 83 | .setOnClickListener(makePrefListener(-1)); 84 | 85 | try { 86 | android.content.pm.PackageInfo pInfo = 87 | this.getPackageManager().getPackageInfo(this.getPackageName(), 0); 88 | String appName = 89 | this.getString(R.string.hello) 90 | + " v" 91 | + pInfo.versionName; 92 | log( 93 | appName 94 | + "\n" 95 | + new String(new char[appName.length()]).replace('\0', '*') 96 | ); 97 | } catch (PackageManager.NameNotFoundException e) { 98 | e.printStackTrace(); 99 | } 100 | 101 | PreferenceManager.setDefaultValues(this, R.xml.preferences, false); 102 | documentRoot = getDocumentRoot(); 103 | 104 | if(null == documentRoot) { 105 | log("E: Document-Root could not be found."); 106 | } 107 | 108 | /** 109 | * Hide QR Code plugin call button if run on SdkVersion older then 16 110 | * because plugin doesn't operate on older versions 111 | * If version is higher set total button group weight to 3 else set to 2 112 | */ 113 | LinearLayout btnGroup = findViewById(R.id.buttonsBlock); 114 | View btnQR = findViewById(R.id.buttonQRCodeURL); 115 | if (Build.VERSION.SDK_INT < 16) { 116 | btnQR.setVisibility(View.GONE); 117 | btnGroup.setWeightSum(2f); 118 | } else { 119 | btnGroup.setWeightSum(3f); 120 | } 121 | 122 | btnStartStop.setOnClickListener(new OnClickListener() { 123 | public void onClick(View arg0) { 124 | Intent intent = new Intent(StartActivity.this, ServerService.class); 125 | if(btnStartStop.isChecked()) { 126 | startServer(mHandler); 127 | startService(intent); 128 | } else { 129 | stopServer(); 130 | stopService(intent); 131 | } 132 | refreshMainScreen(); 133 | } 134 | }); 135 | 136 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { 137 | NotificationManager mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); 138 | NotificationChannel channel = new NotificationChannel( 139 | this.getString(R.string.notif_ch_id), 140 | this.getString(R.string.notif_ch_hr), 141 | NotificationManager.IMPORTANCE_DEFAULT 142 | ); 143 | channel.setSound(null, null); 144 | mNM.createNotificationChannel(channel); 145 | } 146 | 147 | mConnection = new ServiceConnection() { 148 | public void onServiceConnected(ComponentName className, IBinder service) { 149 | mBoundService = ((ServerService.LocalBinder)service).getService(); 150 | Toast.makeText( 151 | StartActivity.this, 152 | "Service connected", 153 | Toast.LENGTH_SHORT 154 | ).show(); 155 | refreshMainScreen(); 156 | } 157 | 158 | public void onServiceDisconnected(ComponentName className) { 159 | mBoundService = null; 160 | Toast.makeText( 161 | StartActivity.this, 162 | "Service disconnected", 163 | Toast.LENGTH_SHORT 164 | ).show(); 165 | } 166 | }; 167 | 168 | doBindService(); 169 | 170 | refreshMainScreen(); 171 | } 172 | 173 | private void doUnbindService() { 174 | if (mBoundService != null) { 175 | getApplicationContext().unbindService(mConnection); 176 | } 177 | 178 | } 179 | 180 | private void startServer(Handler handler) { 181 | if (mBoundService == null) { 182 | Toast.makeText( 183 | StartActivity.this, 184 | "Service not connected", 185 | Toast.LENGTH_SHORT 186 | ).show(); 187 | } else { 188 | if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { 189 | String defaultDocumentRoot = StartActivity.getFilesDir(this).getPath() + "/html/"; 190 | if (!documentRoot.equals(defaultDocumentRoot)) { 191 | if ( 192 | checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) 193 | != PackageManager.PERMISSION_GRANTED 194 | ) { 195 | requestPermissions( 196 | new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 197 | GRANT_WRITE_EXTERNAL_STORAGE 198 | ); 199 | } 200 | } 201 | } 202 | mBoundService.startServer(handler); 203 | } 204 | } 205 | 206 | private void stopServer() { 207 | if (mBoundService == null) { 208 | Toast.makeText( 209 | StartActivity.this, 210 | "Service not connected", 211 | Toast.LENGTH_SHORT 212 | ).show(); 213 | } else { 214 | mBoundService.stopServer(); 215 | } 216 | } 217 | 218 | private void doBindService() { 219 | getApplicationContext() 220 | .bindService( 221 | new Intent( 222 | StartActivity.this, 223 | ServerService.class), 224 | mConnection, 225 | Context.BIND_AUTO_CREATE 226 | ); 227 | } 228 | 229 | @Override 230 | protected void onDestroy() { 231 | doUnbindService(); 232 | super.onDestroy(); 233 | } 234 | 235 | @Override 236 | protected void onResume() { 237 | super.onResume(); 238 | doBindService(); 239 | refreshMainScreen(); 240 | } 241 | 242 | @Override 243 | public void onWindowFocusChanged(boolean hasFocus) { 244 | // Called then status bar pulled up 245 | if (hasFocus) refreshMainScreen(); 246 | super.onWindowFocusChanged(hasFocus); 247 | } 248 | 249 | private void refreshMainScreen() { 250 | final TextView viewDirectoryRoot = (TextView) findViewById(R.id.document_root); 251 | final TextView viewAddress = (TextView) findViewById(R.id.address); 252 | final TextView viewPort = (TextView) findViewById(R.id.port); 253 | final Button btnBrowser = (Button) findViewById(R.id.buttonOpenBrowser); 254 | final Button btnSendURL = (Button) findViewById(R.id.buttonSendURL); 255 | final Button btnQRCodeURL = (Button) findViewById(R.id.buttonQRCodeURL); 256 | 257 | final SharedPreferences sharedPreferences = 258 | PreferenceManager.getDefaultSharedPreferences(this); 259 | 260 | documentRoot = getDocumentRoot(); 261 | viewDirectoryRoot.setText(documentRoot); 262 | viewDirectoryRoot.setOnClickListener(makePrefListener(1)); 263 | 264 | final String port = sharedPreferences.getString( 265 | getString(R.string.pk_port), 266 | "8080" 267 | ); 268 | viewPort.setText(port); 269 | 270 | viewPort.setOnClickListener(makePrefListener(2)); 271 | 272 | if(mBoundService != null) { 273 | btnStartStop.setChecked(mBoundService.isRunning()); 274 | if (mBoundService.isRunning()) { 275 | if (sharedPreferences.getBoolean(getString(R.string.pk_pref_changed), false)) { 276 | SharedPreferences.Editor editor = sharedPreferences.edit(); 277 | stopServer(); 278 | startServer(mHandler); 279 | Toast.makeText(StartActivity.this,"Service restarted because configuration changed", Toast.LENGTH_SHORT).show(); 280 | editor.putBoolean(getString(R.string.pk_pref_changed), false); 281 | editor.commit(); 282 | } 283 | final String ipAddress = mBoundService.getIpAddress(); 284 | viewAddress.setText(ipAddress); 285 | viewAddress.setTextColor(0xFFFFFF00); 286 | 287 | final String url = 288 | "http://" 289 | + ipAddress 290 | + ":" 291 | + port 292 | + "/"; 293 | btnBrowser.setOnClickListener(new OnClickListener() { 294 | @Override 295 | public void onClick(View v) { 296 | Intent i = new Intent(Intent.ACTION_VIEW); 297 | i.setData(Uri.parse(url)); 298 | startActivity(i); 299 | } 300 | }); 301 | btnBrowser.setEnabled(true); 302 | 303 | btnQRCodeURL.setOnClickListener( new OnClickListener() { 304 | @Override 305 | public void onClick(View v) { 306 | PackageManager pm = getApplicationContext().getPackageManager(); 307 | try { 308 | pm.getPackageInfo(getString(R.string.qrPluginPackage), 0); 309 | Intent i = new Intent(getString(R.string.qrIntentAction)); 310 | i.setData(Uri.parse("createqr:")); 311 | i.putExtra("ENCODE_DATA", url); 312 | i.putExtra("ENCODE_LABEL", "Open lWS page
(" + url + ")"); 313 | i.putExtra("ENCODE_CORRECTION", "L"); 314 | i.putExtra("ENCODE_MODULE_SIZE", 6); 315 | i.putExtra("ENCODE_MASK", -1); 316 | i.putExtra("ENCODE_MIN_VERSION", 1); 317 | 318 | // i.putExtra("ENCODE_DATA", url); 319 | // i.putExtra("ENCODE_SIZE", "256"); 320 | // i.putExtra("ENCODE_DARK", "#000"); 321 | // i.putExtra("ENCODE_LIGHT", "#e0ffff"); 322 | // i.putExtra("ENCODE_CORRECTION", "L"); 323 | 324 | startActivity(i); 325 | } catch (PackageManager.NameNotFoundException e_lws_qr) { 326 | try { 327 | pm.getPackageInfo("com.google.zxing.client.android", 0); 328 | Intent i = new Intent("com.google.zxing.client.android.ENCODE"); 329 | i.putExtra("ENCODE_TYPE", "TEXT_TYPE"); 330 | i.putExtra("ENCODE_DATA", url); 331 | i.putExtra("ENCODE_FORMAT", "QRCODE"); 332 | startActivity(i); 333 | } catch (PackageManager.NameNotFoundException e_zxing) { 334 | Intent i = new Intent(Intent.ACTION_VIEW); 335 | i.setData(Uri.parse("market://details?id=" + getString(R.string.qrPluginPackage))); 336 | startActivity(i); 337 | } 338 | } 339 | } 340 | }); 341 | if (!ipAddress.equals("127.0.0.1")) 342 | btnQRCodeURL.setEnabled(true); 343 | 344 | OnClickListener sendListener = new OnClickListener() { 345 | @Override 346 | public void onClick(View v) { 347 | Intent i = new Intent(Intent.ACTION_SEND); 348 | i.setData(Uri.parse(url)); 349 | i.setType("text/html"); 350 | i.putExtra(Intent.EXTRA_SUBJECT, "Current lWS URL"); 351 | i.putExtra(Intent.EXTRA_TEXT, url); 352 | startActivity(i); 353 | } 354 | }; 355 | if (!ipAddress.equals("127.0.0.1")) { 356 | btnSendURL.setOnClickListener(sendListener); 357 | btnSendURL.setEnabled(true); 358 | viewAddress.setOnClickListener(sendListener); 359 | } 360 | 361 | } else { 362 | viewAddress.setText("not running"); 363 | viewAddress.setTextColor(0xFFFF0000); 364 | viewAddress.setOnClickListener(null); 365 | viewAddress.setClickable(false); 366 | btnBrowser.setEnabled(false); 367 | btnSendURL.setEnabled(false); 368 | btnQRCodeURL.setEnabled(false); 369 | } 370 | } else { 371 | viewAddress.setText("not running"); 372 | viewAddress.setTextColor(0xFFFF0000); 373 | viewAddress.setOnClickListener(null); 374 | viewAddress.setClickable(false); 375 | btnBrowser.setEnabled(false); 376 | btnSendURL.setEnabled(false); 377 | btnQRCodeURL.setEnabled(false); 378 | } 379 | } 380 | 381 | public static File getFilesDir(Context c) { 382 | File filesDir; 383 | if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { 384 | if (Build.VERSION.SDK_INT <= 18) 385 | filesDir = new File(Environment.getExternalStorageDirectory() 386 | + "/Android/data/" 387 | + c.getPackageName() 388 | +"/files" 389 | ); 390 | else 391 | filesDir = c.getExternalFilesDir(null); 392 | } else { 393 | filesDir = c.getFilesDir(); 394 | } 395 | return filesDir; 396 | } 397 | 398 | private String getDocumentRoot(){ 399 | String defaultDocumentRoot = getFilesDir(this).getPath() + "/html/"; 400 | final SharedPreferences sharedPreferences = 401 | PreferenceManager.getDefaultSharedPreferences(this); 402 | 403 | String documentRoot = sharedPreferences.getString( 404 | getString(R.string.pk_document_root), 405 | "" 406 | ); 407 | 408 | if (documentRoot.length() == 0 ) { 409 | // if preferences contain empty string or absent reset it to default 410 | documentRoot = defaultDocumentRoot; 411 | SharedPreferences.Editor editor = sharedPreferences.edit(); 412 | editor.putString(getString(R.string.pk_document_root), documentRoot); 413 | editor.commit(); 414 | } 415 | 416 | if (documentRoot.equals(defaultDocumentRoot)) createDefaultIndex(); 417 | 418 | return documentRoot; 419 | } 420 | 421 | private void createDefaultIndex() { 422 | try { 423 | String defaultDocumentRoot = getFilesDir(this).getPath() + "/html/"; 424 | File defaultDocumentRootDirectory = new File(defaultDocumentRoot); 425 | if (!defaultDocumentRootDirectory.exists()) { 426 | if(defaultDocumentRootDirectory.mkdirs()) { 427 | BufferedWriter bout = new BufferedWriter(new FileWriter(defaultDocumentRoot + "index.html")); 428 | bout.write(getString(R.string.def_doc_root_index, defaultDocumentRoot)); 429 | bout.flush(); 430 | bout.close(); 431 | log("I: Default DocumentRoot HTML index file created."); 432 | } else { 433 | throw new Exception("Can't create document root."); 434 | } 435 | } 436 | } catch (Exception e) { 437 | log("E: Error creating HTML index file."); 438 | Log.e(LOG_TAG,e.getMessage()); 439 | } 440 | } 441 | 442 | /** 443 | * Application main screen related functions and handler 444 | */ 445 | 446 | private static void log(String s) { 447 | if (prevMsg.equals(s)) { 448 | prevMsgCount++; 449 | }else { 450 | if (prevMsgCount != 0) 451 | viewLog.append("... previous string repeated " + prevMsgCount +" times.\n"); 452 | prevMsgCount = 0; 453 | prevMsg = s; 454 | viewLog.append(s + "\n"); 455 | } 456 | viewScroll.fullScroll(ScrollView.FOCUS_DOWN); 457 | } 458 | 459 | final Handler mHandler = new Handler() { 460 | @Override 461 | public void handleMessage(Message msg) { 462 | Bundle b = msg.getData(); 463 | if (b.containsKey("toast")){ 464 | Toast.makeText(StartActivity.this, b.getString("msg"), Toast.LENGTH_SHORT).show(); 465 | } 466 | log(b.getString("msg")); 467 | } 468 | }; 469 | 470 | public static void putToLogScreen(String message, Handler msgHandler) { 471 | putToLogScreen(message, msgHandler, false); 472 | } 473 | 474 | public static void putToLogScreen(String message, Handler msgHandler, Boolean isToast) { 475 | Message msg = new Message(); 476 | Bundle b = new Bundle(); 477 | b.putString("msg", message); 478 | if (isToast) 479 | b.putBoolean("toast",true); 480 | msg.setData(b); 481 | msgHandler.sendMessage(msg); 482 | } 483 | 484 | private OnClickListener makePrefListener(final int index) { 485 | return new OnClickListener() { 486 | @Override 487 | public void onClick(View v) { 488 | Intent i = new Intent(StartActivity.this, PreferencesActivity.class); 489 | if (index != -1 ) 490 | i.putExtra("item", index); 491 | startActivity(i); 492 | } 493 | }; 494 | } 495 | 496 | } 497 | -------------------------------------------------------------------------------- /app/src/main/res/layout/main.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 13 | 19 | 20 | 25 | 29 | 35 | 39 | 45 | 46 | 47 | 53 | 58 | 59 |