├── .classpath
├── .gitignore
├── .idea
├── .name
├── artifacts
│ └── unplug_jar.xml
├── compiler.xml
├── encodings.xml
├── libraries
│ ├── KotlinJavaRuntime.xml
│ ├── easybind_1_0_3.xml
│ ├── kotlinfx_core.xml
│ ├── minimal_json_0_9_2.xml
│ ├── okhttp_2_2_0.xml
│ └── okio_1_2_0.xml
├── modules.xml
├── scopes
│ └── scope_settings.xml
└── vcs.xml
├── .project
├── LICENSE
├── README.md
├── build.sh
├── lib
├── easybind-1.0.3.jar
├── kotlinfx-0.2.4.jar
├── minimal-json-0.9.2.jar
├── okhttp-3.6.0.jar
└── okio-1.11.0.jar
├── src
├── META-INF
│ └── MANIFEST.MF
├── chat.css
├── co
│ └── uproot
│ │ └── unplug
│ │ ├── api.kt
│ │ ├── common.kt
│ │ ├── guiClient.kt
│ │ └── guiServices.kt
├── default-avatar-32.png
└── default-avatar.png
└── unplug.iml
/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /out/
2 | /bin/
3 | /build/
4 | /*.jar
5 |
--------------------------------------------------------------------------------
/.idea/.name:
--------------------------------------------------------------------------------
1 | unplug
--------------------------------------------------------------------------------
/.idea/artifacts/unplug_jar.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | $PROJECT_DIR$/out/artifacts/unplug_jar
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/.idea/libraries/KotlinJavaRuntime.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/.idea/libraries/easybind_1_0_3.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/.idea/libraries/kotlinfx_core.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/.idea/libraries/minimal_json_0_9_2.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/.idea/libraries/okhttp_2_2_0.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/.idea/libraries/okio_1_2_0.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/scopes/scope_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | unplug
4 | unplug
5 |
6 |
7 |
8 |
9 | org.jetbrains.kotlin.ui.kotlinBuilder
10 |
11 |
12 |
13 |
14 | org.eclipse.jdt.core.javabuilder
15 |
16 |
17 |
18 |
19 |
20 | org.eclipse.jdt.core.javanature
21 | org.jetbrains.kotlin.core.kotlinNature
22 |
23 |
24 |
25 | kotlin_bin
26 | 2
27 | org.jetbrains.kotlin.core.filesystem:/unplug/kotlin_bin
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/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 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
676 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ### unplug
2 |
3 | A cross-platform [matrix](https://matrix.org) client.
4 |
5 | 
6 |
7 | ### How to run
8 | Download the `.jar` file from the [release page](https://github.com/UprootLabs/unplug/releases). Then,
9 |
10 | ```
11 | java -jar unplug-version.jar
12 | ```
13 |
14 | This will launch the GUI. You can add additional options like this:
15 | ```
16 | java -jar unplug-version.jar [userId] [server] [password]
17 | ```
18 |
19 | A CLI version will soon be available and launching it would be as simple as passing
20 | `-c` as an argument:
21 |
22 | ```
23 | java -jar unplug-version.jar -c
24 | ```
25 |
26 | ### Discuss
27 | [#unplug:matrix.org](https://matrix.org/beta/#/room/#unplug:matrix.org)
28 |
29 | ### Status
30 | Consider this alpha quality, with only rudimentary features.
31 |
32 | Currently, the application doesn't persist any state. The Matrix protocol is very convenient in this regard;
33 | it allows quick bootstrap of the client state with a single API call.
34 |
35 | However, later versions will persist preferences, chat history, etc.
36 |
37 | #### Roadmap
38 |
39 | ##### Version 0.2
40 | * Join / Leave chat rooms
41 | * Handle all types of events (notices, etc)
42 | * History back-filling (scroll up to see earlier chat messages)
43 | * User avatars
44 | * Sorting of Room names by activity
45 | * User presence update (timeout and mark them inactive, etc)
46 | * Some UI polish
47 |
48 | ##### Version 0.3+
49 | * Persistence of preferences, etc
50 | * CLI interface
51 | * More UI polish
52 |
53 | ##### Version 1.0 and beyond
54 | * Audio / Video
55 |
56 | ### Legal
57 | * License: GPL3
58 | * Copyright: Uproot Labs 2015
59 |
60 | #### CLA
61 | When sending contributions to this repo you grant to Uproot Labs and the users of
62 | this software a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
63 | irrevocable copyright license to reproduce, prepare derivative works of,
64 | publicly display, publicly perform, sublicense, and distribute Your
65 | Contributions and such derivative works.
66 |
67 | Uproot Labs guarantees that all contributions to this repo will always be
68 | available under an open-source License.
69 |
--------------------------------------------------------------------------------
/build.sh:
--------------------------------------------------------------------------------
1 | set -ex
2 |
3 | mkdir build
4 | cd build
5 |
6 | for i in ../lib/*.jar; do echo unjarring $i; jar xf $i; done
7 |
8 | cd ../
9 |
10 | kotlinc -include-runtime -d unplug-base.jar -cp build src/
11 |
12 | cd build
13 | jar xf ../unplug-base.jar
14 | cp ../src/chat.css ../src/*.png ./
15 |
16 | jar cfe ../unplug.jar co.uproot.unplug.GuiClientKt *
17 |
18 |
--------------------------------------------------------------------------------
/lib/easybind-1.0.3.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiMium/unplug/8d4ae61484420720128d1498c5d0fff9857c151c/lib/easybind-1.0.3.jar
--------------------------------------------------------------------------------
/lib/kotlinfx-0.2.4.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiMium/unplug/8d4ae61484420720128d1498c5d0fff9857c151c/lib/kotlinfx-0.2.4.jar
--------------------------------------------------------------------------------
/lib/minimal-json-0.9.2.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiMium/unplug/8d4ae61484420720128d1498c5d0fff9857c151c/lib/minimal-json-0.9.2.jar
--------------------------------------------------------------------------------
/lib/okhttp-3.6.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiMium/unplug/8d4ae61484420720128d1498c5d0fff9857c151c/lib/okhttp-3.6.0.jar
--------------------------------------------------------------------------------
/lib/okio-1.11.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiMium/unplug/8d4ae61484420720128d1498c5d0fff9857c151c/lib/okio-1.11.0.jar
--------------------------------------------------------------------------------
/src/META-INF/MANIFEST.MF:
--------------------------------------------------------------------------------
1 | Manifest-Version: 1.0
2 | Main-Class: co.uproot.unplug.gui.GuiPackage
3 |
4 |
--------------------------------------------------------------------------------
/src/chat.css:
--------------------------------------------------------------------------------
1 | .root {
2 | -fx-base: rgb(20, 20, 20);
3 | -fx-background: rgb(22, 22, 22);
4 | -fx-control-inner-background: rgb(30, 30, 30);
5 | -fx-focus-color: transparent;
6 | -fx-faint-focus-color: rgb(25, 38, 25);
7 | -fx-box-border: transparent;
8 | -fx-accent: rgb(70, 70, 70);
9 | -fx-selection-bar-non-focused: rgb(24, 24, 24);
10 | -fx-cell-focus-inner-border: #99999922;
11 | -fx-shadow-highlight-color: transparent;
12 | }
13 |
14 | .text-input {
15 | -fx-faint-focus-color: rgb(35, 48, 35);
16 | -fx-background-insets: -0.2, 1, -1.4, 1;
17 | }
18 |
19 | .button {
20 | -fx-faint-focus-color: rgb(35, 48, 35);
21 | -fx-background-insets: -0.2, 1, 2, -1.4, 1;
22 | }
23 |
24 | .unplug-text {
25 | -fx-fill: #eee;
26 | }
27 |
28 | .unplug-text-muted {
29 | -fx-fill: #888;
30 | }
31 |
32 | .chat-message-text {
33 | -fx-fill: #fff;
34 | }
35 |
36 | .chat-message-id {
37 | -fx-fill: #ccc;
38 | }
39 | .chat-message-meta {
40 | -fx-fill: #999;
41 | }
42 |
43 | .chat-message-error {
44 | -fx-fill: #f33;
45 | }
46 |
47 | .list-view {
48 | -fx-accent: rgb(20, 20, 20);
49 | -fx-selection-bar-non-focused: rgb(24, 24, 24);
50 | }
51 |
52 | .user-default {
53 | -fx-opacity: 0.5;
54 | }
55 |
56 | .user-typing {
57 | -fx-opacity: 1;
58 | }
59 |
60 | .user-present {
61 | -fx-opacity: 1;
62 | }
63 |
64 | .user-id {
65 | -fx-fill: #fff;
66 | -fx-font-size: 1.1em;
67 | }
68 |
69 | .user-displayname {
70 | -fx-fill: #666;
71 | }
72 |
--------------------------------------------------------------------------------
/src/co/uproot/unplug/api.kt:
--------------------------------------------------------------------------------
1 | package co.uproot.unplug
2 |
3 | import com.eclipsesource.json.JsonArray
4 | import com.eclipsesource.json.JsonObject
5 | import okhttp3.MediaType
6 | import okhttp3.OkHttpClient
7 | import okhttp3.Request
8 | import okhttp3.RequestBody
9 | import java.io.IOException
10 | import java.net.URLEncoder
11 | import java.util.ArrayList
12 | import java.util.concurrent.TimeUnit
13 | import java.util.concurrent.atomic.AtomicLong
14 |
15 | data class AccessToken(val token: String)
16 |
17 | data class Message(
18 | val id: String?,
19 | val ts: Long,
20 | val roomId: String?,
21 | val type: String,
22 | val userId: String,
23 | val content: JsonObject)
24 |
25 | data class State(
26 | val type: String,
27 | val ts: Long,
28 | val userId: String,
29 | val stateKey: String,
30 | val content: JsonObject) {
31 | }
32 |
33 | data class Room(val id: String, val aliases: List, val messages: MutableList, val states: List) {
34 | fun isChatMessage(message: Message): Boolean {
35 | return when (message.type) {
36 | "m.room.create" -> true
37 | "m.room.member" -> true
38 | "m.room.message" -> true
39 | else -> false
40 | }
41 | }
42 |
43 | fun chatMessages(): List {
44 | return messages.asSequence().filter({ isChatMessage(it) }).toList()
45 | }
46 |
47 | fun getAliasOrId(): String {
48 | if (aliases.size > 0) {
49 | return aliases.get(0)
50 | } else {
51 | return id
52 | }
53 | }
54 | }
55 |
56 | fun JsonObject.getObject(name: String): JsonObject {
57 | return this.get(name).asObject()
58 | }
59 |
60 | fun JsonObject.getArray(name: String): JsonArray {
61 | return this.get(name).asArray()
62 | }
63 |
64 | class SyncResult(val rooms: List, val presence: List)
65 | class EventResult(val messages: List, val end: String)
66 | class CreateRoomResult(val roomAlias: String, val roomId: String)
67 | class JoinRoomResult(val roomId: String, val servers: String)
68 | class InviteMemResult(val result: String?)
69 | class LeaveRoomResult(val result: String?)
70 | class BanRoomResult(val result: String?)
71 | data class LoginResult(val userId: String, val accessToken: AccessToken, val api: API)
72 |
73 | interface RoomIdentifier
74 |
75 | class RoomId(val id: String) : RoomIdentifier
76 | class RoomName(val name: String) : RoomIdentifier
77 |
78 | // TODO: Change API to be fully type-safe, and not return JSON objects
79 | class API(val baseURL: String) {
80 | val apiURL = baseURL + "_matrix/client/r0/"
81 | val mediaURL = baseURL + "_matrix/media/r0/"
82 |
83 | private final val client = OkHttpClient.Builder()
84 | .followRedirects(false)
85 | .followSslRedirects(false)
86 | .connectTimeout(40, TimeUnit.SECONDS)
87 | .readTimeout(40, TimeUnit.SECONDS)
88 | .writeTimeout(40, TimeUnit.SECONDS)
89 | .build()
90 |
91 | private final val net = Net(client)
92 |
93 | fun login(username: String, password: String): LoginResult? {
94 | try {
95 | val postBody = """
96 | {"type":"m.login.password", "user":"$username", "password":"$password"}
97 | """
98 |
99 | val responseStr = net.doPost(apiURL + "login", postBody)
100 | val jsonObj = JsonObject.readFrom(responseStr)
101 | val tokenStr = jsonObj.getString("access_token", null)
102 | val userId = jsonObj.getString("user_id", null)
103 | if (tokenStr != null && userId != null) {
104 | return LoginResult(userId, AccessToken(tokenStr), this)
105 | } else {
106 | return null
107 | }
108 | } catch(e: IOException) {
109 | e.printStackTrace()
110 | return null;
111 | }
112 | }
113 |
114 | fun createRoom(accessToken: AccessToken, roomname: String, visibility: String): CreateRoomResult {
115 | val post = """
116 | {"room_alias_name":"$roomname", "visibility":"$visibility"}
117 | """
118 | val responseStr = net.doPost(apiURL + "createRoom?access_token=${accessToken.token}", post)
119 | val jsonObj = JsonObject.readFrom(responseStr)
120 | val roomAlias = jsonObj.getString("room_alias", null)
121 | val roomId = jsonObj.getString("room_id", null)
122 | return CreateRoomResult(roomAlias, roomId)
123 | }
124 |
125 | fun joiningRoon(accessToken: AccessToken, room: RoomIdentifier): JoinRoomResult {
126 | val roomId = getRoomId(accessToken, room)
127 | val nameEncode = URLEncoder.encode(roomId, "UTF-8")
128 | val responseStr = net.doPost(apiURL + "join/$nameEncode?access_token=${accessToken.token}", "")
129 | val jsonObj = JsonObject.readFrom(responseStr)
130 | val roomIdResult = jsonObj.getString("room_id", null)
131 | val servers = jsonObj.getString("servers", null)
132 | return JoinRoomResult(roomIdResult, servers)
133 | }
134 |
135 | fun invitingMember(accessToken: AccessToken, room: RoomIdentifier, memId: String): InviteMemResult {
136 | val roomId = getRoomId(accessToken, room)
137 | val roomIdEncode = URLEncoder.encode(roomId, "UTF-8")
138 | val rmIdEncode = roomIdEncode.substring(3)
139 | val post = """
140 | {"user_id":"$memId"}"""
141 | val responseStr = net.doPost(apiURL + "rooms/state!$rmIdEncode/invite?access_token=${accessToken.token}", post)
142 | return InviteMemResult(responseStr)
143 | }
144 |
145 | fun banningMember(accessToken: AccessToken, room: RoomIdentifier, memId: String, appState: AppState): BanRoomResult {
146 | val roomId = getRoomId(accessToken, room)
147 | val ban = "ban"
148 | val roomIdEncode = URLEncoder.encode(roomId, "UTF-8")
149 | val rmIdEncode = roomIdEncode.substring(3)
150 | val memIdEncode = URLEncoder.encode(memId, "UTF-8")
151 | if (roomId != null) {
152 | val mediaURL1 = baseURL + "/_matrix/media/v1/"
153 | val badUrl = mediaURL1 + "thumbnail/"
154 | val url = appState.getRoomUsers(roomId)
155 | val a = url.firstOrNull { it.id == memId }
156 | if (a != null) {
157 | val displayName = a.displayName.getValue()
158 | val url1 = a.avatarURL.getValue()
159 | // TODO: val url2 = url1.toString().replaceAll(badUrl, "mcx://")
160 | val url2 = url1.toString()
161 |
162 | val finalUrl = url2.substringBefore("?")
163 | val header = """
164 | {"avatar_url":"$finalUrl","displayName":"$displayName","membership":"$ban"}"""
165 | val responseStr = net.doPut(apiURL + "rooms/!$rmIdEncode/state/m.room.member/$memIdEncode?access_token=${accessToken.token}", header)
166 | return BanRoomResult(responseStr)
167 | }
168 | }
169 | return BanRoomResult(null)
170 | }
171 |
172 | fun leavingRoom(accessToken: AccessToken, room: RoomIdentifier): LeaveRoomResult {
173 | val roomId = getRoomId(accessToken, room)
174 | val roomIdEncode = URLEncoder.encode(roomId, "UTF-8")
175 | val rmIdEncode = roomIdEncode.substring(3)
176 | val responseStr = net.doPost(apiURL + "rooms/!$rmIdEncode/leave?access_token=${accessToken.token}", "{}")
177 | // TODO: Parse response
178 | return LeaveRoomResult(null)
179 | }
180 |
181 | private fun getRoomId(accessToken: AccessToken, room: RoomIdentifier): String? {
182 | return when (room) {
183 | is RoomId -> room.id
184 | is RoomName -> getRoomId(accessToken, room.name)
185 | else -> throw UnknownError("Unknown room identifier") // TODO: Use sealed class
186 | }
187 | }
188 |
189 | fun getRoomId(accessToken: AccessToken, roomAlias: String): String? {
190 | val roomAliasEscaped = URLEncoder.encode(roomAlias, "UTF-8")
191 | val responseStr = net.doGet(apiURL + "directory/room/$roomAliasEscaped?access_token=${accessToken.token}")
192 | if (responseStr == null) {
193 | return null
194 | } else {
195 | val jsonObj = JsonObject.readFrom(responseStr)
196 | return jsonObj.getString("room_id", null)
197 | }
198 | }
199 |
200 | private var txnIdUnique = AtomicLong()
201 |
202 | fun sendMessage(accessToken: AccessToken, roomId: String, message: String): String {
203 | val postBody = """
204 | {"msgtype":"m.text", "body":"$message"}
205 | """
206 |
207 | val txnId = txnIdUnique.addAndGet(1L)
208 |
209 | val responseStr = net.doPut(apiURL + "rooms/$roomId/send/m.room.message/$txnId?access_token=${accessToken.token}", postBody)
210 | val jsonObj = JsonObject.readFrom(responseStr)
211 | val eventId = jsonObj.getString("event_id", null)
212 | return eventId
213 | }
214 |
215 | fun roomInitialSync(accessToken: AccessToken, roomId: String): SyncResult? {
216 | val roomIdEncode = URLEncoder.encode(roomId, "UTF-8")
217 | val rmIdEncode = roomIdEncode.substring(3)
218 | val responseStr = net.doGet(apiURL + "rooms/!$rmIdEncode/initialSync?access_token=${accessToken.token}")
219 | if (responseStr == null) {
220 | return null
221 | }
222 | val room = JsonObject.readFrom(responseStr)
223 | val roomObj = room.asObject()
224 | val messages = roomObj.getObject("messages")
225 | val chunks = messages.getArray("chunk").map { it.asObject() }
226 | val messageList = parseChunks(chunks)
227 | val states = roomObj.getArray("state")
228 | val aliasStates = states.filter { it.asObject().getString("type", null) == "m.room.aliases" }
229 | val aliases = aliasStates.flatMap {
230 | it.asObject().getObject("content").getArray("aliases").map { it.asString() }
231 | }
232 | val stateList = states.map { state ->
233 | val so = state.asObject()
234 | State(so.getString("type", null), so.getLong("origin_server_ts", 0L), so.getString("user_id", null), so.getString("state_key", null), so.getObject("content"))
235 | }
236 | val arrayList = ArrayList()
237 | val a = Room(roomObj.getString("room_id", null), aliases, messageList.toMutableList(), stateList)
238 | arrayList.add(a)
239 | val presence = parseChunks(room.getArray("presence").map { it.asObject() })
240 | return SyncResult(arrayList, presence)
241 | }
242 |
243 | fun initialSync(accessToken: AccessToken): SyncResult? {
244 | val responseStr = net.doGet(apiURL + "initialSync?access_token=${accessToken.token}")
245 | if (responseStr == null) {
246 | return null
247 | }
248 | val jsonObj = JsonObject.readFrom(responseStr)
249 | val rooms = jsonObj.getArray("rooms")
250 | val roomList = rooms.map { room ->
251 | val roomObj = room.asObject()
252 | val messages = roomObj.getObject("messages")
253 | val chunks = messages.getArray("chunk").map { it.asObject() }
254 | val messageList = parseChunks(chunks)
255 | val states = roomObj.getArray("state")
256 | val aliasStates = states.filter { it.asObject().getString("type", null) == "m.room.aliases" }
257 | val aliases = aliasStates.flatMap {
258 | it.asObject().getObject("content").getArray("aliases").map { it.asString() }
259 | }
260 | val stateList = states.map { state ->
261 | val so = state.asObject()
262 | State(so.getString("type", null), so.getLong("origin_server_ts", 0L), so.getString("user_id", null), so.getString("state_key", null), so.getObject("content"))
263 | }
264 | Room(roomObj.getString("room_id", null), aliases, messageList.toMutableList(), stateList)
265 | }
266 | val presence = parseChunks(jsonObj.getArray("presence").map { it.asObject() })
267 | return SyncResult(roomList, presence)
268 | }
269 |
270 | fun getEvents(accessToken: AccessToken, from: String?): EventResult? {
271 | val eventURL = apiURL + "events?access_token=${accessToken.token}" + (from?.let { "&from=" + it } ?: "")
272 | val responseStr = net.doGet(eventURL)
273 | val jsonObj = JsonObject.readFrom(responseStr)
274 | val chunks = jsonObj.getArray("chunk")
275 | return EventResult(parseChunks(chunks.map { it.asObject() }), jsonObj.getString("end", null))
276 | }
277 |
278 | private fun parseChunks(chunk: List): List {
279 | val messageList = chunk.map { messageObj ->
280 | val userId = messageObj.getString("user_id", "")
281 | val type = messageObj.getString("type", "")
282 | val eventId: String? = messageObj.getString("event_id", null)
283 | val roomId: String? = messageObj.getString("room_id", null)
284 | Message(eventId, messageObj.getLong("origin_server_ts", 0L), roomId, type, userId, messageObj.getObject("content"))
285 | }
286 | return messageList
287 | }
288 |
289 | private val mxcRegex = "^mxc://(.*)/([^#]*)(#auto)?$".toRegex()
290 |
291 | fun getAvatarThumbnailURL(mxcURL: String): String {
292 | /*
293 | val matchResult = mxcRegex.matchEntire(mxcURL)
294 | matchResult.let{ r ->
295 | val serverName = r.groupValues.get(1)
296 | val mediaId = r.groupValues.get(2)
297 | mediaURL + "thumbnail/$serverName/$mediaId?width=24&height=24"
298 | }
299 |
300 | val matcher = mxcRegex.matcher(mxcURL)
301 | if (matcher.matches()) {
302 | val serverName = matcher.group(1)
303 | val mediaId = matcher.group(2)
304 | return mediaURL + "thumbnail/$serverName/$mediaId?width=24&height=24"
305 | } else {
306 | return ""
307 | }
308 | */
309 | return ""
310 | }
311 | }
312 |
313 | private class Net(val client: OkHttpClient) {
314 | private final val jsonMediaType = MediaType.parse("application/json;; charset=utf-8")
315 |
316 | // TODO: a non-blank UA String
317 | private final val uaString = ""
318 |
319 | fun doGet(url: String): String? {
320 | val request = Request.Builder()
321 | .url(url)
322 | .addHeader("User-Agent", uaString)
323 | .build()
324 |
325 | val response = client.newCall(request).execute()
326 |
327 | if (!response.isSuccessful()) {
328 | return null
329 | } else {
330 | return response.body().string()
331 | }
332 | }
333 |
334 | fun doPost(url: String, json: String): String {
335 | return doVerb("post", url, json)
336 | }
337 |
338 | fun doPut(url: String, json: String): String {
339 | return doVerb("put", url, json)
340 | }
341 |
342 | fun doVerb(verb: String, url: String, json: String): String {
343 | val requestBody = RequestBody.create(jsonMediaType, json)
344 |
345 | val requestBuilder = Request.Builder()
346 | .url(url)
347 | .addHeader("User-Agent", uaString)
348 |
349 | when (verb) {
350 | "put" -> requestBuilder.put(requestBody)
351 | "post" -> requestBuilder.post(requestBody)
352 | else -> throw NotImplementedError("http verb is not yet implemented: $verb")
353 | }
354 |
355 | val request = requestBuilder.build()
356 |
357 | val response = client.newCall(request).execute()
358 | if (!response.isSuccessful()) {
359 | throw IOException("Unexpected code " + response)
360 | } else {
361 | return response.body().string()
362 | }
363 | }
364 | }
365 |
--------------------------------------------------------------------------------
/src/co/uproot/unplug/common.kt:
--------------------------------------------------------------------------------
1 | package co.uproot.unplug
2 |
3 | import javafx.beans.property.SimpleStringProperty
4 | import javafx.beans.property.SimpleListProperty
5 | import javafx.beans.property.SimpleObjectProperty
6 | import javafx.collections.ObservableList
7 | import org.fxmisc.easybind.EasyBind
8 | import java.util.HashMap
9 | import javafx.collections.FXCollections
10 |
11 | import javafx.beans.property.SimpleBooleanProperty
12 | import java.util.LinkedList
13 | import com.eclipsesource.json.JsonObject
14 | import javafx.scene.image.Image
15 | import javafx.beans.property.SimpleLongProperty
16 |
17 | data class UserState(val id: String) {
18 | val typing = SimpleBooleanProperty(false)
19 | val present = SimpleBooleanProperty(false)
20 | val displayName = SimpleStringProperty("");
21 | val avatarURL = SimpleStringProperty("");
22 | val lastActiveAgo = SimpleLongProperty(java.lang.Long.MAX_VALUE)
23 |
24 | private val SECONDS_PER_YEAR = (60L * 60L * 24L * 365L)
25 | private val SECONDS_PER_DECADE = (10L * SECONDS_PER_YEAR)
26 |
27 | val weight = EasyBind.combine(typing, present, lastActiveAgo, { t, p, la ->
28 | val laSec = Math.min(la.toLong() / 1000, SECONDS_PER_DECADE)
29 | var result = (1 + (SECONDS_PER_DECADE - laSec )).toInt()
30 | if (t) {
31 | result *= 2
32 | }
33 | if (p) {
34 | result *= 2
35 | }
36 | result
37 | })
38 |
39 | override fun toString() = "$id ${typing.get()} ${present.get()} ${weight.get()}"
40 |
41 | }
42 |
43 | data class RoomState(val id: String, val aliases: ObservableList)
44 |
45 | // TODO: Avoid storing entire user state for every room. Instead have a common store and a lookup table
46 | class AppState() {
47 | val currRoomId = SimpleStringProperty("")
48 |
49 | val currChatMessageList = SimpleObjectProperty>()
50 | val currUserList = SimpleObjectProperty>()
51 |
52 | val roomStateList = SimpleListProperty(FXCollections.observableArrayList({ roomState -> arrayOf(roomState.aliases) }))
53 | val roomNameList = EasyBind.map(roomStateList, { room: RoomState -> room.aliases.firstOrNull() ?: room.id })
54 |
55 | private final val roomChatMessageStore = HashMap>()
56 | private final val roomUserStore = HashMap>()
57 |
58 | @Synchronized
59 | fun processSyncResult(result: SyncResult, api: API) {
60 | result.rooms.asSequence().forEach { room ->
61 | val existingRoomState = roomStateList.firstOrNull { it.id == room.id }
62 | if (existingRoomState == null) {
63 | val aliasList = FXCollections.observableArrayList()
64 | aliasList.addAll(room.aliases)
65 | roomStateList.add(RoomState(room.id, aliasList))
66 | } else {
67 | existingRoomState.aliases.addAll(room.aliases)
68 | }
69 | getRoomChatMessages(room.id).setAll(room.chatMessages())
70 | val users = getRoomUsers(room.id)
71 | room.states.forEach { state: State ->
72 | when (state.type) {
73 | "m.room.member" -> {
74 | val membership = state.content.getString("membership", "")
75 | if (membership == "join") {
76 | val us = UserState(state.stateKey)
77 | val displayName = state.content.getStringOrElse("displayname", state.stateKey)
78 | us.displayName.setValue(displayName)
79 | us.avatarURL.setValue(api.getAvatarThumbnailURL(state.content.getStringOrElse("avatar_url", "")))
80 | users.add(us)
81 | } else if (membership == "leave") {
82 | users.removeFirstMatching { it.id == state.userId }
83 | } else {
84 | println("Not handled membership message: $membership")
85 | println(" room: ${room.getAliasOrId()}, from: ${state.userId}, key: ${state.stateKey}")
86 | }
87 | }
88 | "m.room.aliases" -> {
89 | // TODO: This doesn't need to handled here, because aliases are being already parsed by the API class
90 | /*
91 | val aliases = state.content.getArray("aliases").map{it.asString()}
92 | existingRoomState?.let {it.aliases.addAll(aliases)}
93 | */
94 | }
95 | "m.room.power_levels" -> {
96 | // TODO
97 | }
98 | "m.room.join_rules" -> {
99 | // TODO
100 | }
101 | "m.room.create" -> {
102 | // TODO
103 | }
104 | "m.room.topic" -> {
105 | // TODO
106 | }
107 | "m.room.name" -> {
108 | // TODO
109 | }
110 | "m.room.config" -> {
111 | // TODO
112 | }
113 | else -> {
114 | System.err.println("Unhandled state type: " + state.type)
115 | System.err.println(Thread.currentThread().getStackTrace().take(2).joinToString("\n"))
116 | System.err.println()
117 | }
118 | }
119 | }
120 | }
121 |
122 | result.presence.forEach { p ->
123 | if (p.type == "m.presence") {
124 | roomUserStore.values.forEach { users ->
125 | val userId = p.content.getString("user_id", null)
126 | users.firstOrNull { it.id == userId }?.let {
127 | it.present.set(p.content.getString("presence", "") == "online")
128 | it.lastActiveAgo.set(p.content.getLong("last_active_ago", java.lang.Long.MAX_VALUE))
129 | }
130 | }
131 | }
132 | }
133 |
134 | roomUserStore.values.forEach { users ->
135 | FXCollections.sort(users, { a, b -> b.weight.get() - a.weight.get() })
136 | }
137 | }
138 |
139 | fun processEventsResult(eventResult: EventResult, api: API, loginResult: LoginResult) {
140 | eventResult.messages.forEach { message ->
141 | when (message.type) {
142 | "m.typing" -> {
143 | val usersTyping = message.content.getArray("user_ids").map { it.asString() }
144 | roomUserStore.values.forEach { users ->
145 | users.forEach { it.typing.set(usersTyping.contains(it.id)) }
146 | }
147 | }
148 | "m.presence" -> {
149 | roomUserStore.values.forEach { users ->
150 | val userId = message.content.getString("user_id", null)
151 | users.firstOrNull { it.id == userId }?.let {
152 | it.present.set(message.content.getString("presence", "") == "online")
153 | it.lastActiveAgo.set(message.content.getLong("last_active_ago", java.lang.Long.MAX_VALUE))
154 | }
155 | }
156 | }
157 | "m.room.message" -> {
158 | if (message.roomId != null) {
159 | getRoomChatMessages(message.roomId).add(message)
160 | }
161 | }
162 | "m.room.member" -> {
163 | if (message.roomId != null) {
164 | val messageFromLoggedInUser = loginResult.userId == message.userId
165 |
166 | val users = getRoomUsers(message.roomId)
167 |
168 | val membership = message.content.getString("membership", "")
169 |
170 | if (membership == "join") {
171 | if (messageFromLoggedInUser) {
172 | val roomService = RoomSyncService(loginResult, message.roomId)
173 | roomService.setOnSucceeded {
174 | val value = roomService.getValue()
175 | if (value != null) {
176 | processSyncResult(value, loginResult.api)
177 | }
178 | }
179 | roomService.start()
180 | } else {
181 | val existingUser = users.firstOrNull { it.id == message.userId }
182 | val displayName = message.content.get("displayname")?.let { if (it.isString()) it.asString() else null } ?: message.userId
183 | val avatarURL = api.getAvatarThumbnailURL(message.content.getStringOrElse("avatar_url", ""))
184 | val user = if (existingUser == null) {
185 | val us = UserState(message.userId)
186 | users.add(us)
187 | us
188 | } else {
189 | existingUser
190 | }
191 | user.displayName.set(displayName)
192 | user.avatarURL.set(avatarURL)
193 | }
194 | } else if (membership == "leave") {
195 | users.removeFirstMatching { it.id == message.userId }
196 | if (messageFromLoggedInUser) {
197 | roomStateList.removeFirstMatching { it.id == message.roomId }
198 | roomUserStore.remove(message.roomId)
199 | roomChatMessageStore.remove(message.roomId)
200 | }
201 | } else if (membership == "ban") {
202 | val name = message.content.getString("displayname", "")
203 | users.removeFirstMatching { it.displayName.get().equals(name) }
204 | } else {
205 | println("Unhandled membership: $membership")
206 | }
207 | }
208 | }
209 | "m.room.aliases" -> {
210 |
211 | val existingRoomState = roomStateList.firstOrNull { it.id == message.roomId }
212 | if (existingRoomState != null) {
213 | val alias = message.content.getArray("aliases").map { it.asString() }
214 | val length = alias.toString().length
215 | val aliases = alias.toString().substring(1, length - 1)
216 | existingRoomState.aliases.add(aliases)
217 | }
218 | }
219 | else -> {
220 | println("Unhandled message: " + message)
221 |
222 | }
223 |
224 | }
225 | }
226 |
227 | roomUserStore.values.forEach { users ->
228 | FXCollections.sort(users, { a, b -> b.weight.get() - a.weight.get() })
229 | }
230 | }
231 |
232 | @Synchronized private fun getRoomChatMessages(roomId: String): ObservableList {
233 | return getOrCreate(roomChatMessageStore, roomId, { FXCollections.observableArrayList() })
234 | }
235 |
236 | @Synchronized public fun getRoomUsers(roomId: String): ObservableList {
237 | return getOrCreate(roomUserStore, roomId, {
238 | FXCollections.observableArrayList({ userState -> arrayOf(userState.present, userState.displayName, userState.avatarURL, userState.typing, userState.weight) })
239 | })
240 | }
241 |
242 | @Synchronized public fun getCurrRoomNameOrId(): String? {
243 | val currRoom = roomStateList.firstOrNull { it.id == currRoomId.get() }
244 | val alias = currRoom?.aliases?.firstOrNull()
245 | val name = alias ?: currRoom?.id
246 | return name
247 | }
248 |
249 | init {
250 | EasyBind.subscribe(currRoomId, { id: String? ->
251 | if (id != null && !id.isEmpty()) {
252 | currChatMessageList.set(getRoomChatMessages(id))
253 | currUserList.set(getRoomUsers(id))
254 | } else {
255 | currChatMessageList.set(SimpleListProperty())
256 | currUserList.set(SimpleListProperty())
257 | }
258 | })
259 |
260 | }
261 |
262 | @Synchronized private fun getOrCreate(store: HashMap>, roomId: String, creator: () -> ObservableList): ObservableList {
263 | val messages = store.get(roomId)
264 | if (messages == null) {
265 | val newList = SimpleListProperty(creator())
266 | store.put(roomId, newList)
267 | return newList
268 | } else {
269 | return messages
270 | }
271 |
272 | }
273 |
274 | }
275 |
276 | fun ObservableList.removeFirstMatching(predicate: (T) -> Boolean) {
277 | for ((index, value) in this.withIndex()) {
278 | if (predicate(value)) {
279 | this.removeAt(index)
280 | break;
281 | }
282 | }
283 |
284 | }
285 |
286 | fun JsonObject.getStringOrElse(name: String, elseValue: String): String {
287 | return get(name)?.let { if (it.isString()) it.asString() else null } ?: elseValue
288 | }
289 |
--------------------------------------------------------------------------------
/src/co/uproot/unplug/guiClient.kt:
--------------------------------------------------------------------------------
1 | package co.uproot.unplug
2 |
3 | import javafx.application.Application
4 | import javafx.stage.Stage
5 | import kotlinfx.builders.*
6 | import kotlinfx.kalium.*
7 | import kotlinfx.abbreviations.*
8 | import kotlinfx.bindings.*
9 | // import kotlinfx.properties.*
10 | import javafx.beans.property.SimpleStringProperty
11 | import org.fxmisc.easybind.EasyBind
12 | import javafx.scene.control.ListCell
13 | import javafx.util.Callback
14 | import javafx.scene.layout.Priority
15 | import javafx.beans.value.ObservableNumberValue
16 | import javafx.collections.FXCollections
17 | import javafx.concurrent.Worker
18 | import co.uproot.unplug.*
19 | import javafx.beans.binding.DoubleBinding
20 | import javafx.geometry.Pos
21 | import java.util.concurrent.ConcurrentHashMap
22 | import javafx.scene.image.Image
23 | import java.util.function.BiFunction
24 |
25 | fun main(args: Array) {
26 | Application.launch(UnplugApp::class.java, *args)
27 | }
28 |
29 | class UnplugApp : Application() {
30 | override fun start(stage: Stage?) {
31 | val args = getParameters().getRaw()
32 | val userIdInit = if (args.size > 0) args[0] else ""
33 | val serverInit = if (args.size > 1) args[1] else null
34 | val passwordInit = if (args.size > 2) args[2] else ""
35 |
36 | val loginService = LoginService()
37 | val userId = TextField(userIdInit) { promptText = "Eg: bob" }
38 |
39 | // TODO: Use the auto-complete box from here: https://github.com/privatejava/javafx-autocomplete-field
40 | val serverCommonUrls = FXCollections.observableArrayList("https://matrix.org", "http://localhost:8008")
41 | val serverCombo = ComboBox(serverCommonUrls) {
42 | // editable = true
43 | setEditable(true)
44 |
45 | if (serverInit == null) {
46 | getSelectionModel().select(0)
47 | } else {
48 | getEditor().text = serverInit
49 | }
50 | }
51 | val password = PasswordField() { text = passwordInit }
52 | password.setOnAction {
53 | val serverText = serverCombo.editor.text()
54 | startLogin(loginService, serverText, stage!!)
55 | }
56 |
57 | val login = Button("Login")
58 | val loginStatus = Label("")
59 |
60 | loginStatus.textProperty().bind(loginService.messageProperty())
61 | loginService.userName.bind(userId.textProperty())
62 | loginService.password.bind(password.textProperty())
63 |
64 | val loginForm = GridPane(padding = Insets(left = 10.0)) {
65 | hgap = 10.0
66 | vgap = 10.0
67 | addRow(0, Label("User id: "), userId)
68 | addRow(1, Label("Server: "), serverCombo)
69 | addRow(2, Label("Password: "), password)
70 | addRow(3, login)
71 | addRow(4, loginStatus)
72 | }
73 |
74 | login.setOnAction {
75 | val serverText = serverCombo.editor.text()
76 | startLogin(loginService, serverText, stage!!)
77 | }
78 |
79 | loginForm.disableProperty().bind(loginService.stateProperty().isNotEqualTo(Worker.State.READY))
80 | login.disable {
81 | userId.text().length == 0 || serverCombo.editor.text().length == 0
82 | }
83 | loginStatus.visible { loginStatus.text().length > 0 }
84 |
85 | Stage(stage, title = "unplug") {
86 | scene = Scene {
87 | stylesheets.add("/chat.css")
88 | root = VBox(spacing = 10.0, padding = Insets(10.0)) {
89 | +loginForm
90 | +loginStatus
91 | }
92 | }
93 | }.show()
94 | }
95 |
96 | private fun startLogin(loginService: LoginService, serverText: String, stage: Stage) {
97 | loginService.baseURL = "$serverText/"
98 | loginService.setOnSucceeded {
99 | val loginResult = loginService.getValue();
100 | if (loginResult == null) {
101 | alert("Invalid user-id/password")
102 | // logginIn u false
103 | loginService.reset()
104 | } else {
105 | stage.title = "[unplug] " + loginService.userName.get() + " : " + serverText
106 | postLogin(stage, loginResult)
107 | }
108 | }
109 | loginService.setOnFailed {
110 | loginService.reset()
111 | }
112 | loginService.restart()
113 | }
114 |
115 | val status = SimpleStringProperty("Loading")
116 |
117 | val appState = AppState()
118 |
119 | fun postLogin(stage: Stage, loginResult: LoginResult) {
120 | val statusLabel = Label()
121 | statusLabel.textProperty().bind(status)
122 | statusLabel.visible { status.get().length > 0 }
123 |
124 | val userListView = ListView(appState.currUserList.get()) {
125 | getStyleClass().add("user-list")
126 | }
127 | userListView.itemsProperty().bind(appState.currUserList)
128 |
129 | userListView.setCellFactory (object : Callback, ListCell> {
130 | override fun call(list: javafx.scene.control.ListView): ListCell {
131 | return UserFormatCell()
132 | }
133 | })
134 |
135 | val roomListView = ListView(appState.roomNameList)
136 |
137 | val selectedRoomIndexProperty = roomListView.selectionModel.selectedIndexProperty()
138 | EasyBind.subscribe(selectedRoomIndexProperty, { indexNum ->
139 | val index = indexNum as Int
140 | if (index >= 0) {
141 | val room = appState.roomStateList.get(index)
142 | appState.currRoomId.set(room.id)
143 | } else {
144 | appState.currRoomId.set(null)
145 | }
146 | })
147 |
148 | val messageListView = ListView(appState.currChatMessageList.get()) {
149 | fixedCellSize = -1.0
150 | }
151 |
152 | messageListView.itemsProperty().bind(appState.currChatMessageList)
153 |
154 | messageListView.setCellFactory (object : Callback, ListCell> {
155 | override fun call(list: javafx.scene.control.ListView): ListCell {
156 | return MessageFormatCell(messageListView.widthProperty().add(-20), appState)
157 | }
158 | })
159 |
160 | val messageInputView = TextField()
161 | messageInputView.setOnAction {
162 | val msg = messageInputView.text
163 | if (msg != "") {
164 | messageInputView.text = ""
165 | val sendService = SendMessageService(loginResult, appState.currRoomId.get(), msg)
166 | sendService.start()
167 | }
168 | }
169 |
170 | val roomOptionView = VBox(spacing = 10.0) {
171 | +createRoom(loginResult)
172 | +joinRoom(loginResult)
173 | }
174 |
175 | val roomList = VBox(spacing = 10.0) {
176 | +roomListView
177 | +roomOptionView
178 | }
179 |
180 | val optionView = HBox(spacing = 10.0) {
181 | +inviteMember(loginResult)
182 | +banMember(loginResult)
183 | +leaveRoom(loginResult)
184 | }
185 |
186 | val messageView = VBox(spacing = 10.0) {
187 | +optionView
188 | +messageListView
189 | +messageInputView
190 | }
191 |
192 | javafx.scene.layout.HBox.setHgrow(messageView, Priority.ALWAYS)
193 | javafx.scene.layout.HBox.setHgrow(messageInputView, Priority.ALWAYS)
194 | javafx.scene.layout.VBox.setVgrow(messageListView, Priority.ALWAYS)
195 | javafx.scene.layout.VBox.setVgrow(roomListView, Priority.ALWAYS)
196 |
197 |
198 | val chatView = HBox(spacing = 10.0, padding = Insets(10.0)) {
199 | +roomList
200 | +messageView
201 | +userListView
202 | }
203 |
204 | javafx.scene.layout.VBox.setVgrow(chatView, Priority.ALWAYS)
205 |
206 | stage.setScene(Scene {
207 | stylesheets.add("/chat.css")
208 |
209 | root = VBox(spacing = 10.0, padding = Insets(10.0)) {
210 | +statusLabel
211 | +chatView
212 | }
213 | })
214 |
215 | stage.setMaximized(true)
216 | stage.centerOnScreen()
217 |
218 | val syncService = SyncService(loginResult)
219 | status.bind(syncService.messageProperty())
220 | syncService.setOnSucceeded {
221 | val syncResult = syncService.getValue()
222 | if (syncResult == null) {
223 | status.setValue("Sync error")
224 | } else {
225 | appState.processSyncResult(syncResult, loginResult.api)
226 | postSync(loginResult)
227 | }
228 | }
229 | syncService.setOnFailed { showSyncError() }
230 |
231 | syncService.start()
232 | }
233 |
234 | fun createRoom(loginResult: LoginResult): javafx.scene.control.Button {
235 | val createRoomButton = Button("Create Room")
236 | createRoomButton.setOnAction {
237 | val stage1 = Stage()
238 | Stage(stage1, title = "Creating Room") {
239 | scene = Scene {
240 | stylesheets.add("/chat.css")
241 | val name = Label("Enter name :")
242 | val textfld = TextField()
243 | val visibility = RadioButton("public")
244 | val create = Button("Create")
245 | create.setOnAction {
246 | val createRoom1 = CreateRoomService(loginResult, textfld.text(), visibility.getText())
247 | createRoom1.start()
248 | stage1.close()
249 | }
250 | create.disable {
251 | textfld.text().length == 0
252 | }
253 | val hb = HBox(spacing = 10.0) {
254 | +name
255 | +textfld
256 | }
257 | root = VBox(spacing = 15.0, padding = Insets(60.0, 60.0, 150.0, 60.0)) {
258 | +visibility
259 | +hb
260 | +create
261 | }
262 | }
263 | }.show()
264 | }
265 | return createRoomButton
266 | }
267 |
268 | private fun getRoomIdentifier(room: String): RoomIdentifier? {
269 | val first = room.get(0)
270 | if (first == '#') {
271 | return RoomName(room)
272 | } else if (first == '!') {
273 | return RoomId(room)
274 | } else {
275 | return null
276 | }
277 | }
278 |
279 | fun joinRoom(loginResult: LoginResult): javafx.scene.control.Button {
280 | val joinRoomButton = Button("Join Room")
281 | joinRoomButton.setOnAction {
282 | val stage2 = Stage()
283 | Stage(stage2, title = "Joining Room") {
284 | scene = Scene {
285 | stylesheets.add("/chat.css")
286 | val lblName = Label("Enter room name ")
287 | val name = TextField()
288 | val join = Button("Join")
289 | join.setOnAction {
290 | val room = getRoomIdentifier(name.text)
291 | if (room != null) {
292 | try {
293 | val joinRoom = JoinRoomService(loginResult, room)
294 | joinRoom.start()
295 | } catch(e: Exception) {
296 | e.printStackTrace()
297 | alert("Room joining failed; room might be private")
298 | }
299 | stage2.close()
300 | } else {
301 | alert("Invalid Room Name or id")
302 | }
303 | }
304 | join.disable {
305 | name.text().length == 0
306 | }
307 | val hbox = HBox(spacing = 10.0) {
308 | +lblName
309 | +name
310 | }
311 | root = VBox(spacing = 10.0, padding = Insets(80.0, 60.0, 60.0, 60.0)) {
312 | +hbox
313 | +join
314 | }
315 | }
316 | }.show()
317 | }
318 | return joinRoomButton
319 | }
320 |
321 | fun inviteMember(loginResult: LoginResult): javafx.scene.control.Button {
322 | val inviteMemberButton = Button("Invite Member")
323 | inviteMemberButton.setOnAction {
324 | val stage4 = Stage()
325 | Stage(stage4, title = "Inviting member") {
326 | scene = Scene {
327 | stylesheets.add("/chat.css")
328 | val lblroomName = Label("Enter room name")
329 | val roomName = TextField(appState.getCurrRoomNameOrId() ?: "")
330 | val lblmemId = Label("Enter member Id :")
331 | val memberId = TextField()
332 | val invite = Button("Invite")
333 | invite.setOnAction {
334 | val room = getRoomIdentifier(roomName.text)
335 | if (room != null) {
336 | val inviteService = InviteMemberService(loginResult, room, memberId.text())
337 | inviteService.start()
338 | stage4.close()
339 | } else {
340 | alert("Invalid Room Name or Id")
341 | }
342 | }
343 | invite.disable {
344 | roomName.text().length == 0 || memberId.text().length == 0
345 | }
346 | val hbox1 = HBox(spacing = 20.0) {
347 | +lblroomName
348 | +roomName
349 | }
350 | val hbox2 = HBox(spacing = 15.0) {
351 | +lblmemId
352 | +memberId
353 | }
354 | root = VBox(spacing = 15.0, padding = Insets(80.0, 60.0, 60.0, 60.0)) {
355 | +hbox1
356 | +hbox2
357 | +invite
358 | }
359 |
360 | }
361 | }.show()
362 | }
363 | return inviteMemberButton
364 | }
365 |
366 | fun banMember(loginResult: LoginResult): javafx.scene.control.Button {
367 | val banMemberButton = Button("Ban Member")
368 | banMemberButton.setOnAction {
369 | val stage3 = Stage()
370 | Stage(stage3, title = "Banning Member") {
371 | scene = Scene {
372 | stylesheets.add("/chat.css")
373 | val lblroomName = Label("Enter room name")
374 | val roomName = TextField(appState.getCurrRoomNameOrId() ?: "")
375 | val lblMId = Label("Enter member Id")
376 | val memId = TextField()
377 | val ban = Button("Ban")
378 | ban.setOnAction {
379 | val room = getRoomIdentifier(roomName.text)
380 | if (room != null) {
381 | val banService = BanRoomService(loginResult, room, memId.text(), appState)
382 | banService.start()
383 | stage3.close()
384 | } else {
385 | alert("Invalid Room Name or Id")
386 | }
387 | }
388 | ban.disable {
389 | roomName.text().length == 0 || memId.text().length == 0
390 | }
391 | val hbox1 = HBox(spacing = 20.0) {
392 | +lblroomName
393 | +roomName
394 | }
395 | val hbox2 = HBox(spacing = 23.0) {
396 | +lblMId
397 | +memId
398 | }
399 | root = VBox(spacing = 15.0, padding = Insets(80.0, 60.0, 60.0, 60.0)) {
400 | +hbox1
401 | +hbox2
402 | +ban
403 | }
404 | }
405 | }.show()
406 | }
407 | return banMemberButton
408 | }
409 |
410 | fun leaveRoom(loginResult: LoginResult): javafx.scene.control.Button {
411 | val leaveRoomButton = Button("Leave Room")
412 | leaveRoomButton.setOnAction {
413 | val stage4 = Stage()
414 | Stage(stage4, title = "Leaving Room") {
415 | scene = Scene {
416 | stylesheets.add("/chat.css")
417 | val lblname = Label("Enter room name")
418 | val name = TextField(appState.getCurrRoomNameOrId() ?: "")
419 | val leave = Button("Leave")
420 | leave.setOnAction {
421 | val room = getRoomIdentifier(name.text)
422 | if (room != null) {
423 | val leaveRoomSer = LeaveRoomService(loginResult, room)
424 | leaveRoomSer.start()
425 | stage4.close()
426 | } else {
427 | alert("Invalid Room Name or Id")
428 | }
429 | }
430 | leave.disable {
431 | name.text().length == 0
432 | }
433 | val hbox = HBox(spacing = 10.0) {
434 | +lblname
435 | +name
436 | }
437 | root = VBox(spacing = 10.0, padding = Insets(80.0, 60.0, 60.0, 60.0)) {
438 | +hbox
439 | +leave
440 | }
441 | }
442 | }.show()
443 | }
444 | return leaveRoomButton
445 | }
446 |
447 | fun alert(msg: String) {
448 | val stage01 = Stage()
449 | Stage(stage01, title = "Alert!!") {
450 | scene = Scene {
451 | stylesheets.add("/chat.css")
452 | val msgLabel = Label(msg)
453 | val btn = Button("Close")
454 | root = VBox(spacing = 15.0, padding = Insets(60.0, 60.0, 150.0, 60.0)) {
455 | +msgLabel
456 | +btn
457 | }
458 | btn.setOnAction {
459 | stage01.close()
460 | }
461 | }
462 | }.show()
463 | }
464 |
465 | private fun showSyncError() {
466 | Stage(Stage(), "Error") {
467 | scene = Scene() {
468 | root = VBox() {
469 | +Label ("Error while syncing")
470 | }
471 | }
472 | }
473 | }
474 |
475 | fun postSync(loginResult: LoginResult) {
476 | val eventsService = EventService(loginResult)
477 | status.bind(eventsService.messageProperty())
478 | eventsService.setOnSucceeded {
479 | val eventResult = eventsService.getValue()
480 | if (eventResult != null) {
481 | appState.processEventsResult(eventResult, loginResult.api, loginResult)
482 | }
483 | eventsService.restart()
484 | }
485 |
486 | eventsService.setOnFailed {
487 | eventsService.restart()
488 | }
489 |
490 | eventsService.start()
491 | }
492 | }
493 |
494 | object ImageCache {
495 |
496 | final private class ImageEntry(val url: String, val img: Image)
497 |
498 | private val imageStore = ConcurrentHashMap()
499 |
500 | private class ImageMakerAndUpdater(val url: String) : BiFunction {
501 | override fun apply(id: String, oldImg: ImageEntry?): ImageEntry {
502 | val saneURL = if (url.isEmpty()) "/default-avatar-32.png" else url
503 | val imgEntry = if (oldImg == null) {
504 | ImageEntry(saneURL, Image(saneURL, 32.0, 32.0, true, true, true))
505 | } else {
506 | if (oldImg.url == saneURL) {
507 | oldImg
508 | } else {
509 | ImageEntry(saneURL, Image(saneURL, 32.0, 32.0, true, true, true))
510 | }
511 | }
512 | return imgEntry
513 | }
514 | }
515 |
516 | fun getOrCreate(userId: String, url: String): Image {
517 | return imageStore.compute(userId, ImageMakerAndUpdater(url))!!.img
518 | }
519 | }
520 |
521 | class UserFormatCell() : ListCell() {
522 |
523 | override fun updateItem(us: UserState?, empty: Boolean) {
524 | super.updateItem(us, empty)
525 | if (us == null || empty) {
526 | setGraphic(null)
527 | } else {
528 | val typing = us.typing.get()
529 | val present = us.present.get()
530 | val typingStr = if (typing) "⌨" else ""
531 | val id = Text("${us.id} $typingStr") {
532 | getStyleClass().add("unplug-text")
533 | getStyleClass().add("user-id")
534 | }
535 | val displayName = Text("${us.displayName.get()}") {
536 | getStyleClass().add("unplug-text")
537 | getStyleClass().add("user-displayname")
538 | }
539 | val userDetails = VBox(spacing = 2.0, padding = Insets(0.0)) {
540 | +id
541 | +displayName
542 | }
543 |
544 | val image = ImageCache.getOrCreate(us.id, us.avatarURL.get())
545 | val avatar = ImageView(image) {
546 | setCache(true)
547 | setPreserveRatio(true)
548 | }
549 |
550 | // The wrap ensures that the avatar image doesn't collapse when its width is smaller than 32
551 | val avatarWrap = StackPane() {
552 | +avatar
553 |
554 | setMinWidth(32.0)
555 | setAlignment(Pos.CENTER)
556 | }
557 |
558 | val graphic = HBox(spacing = 10.0, padding = Insets(2.0)) {
559 | +avatarWrap
560 | +userDetails
561 |
562 | setAlignment(Pos.CENTER_LEFT)
563 |
564 | if (typing || present) {
565 | if (typing) {
566 | getStyleClass().add("user-typing")
567 | }
568 | if (present) {
569 | getStyleClass().add("user-present")
570 | }
571 | } else {
572 | getStyleClass().add("user-default")
573 | }
574 | }
575 | setGraphic(graphic)
576 | }
577 |
578 | }
579 | }
580 |
581 |
582 | class MessageFormatCell(val containerWidthProperty: DoubleBinding, val appState: AppState) : ListCell() {
583 | private class MessageView(val userId: String, val time: java.util.Date, val msgBody: String, val meta: Boolean)
584 |
585 | override fun updateItem(message: Message?, empty: Boolean) {
586 | super.updateItem(message, empty)
587 | if (message == null || empty) {
588 | setGraphic(null)
589 | } else {
590 | val d = java.util.Date(message.ts)
591 | val m =
592 | when (message.type) {
593 | "m.room.create" -> MessageView(message.content.getString("creator", "(unexpected missing creator)"), d, "Room created", true)
594 | "m.room.member" -> {
595 | val status = if (message.content.getString("membership", "") == "join") "Joined" else "Left"
596 | MessageView(message.userId, d, status, true)
597 | }
598 | "m.room.message" -> MessageView(message.userId, d, message.content.getString("body", "(unexpected empty body)"), false)
599 | else -> {
600 | MessageView(message.userId, d, "Unhandled message type: ${message.type}", true)
601 | }
602 | }
603 |
604 | if (message.roomId != null) {
605 | val users = appState.getRoomUsers(message.roomId)
606 | val messageUser = users.firstOrNull { it.id == message.userId }
607 | val avatarWrap =
608 | if (messageUser != null) {
609 | val url = messageUser.avatarURL
610 | val image = ImageCache.getOrCreate(message.userId, url.get())
611 | val avatar = ImageView(image) {
612 | setCache(true)
613 | setPreserveRatio(true)
614 | }
615 |
616 | // The wrap ensures that the avatar image doesn't collapse when its width is smaller than 32
617 | StackPane() {
618 | +avatar
619 |
620 | setMinWidth(32.0)
621 | setAlignment(Pos.CENTER)
622 | }
623 |
624 | } else {
625 | StackPane() {
626 | setMinWidth(32.0)
627 | }
628 | }
629 |
630 | val id = Text(m.userId) {
631 | getStyleClass().add("chat-message-id")
632 | }
633 | val time = Text(m.time.toString()) {
634 | getStyleClass().add("unplug-text-muted")
635 | }
636 | val userDetails = VBox(spacing = 2.0, padding = Insets(0.0)) {
637 | +id
638 | +time
639 | }
640 |
641 | val body = Text(m.msgBody) {
642 | if (m.meta) {
643 | getStyleClass().add("chat-message-meta")
644 | } else {
645 | getStyleClass().add("chat-message-text")
646 | }
647 | }
648 | val bodyFlow = TextFlow(body)
649 |
650 | val graphic = HBox(spacing = 10.0, padding = Insets(2.0)) {
651 | +avatarWrap
652 | +userDetails
653 | +bodyFlow
654 | }
655 | graphic.prefWidthProperty().bind(containerWidthProperty)
656 |
657 | setGraphic(graphic)
658 |
659 | } else {
660 | throw IllegalStateException("Room id of message is null: " + message)
661 | }
662 | }
663 | }
664 | }
665 |
--------------------------------------------------------------------------------
/src/co/uproot/unplug/guiServices.kt:
--------------------------------------------------------------------------------
1 | package co.uproot.unplug
2 |
3 | import javafx.beans.property.SimpleStringProperty
4 | import javafx.concurrent.Service
5 | import javafx.concurrent.Task
6 |
7 |
8 | class LoginService() : Service() {
9 | val userName = SimpleStringProperty("")
10 | val password = SimpleStringProperty("")
11 |
12 | var baseURL: String = ""
13 |
14 | override fun createTask(): Task? {
15 | val api = API(baseURL)
16 | return object : Task() {
17 | override fun call(): LoginResult? {
18 | updateMessage("Logging In")
19 | val loginResult = api.login(userName.get(), password.get())
20 | if (loginResult == null) {
21 | updateMessage("Login Failed")
22 | failed()
23 | return null
24 | } else {
25 | updateMessage("Logged In Successfully")
26 | return loginResult
27 | }
28 | }
29 | }
30 | }
31 | }
32 |
33 | class RoomSyncService(val loginResult: LoginResult, val roomId: String) : Service() {
34 | override fun createTask(): Task? {
35 | val api = loginResult.api
36 | return object : Task() {
37 | override fun call(): SyncResult? {
38 | updateMessage("Syncing")
39 | val result = api.roomInitialSync(loginResult.accessToken, roomId)
40 | if (result == null) {
41 | updateMessage("Sync Failed")
42 | failed()
43 | return null
44 | } else {
45 | updateMessage("")
46 | return result
47 | }
48 | }
49 | }
50 | }
51 | }
52 |
53 |
54 | class SyncService(val loginResult: LoginResult) : Service() {
55 | val userName = SimpleStringProperty("")
56 | val password = SimpleStringProperty("")
57 |
58 | override fun createTask(): Task? {
59 | val api = loginResult.api
60 | return object : Task() {
61 | override fun call(): SyncResult? {
62 | updateMessage("Syncing")
63 | val result = api.initialSync(loginResult.accessToken)
64 | if (result == null) {
65 | updateMessage("Sync Failed")
66 | failed()
67 | return null
68 | } else {
69 | updateMessage("")
70 | return result
71 | }
72 | }
73 | }
74 | }
75 | }
76 |
77 |
78 | class CreateRoomService(val loginResult: LoginResult, val roomname: String, val visibility: String) : Service() {
79 |
80 | override fun createTask(): Task? {
81 | return object : Task() {
82 | override fun call(): CreateRoomResult? {
83 | val createRoomResult = loginResult.api.createRoom(loginResult.accessToken, roomname, visibility)
84 | if (createRoomResult == null) {
85 | updateMessage("Failed")
86 | failed()
87 | return null
88 | } else {
89 | updateMessage("")
90 | return createRoomResult
91 | }
92 | }
93 | }
94 | }
95 | }
96 |
97 | class JoinRoomService(val loginResult: LoginResult, val room: RoomIdentifier) : Service() {
98 |
99 | override fun createTask(): Task? {
100 | return object : Task() {
101 | override fun call(): JoinRoomResult? {
102 | val joinResult = loginResult.api.joiningRoon(loginResult.accessToken, room)
103 | if (joinResult == null) {
104 | updateMessage("Failed")
105 | failed()
106 | return null
107 | } else {
108 | updateMessage("")
109 | return joinResult
110 | }
111 | }
112 | }
113 | }
114 | }
115 |
116 | class InviteMemberService(val loginResult: LoginResult, val room: RoomIdentifier, val memName: String) : Service() {
117 |
118 | override fun createTask(): Task? {
119 | return object : Task() {
120 | override fun call(): InviteMemResult? {
121 | val inviteResult = loginResult.api.invitingMember(loginResult.accessToken, room, memName)
122 | if (inviteResult == null) {
123 | updateMessage("Failed")
124 | failed()
125 | return null
126 | } else {
127 | updateMessage("")
128 | return inviteResult
129 | }
130 | }
131 | }
132 | }
133 | }
134 |
135 | class BanRoomService(val loginResult: LoginResult, val room: RoomIdentifier, val memId: String, val appState: AppState) : Service() {
136 |
137 | override fun createTask(): Task? {
138 | return object : Task() {
139 | override fun call(): BanRoomResult? {
140 | val banRoomResult = loginResult.api.banningMember(loginResult.accessToken, room, memId, appState)
141 | if (banRoomResult == null) {
142 | updateMessage("Failed")
143 | failed()
144 | return null
145 | } else {
146 | updateMessage("")
147 | return banRoomResult
148 | }
149 | }
150 | }
151 | }
152 | }
153 |
154 | class LeaveRoomService(val loginResult: LoginResult, val roomIdentifier: RoomIdentifier) : Service() {
155 |
156 | override fun createTask(): Task? {
157 | return object : Task() {
158 | override fun call(): LeaveRoomResult? {
159 | val leaveResult = loginResult.api.leavingRoom(loginResult.accessToken, roomIdentifier)
160 | if (leaveResult == null) {
161 | updateMessage("Failed")
162 | failed()
163 | return null
164 | } else {
165 | updateMessage("")
166 | return leaveResult
167 | }
168 | }
169 | }
170 | }
171 | }
172 |
173 | class EventService(val loginResult: LoginResult) : Service() {
174 | private var from: String? = null
175 |
176 | override fun createTask(): Task? {
177 | return object : Task() {
178 | override fun call(): EventResult? {
179 | val eventResult = loginResult.api.getEvents(loginResult.accessToken, from)
180 | if (eventResult == null) {
181 | updateMessage("Events Failed")
182 | failed()
183 | return null
184 | } else {
185 | updateMessage("")
186 | from = eventResult.end
187 | return eventResult
188 | }
189 | }
190 | }
191 | }
192 | }
193 |
194 | class SendResult(eventId: String)
195 |
196 | class SendMessageService(val loginResult: LoginResult, val roomId: String, val msg: String) : Service() {
197 |
198 | override fun createTask(): Task? {
199 | return object : Task() {
200 | override fun call(): SendResult? {
201 | val eventId = loginResult.api.sendMessage(loginResult.accessToken, roomId, msg)
202 | if (eventId == null) {
203 | updateMessage("Sending Failed")
204 | failed()
205 | return null
206 | } else {
207 | updateMessage("")
208 | return SendResult(eventId)
209 | }
210 | }
211 | }
212 | }
213 | }
214 |
--------------------------------------------------------------------------------
/src/default-avatar-32.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiMium/unplug/8d4ae61484420720128d1498c5d0fff9857c151c/src/default-avatar-32.png
--------------------------------------------------------------------------------
/src/default-avatar.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/LiMium/unplug/8d4ae61484420720128d1498c5d0fff9857c151c/src/default-avatar.png
--------------------------------------------------------------------------------
/unplug.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------