├── .gitignore
├── LICENSE
├── Makefile
├── README.md
├── client.rst
├── client
├── dist
│ └── messenger_client-0.1-py3-none-any.whl
├── setup.py
└── src
│ ├── CLIENT_CONSOLE.bat
│ ├── CLIENT_GUI.bat
│ ├── __init__.py
│ ├── client.py
│ ├── client_gui.pyw
│ ├── client_gui.ui
│ ├── client_pyqt.py
│ ├── helpers.py
│ ├── jim.py
│ ├── log_confing.py
│ ├── security.py
│ ├── storage.py
│ ├── test_client.py
│ ├── test_jim.py
│ ├── test_security.py
│ ├── test_storage.py
│ └── update_ui.bat
├── conf.py
├── index.rst
├── make.bat
├── screen.png
├── server.rst
└── server
├── dist
└── messenger_server-0.1-py3-none-any.whl
├── setup.py
└── src
├── SERVER_CONSOLE.bat
├── SERVER_GUI.bat
├── __init__.py
├── helpers.py
├── jim.py
├── log_confing.py
├── security.py
├── server.py
├── server_gui.pyw
├── server_gui.ui
├── server_pyqt.py
├── storage.py
├── test_jim.py
├── test_security.py
├── test_server.py
├── test_storage.py
└── update_ui.bat
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | *.egg-info/
24 | .installed.cfg
25 | *.egg
26 | MANIFEST
27 |
28 | # PyInstaller
29 | # Usually these files are written by a python script from a template
30 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
31 | *.manifest
32 | *.spec
33 |
34 | # Installer logs
35 | pip-log.txt
36 | pip-delete-this-directory.txt
37 |
38 | # Unit test / coverage reports
39 | htmlcov/
40 | .tox/
41 | .coverage
42 | .coverage.*
43 | .cache
44 | nosetests.xml
45 | coverage.xml
46 | *.cover
47 | .hypothesis/
48 | .pytest_cache/
49 |
50 | # Translations
51 | *.mo
52 | *.pot
53 |
54 | # Django stuff:
55 | *.log
56 | local_settings.py
57 | db.sqlite3
58 |
59 | # Flask stuff:
60 | instance/
61 | .webassets-cache
62 |
63 | # Scrapy stuff:
64 | .scrapy
65 |
66 | # Sphinx documentation
67 | docs/_build/
68 |
69 | # PyBuilder
70 | target/
71 |
72 | # Jupyter Notebook
73 | .ipynb_checkpoints
74 |
75 | # pyenv
76 | .python-version
77 |
78 | # celery beat schedule file
79 | celerybeat-schedule
80 |
81 | # SageMath parsed files
82 | *.sage.py
83 |
84 | # Environments
85 | .env
86 | .venv
87 | env/
88 | venv/
89 | ENV/
90 | env.bak/
91 | venv.bak/
92 |
93 | # Spyder project settings
94 | .spyderproject
95 | .spyproject
96 |
97 | # Rope project settings
98 | .ropeproject
99 |
100 | # mkdocs documentation
101 | /site
102 |
103 | # mypy
104 | .mypy_cache/
105 |
106 | # pycharm
107 | .idea/*
108 |
109 | # TimedRotatingFileHandler logs
110 | messenger.server.log.*
111 |
112 | *.sqlite
113 |
114 | # sphinx
115 | _build/*
116 |
117 | !dist/
--------------------------------------------------------------------------------
/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 |
635 | Copyright (C)
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 | Copyright (C)
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 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | # Minimal makefile for Sphinx documentation
2 | #
3 |
4 | # You can set these variables from the command line.
5 | SPHINXOPTS =
6 | SPHINXBUILD = sphinx-build
7 | SPHINXPROJ = Messenger
8 | SOURCEDIR = .
9 | BUILDDIR = _build
10 |
11 | # Put it first so that "make" without argument is like "make help".
12 | help:
13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
14 |
15 | .PHONY: help Makefile
16 |
17 | # Catch-all target: route all unknown targets to Sphinx using the new
18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
19 | %: Makefile
20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Messenger
2 | Проект представяет собой учебный чат-мессенджер на Python.
3 | Состоит из клиентской и серверной частей.
4 | Сетевое взаимодействие осуществляется с использованием сокетов.
5 | Сервер использует библиотеку select для работы с несколькими клиентами сразу.
6 | Для обмена сообщениями используется протокол JIM.
7 | Клиент и сервер имеют как консольную, так и графическую версии. Последняя предпочтительнее по удобству и полноте поддерживаемого функционала.
8 | Графический интерфейс пользователя реализован с использованием PyQT5.
9 | В качестве базы данных используется sqlite, при этом ORM не применяется.
10 | Реализован механизм авторизации пользователей с использованием модулей hmac и hashlib.
11 |
12 | 
13 |
14 | ## Сервер
15 | Рассмотрим графическую версию сервера.
16 |
17 | ### Parameters
18 | В данном блоке можно задать хост и порт для сервера, а также запустить или остановить его. Если сервер запущен, в поле `Status` появится значение `Started`.
19 |
20 | ### Clients
21 | Таблица содержит историю активности клиентов: логин, дата и время последнего посещения, IP-адрес, с которого в последний раз заходил пользователь. Данные отсортированы по времени (более новые вверху).
22 |
23 | ### Add new client
24 | Чтобы клиент мог пользоваться чатом, его нужно сначала зарегистрировать на сервере. Для этого в данном блоке нужно ввести его логин и пароль, затем нажать кнопку `Add client`.
25 |
26 | ### Service info
27 | В данное поле выводится вся информация о работе сервера: служебные данные, сообщения об ошибках, а также все сообщения, которые принимает и отправляет сервер, плюс информация о подключениях и отключениях клиентов.
28 |
29 | ## Клиент
30 | Рассмотрим графическую версию клиента.
31 |
32 | ### Connection
33 | Для начала работы нужно ввести данные для соединения с сервером:
34 |
35 | - `User name` - логин
36 | - `Password` - пароль
37 | - `Server IP` - адрес или имя хоста сервера
38 | - `Server port` - номер порта, на котором работает сервер
39 |
40 | Кнопка `Connect` позволяет выполнить подключение к серверу, кнопка `Disconnect` - отключение.
41 |
42 | ### Parameters
43 | Когда клиент успешно подключился к серверу, в данном блоке отображается информация о подключении: логин пользователя, адрес хоста и номер порта сервера.
44 |
45 | ### Контакты
46 | В блоке `Contacts` отображается список контактов пользователя. Чтобы добавить новый контакт, нужно ввести логин в поле `Add contact` и нажать кнопку `Add`. После этого можно писать данному пользователю сообщения. Если клиенту приходит сообщение от контакта, которого ещё нет в списке, то он автоматически там появляется.
47 | Для удаления контакта нужно выбрать его из списка и нажать кнопку `Delete selected contact`.
48 |
49 | ### Сообщения
50 | Для отправки сообщения контакту нужно выбрать его в списке щелчком левой кнопки мыши. После этого в поле `Messages` появится история переписки с данным пользователем (если она была ранее). Чтобы послать ему новое сообщение, требуется ввести текст в поле `Input` и нажать кнопку `Send`. Для успешной доставки сообщения необходимо, чтобы получатель также был подключен к серверу. В противном случае сервер ответит ошибкой с текстом "client not online".
51 | Входящие сообщения будут отображаться в `Messages` по их получения клиентом.
52 |
53 | ### Service info
54 | В данном блоке выводится информация о работе клиента, это служебные данные и сообщения об ошибках.
--------------------------------------------------------------------------------
/client.rst:
--------------------------------------------------------------------------------
1 | Клиент
2 | ======
3 | Рассмотрим графическую версию клиента.
4 |
5 | Основные области окна программы описаны далее.
6 |
7 | Connection
8 | ----------
9 | Для начала работы нужно ввести данные для соединения с сервером:
10 |
11 | * ``User name`` - логин
12 | * ``Password`` - пароль
13 | * ``Server IP`` - адрес или имя хоста сервера
14 | * ``Server port`` - номер порта, на котором работает сервер
15 |
16 | Кнопка ``Connect`` позволяет выполнить подключение к серверу, кнопка ``Disconnect`` - отключение.
17 |
18 | Parameters
19 | ----------
20 | Когда клиент успешно подключился к серверу, в данном блоке отображается **информация** о подключении: логин пользователя, адрес хоста и номер порта сервера.
21 |
22 | Контакты
23 | --------
24 | В блоке ``Contacts`` отображается список контактов пользователя.
25 |
26 | Чтобы **добавить** новый контакт, нужно ввести логин в поле ``Add contact`` и нажать кнопку ``Add``.
27 | После этого можно писать данному пользователю сообщения.
28 |
29 | Если клиенту приходит сообщение от контакта, которого ещё нет в списке, то он автоматически там появляется.
30 |
31 | Для **удаления** контакта нужно выбрать его из списка и нажать кнопку ``Delete selected contact``.
32 |
33 | Сообщения
34 | ---------
35 | Для **отправки** сообщения контакту нужно выбрать его в списке щелчком левой кнопки мыши.
36 | После этого в поле ``Messages`` появится история переписки с данным пользователем (если она была ранее).
37 |
38 | Чтобы послать ему новое сообщение, требуется ввести текст в поле ``Input`` и нажать кнопку ``Send``.
39 | Для успешной доставки сообщения необходимо, чтобы получатель также был подключен к серверу.
40 | В противном случае сервер ответит ошибкой с текстом "client not online".
41 |
42 | Входящие сообщения будут отображаться в ``Messages`` по их получения клиентом.
43 |
44 | Service info
45 | ------------
46 | В данном блоке выводится информация о работе клиента, это служебные данные и сообщения об ошибках.
47 |
--------------------------------------------------------------------------------
/client/dist/messenger_client-0.1-py3-none-any.whl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dmitry-vs/python-messenger/e2ac312c83dfb24253698e14d237f531ee14b831/client/dist/messenger_client-0.1-py3-none-any.whl
--------------------------------------------------------------------------------
/client/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import setup
2 |
3 | setup(name = "messenger_client",
4 | version = "0.1",
5 | description = "Python 2 Messenger Client",
6 | author = "Dmitry VS",
7 | author_email = "dmitryselin@inbox.ru",
8 | url = "http://www.blog.pythonlibrary.org/2012/07/08/python-201-creating-modules-and-packages/",
9 | packages=["src"]
10 | )
--------------------------------------------------------------------------------
/client/src/CLIENT_CONSOLE.bat:
--------------------------------------------------------------------------------
1 | client.py
--------------------------------------------------------------------------------
/client/src/CLIENT_GUI.bat:
--------------------------------------------------------------------------------
1 | start client_gui.pyw
--------------------------------------------------------------------------------
/client/src/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dmitry-vs/python-messenger/e2ac312c83dfb24253698e14d237f531ee14b831/client/src/__init__.py
--------------------------------------------------------------------------------
/client/src/client.py:
--------------------------------------------------------------------------------
1 | import sys
2 | from socket import socket, AF_INET, SOCK_STREAM
3 | import argparse
4 | import logging
5 | import inspect
6 | import os
7 | from threading import Thread
8 | from queue import Queue
9 |
10 | import helpers
11 | import jim
12 | from storage import DBStorageClient
13 | import security
14 | import log_confing
15 |
16 | log = logging.getLogger(helpers.CLIENT_LOGGER_NAME)
17 |
18 |
19 | def parse_commandline_args(cmd_args):
20 | parser = argparse.ArgumentParser()
21 | parser.add_argument('-sa', dest='server_ip', type=str, default=helpers.DEFAULT_SERVER_IP, help='server ip, default 127.0.0.1')
22 | parser.add_argument('-sp', dest='server_port', type=int, default=helpers.DEFAULT_SERVER_PORT, help='server port, default 7777')
23 | parser.add_argument('-u', dest='user_name', type=str, default=helpers.DEFAULT_CLIENT_LOGIN, help='client login, default "TestClient"')
24 | parser.add_argument('-p', dest='user_password', type=str, default=helpers.DEFAULT_CLIENT_PASSWORD, help='client password, default "TestPassword"')
25 | return parser.parse_args(cmd_args)
26 |
27 |
28 | class ClientVerifierMeta(type):
29 | def __init__(cls, clsname, bases, clsdict):
30 | tcp_found = False
31 |
32 | for key, value in clsdict.items():
33 | if type(value) is socket: # check this is not class-level socket
34 | raise RuntimeError('Client must not use class-level sockets')
35 |
36 | if not hasattr(value, '__call__'): # we need only methods further
37 | continue
38 |
39 | source = inspect.getsource(value)
40 | if '.accept(' in source or '.listen(' in source: # check there are no accept() or listen() socket calls
41 | raise RuntimeError('Client must not use accept or listen for sockets')
42 |
43 | if 'SOCK_STREAM' in source: # check that TCP sockets are used
44 | tcp_found = True
45 |
46 | if not tcp_found:
47 | raise RuntimeError('Client must use only TCP sockets')
48 |
49 | type.__init__(cls, clsname, bases, clsdict)
50 |
51 |
52 | class Client(metaclass=ClientVerifierMeta):
53 | def __init__(self, username, password, storage_file):
54 | self.__username = username
55 | self.__security_key = security.create_password_hash(password)
56 | self.__socket = socket(AF_INET, SOCK_STREAM)
57 | self.__storage = DBStorageClient(storage_file)
58 | self.__service_messages = Queue()
59 | self.__user_messages = Queue()
60 | self.__reader_thread = Thread(target=self.read_messages_thread_function)
61 | self.__reader_thread.daemon = True
62 | self.__need_terminate = False
63 |
64 | def __del__(self):
65 | self.close_client()
66 |
67 | def close_client(self):
68 | self.__socket.close()
69 | self.__need_terminate = True
70 | self.__reader_thread.join()
71 |
72 | def read_messages_thread_function(self):
73 | while True:
74 | if self.__need_terminate:
75 | return
76 | try:
77 | msg = self.receive_message_from_server()
78 | if 'action' in msg.datadict.keys() and msg.datadict['action'] == 'msg': # user message
79 | self.__user_messages.put(msg)
80 | else: # service message
81 | self.__service_messages.put(msg)
82 | except OSError:
83 | pass
84 |
85 | @property
86 | def user_messages_queue(self):
87 | return self.__user_messages
88 |
89 | @property
90 | def username(self):
91 | return self.__username
92 |
93 | @property
94 | def storage(self):
95 | return self.__storage
96 |
97 | def send_data(self, data: bytes) -> int:
98 | if type(data) is not bytes:
99 | raise TypeError
100 | return self.__socket.send(data)
101 |
102 | def receive_data(self, size=helpers.TCP_MSG_BUFFER_SIZE) -> bytes:
103 | if size <= 0:
104 | raise ValueError
105 | return self.__socket.recv(size)
106 |
107 | def send_message_to_server(self, msg: jim.JimRequest):
108 | msg_bytes = msg.to_bytes()
109 | msg_bytes_len = len(msg_bytes)
110 | bytes_sent = self.send_data(msg_bytes)
111 | if bytes_sent != msg_bytes_len:
112 | raise RuntimeError(f'socket.send() returned {bytes_sent}, but expected {msg_bytes_len}')
113 |
114 | def receive_message_from_server(self) -> jim.JimResponse:
115 | received_data = self.receive_data()
116 | return jim.response_from_bytes(received_data)
117 |
118 | def check_connection(self):
119 | request = jim.presence_request(self.__username)
120 | self.send_message_to_server(request)
121 | response = self.__service_messages.get()
122 | if response.response == 200: # all ok
123 | return
124 | elif response.response == 401: # authentication needed
125 | self.authenticate(response.datadict['token'])
126 | else:
127 | raise RuntimeError(f'Presence: expected 200, '
128 | f'received {response.response}, error: {response.datadict["error"]}')
129 |
130 | def authenticate(self, auth_token: str):
131 | auth_digest = security.create_auth_digest(self.__security_key, auth_token)
132 | auth_message = jim.auth_client_message(self.__username, auth_digest)
133 | self.send_message_to_server(auth_message)
134 | response = self.__service_messages.get()
135 | if response.response != 200:
136 | raise RuntimeError(f'Authenticate: expected 200, '
137 | f'received {response.response}, error: {response.datadict["error"]}')
138 |
139 | def connect(self, server_ip: str, server_port: int):
140 | self.__socket.connect((server_ip, server_port))
141 | self.__reader_thread.start()
142 | self.check_connection()
143 |
144 | def update_contacts_from_server(self):
145 | request = jim.get_contacts_request()
146 | self.send_message_to_server(request)
147 | response = self.__service_messages.get()
148 | if response.response != 202:
149 | raise RuntimeError(f'Get contacts: expected 202, '
150 | f'received: {response.response}, error: {response.datadict["error"]}')
151 | contacts_server = []
152 | for _ in range(0, response.datadict['quantity']):
153 | contact_message = self.__service_messages.get()
154 |
155 | if contact_message.datadict['action'] != 'contact_list':
156 | raise RuntimeError(f'Get contacts: expected action "contact_list", '
157 | f'received: {contact_message.datadict["action"]}')
158 | if contact_message.datadict['user_id'] not in contacts_server:
159 | contacts_server.append(contact_message.datadict['user_id'])
160 |
161 | self.storage.update_contacts(contacts_server)
162 |
163 | def add_contact_on_server(self, login: str):
164 | if not login:
165 | raise RuntimeError('Login cannot be empty')
166 | request = jim.add_contact_request(login)
167 | self.send_message_to_server(request)
168 | response = self.__service_messages.get()
169 | if response.response != 200:
170 | raise RuntimeError(f'Add contact: expected response 200, '
171 | f'received: {response.response}, error: {response.datadict["error"]}')
172 |
173 | def delete_contact_on_server(self, login: str):
174 | if not login:
175 | raise RuntimeError('Login cannot be empty')
176 | request = jim.delete_contact_request(login)
177 | self.send_message_to_server(request)
178 | response = self.__service_messages.get()
179 | if response.response != 200:
180 | raise RuntimeError(f'Delete contact: expected response 200, '
181 | f'received: {response.response}, error: {response.datadict["error"]}')
182 |
183 | def get_current_contacts(self) -> list:
184 | contacts = self.storage.get_contacts()
185 | return contacts if contacts else []
186 |
187 | def send_message_to_contact(self, login: str, message: str):
188 | if not message:
189 | raise RuntimeError('Message cannot be empty')
190 | request = jim.message_request(self.username, login, message)
191 | self.send_message_to_server(request)
192 | response = self.__service_messages.get()
193 | if response.response != 200:
194 | raise RuntimeError(f'Send message: expected response 200, '
195 | f'received: {response.response}, error: {response.datadict["error"]}')
196 | self.storage.add_message(login, message)
197 |
198 | def get_messages(self, login: str) -> list:
199 | messages = self.storage.get_messages(login)
200 | return [{'text': item[0], 'incoming': bool(item[1])} for item in messages]
201 |
202 |
203 | def check_new_incoming_messages_thread_function(message_queue: Queue):
204 | while True:
205 | if message_queue:
206 | msg = message_queue.get()
207 | formatted_message = f"New message from {msg.datadict['from']}: {msg.datadict['message']}"
208 | print(formatted_message)
209 |
210 |
211 | if __name__ == '__main__':
212 | try:
213 | args = parse_commandline_args(sys.argv[1:])
214 | storage_file = os.path.join(helpers.get_this_script_full_dir(), f'{args.user_name}.sqlite')
215 | client = Client(username=args.user_name, password=args.user_password, storage_file=storage_file)
216 | print(f'Started client with username {client.username}')
217 | print(f'Connecting to server {args.server_ip} on port {args.server_port}...')
218 | client.connect(args.server_ip, args.server_port)
219 | print('Connected, updating contacts...')
220 | client.update_contacts_from_server()
221 | print('Starting incoming message monitor thread...')
222 | incoming_monitor = Thread(target=check_new_incoming_messages_thread_function,
223 | args=(client.user_messages_queue,))
224 | incoming_monitor.daemon = True
225 | incoming_monitor.start()
226 |
227 | # console command loop
228 | supported_commands = ['show_contacts', 'add_contact', 'delete_contact', 'send_message']
229 | main_menu = helpers.Menu(supported_commands)
230 | while True:
231 | user_choice = None
232 | try:
233 | user_choice = int(input(main_menu))
234 | command = main_menu.get_command(user_choice)
235 | if command == 'show_contacts':
236 | client.update_contacts_from_server()
237 | print(client.get_current_contacts())
238 | elif command == 'add_contact':
239 | client.add_contact_on_server(input('Print login of user to add: >'))
240 | elif command == 'delete_contact':
241 | client.delete_contact_on_server(input('Print login of user to delete: >'))
242 | elif command == 'send_message':
243 | current_contacts = client.get_current_contacts()
244 | if not current_contacts:
245 | print('No contacts available')
246 | continue
247 | login_to = input('Print user login: >')
248 | text = input('Print text: >')
249 | client.send_message_to_contact(login_to, text)
250 | except KeyboardInterrupt:
251 | exit(1)
252 | except BaseException as e:
253 | print(f'Error: {str(e)}')
254 | continue
255 | except BaseException as e:
256 | log.critical(str(e))
257 | raise e
258 |
--------------------------------------------------------------------------------
/client/src/client_gui.pyw:
--------------------------------------------------------------------------------
1 | import sys
2 | from PyQt5 import QtWidgets, QtGui
3 | from PyQt5.QtCore import QObject, QThread, pyqtSignal, pyqtSlot
4 | import os
5 | import logging
6 |
7 | import client_pyqt
8 | from client import Client
9 | import helpers
10 | from jim import request_from_bytes
11 | import log_confing
12 |
13 | log = logging.getLogger(helpers.CLIENT_LOGGER_NAME)
14 |
15 | ERROR_FORMAT = 'Error: {}'
16 |
17 |
18 | class ClientMonitor(QObject):
19 | gotUserMessage = pyqtSignal(bytes)
20 |
21 | def __init__(self, parent):
22 | super().__init__()
23 | self.parent = parent
24 | self._user_messages_queue = None
25 |
26 | def set_queue(self, queue):
27 | self._user_messages_queue = queue
28 |
29 | def check_new_messages(self):
30 | while True:
31 | if self._user_messages_queue:
32 | msg = self._user_messages_queue.get()
33 | self.gotUserMessage.emit(msg.to_bytes())
34 |
35 |
36 | class MainWindow(QtWidgets.QMainWindow):
37 | def __init__(self, parent=None):
38 | QtWidgets.QWidget.__init__(self, parent)
39 | self.ui = client_pyqt.Ui_MainWindow()
40 | self.ui.setupUi(self)
41 | self.ui.label_username_val.setText('')
42 | self.ui.label_server_ip_val.setText('')
43 | self.ui.label_server_port_val.setText('')
44 | self.client = None
45 | self.username = None
46 | self.password = None
47 | self.server_ip = None
48 | self.server_port = None
49 |
50 | # connect slots
51 | self.ui.pushButton_connect.clicked.connect(self.connect_click)
52 | self.ui.pushButton_disconnect.clicked.connect(self.disconnect_click)
53 | self.ui.pushButton_add_contact.clicked.connect(self.add_contact_click)
54 | self.ui.pushButton_delete_contact.clicked.connect(self.delete_contact_click)
55 | self.ui.pushButton_send.clicked.connect(self.send_message_click)
56 | self.ui.listWidget_contacts.itemClicked.connect(self.contact_clicked)
57 |
58 | # create monitor and thread
59 | self.monitor = ClientMonitor(self)
60 | self.thread = QThread()
61 | self.monitor.moveToThread(self.thread)
62 | self.monitor.gotUserMessage.connect(self.new_message_received)
63 | self.thread.started.connect(self.monitor.check_new_messages)
64 |
65 | @pyqtSlot(bytes)
66 | def new_message_received(self, msg_bytes):
67 | msg = request_from_bytes(msg_bytes)
68 | login = msg.datadict['from']
69 | text = msg.datadict['message']
70 | if not self.client.storage.get_contact_id(login):
71 | self.client.add_contact_on_server(login)
72 | self.client.update_contacts_from_server()
73 | self.update_contacts_widget()
74 | self.client.storage.add_message(login, text, True)
75 | if login == self.get_current_contact():
76 | self.update_messages_widget(login)
77 |
78 | def print_info(self, info: str):
79 | current_text = self.ui.textBrowser_service_info.toPlainText()
80 | new_text = info if not current_text else f'{current_text}\n{info}'
81 | self.ui.textBrowser_service_info.setText(new_text)
82 | self.ui.textBrowser_service_info.moveCursor(QtGui.QTextCursor.End)
83 |
84 | def clear_state(self):
85 | self.monitor.set_queue(None)
86 | self.client.close_client()
87 | self.client = None
88 | self.username = None
89 | self.password = None
90 | self.server_ip = None
91 | self.server_port = None
92 |
93 | def connect_click(self):
94 | # check already connected
95 | if self.client:
96 | try:
97 | self.client.check_connection()
98 | self.print_info('Already connected')
99 | return
100 | except BaseException as e: # connection lost, need to make new one
101 | self.print_info(ERROR_FORMAT.format(str(e)))
102 |
103 | # read input values
104 | username = self.ui.lineEdit_username.text()
105 | password = self.ui.lineEdit_password.text()
106 | server_ip = self.ui.lineEdit_server_ip.text()
107 | server_port_str = self.ui.lineEdit_server_port.text()
108 | if not username or not server_ip or not server_port_str:
109 | self.print_info('Error: user name, server ip and server port cannot be empty')
110 | return
111 |
112 | # create client and connect to server, update contacts, start monitor
113 | try:
114 | server_port = int(server_port_str)
115 | self.username = username
116 | self.password = password
117 | storage_file = os.path.join(helpers.get_this_script_full_dir(), f'{self.username}.sqlite')
118 | self.server_ip = server_ip
119 | self.server_port = server_port
120 | self.client = Client(username=self.username, password=self.password, storage_file=storage_file)
121 | self.print_info(f'Connecting to server {self.server_ip} on port {str(self.server_port)}...')
122 | self.client.connect(self.server_ip, self.server_port)
123 | self.print_info('Connected')
124 | self.ui.label_username_val.setText(self.username)
125 | self.ui.label_server_ip_val.setText(self.server_ip)
126 | self.ui.label_server_port_val.setText(str(self.server_port))
127 | self.client.update_contacts_from_server()
128 | self.update_contacts_widget()
129 | self.monitor.set_queue(self.client.user_messages_queue)
130 | self.thread.start()
131 | except BaseException as e:
132 | self.print_info(ERROR_FORMAT.format(str(e)))
133 | self.clear_state()
134 |
135 | def clear_parameters_widgets(self):
136 | self.ui.label_username_val.clear()
137 | self.ui.label_server_ip_val.clear()
138 | self.ui.label_server_port_val.clear()
139 |
140 | def disconnect_click(self):
141 | if not self.client:
142 | self.print_info('Not connected')
143 | return
144 | self.print_info('Disconnecting')
145 | self.clear_state()
146 | self.clear_parameters_widgets()
147 | self.clear_messages_widget()
148 | self.clear_contacts_widget()
149 |
150 | def clear_contacts_widget(self):
151 | self.ui.listWidget_contacts.clear()
152 |
153 | def update_contacts_widget(self):
154 | contacts = self.client.get_current_contacts()
155 | self.clear_contacts_widget()
156 | for contact in contacts:
157 | self.ui.listWidget_contacts.addItem(QtWidgets.QListWidgetItem(contact))
158 |
159 | def add_contact_click(self):
160 | try:
161 | login = self.ui.lineEdit_add_contact.text()
162 | self.client.add_contact_on_server(login)
163 | self.client.update_contacts_from_server()
164 | self.update_contacts_widget()
165 | except BaseException as e:
166 | self.print_info(ERROR_FORMAT.format(str(e)))
167 |
168 | def delete_contact_click(self):
169 | try:
170 | login = self.ui.listWidget_contacts.selectedItems()[0].text()
171 | self.client.delete_contact_on_server(login)
172 | self.client.update_contacts_from_server()
173 | self.update_contacts_widget()
174 | self.clear_messages_widget()
175 | except BaseException as e:
176 | self.print_info(ERROR_FORMAT.format(str(e)))
177 |
178 | def send_message_click(self):
179 | try:
180 | selected_contacts = self.ui.listWidget_contacts.selectedItems()
181 | if not selected_contacts:
182 | self.print_info('Contact not selected')
183 | return
184 | login = selected_contacts[0].text()
185 | text = self.ui.textEdit_input.toPlainText()
186 | if not text:
187 | self.print_info('Message text cannot be empty')
188 | return
189 | self.client.send_message_to_contact(login, text)
190 | self.update_messages_widget(login)
191 | self.ui.textEdit_input.clear()
192 | except BaseException as e:
193 | self.print_info(ERROR_FORMAT.format(str(e)))
194 |
195 | def format_message(self, login: str, message: dict) -> str:
196 | """Format message dict returned by Client.get_messages()"""
197 | login_from = login if message['incoming'] else self.username
198 | login_to = self.username if message['incoming'] else login
199 | return f'{login_from} -> {login_to}:\n{message["text"]}'
200 |
201 | def update_messages_widget(self, login: str):
202 | current_messages = self.client.get_messages(login)
203 | messages_widget_text = ''
204 | for message in current_messages:
205 | msg_formatted = self.format_message(login, message)
206 | messages_widget_text = msg_formatted if not messages_widget_text else \
207 | f'{messages_widget_text}\n{msg_formatted}'
208 | self.ui.textBrowser_messages.setText(messages_widget_text)
209 | self.ui.textBrowser_messages.moveCursor(QtGui.QTextCursor.End)
210 |
211 | def contact_clicked(self):
212 | login = self.get_current_contact()
213 | self.update_messages_widget(login)
214 |
215 | def get_current_contact(self):
216 | selected_items = self.ui.listWidget_contacts.selectedItems()
217 | return self.ui.listWidget_contacts.selectedItems()[0].text() if selected_items else None
218 |
219 | def clear_messages_widget(self):
220 | self.ui.textBrowser_messages.clear()
221 |
222 |
223 | if __name__ == '__main__':
224 | app = QtWidgets.QApplication(sys.argv)
225 | window = MainWindow()
226 | window.show()
227 | sys.exit(app.exec_())
228 |
--------------------------------------------------------------------------------
/client/src/client_gui.ui:
--------------------------------------------------------------------------------
1 |
2 |
3 | MainWindow
4 |
5 |
6 | true
7 |
8 |
9 |
10 | 0
11 | 0
12 | 662
13 | 711
14 |
15 |
16 |
17 | Messenger
18 |
19 |
20 |
21 |
22 |
23 | 30
24 | 10
25 | 601
26 | 71
27 |
28 |
29 |
30 | Parameters
31 |
32 |
33 |
34 |
35 | 20
36 | 20
37 | 61
38 | 16
39 |
40 |
41 |
42 | User name:
43 |
44 |
45 |
46 |
47 |
48 | 260
49 | 20
50 | 61
51 | 16
52 |
53 |
54 |
55 | Server IP:
56 |
57 |
58 |
59 |
60 |
61 | 520
62 | 20
63 | 61
64 | 16
65 |
66 |
67 |
68 | Server port:
69 |
70 |
71 |
72 |
73 |
74 | 20
75 | 40
76 | 121
77 | 16
78 |
79 |
80 |
81 | TestUser
82 |
83 |
84 |
85 |
86 |
87 | 260
88 | 40
89 | 121
90 | 16
91 |
92 |
93 |
94 | 127.0.0.1
95 |
96 |
97 |
98 |
99 |
100 | 520
101 | 40
102 | 51
103 | 16
104 |
105 |
106 |
107 | 65789
108 |
109 |
110 |
111 |
112 |
113 |
114 | 30
115 | 240
116 | 201
117 | 51
118 |
119 |
120 |
121 | Add contact
122 |
123 |
124 |
125 |
126 | 10
127 | 20
128 | 131
129 | 21
130 |
131 |
132 |
133 |
134 |
135 |
136 | 150
137 | 20
138 | 41
139 | 21
140 |
141 |
142 |
143 | Add
144 |
145 |
146 |
147 |
148 |
149 |
150 | 30
151 | 300
152 | 201
153 | 371
154 |
155 |
156 |
157 | Contacts
158 |
159 |
160 |
161 |
162 | 10
163 | 340
164 | 121
165 | 21
166 |
167 |
168 |
169 | Delete selected contact
170 |
171 |
172 |
173 |
174 |
175 | 10
176 | 20
177 | 181
178 | 311
179 |
180 |
181 |
182 |
183 |
184 |
185 |
186 | 250
187 | 420
188 | 381
189 | 111
190 |
191 |
192 |
193 | Input
194 |
195 |
196 |
197 |
198 | 10
199 | 20
200 | 301
201 | 81
202 |
203 |
204 |
205 | Type your message here
206 |
207 |
208 |
209 |
210 |
211 | 320
212 | 20
213 | 51
214 | 23
215 |
216 |
217 |
218 | Send
219 |
220 |
221 |
222 |
223 |
224 |
225 | 250
226 | 90
227 | 381
228 | 321
229 |
230 |
231 |
232 | Messages
233 |
234 |
235 |
236 |
237 | 10
238 | 20
239 | 361
240 | 291
241 |
242 |
243 |
244 |
245 |
246 |
247 |
248 | 250
249 | 540
250 | 381
251 | 131
252 |
253 |
254 |
255 | Service info
256 |
257 |
258 |
259 | true
260 |
261 |
262 |
263 | 10
264 | 20
265 | 361
266 | 101
267 |
268 |
269 |
270 |
271 |
272 |
273 |
274 | 30
275 | 90
276 | 201
277 | 141
278 |
279 |
280 |
281 | Connection
282 |
283 |
284 |
285 |
286 | 10
287 | 80
288 | 111
289 | 20
290 |
291 |
292 |
293 | 127.0.0.1
294 |
295 |
296 | Server IP
297 |
298 |
299 |
300 |
301 |
302 | 10
303 | 110
304 | 111
305 | 20
306 |
307 |
308 |
309 | 7777
310 |
311 |
312 | Server port
313 |
314 |
315 |
316 |
317 |
318 | 130
319 | 80
320 | 61
321 | 21
322 |
323 |
324 |
325 | Connect
326 |
327 |
328 |
329 |
330 |
331 | 10
332 | 20
333 | 181
334 | 20
335 |
336 |
337 |
338 | TestUser
339 |
340 |
341 | User name
342 |
343 |
344 |
345 |
346 | true
347 |
348 |
349 |
350 | 10
351 | 50
352 | 181
353 | 20
354 |
355 |
356 |
357 | TestPassword
358 |
359 |
360 | Password
361 |
362 |
363 |
364 |
365 |
366 | 130
367 | 110
368 | 61
369 | 21
370 |
371 |
372 |
373 | Disconnect
374 |
375 |
376 |
377 |
378 |
388 |
389 |
390 |
391 |
392 |
393 |
--------------------------------------------------------------------------------
/client/src/client_pyqt.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | # Form implementation generated from reading ui file 'client_gui.ui'
4 | #
5 | # Created by: PyQt5 UI code generator 5.10.1
6 | #
7 | # WARNING! All changes made in this file will be lost!
8 |
9 | from PyQt5 import QtCore, QtGui, QtWidgets
10 |
11 | class Ui_MainWindow(object):
12 | def setupUi(self, MainWindow):
13 | MainWindow.setObjectName("MainWindow")
14 | MainWindow.setEnabled(True)
15 | MainWindow.resize(662, 711)
16 | self.centralwidget = QtWidgets.QWidget(MainWindow)
17 | self.centralwidget.setObjectName("centralwidget")
18 | self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
19 | self.groupBox.setGeometry(QtCore.QRect(30, 10, 601, 71))
20 | self.groupBox.setObjectName("groupBox")
21 | self.label_username_key = QtWidgets.QLabel(self.groupBox)
22 | self.label_username_key.setGeometry(QtCore.QRect(20, 20, 61, 16))
23 | self.label_username_key.setObjectName("label_username_key")
24 | self.label_server_ip_key = QtWidgets.QLabel(self.groupBox)
25 | self.label_server_ip_key.setGeometry(QtCore.QRect(260, 20, 61, 16))
26 | self.label_server_ip_key.setObjectName("label_server_ip_key")
27 | self.label_server_port_key = QtWidgets.QLabel(self.groupBox)
28 | self.label_server_port_key.setGeometry(QtCore.QRect(520, 20, 61, 16))
29 | self.label_server_port_key.setObjectName("label_server_port_key")
30 | self.label_username_val = QtWidgets.QLabel(self.groupBox)
31 | self.label_username_val.setGeometry(QtCore.QRect(20, 40, 121, 16))
32 | self.label_username_val.setObjectName("label_username_val")
33 | self.label_server_ip_val = QtWidgets.QLabel(self.groupBox)
34 | self.label_server_ip_val.setGeometry(QtCore.QRect(260, 40, 121, 16))
35 | self.label_server_ip_val.setObjectName("label_server_ip_val")
36 | self.label_server_port_val = QtWidgets.QLabel(self.groupBox)
37 | self.label_server_port_val.setGeometry(QtCore.QRect(520, 40, 51, 16))
38 | self.label_server_port_val.setObjectName("label_server_port_val")
39 | self.groupBox_2 = QtWidgets.QGroupBox(self.centralwidget)
40 | self.groupBox_2.setGeometry(QtCore.QRect(30, 240, 201, 51))
41 | self.groupBox_2.setObjectName("groupBox_2")
42 | self.lineEdit_add_contact = QtWidgets.QLineEdit(self.groupBox_2)
43 | self.lineEdit_add_contact.setGeometry(QtCore.QRect(10, 20, 131, 21))
44 | self.lineEdit_add_contact.setObjectName("lineEdit_add_contact")
45 | self.pushButton_add_contact = QtWidgets.QPushButton(self.groupBox_2)
46 | self.pushButton_add_contact.setGeometry(QtCore.QRect(150, 20, 41, 21))
47 | self.pushButton_add_contact.setObjectName("pushButton_add_contact")
48 | self.groupBox_3 = QtWidgets.QGroupBox(self.centralwidget)
49 | self.groupBox_3.setGeometry(QtCore.QRect(30, 300, 201, 371))
50 | self.groupBox_3.setObjectName("groupBox_3")
51 | self.pushButton_delete_contact = QtWidgets.QPushButton(self.groupBox_3)
52 | self.pushButton_delete_contact.setGeometry(QtCore.QRect(10, 340, 121, 21))
53 | self.pushButton_delete_contact.setObjectName("pushButton_delete_contact")
54 | self.listWidget_contacts = QtWidgets.QListWidget(self.groupBox_3)
55 | self.listWidget_contacts.setGeometry(QtCore.QRect(10, 20, 181, 311))
56 | self.listWidget_contacts.setObjectName("listWidget_contacts")
57 | self.groupBox_4 = QtWidgets.QGroupBox(self.centralwidget)
58 | self.groupBox_4.setGeometry(QtCore.QRect(250, 420, 381, 111))
59 | self.groupBox_4.setObjectName("groupBox_4")
60 | self.textEdit_input = QtWidgets.QTextEdit(self.groupBox_4)
61 | self.textEdit_input.setGeometry(QtCore.QRect(10, 20, 301, 81))
62 | self.textEdit_input.setObjectName("textEdit_input")
63 | self.pushButton_send = QtWidgets.QPushButton(self.groupBox_4)
64 | self.pushButton_send.setGeometry(QtCore.QRect(320, 20, 51, 23))
65 | self.pushButton_send.setObjectName("pushButton_send")
66 | self.groupBox_5 = QtWidgets.QGroupBox(self.centralwidget)
67 | self.groupBox_5.setGeometry(QtCore.QRect(250, 90, 381, 321))
68 | self.groupBox_5.setObjectName("groupBox_5")
69 | self.textBrowser_messages = QtWidgets.QTextBrowser(self.groupBox_5)
70 | self.textBrowser_messages.setGeometry(QtCore.QRect(10, 20, 361, 291))
71 | self.textBrowser_messages.setObjectName("textBrowser_messages")
72 | self.groupBox_6 = QtWidgets.QGroupBox(self.centralwidget)
73 | self.groupBox_6.setGeometry(QtCore.QRect(250, 540, 381, 131))
74 | self.groupBox_6.setObjectName("groupBox_6")
75 | self.textBrowser_service_info = QtWidgets.QTextBrowser(self.groupBox_6)
76 | self.textBrowser_service_info.setEnabled(True)
77 | self.textBrowser_service_info.setGeometry(QtCore.QRect(10, 20, 361, 101))
78 | self.textBrowser_service_info.setObjectName("textBrowser_service_info")
79 | self.groupBox_7 = QtWidgets.QGroupBox(self.centralwidget)
80 | self.groupBox_7.setGeometry(QtCore.QRect(30, 90, 201, 141))
81 | self.groupBox_7.setObjectName("groupBox_7")
82 | self.lineEdit_server_ip = QtWidgets.QLineEdit(self.groupBox_7)
83 | self.lineEdit_server_ip.setGeometry(QtCore.QRect(10, 80, 111, 20))
84 | self.lineEdit_server_ip.setObjectName("lineEdit_server_ip")
85 | self.lineEdit_server_port = QtWidgets.QLineEdit(self.groupBox_7)
86 | self.lineEdit_server_port.setGeometry(QtCore.QRect(10, 110, 111, 20))
87 | self.lineEdit_server_port.setObjectName("lineEdit_server_port")
88 | self.pushButton_connect = QtWidgets.QPushButton(self.groupBox_7)
89 | self.pushButton_connect.setGeometry(QtCore.QRect(130, 80, 61, 21))
90 | self.pushButton_connect.setObjectName("pushButton_connect")
91 | self.lineEdit_username = QtWidgets.QLineEdit(self.groupBox_7)
92 | self.lineEdit_username.setGeometry(QtCore.QRect(10, 20, 181, 20))
93 | self.lineEdit_username.setObjectName("lineEdit_username")
94 | self.lineEdit_password = QtWidgets.QLineEdit(self.groupBox_7)
95 | self.lineEdit_password.setEnabled(True)
96 | self.lineEdit_password.setGeometry(QtCore.QRect(10, 50, 181, 20))
97 | self.lineEdit_password.setObjectName("lineEdit_password")
98 | self.pushButton_disconnect = QtWidgets.QPushButton(self.groupBox_7)
99 | self.pushButton_disconnect.setGeometry(QtCore.QRect(130, 110, 61, 21))
100 | self.pushButton_disconnect.setObjectName("pushButton_disconnect")
101 | MainWindow.setCentralWidget(self.centralwidget)
102 | self.menubar = QtWidgets.QMenuBar(MainWindow)
103 | self.menubar.setGeometry(QtCore.QRect(0, 0, 662, 21))
104 | self.menubar.setObjectName("menubar")
105 | MainWindow.setMenuBar(self.menubar)
106 | self.statusbar = QtWidgets.QStatusBar(MainWindow)
107 | self.statusbar.setObjectName("statusbar")
108 | MainWindow.setStatusBar(self.statusbar)
109 |
110 | self.retranslateUi(MainWindow)
111 | QtCore.QMetaObject.connectSlotsByName(MainWindow)
112 |
113 | def retranslateUi(self, MainWindow):
114 | _translate = QtCore.QCoreApplication.translate
115 | MainWindow.setWindowTitle(_translate("MainWindow", "Messenger"))
116 | self.groupBox.setTitle(_translate("MainWindow", "Parameters"))
117 | self.label_username_key.setText(_translate("MainWindow", "User name:"))
118 | self.label_server_ip_key.setText(_translate("MainWindow", "Server IP:"))
119 | self.label_server_port_key.setText(_translate("MainWindow", "Server port:"))
120 | self.label_username_val.setText(_translate("MainWindow", "TestUser"))
121 | self.label_server_ip_val.setText(_translate("MainWindow", "127.0.0.1"))
122 | self.label_server_port_val.setText(_translate("MainWindow", "65789"))
123 | self.groupBox_2.setTitle(_translate("MainWindow", "Add contact"))
124 | self.pushButton_add_contact.setText(_translate("MainWindow", "Add"))
125 | self.groupBox_3.setTitle(_translate("MainWindow", "Contacts"))
126 | self.pushButton_delete_contact.setText(_translate("MainWindow", "Delete selected contact"))
127 | self.groupBox_4.setTitle(_translate("MainWindow", "Input"))
128 | self.textEdit_input.setPlaceholderText(_translate("MainWindow", "Type your message here"))
129 | self.pushButton_send.setText(_translate("MainWindow", "Send"))
130 | self.groupBox_5.setTitle(_translate("MainWindow", "Messages"))
131 | self.groupBox_6.setTitle(_translate("MainWindow", "Service info"))
132 | self.groupBox_7.setTitle(_translate("MainWindow", "Connection"))
133 | self.lineEdit_server_ip.setText(_translate("MainWindow", "127.0.0.1"))
134 | self.lineEdit_server_ip.setPlaceholderText(_translate("MainWindow", "Server IP"))
135 | self.lineEdit_server_port.setText(_translate("MainWindow", "7777"))
136 | self.lineEdit_server_port.setPlaceholderText(_translate("MainWindow", "Server port"))
137 | self.pushButton_connect.setText(_translate("MainWindow", "Connect"))
138 | self.lineEdit_username.setText(_translate("MainWindow", "TestUser"))
139 | self.lineEdit_username.setPlaceholderText(_translate("MainWindow", "User name"))
140 | self.lineEdit_password.setText(_translate("MainWindow", "TestPassword"))
141 | self.lineEdit_password.setPlaceholderText(_translate("MainWindow", "Password"))
142 | self.pushButton_disconnect.setText(_translate("MainWindow", "Disconnect"))
143 |
144 |
--------------------------------------------------------------------------------
/client/src/helpers.py:
--------------------------------------------------------------------------------
1 | import os
2 | from functools import wraps
3 | import inspect
4 | import binascii
5 |
6 | DEFAULT_SERVER_PORT = 7777
7 | TCP_MSG_BUFFER_SIZE = 1024
8 | DEFAULT_SERVER_IP = '127.0.0.1'
9 | SERVER_SOCKET_TIMEOUT = 0.2
10 | CLIENTS_COUNT_LIMIT = 100
11 | APP_NAME = 'messenger'
12 | SERVER_LOGGER_NAME = f'{APP_NAME}.server'
13 | CLIENT_LOGGER_NAME = f'{APP_NAME}.client'
14 | DEFAULT_CLIENT_LOGIN = 'TestUser'
15 | DEFAULT_CLIENT_PASSWORD = 'TestPassword'
16 |
17 |
18 | def get_this_script_full_dir():
19 | return os.path.dirname(os.path.realpath(__file__))
20 |
21 |
22 | # decorator for function call logging
23 | def log_func_call(logger):
24 | def log_func_call_decorator(func):
25 | @wraps(func)
26 | def log_func_call_decorated(*args, **kwargs):
27 | ret = func(*args, **kwargs)
28 | logger.info(f'Called function {func.__name__} with parameters: {args} {kwargs}, returned: {ret}, '
29 | f'caller name: {str(inspect.stack()[1][3])}')
30 | return ret
31 | return log_func_call_decorated
32 | return log_func_call_decorator
33 |
34 |
35 | class Menu:
36 | def __init__(self, commands: list):
37 | self._commands = {i + 1: item for i, item in enumerate(commands)}
38 |
39 | def get_command(self, command_index):
40 | return self._commands[command_index]
41 |
42 | def __str__(self):
43 | result = '\nChoose command:\n'
44 | for key, val in self._commands.items():
45 | result += f'{key}. {val}\n'
46 | result += '>'
47 | return result
48 |
49 |
50 | def bytes_to_hexstring(data: bytes) -> str:
51 | return binascii.hexlify(data).decode('utf-8')
52 |
53 |
54 | def hexstring_to_bytes(hexstring: str) -> bytes:
55 | return binascii.unhexlify(hexstring)
56 |
--------------------------------------------------------------------------------
/client/src/jim.py:
--------------------------------------------------------------------------------
1 | import json
2 | import time
3 |
4 |
5 | class JimMessage:
6 | def __init__(self):
7 | self._datadict = {}
8 |
9 | def set_field(self, key, val):
10 | self._datadict[key] = val
11 |
12 | def set_time(self):
13 | self.set_field('time', str(int(time.time())))
14 |
15 | @property
16 | def datadict(self):
17 | return self._datadict
18 |
19 | def to_bytes(self):
20 | self_json = json.dumps(self._datadict)
21 | return self_json.encode('utf-8')
22 |
23 | def from_bytes(self, bytedata):
24 | json_data = bytedata.decode('utf-8')
25 | self._datadict = json.loads(json_data)
26 |
27 | def __str__(self):
28 | return json.dumps(self._datadict, indent=1)
29 |
30 | def __eq__(self, other):
31 | return self._datadict == other.datadict
32 |
33 |
34 | class JimRequest(JimMessage):
35 | def __init__(self, action=None):
36 | super().__init__()
37 | self._action = None
38 | if action is not None:
39 | self.action = action
40 |
41 | @property
42 | def action(self):
43 | return self._action
44 |
45 | @action.setter
46 | def action(self, value: str):
47 | self._action = value
48 | self.set_field('action', self._action)
49 |
50 | def from_bytes(self, bytedata):
51 | super().from_bytes(bytedata)
52 | if 'action' in self._datadict:
53 | self._action = self._datadict['action']
54 |
55 |
56 | def request_from_bytes(bytedata: bytes) -> JimRequest:
57 | ret = JimRequest()
58 | ret.from_bytes(bytedata)
59 | return ret
60 |
61 |
62 | class JimResponse(JimMessage):
63 | def __init__(self, response_code=None):
64 | super().__init__()
65 | self._response = None
66 | if response_code is not None:
67 | self.response = response_code
68 |
69 | @property
70 | def response(self):
71 | return self._response
72 |
73 | @response.setter
74 | def response(self, value: int):
75 | self._response = value
76 | self.set_field('response', self._response)
77 |
78 | def from_bytes(self, bytedata):
79 | super().from_bytes(bytedata)
80 | if 'response' in self._datadict:
81 | self._response = self._datadict['response']
82 |
83 |
84 | def response_from_bytes(bytedata: bytes) -> JimResponse:
85 | ret = JimResponse()
86 | ret.from_bytes(bytedata)
87 | return ret
88 |
89 |
90 | def presence_request(username: str) -> JimRequest:
91 | message = JimRequest()
92 | message.set_field('action', 'presence')
93 | message.set_time()
94 | message.set_field('user', {'account_name': username})
95 | return message
96 |
97 |
98 | def get_contacts_request() -> JimRequest:
99 | message = JimRequest()
100 | message.set_field('action', 'get_contacts')
101 | message.set_time()
102 | return message
103 |
104 |
105 | def add_contact_request(login: str) -> JimRequest:
106 | message = JimRequest()
107 | message.set_field('action', 'add_contact')
108 | message.set_field('user_id', login)
109 | message.set_time()
110 | return message
111 |
112 |
113 | def delete_contact_request(login: str) -> JimRequest:
114 | message = JimRequest()
115 | message.set_field('action', 'del_contact')
116 | message.set_field('user_id', login)
117 | message.set_time()
118 | return message
119 |
120 |
121 | def message_request(login_from: str, login_to: str, text: str) -> JimRequest:
122 | message = JimRequest()
123 | message.set_field('action', 'msg')
124 | message.set_time()
125 | message.set_field('to', login_to)
126 | message.set_field('from', login_from)
127 | message.set_field('encoding', 'utf-8')
128 | message.set_field('message', text)
129 | return message
130 |
131 |
132 | def auth_server_message(auth_token: str) -> JimResponse:
133 | message = JimResponse(401)
134 | message.set_field('error', 'Authentication required')
135 | message.set_field('token', auth_token)
136 | return message
137 |
138 |
139 | def auth_client_message(login: str, auth_digest: str) -> JimRequest:
140 | message = JimRequest()
141 | message.set_field('action', 'authenticate')
142 | message.set_time()
143 | user_data = {'account_name': login, 'password': auth_digest}
144 | message.set_field('user', user_data)
145 | return message
146 |
--------------------------------------------------------------------------------
/client/src/log_confing.py:
--------------------------------------------------------------------------------
1 | import logging.handlers
2 | import os
3 |
4 | import helpers
5 |
6 | log_format = logging.Formatter('%(asctime)-s %(levelname)-s %(module)-s %(funcName)-s %(message)s')
7 |
8 | # logger for server
9 | server_logger_name = helpers.SERVER_LOGGER_NAME
10 | server_log_file = os.path.join(helpers.get_this_script_full_dir(), f'{server_logger_name}.log')
11 | server_log_handler = logging.handlers.TimedRotatingFileHandler(filename=server_log_file, when='D', interval=1, delay=True)
12 | server_log_handler.setFormatter(log_format)
13 | server_logger = logging.getLogger(server_logger_name)
14 | server_logger.setLevel(logging.INFO)
15 | server_logger.addHandler(server_log_handler)
16 |
17 | # logger for client
18 | client_logger_name = helpers.CLIENT_LOGGER_NAME
19 | client_log_file = os.path.join(helpers.get_this_script_full_dir(), f'{client_logger_name}.log')
20 | client_log_handler = logging.FileHandler(filename=client_log_file, delay=True)
21 | client_log_handler.setFormatter(log_format)
22 | client_logger = logging.getLogger(client_logger_name)
23 | client_logger.setLevel(logging.DEBUG)
24 | client_logger.addHandler(client_log_handler)
25 |
--------------------------------------------------------------------------------
/client/src/security.py:
--------------------------------------------------------------------------------
1 | import hashlib
2 | from os import urandom
3 | import hmac
4 |
5 | from helpers import bytes_to_hexstring, hexstring_to_bytes
6 |
7 | HASH_ALGORITHM = 'sha256'
8 | HASH_SALT = b'\xca\xfe\xbe\xef\xca\xfe\xbe\xef\xca\xfe\xbe\xef\xca\xfe\xbe\xef\xca\xfe\xbe\xef\xca\xfe\xbe\xef'
9 | HASH_ITERATIONS = 100000
10 | AUTH_TOKEN_LEN = 16
11 |
12 |
13 | def create_password_hash(password: str) -> str:
14 | if not password:
15 | raise RuntimeError('password value empty or incorrect')
16 | digest = hashlib.pbkdf2_hmac(HASH_ALGORITHM, password.encode('utf-8'), HASH_SALT, HASH_ITERATIONS)
17 | return bytes_to_hexstring(digest)
18 |
19 |
20 | def create_auth_token() -> str:
21 | return bytes_to_hexstring(urandom(AUTH_TOKEN_LEN))
22 |
23 |
24 | def create_auth_digest(secret: str, token: str) -> str:
25 | if not secret or not token:
26 | raise RuntimeError('secret or token value empty or incorrect')
27 | digest = hmac.new(hexstring_to_bytes(secret), hexstring_to_bytes(token)).digest()
28 | return bytes_to_hexstring(digest)
29 |
30 |
31 | def check_auth_digest_equal(digest_1: str, digest_2: str) -> bool:
32 | return hmac.compare_digest(digest_1, digest_2)
33 |
--------------------------------------------------------------------------------
/client/src/storage.py:
--------------------------------------------------------------------------------
1 | import sqlite3
2 |
3 |
4 | class DBStorage:
5 | def __init__(self, database):
6 | self._conn = sqlite3.connect(database)
7 | self._cursor = self._conn.cursor()
8 |
9 | def __del__(self):
10 | self._conn.close()
11 |
12 | @property
13 | def conn(self):
14 | return self._conn
15 |
16 | @property
17 | def cursor(self):
18 | return self._cursor
19 |
20 |
21 | class DBStorageServer(DBStorage):
22 | def __init__(self, database):
23 | super().__init__(database)
24 | self._cursor.executescript('''
25 | CREATE TABLE IF NOT EXISTS `Clients`(
26 | `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
27 | `login` TEXT NOT NULL UNIQUE,
28 | `info` TEXT,
29 | `last_connect_time` INTEGER,
30 | `last_connect_ip` TEXT
31 | );
32 | ''')
33 | self._cursor.execute('PRAGMA foreign_keys = ON;')
34 | self._cursor.executescript('''
35 | CREATE TABLE IF NOT EXISTS `ClientContacts` (
36 | `owner_id` INTEGER,
37 | `contact_id` INTEGER,
38 | PRIMARY KEY(`owner_id`,`contact_id`),
39 | FOREIGN KEY(`owner_id`) REFERENCES `Clients`(`id`),
40 | FOREIGN KEY(`contact_id`) REFERENCES `Clients`(`id`)
41 | );
42 | ''')
43 | self._conn.commit()
44 |
45 | def get_client_id(self, login: str):
46 | """ Returns client id by login from Clients table, or None if there is no such client """
47 | self._cursor.execute('SELECT `id` FROM `Clients` WHERE `login` == ?', (login,))
48 | return self._cursor.fetchall()[0][0]
49 |
50 | def get_clients(self):
51 | self._cursor.execute(
52 | '''
53 | SELECT `login`, `last_connect_time`, `last_connect_ip`
54 | FROM `Clients`
55 | ORDER BY `last_connect_time` DESC
56 | '''
57 | )
58 | result = self._cursor.fetchall()
59 | return result if result else []
60 |
61 | def get_client_hash(self, login: str) -> str:
62 | self._cursor.execute('SELECT `info` FROM `Clients` WHERE `login` == ?', (login,))
63 | return self._cursor.fetchall()[0][0]
64 |
65 | def check_client_exists(self, login: str) -> bool:
66 | try:
67 | self.get_client_id(login)
68 | return True
69 | except IndexError:
70 | return False
71 |
72 | def add_client(self, login: str, password_hash: str):
73 | if not login:
74 | raise ValueError('login cannot be None or empty')
75 | if not password_hash:
76 | raise ValueError('password hash cannot be None or empty')
77 | if self.check_client_exists(login) is True:
78 | raise RuntimeError(f'client with this login already exists: {login}')
79 | self._cursor.execute('INSERT INTO `Clients` VALUES (NULL, ?, ?, NULL, NULL)', (login, password_hash))
80 | self._conn.commit()
81 |
82 | def update_client(self, login: str, connection_time: float, connection_ip: str):
83 | client_id = self.get_client_id(login)
84 | self._cursor.execute(
85 | """
86 | UPDATE `Clients` SET
87 | `last_connect_time` = ?,
88 | `last_connect_ip` = ?
89 | WHERE `id` == ?;
90 | """, (connection_time, connection_ip, client_id)
91 | )
92 | self._conn.commit()
93 |
94 | def check_client_in_contacts(self, owner_login: str, client_login: str) -> bool:
95 | owner_id = self.get_client_id(owner_login)
96 | client_id = self.get_client_id(client_login)
97 | self._cursor.execute('SELECT COUNT() FROM `ClientContacts` WHERE `owner_id` == ? AND `contact_id` == ?;',
98 | (owner_id, client_id))
99 | return True if self._cursor.fetchall()[0][0] == 1 else False
100 |
101 | def add_client_to_contacts(self, owner_login: str, client_login: str):
102 | owner_id = self.get_client_id(owner_login)
103 | client_id = self.get_client_id(client_login)
104 | self._cursor.execute('INSERT INTO `ClientContacts` VALUES (?, ?);', (owner_id, client_id))
105 | self._conn.commit()
106 |
107 | def del_client_from_contacts(self, owner_login: str, client_login: str):
108 | owner_id = self.get_client_id(owner_login)
109 | client_id = self.get_client_id(client_login)
110 | self._cursor.execute('DELETE FROM `ClientContacts` WHERE `owner_id` == ? AND `contact_id` == ?',
111 | (owner_id, client_id))
112 | self._conn.commit()
113 |
114 | def get_client_contacts(self, client_login: str) -> list:
115 | client_id = self.get_client_id(client_login)
116 | query = '''select `Clients`.login from `ClientContacts` join `Clients`
117 | where (`ClientContacts`.contact_id == `Clients`.id and `ClientContacts`.owner_id == ?);'''
118 | self._cursor.execute(query, (client_id,))
119 | result = self._cursor.fetchall()
120 | return [item[0] for item in result] if result is not None else []
121 |
122 |
123 | class DBStorageClient(DBStorage):
124 | def __init__(self, database):
125 | # connect to database, create it if not exists,
126 | # create db schema if not exists (tables Contacts, Messages)
127 | super().__init__(database)
128 | self._cursor.executescript('''
129 | CREATE TABLE IF NOT EXISTS `Contacts`(
130 | `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
131 | `login` TEXT NOT NULL UNIQUE
132 | );
133 | ''')
134 | self._cursor.execute('PRAGMA foreign_keys = ON;')
135 | self._cursor.executescript('''
136 | CREATE TABLE IF NOT EXISTS `Messages` (
137 | `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
138 | `contact_id` INTEGER NOT NULL,
139 | `incoming` INTEGER NOT NULL,
140 | `text` TEXT NOT NULL,
141 | FOREIGN KEY(`contact_id`) REFERENCES `Contacts`(`id`) ON DELETE CASCADE
142 | );
143 | ''')
144 | self._conn.commit()
145 |
146 | def add_contact(self, login: str):
147 | self._cursor.execute('INSERT INTO `Contacts` VALUES(NULL, ?)', (login,))
148 | self._conn.commit()
149 |
150 | def get_contact_id(self, login: str):
151 | self._cursor.execute('SELECT `id` FROM `Contacts` WHERE `login` == ?', (login,))
152 | try:
153 | return self._cursor.fetchall()[0][0]
154 | except IndexError:
155 | return None
156 |
157 | def add_message(self, login: str, text: str, incoming: bool=False):
158 | contact_id = self.get_contact_id(login)
159 | self._cursor.execute('INSERT INTO `Messages` VALUES (NULL, ?, ?, ?)', (contact_id, int(incoming), text))
160 | self._conn.commit()
161 |
162 | def get_messages(self, login: str):
163 | contact_id = self.get_contact_id(login)
164 | self.cursor.execute('''
165 | SELECT `text`, `incoming`
166 | FROM `Messages`
167 | WHERE `contact_id` == ?
168 | ORDER BY `id`
169 | ''', (contact_id,))
170 | return self._cursor.fetchall()
171 |
172 | def get_contacts(self) -> list:
173 | self._cursor.execute('SELECT `login` FROM `Contacts`')
174 | return [item[0] for item in self._cursor.fetchall()]
175 |
176 | def delete_contact(self, login: str):
177 | self._cursor.execute('DELETE FROM `Contacts` WHERE `login` == ?', (login,))
178 | self._conn.commit()
179 |
180 | def update_contacts(self, server_contacts: list):
181 | """
182 | If contact in client list, but not in server list - delete from client list
183 | If contact in server list, but not in client list - add to client list
184 | """
185 | client_contacts = self.get_contacts()
186 | for contact in client_contacts:
187 | if contact not in server_contacts:
188 | self.delete_contact(contact)
189 | for contact in server_contacts:
190 | if contact not in client_contacts:
191 | self.add_contact(contact)
192 |
193 |
194 | class FileStorage:
195 | pass
196 |
--------------------------------------------------------------------------------
/client/src/test_client.py:
--------------------------------------------------------------------------------
1 | import pytest
2 |
3 | from client import parse_commandline_args, Client
4 | import helpers
5 | from jim import JimRequest
6 |
7 |
8 | # tests for: parse_commandline_args
9 | test_ip = '1.2.3.4'
10 | test_port = '1234'
11 | test_user = 'TestClientUserName'
12 |
13 |
14 | def test_none_args_set__correct_default_values():
15 | test = parse_commandline_args([])
16 | assert test.server_ip == helpers.DEFAULT_SERVER_IP
17 | assert test.server_port == helpers.DEFAULT_SERVER_PORT
18 | assert test.user_name == helpers.DEFAULT_CLIENT_LOGIN
19 |
20 |
21 | def test_sever_set__correct_server_others_default():
22 | test = parse_commandline_args(['-s', test_ip])
23 | assert test.server_ip == test_ip
24 | assert test.server_port == helpers.DEFAULT_SERVER_PORT
25 | assert test.user_name == helpers.DEFAULT_CLIENT_LOGIN
26 |
27 |
28 | def test_port_set__correct_port_others_default():
29 | test = parse_commandline_args(['-p', test_port])
30 | assert test.server_ip == helpers.DEFAULT_SERVER_IP
31 | assert test.server_port == int(test_port)
32 | assert test.user_name == helpers.DEFAULT_CLIENT_LOGIN
33 |
34 |
35 | def test_user_name_set__correct_value_others_default():
36 | test = parse_commandline_args(['-u', test_user])
37 | assert test.server_ip == helpers.DEFAULT_SERVER_IP
38 | assert test.server_port == helpers.DEFAULT_SERVER_PORT
39 | assert test.user_name == test_user
40 |
41 |
42 | class TestClient:
43 | test_username = helpers.DEFAULT_CLIENT_LOGIN
44 |
45 | @staticmethod
46 | def socket_send_mock(self, data):
47 | return len(data)
48 |
49 | @staticmethod
50 | def socket_recv_mock(self, size):
51 | return b'\xff' * size
52 |
53 | def setup(self):
54 | self.test_client = Client(self.test_username, ':memory:')
55 |
56 | def test__init_and_del__do_not_raise(self):
57 | Client(self.test_username, ':memory:')
58 |
59 | def test__send_data__test_data_not_empty__return_data_len(self, monkeypatch):
60 | test_data = b'test_data'
61 | monkeypatch.setattr('socket.socket.send', self.socket_send_mock)
62 | assert self.test_client.send_data(test_data) == len(test_data)
63 |
64 | def test__send_data__data_empty__return_zero(self, monkeypatch):
65 | monkeypatch.setattr('socket.socket.send', self.socket_send_mock)
66 | assert self.test_client.send_data(b'') == 0
67 |
68 | def test__send_data__data_has_wrong_type__raises_typeerror(self, monkeypatch):
69 | monkeypatch.setattr('socket.socket.send', self.socket_send_mock)
70 | with pytest.raises(Exception):
71 | self.test_client.send_data([1, 2, 3])
72 |
73 | def test__receive_data__size_positive__correct_number_of_bytes_received(self, monkeypatch):
74 | monkeypatch.setattr('socket.socket.recv', self.socket_recv_mock)
75 | test_len = 150
76 | assert len(self.test_client.receive_data(test_len)) == test_len
77 |
78 | def test__receive_data__size_not_positive__raises_valueerror(self, monkeypatch):
79 | monkeypatch.setattr('socket.socket.recv', self.socket_recv_mock)
80 | with pytest.raises(ValueError):
81 | self.test_client.receive_data(0)
82 | with pytest.raises(ValueError):
83 | self.test_client.receive_data(-123)
84 |
85 | def test__send_message_to_server__correct_message__no_errors(self, monkeypatch):
86 | monkeypatch.setattr('socket.socket.send', self.socket_send_mock)
87 | test_message = JimRequest()
88 | test_message.set_field('test_key', 'test_val')
89 | self.test_client.send_message_to_server(test_message)
90 |
91 | def test__send_message_to_server__incorrect_input_type_raises(self):
92 | with pytest.raises(AttributeError):
93 | self.test_client.send_message_to_server([1, 2, 3])
94 |
--------------------------------------------------------------------------------
/client/src/test_jim.py:
--------------------------------------------------------------------------------
1 | import pytest
2 |
3 | from jim import *
4 |
5 |
6 | class TestJimMessage:
7 | test = None
8 |
9 | def setup(self):
10 | self.test = JimMessage()
11 |
12 | def teardown(self):
13 | self.test = None
14 |
15 | def test_init__dictionary_empty(self):
16 | assert len(self.test.datadict) == 0
17 |
18 | def test_setfield__correct_data_added(self):
19 | testkey, testval = 'testkey', 'testval'
20 | self.test.set_field(testkey, testval)
21 | assert self.test.datadict[testkey] == testval
22 |
23 | def test_settime__time_field_added_positive_float(self):
24 | self.test.set_time()
25 | time_value = float(self.test.datadict['time'])
26 | assert time_value > 0
27 |
28 | def test_eq__two_empty_messages_return_true(self):
29 | assert JimMessage() == JimMessage()
30 |
31 | def test_eq__one_empty_other_not_empty_return_false(self):
32 | self.test.set_time()
33 | assert self.test != JimMessage()
34 |
35 | def test_eq__both_not_empty_not_equal_return_false(self):
36 | test1, test2 = JimMessage(), JimMessage()
37 | test1.set_field('key1', 'val1')
38 | test2.set_field('key2', 'val2')
39 | assert test1 != test2
40 |
41 | def test_eq__both_not_empty_equal_return_true(self):
42 | test1, test2 = JimMessage(), JimMessage()
43 | testkey, testval = 'key', 'val'
44 | test1.set_field(testkey, testval)
45 | test2.set_field(testkey, testval)
46 | assert test1 == test2
47 |
48 | def test_tobytes__result_not_empty(self):
49 | assert len(JimMessage().to_bytes()) > 0
50 |
51 | def test_frombytes__tobytes_then_frombytes_result_the_same(self):
52 | self.test.set_time()
53 | test_bytes = self.test.to_bytes()
54 | decoded = JimMessage()
55 | decoded.from_bytes(test_bytes)
56 | assert decoded == self.test
57 |
58 | def test_frombytes__incorrect_binary_data_raises(self):
59 | baddata = b'\xde\xad\xbe\xef'
60 | with pytest.raises(UnicodeDecodeError):
61 | self.test.from_bytes(baddata)
62 |
63 |
64 | # tests for: jim_request_from_bytes
65 | def test__jim_request_from_bytes__incorrect_input__raises():
66 | baddata = b'\xde\xad\xbe\xef'
67 | with pytest.raises(UnicodeDecodeError):
68 | request_from_bytes(baddata)
69 |
70 |
71 | def test__jim_request_from_bytes__correct_input__correct_empty_object_created():
72 | test = request_from_bytes(b'{}')
73 | assert len(test.datadict) == 0
74 |
75 |
76 | def test__jim_request_from_bytes__correct_input__correct_not_empty_object_created():
77 | test = request_from_bytes(b'{"key":"val"}')
78 | assert test.datadict['key'] == 'val'
79 |
80 |
81 | class TestJimResponse:
82 | test_response = 123
83 | test_alert = "Test alert"
84 | test_error = "Test error"
85 |
86 | def test_getters_setters__object_is_correct(self):
87 | test = JimResponse()
88 | test.response = self.test_response
89 | assert test.response == self.test_response
90 | assert test.datadict["response"] == self.test_response
91 |
92 | def test_tobytes_frombytes__result_the_same(self):
93 | test = JimResponse()
94 | test.response = self.test_response
95 | test_bytedata = test.to_bytes()
96 | test_from_bytes = JimResponse()
97 | test_from_bytes.from_bytes(test_bytedata)
98 | assert test == test_from_bytes
99 |
100 |
101 | # tests for: jim_response_from_bytes
102 | def test__jim_response_from_bytes__incorrect_input__raises():
103 | bad_data = b'\xde\xad\xbe\xef'
104 | with pytest.raises(UnicodeDecodeError):
105 | response_from_bytes(bad_data)
106 |
107 |
108 | def test__jim_response_from_bytes__input_is_not_response__result_response_is_none():
109 | test = JimRequest()
110 | test.set_field('test_key_1', 'test_val_1')
111 | test.set_field('test_key_2', 'test_val_2')
112 | byte_data = test.to_bytes()
113 | test_from_bytes = response_from_bytes(byte_data)
114 | assert test_from_bytes.response is None
115 |
116 |
117 | def test__jim_response_from_bytes__response_set__correct_result():
118 | test = JimResponse()
119 | test.response = 321
120 | byte_data = test.to_bytes()
121 | actual = response_from_bytes(byte_data)
122 | assert test == actual
123 |
--------------------------------------------------------------------------------
/client/src/test_security.py:
--------------------------------------------------------------------------------
1 | import pytest
2 |
3 | from security import *
4 |
5 |
6 | # tests for create_password_hash()
7 | def test__correct_input__correct_results():
8 | assert create_password_hash('test') is not None
9 | assert isinstance(create_password_hash('test'), str)
10 | assert create_password_hash('test') == create_password_hash('test')
11 | assert len(create_password_hash('test1')) == len(create_password_hash('test2'))
12 | assert create_password_hash('test1') != create_password_hash('test2')
13 | assert create_password_hash('test') != 'test'
14 |
15 |
16 | def test__empty_or_incorrect_input__raises():
17 | with pytest.raises(RuntimeError):
18 | create_password_hash('')
19 | with pytest.raises(RuntimeError):
20 | create_password_hash(None)
21 | with pytest.raises(AttributeError):
22 | create_password_hash(1)
23 | with pytest.raises(AttributeError):
24 | create_password_hash([1, 2, 3])
25 | with pytest.raises(AttributeError):
26 | create_password_hash({'key': 'value'})
27 | # end tests for create_password_hash()
28 |
29 |
30 | # tests for create_auth_token()
31 | def test__values_are_correct():
32 | assert create_auth_token() is not None
33 | assert isinstance(create_auth_token(), str)
34 | assert len(create_auth_token()) == AUTH_TOKEN_LEN * 2
35 | assert create_auth_token() != create_auth_token()
36 | # end tests for create_auth_token()
37 |
38 |
39 | test_secret = 'cafecafe'
40 | test_token = 'fefefefe'
41 |
42 |
43 | # tests for create_auth_digest()
44 | def test__correct_input__correct_output():
45 | assert create_auth_digest(test_secret, test_token) is not None
46 | assert isinstance(create_auth_digest(test_secret, test_token), str)
47 |
48 |
49 | def test__incorrect_input__raises():
50 | with pytest.raises(BaseException):
51 | create_auth_digest('not_hex_string', test_token)
52 | with pytest.raises(BaseException):
53 | create_auth_digest(test_secret, 'not_hex_string')
54 | with pytest.raises(RuntimeError):
55 | create_auth_digest(None, test_token)
56 | with pytest.raises(RuntimeError):
57 | create_auth_digest(test_secret, None)
58 | with pytest.raises(TypeError):
59 | create_auth_digest(1, test_token)
60 | with pytest.raises(TypeError):
61 | create_auth_digest(test_secret, 2)
62 | with pytest.raises(RuntimeError):
63 | create_auth_digest('', test_token)
64 | with pytest.raises(RuntimeError):
65 | create_auth_digest(test_secret, '')
66 | # end tests for create_auth_digest()
67 |
68 |
69 | test_digest = create_auth_digest(test_secret, test_token)
70 |
71 |
72 | # tests for check_auth_digest_equal()
73 | def test__equal_digests__return_true():
74 | digest2 = create_auth_digest(test_secret, test_token)
75 | assert check_auth_digest_equal(test_digest, digest2) is True
76 | assert check_auth_digest_equal(digest2, test_digest) is True
77 |
78 |
79 | def test__different_digests__return_false():
80 | another_secret = 'aabbccddeeff'
81 | another_token = 'ffeeddccbb'
82 | digest2 = create_auth_digest(another_secret, test_token)
83 | assert check_auth_digest_equal(test_digest, digest2) is False
84 | digest3 = create_auth_digest(test_secret, another_token)
85 | assert check_auth_digest_equal(test_digest, digest3) is False
86 | digest4 = create_auth_digest(another_secret, another_token)
87 | assert check_auth_digest_equal(test_digest, digest4) is False
88 | digest5 = create_auth_digest(test_token, test_secret)
89 | assert check_auth_digest_equal(test_digest, digest5) is False
90 |
91 |
92 | def test__input_empty__raises():
93 | with pytest.raises(TypeError):
94 | check_auth_digest_equal(None, test_digest)
95 | with pytest.raises(TypeError):
96 | check_auth_digest_equal(test_digest, None)
97 | # end tests for check_auth_digest_equal()
98 |
--------------------------------------------------------------------------------
/client/src/test_storage.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | import sqlite3
3 |
4 | from storage import DBStorageServer, DBStorageClient
5 |
6 |
7 | class TestDBStorageServer:
8 | test_db = ':memory:'
9 | test_login = 'TestLogin'
10 | test_time = 123456
11 | test_ip = '1.2.3.4'
12 | test_info = 'test_info'
13 | test_second_login = 'TestLogin2'
14 |
15 | def setup(self):
16 | self.storage = DBStorageServer(self.test_db)
17 | self.conn = self.storage.conn
18 | self.cursor = self.storage.cursor
19 |
20 | def test__init__tables_created(self):
21 | self.cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
22 | table_names = [t[0] for t in self.cursor.fetchall()]
23 | assert 'Clients' in table_names
24 | assert 'ClientContacts' in table_names
25 |
26 | def test__get_client_id__client_exists__return_correct_id(self):
27 | self.cursor.execute(f'INSERT INTO `Clients` VALUES (NULL, ?, NULL, NULL, NULL)', (self.test_login,))
28 | self.conn.commit()
29 | actual = self.storage.get_client_id(self.test_login)
30 | assert actual == 1
31 |
32 | def test__get_client_id__no_such_client__raises(self):
33 | with pytest.raises(IndexError):
34 | self.storage.get_client_id(self.test_login)
35 | # assert self.storage.get_client_id(self.test_login) is None
36 |
37 | def test__get_client_id___input_none_or_empty__return_none(self):
38 | with pytest.raises(IndexError):
39 | self.storage.get_client_id(None)
40 | with pytest.raises(IndexError):
41 | self.storage.get_client_id('')
42 |
43 | def test__get_client_id__input_collection__raises(self):
44 | with pytest.raises(sqlite3.Error):
45 | self.storage.get_client_id([1, 2, 3])
46 | with pytest.raises(sqlite3.Error):
47 | self.storage.get_client_id({})
48 |
49 | def test__add_new_client__correct_input__can_find_client_by_login(self):
50 | self.storage.add_client(self.test_login)
51 | assert self.storage.get_client_id(self.test_login) == 1
52 |
53 | def test__add_new_client__already_exists__raises(self):
54 | with pytest.raises(sqlite3.Error):
55 | self.storage.add_client(self.test_login)
56 | self.storage.add_client(self.test_login)
57 |
58 | def test__add_new_client__login_none_or_empty__raises(self):
59 | with pytest.raises(ValueError):
60 | self.storage.add_client(None)
61 | with pytest.raises(ValueError):
62 | self.storage.add_client('')
63 |
64 | def test__add_new_client__login_not_str__raises(self):
65 | with pytest.raises(sqlite3.Error):
66 | self.storage.add_client([1, 2])
67 | with pytest.raises(ValueError):
68 | self.storage.add_client({})
69 |
70 | def test__update_client__client_exists__correct_parameters_in_table(self):
71 | self.storage.add_client(self.test_login)
72 | client_id = self.storage.get_client_id(self.test_login)
73 |
74 | self.storage.update_client(self.test_login, self.test_time, self.test_ip, self.test_info)
75 | self.cursor.execute('SELECT login, info, last_connect_time, last_connect_ip FROM Clients WHERE id == ?',
76 | (client_id,))
77 | actual_values = self.cursor.fetchall()
78 | assert actual_values[0] == (self.test_login, self.test_info, self.test_time, self.test_ip)
79 |
80 | def test__update_client__info_is_none__correct_parameters_in_table(self):
81 | self.storage.add_client(self.test_login)
82 | client_id = self.storage.get_client_id(self.test_login)
83 |
84 | self.storage.update_client(self.test_login, self.test_time, self.test_ip)
85 |
86 | self.cursor.execute('SELECT login, info, last_connect_time, last_connect_ip FROM Clients WHERE id == ?',
87 | (client_id,))
88 | actual_values = self.cursor.fetchall()
89 | assert actual_values[0] == (self.test_login, None, self.test_time, self.test_ip)
90 |
91 | def test__add_client_to_contacts__client_not_in_contacts__client_added(self):
92 | self.storage.add_client(self.test_login)
93 | self.storage.add_client(self.test_second_login)
94 | first_client_id = self.storage.get_client_id(self.test_login)
95 | second_client_id = self.storage.get_client_id(self.test_second_login)
96 |
97 | self.storage.add_client_to_contacts(self.test_login, self.test_second_login)
98 |
99 | self.cursor.execute('SELECT COUNT() FROM `ClientContacts` WHERE `owner_id` == ? AND `contact_id` == ?;',
100 | (first_client_id, second_client_id))
101 | assert self.cursor.fetchall()[0][0] == 1
102 |
103 | def test__add_client_to_contacts_clients_add_each_other__no_errors(self):
104 | self.storage.add_client(self.test_login)
105 | self.storage.add_client(self.test_second_login)
106 | self.storage.add_client_to_contacts(self.test_login, self.test_second_login)
107 | self.storage.add_client_to_contacts(self.test_second_login, self.test_login)
108 |
109 | def test__add_client_to_contacts__client_already_in_contacts__raises(self):
110 | self.storage.add_client(self.test_login)
111 | self.storage.add_client(self.test_second_login)
112 | self.storage.add_client_to_contacts(self.test_login, self.test_second_login)
113 | with pytest.raises(sqlite3.Error):
114 | self.storage.add_client_to_contacts(self.test_login, self.test_second_login)
115 |
116 | def test__add_client_to_contacts__incorrect_input__raises(self):
117 | with pytest.raises(IndexError):
118 | self.storage.add_client_to_contacts(None, {})
119 | with pytest.raises(sqlite3.InterfaceError):
120 | self.storage.add_client_to_contacts({}, None)
121 |
122 | def test__check_client_in_contacts__client_in_contacts__return_true(self):
123 | self.storage.add_client(self.test_login)
124 | self.storage.add_client(self.test_second_login)
125 | self.storage.add_client_to_contacts(self.test_login, self.test_second_login)
126 | assert self.storage.check_client_in_contacts(self.test_login, self.test_second_login) is True
127 |
128 | def test__check_client_in_contacts__client_not_in_contacts__return_false(self):
129 | self.storage.add_client(self.test_login)
130 | self.storage.add_client(self.test_second_login)
131 | assert self.storage.check_client_in_contacts(self.test_login, self.test_second_login) is False
132 |
133 | def test__check_client_in_contacts__incorrect_input__raises(self):
134 | with pytest.raises(IndexError):
135 | self.storage.check_client_in_contacts('qwerty', 'asdfgh')
136 | with pytest.raises(IndexError):
137 | self.storage.check_client_in_contacts(None, None)
138 |
139 |
140 | class TestDBStorageClient:
141 | test_db = ':memory:'
142 | test_login = 'TestLogin'
143 | test_second_login = 'TestLogin2'
144 | test_message = 'Test message'
145 |
146 | def setup(self):
147 | self.storage = DBStorageClient(self.test_db)
148 | self.conn = self.storage.conn
149 | self.cursor = self.storage.cursor
150 |
151 | def test__init__tables_created(self):
152 | self.cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
153 | table_names = [t[0] for t in self.cursor.fetchall()]
154 | assert 'Contacts' in table_names
155 | assert 'Messages' in table_names
156 |
157 | def test__add_new_contact__not_added_yet__correct_row_added(self):
158 | self.storage.add_contact(self.test_login)
159 | self.cursor.execute('SELECT `login` FROM `Contacts` WHERE `id` == 1')
160 | assert self.cursor.fetchall()[0][0] == self.test_login
161 |
162 | def test__add_new_contact__already_added__raises(self):
163 | self.storage.add_contact(self.test_login)
164 | with pytest.raises(sqlite3.Error):
165 | self.storage.add_contact(self.test_login)
166 |
167 | def test__add_new_contact__input_incorrect__raises(self):
168 | with pytest.raises(sqlite3.Error):
169 | self.storage.add_contact(None)
170 | with pytest.raises(sqlite3.Error):
171 | self.storage.add_contact({})
172 |
173 | def test__get_contact_id__contact_exists__return_correct_value(self):
174 | self.storage.add_contact(self.test_login)
175 | assert self.storage.get_contact_id(self.test_login) == 1
176 |
177 | def test__get_contact_id__no_such_contact__return_none(self):
178 | assert self.storage.get_contact_id(self.test_login) is None
179 |
180 | def test__get_contact_id__input_none__return_none(self):
181 | assert self.storage.get_contact_id(None) is None
182 |
183 | def test__add_new_message__input_ok_incoming__correct_row_added(self):
184 | self.storage.add_contact(self.test_login)
185 | self.storage.add_message(self.test_login, self.test_message, True)
186 | self.cursor.execute('SELECT * FROM `Messages`')
187 | result = self.cursor.fetchall()
188 | assert len(result) == 1
189 | assert result[0] == (1, 1, int(True), self.test_message)
190 |
191 | def test__add_new_message__input_ok_outcoming__correct_row_added(self):
192 | self.storage.add_contact(self.test_login)
193 | self.storage.add_message(self.test_login, self.test_message)
194 | self.cursor.execute('SELECT * FROM `Messages`')
195 | result = self.cursor.fetchall()
196 | assert len(result) == 1
197 | assert result[0] == (1, 1, int(False), self.test_message)
198 |
199 | def test__add_new_message__input_incorrect__raises(self):
200 | with pytest.raises(sqlite3.Error):
201 | self.storage.add_message(None, self.test_message, True)
202 |
203 | self.storage.add_contact(self.test_login)
204 | with pytest.raises(TypeError):
205 | self.storage.add_message(1, self.test_message, None)
206 | with pytest.raises(sqlite3.Error):
207 | self.storage.add_message(1, None, True)
208 | with pytest.raises(sqlite3.Error):
209 | self.storage.add_message(1, None, False)
210 |
--------------------------------------------------------------------------------
/client/src/update_ui.bat:
--------------------------------------------------------------------------------
1 | "c:\Program Files (x86)\Python36-32\Scripts\pyuic5.exe" client_gui.ui -o client_pyqt.py
--------------------------------------------------------------------------------
/conf.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Configuration file for the Sphinx documentation builder.
4 | #
5 | # This file does only contain a selection of the most common options. For a
6 | # full list see the documentation:
7 | # http://www.sphinx-doc.org/en/master/config
8 |
9 | # -- Path setup --------------------------------------------------------------
10 |
11 | # If extensions (or modules to document with autodoc) are in another directory,
12 | # add these directories to sys.path here. If the directory is relative to the
13 | # documentation root, use os.path.abspath to make it absolute, like shown here.
14 | #
15 | # import os
16 | # import sys
17 | # sys.path.insert(0, os.path.abspath('.'))
18 |
19 |
20 | # -- Project information -----------------------------------------------------
21 |
22 | project = 'Messenger'
23 | copyright = '2018, Dmitry_VS'
24 | author = 'Dmitry_VS'
25 |
26 | # The short X.Y version
27 | version = ''
28 | # The full version, including alpha/beta/rc tags
29 | release = ''
30 |
31 |
32 | # -- General configuration ---------------------------------------------------
33 |
34 | # If your documentation needs a minimal Sphinx version, state it here.
35 | #
36 | # needs_sphinx = '1.0'
37 |
38 | # Add any Sphinx extension module names here, as strings. They can be
39 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
40 | # ones.
41 | extensions = [
42 | ]
43 |
44 | # Add any paths that contain templates here, relative to this directory.
45 | templates_path = ['_templates']
46 |
47 | # The suffix(es) of source filenames.
48 | # You can specify multiple suffix as a list of string:
49 | #
50 | # source_suffix = ['.rst', '.md']
51 | source_suffix = '.rst'
52 |
53 | # The master toctree document.
54 | master_doc = 'index'
55 |
56 | # The language for content autogenerated by Sphinx. Refer to documentation
57 | # for a list of supported languages.
58 | #
59 | # This is also used if you do content translation via gettext catalogs.
60 | # Usually you set "language" from the command line for these cases.
61 | language = None
62 |
63 | # List of patterns, relative to source directory, that match files and
64 | # directories to ignore when looking for source files.
65 | # This pattern also affects html_static_path and html_extra_path .
66 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
67 |
68 | # The name of the Pygments (syntax highlighting) style to use.
69 | pygments_style = 'sphinx'
70 |
71 |
72 | # -- Options for HTML output -------------------------------------------------
73 |
74 | # The theme to use for HTML and HTML Help pages. See the documentation for
75 | # a list of builtin themes.
76 | #
77 | html_theme = 'alabaster'
78 |
79 | # Theme options are theme-specific and customize the look and feel of a theme
80 | # further. For a list of options available for each theme, see the
81 | # documentation.
82 | #
83 | # html_theme_options = {}
84 |
85 | # Add any paths that contain custom static files (such as style sheets) here,
86 | # relative to this directory. They are copied after the builtin static files,
87 | # so a file named "default.css" will overwrite the builtin "default.css".
88 | html_static_path = ['_static']
89 |
90 | # Custom sidebar templates, must be a dictionary that maps document names
91 | # to template names.
92 | #
93 | # The default sidebars (for documents that don't match any pattern) are
94 | # defined by theme itself. Builtin themes are using these templates by
95 | # default: ``['localtoc.html', 'relations.html', 'sourcelink.html',
96 | # 'searchbox.html']``.
97 | #
98 | # html_sidebars = {}
99 |
100 |
101 | # -- Options for HTMLHelp output ---------------------------------------------
102 |
103 | # Output file base name for HTML help builder.
104 | htmlhelp_basename = 'Messengerdoc'
105 |
106 |
107 | # -- Options for LaTeX output ------------------------------------------------
108 |
109 | latex_elements = {
110 | # The paper size ('letterpaper' or 'a4paper').
111 | #
112 | # 'papersize': 'letterpaper',
113 |
114 | # The font size ('10pt', '11pt' or '12pt').
115 | #
116 | # 'pointsize': '10pt',
117 |
118 | # Additional stuff for the LaTeX preamble.
119 | #
120 | # 'preamble': '',
121 |
122 | # Latex figure (float) alignment
123 | #
124 | # 'figure_align': 'htbp',
125 | }
126 |
127 | # Grouping the document tree into LaTeX files. List of tuples
128 | # (source start file, target name, title,
129 | # author, documentclass [howto, manual, or own class]).
130 | latex_documents = [
131 | (master_doc, 'Messenger.tex', 'Messenger Documentation',
132 | 'Dmitry\\_VS', 'manual'),
133 | ]
134 |
135 |
136 | # -- Options for manual page output ------------------------------------------
137 |
138 | # One entry per manual page. List of tuples
139 | # (source start file, name, description, authors, manual section).
140 | man_pages = [
141 | (master_doc, 'messenger', 'Messenger Documentation',
142 | [author], 1)
143 | ]
144 |
145 |
146 | # -- Options for Texinfo output ----------------------------------------------
147 |
148 | # Grouping the document tree into Texinfo files. List of tuples
149 | # (source start file, target name, title, author,
150 | # dir menu entry, description, category)
151 | texinfo_documents = [
152 | (master_doc, 'Messenger', 'Messenger Documentation',
153 | author, 'Messenger', 'One line description of project.',
154 | 'Miscellaneous'),
155 | ]
--------------------------------------------------------------------------------
/index.rst:
--------------------------------------------------------------------------------
1 | .. Messenger documentation master file, created by
2 | sphinx-quickstart on Wed Jul 11 20:58:46 2018.
3 | You can adapt this file completely to your liking, but it should at least
4 | contain the root `toctree` directive.
5 |
6 | Messenger
7 | =========
8 |
9 | Проект представяет собой учебный чат-мессенджер на `Python`.
10 |
11 | Состоит из **клиентской** и **серверной** частей.
12 |
13 | Сетевое взаимодействие осуществляется с использованием сокетов. Сервер использует библиотеку `select` для работы с несколькими клиентами сразу.
14 |
15 | Для обмена сообщениями используется протокол `JIM`.
16 |
17 | Клиент и сервер имеют как **консольную**, так и **графическую** версии. Последняя предпочтительнее по удобству и полноте поддерживаемого функционала.
18 |
19 | Графический интерфейс пользователя реализован с использованием `PyQT5`.
20 |
21 | В качестве базы данных используется `sqlite`, при этом ORM не применяется.
22 |
23 | Реализован механизм авторизации пользователей с использованием модулей `hmac` и `hashlib`.
24 |
25 | .. toctree::
26 | :maxdepth: 1
27 |
28 | client
29 | server
30 |
--------------------------------------------------------------------------------
/make.bat:
--------------------------------------------------------------------------------
1 | @ECHO OFF
2 |
3 | pushd %~dp0
4 |
5 | REM Command file for Sphinx documentation
6 |
7 | if "%SPHINXBUILD%" == "" (
8 | set SPHINXBUILD=sphinx-build
9 | )
10 | set SOURCEDIR=.
11 | set BUILDDIR=_build
12 | set SPHINXPROJ=Messenger
13 |
14 | if "%1" == "" goto help
15 |
16 | %SPHINXBUILD% >NUL 2>NUL
17 | if errorlevel 9009 (
18 | echo.
19 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
20 | echo.installed, then set the SPHINXBUILD environment variable to point
21 | echo.to the full path of the 'sphinx-build' executable. Alternatively you
22 | echo.may add the Sphinx directory to PATH.
23 | echo.
24 | echo.If you don't have Sphinx installed, grab it from
25 | echo.http://sphinx-doc.org/
26 | exit /b 1
27 | )
28 |
29 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%
30 | goto end
31 |
32 | :help
33 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%
34 |
35 | :end
36 | popd
37 |
--------------------------------------------------------------------------------
/screen.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dmitry-vs/python-messenger/e2ac312c83dfb24253698e14d237f531ee14b831/screen.png
--------------------------------------------------------------------------------
/server.rst:
--------------------------------------------------------------------------------
1 | Сервер
2 | ======
3 | Рассмотрим графическую версию сервера.
4 |
5 | Основные области окна программы описаны далее.
6 |
7 | Parameters
8 | ----------
9 | В данном блоке можно задать хост и порт для сервера, а также запустить или остановить его.
10 |
11 | Если сервер запущен, в поле ``Status`` появится значение ``Started``.
12 |
13 | Clients
14 | -------
15 | Таблица содержит историю активности клиентов: логин, дата и время последнего посещения, IP-адрес, с которого в последний раз заходил пользователь.
16 |
17 | Данные отсортированы по времени (более новые вверху).
18 |
19 | Add new client
20 | --------------
21 | Чтобы клиент мог пользоваться чатом, его нужно сначала `зарегистрировать` на сервере.
22 |
23 | Для этого в данном блоке нужно ввести его логин и пароль, затем нажать кнопку ``Add client``.
24 |
25 | Service info
26 | ------------
27 | В данное поле выводится вся информация о работе сервера: служебные данные, сообщения об ошибках, а также все сообщения,
28 | которые принимает и отправляет сервер, плюс информация о подключениях и отключениях клиентов.
29 |
--------------------------------------------------------------------------------
/server/dist/messenger_server-0.1-py3-none-any.whl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dmitry-vs/python-messenger/e2ac312c83dfb24253698e14d237f531ee14b831/server/dist/messenger_server-0.1-py3-none-any.whl
--------------------------------------------------------------------------------
/server/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import setup
2 |
3 | setup(name = "messenger_server",
4 | version = "0.1",
5 | description = "Python 2 Messenger Server",
6 | author = "Dmitry VS",
7 | author_email = "dmitryselin@inbox.ru",
8 | url = "http://www.blog.pythonlibrary.org/2012/07/08/python-201-creating-modules-and-packages/",
9 | packages=["src"]
10 | )
--------------------------------------------------------------------------------
/server/src/SERVER_CONSOLE.bat:
--------------------------------------------------------------------------------
1 | server.py
--------------------------------------------------------------------------------
/server/src/SERVER_GUI.bat:
--------------------------------------------------------------------------------
1 | start server_gui.pyw
--------------------------------------------------------------------------------
/server/src/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dmitry-vs/python-messenger/e2ac312c83dfb24253698e14d237f531ee14b831/server/src/__init__.py
--------------------------------------------------------------------------------
/server/src/helpers.py:
--------------------------------------------------------------------------------
1 | import os
2 | from functools import wraps
3 | import inspect
4 | import binascii
5 |
6 | DEFAULT_SERVER_PORT = 7777
7 | TCP_MSG_BUFFER_SIZE = 1024
8 | DEFAULT_SERVER_IP = '127.0.0.1'
9 | SERVER_SOCKET_TIMEOUT = 0.2
10 | CLIENTS_COUNT_LIMIT = 100
11 | APP_NAME = 'messenger'
12 | SERVER_LOGGER_NAME = f'{APP_NAME}.server'
13 | CLIENT_LOGGER_NAME = f'{APP_NAME}.client'
14 | DEFAULT_CLIENT_LOGIN = 'TestUser'
15 | DEFAULT_CLIENT_PASSWORD = 'TestPassword'
16 |
17 |
18 | def get_this_script_full_dir():
19 | return os.path.dirname(os.path.realpath(__file__))
20 |
21 |
22 | # decorator for function call logging
23 | def log_func_call(logger):
24 | def log_func_call_decorator(func):
25 | @wraps(func)
26 | def log_func_call_decorated(*args, **kwargs):
27 | ret = func(*args, **kwargs)
28 | logger.info(f'Called function {func.__name__} with parameters: {args} {kwargs}, returned: {ret}, '
29 | f'caller name: {str(inspect.stack()[1][3])}')
30 | return ret
31 | return log_func_call_decorated
32 | return log_func_call_decorator
33 |
34 |
35 | class Menu:
36 | def __init__(self, commands: list):
37 | self._commands = {i + 1: item for i, item in enumerate(commands)}
38 |
39 | def get_command(self, command_index):
40 | return self._commands[command_index]
41 |
42 | def __str__(self):
43 | result = '\nChoose command:\n'
44 | for key, val in self._commands.items():
45 | result += f'{key}. {val}\n'
46 | result += '>'
47 | return result
48 |
49 |
50 | def bytes_to_hexstring(data: bytes) -> str:
51 | return binascii.hexlify(data).decode('utf-8')
52 |
53 |
54 | def hexstring_to_bytes(hexstring: str) -> bytes:
55 | return binascii.unhexlify(hexstring)
56 |
--------------------------------------------------------------------------------
/server/src/jim.py:
--------------------------------------------------------------------------------
1 | import json
2 | import time
3 |
4 |
5 | class JimMessage:
6 | def __init__(self):
7 | self._datadict = {}
8 |
9 | def set_field(self, key, val):
10 | self._datadict[key] = val
11 |
12 | def set_time(self):
13 | self.set_field('time', str(int(time.time())))
14 |
15 | @property
16 | def datadict(self):
17 | return self._datadict
18 |
19 | def to_bytes(self):
20 | self_json = json.dumps(self._datadict)
21 | return self_json.encode('utf-8')
22 |
23 | def from_bytes(self, bytedata):
24 | json_data = bytedata.decode('utf-8')
25 | self._datadict = json.loads(json_data)
26 |
27 | def __str__(self):
28 | return json.dumps(self._datadict, indent=1)
29 |
30 | def __eq__(self, other):
31 | return self._datadict == other.datadict
32 |
33 |
34 | class JimRequest(JimMessage):
35 | def __init__(self, action=None):
36 | super().__init__()
37 | self._action = None
38 | if action is not None:
39 | self.action = action
40 |
41 | @property
42 | def action(self):
43 | return self._action
44 |
45 | @action.setter
46 | def action(self, value: str):
47 | self._action = value
48 | self.set_field('action', self._action)
49 |
50 | def from_bytes(self, bytedata):
51 | super().from_bytes(bytedata)
52 | if 'action' in self._datadict:
53 | self._action = self._datadict['action']
54 |
55 |
56 | def request_from_bytes(bytedata: bytes) -> JimRequest:
57 | ret = JimRequest()
58 | ret.from_bytes(bytedata)
59 | return ret
60 |
61 |
62 | class JimResponse(JimMessage):
63 | def __init__(self, response_code=None):
64 | super().__init__()
65 | self._response = None
66 | if response_code is not None:
67 | self.response = response_code
68 |
69 | @property
70 | def response(self):
71 | return self._response
72 |
73 | @response.setter
74 | def response(self, value: int):
75 | self._response = value
76 | self.set_field('response', self._response)
77 |
78 | def from_bytes(self, bytedata):
79 | super().from_bytes(bytedata)
80 | if 'response' in self._datadict:
81 | self._response = self._datadict['response']
82 |
83 |
84 | def response_from_bytes(bytedata: bytes) -> JimResponse:
85 | ret = JimResponse()
86 | ret.from_bytes(bytedata)
87 | return ret
88 |
89 |
90 | def presence_request(username: str) -> JimRequest:
91 | message = JimRequest()
92 | message.set_field('action', 'presence')
93 | message.set_time()
94 | message.set_field('user', {'account_name': username})
95 | return message
96 |
97 |
98 | def get_contacts_request() -> JimRequest:
99 | message = JimRequest()
100 | message.set_field('action', 'get_contacts')
101 | message.set_time()
102 | return message
103 |
104 |
105 | def add_contact_request(login: str) -> JimRequest:
106 | message = JimRequest()
107 | message.set_field('action', 'add_contact')
108 | message.set_field('user_id', login)
109 | message.set_time()
110 | return message
111 |
112 |
113 | def delete_contact_request(login: str) -> JimRequest:
114 | message = JimRequest()
115 | message.set_field('action', 'del_contact')
116 | message.set_field('user_id', login)
117 | message.set_time()
118 | return message
119 |
120 |
121 | def message_request(login_from: str, login_to: str, text: str) -> JimRequest:
122 | message = JimRequest()
123 | message.set_field('action', 'msg')
124 | message.set_time()
125 | message.set_field('to', login_to)
126 | message.set_field('from', login_from)
127 | message.set_field('encoding', 'utf-8')
128 | message.set_field('message', text)
129 | return message
130 |
131 |
132 | def auth_server_message(auth_token: str) -> JimResponse:
133 | message = JimResponse(401)
134 | message.set_field('error', 'Authentication required')
135 | message.set_field('token', auth_token)
136 | return message
137 |
138 |
139 | def auth_client_message(login: str, auth_digest: str) -> JimRequest:
140 | message = JimRequest()
141 | message.set_field('action', 'authenticate')
142 | message.set_time()
143 | user_data = {'account_name': login, 'password': auth_digest}
144 | message.set_field('user', user_data)
145 | return message
146 |
--------------------------------------------------------------------------------
/server/src/log_confing.py:
--------------------------------------------------------------------------------
1 | import logging.handlers
2 | import os
3 |
4 | import helpers
5 |
6 | log_format = logging.Formatter('%(asctime)-s %(levelname)-s %(module)-s %(funcName)-s %(message)s')
7 |
8 | # logger for server
9 | server_logger_name = helpers.SERVER_LOGGER_NAME
10 | server_log_file = os.path.join(helpers.get_this_script_full_dir(), f'{server_logger_name}.log')
11 | server_log_handler = logging.handlers.TimedRotatingFileHandler(filename=server_log_file, when='D', interval=1, delay=True)
12 | server_log_handler.setFormatter(log_format)
13 | server_logger = logging.getLogger(server_logger_name)
14 | server_logger.setLevel(logging.INFO)
15 | server_logger.addHandler(server_log_handler)
16 |
17 | # logger for client
18 | client_logger_name = helpers.CLIENT_LOGGER_NAME
19 | client_log_file = os.path.join(helpers.get_this_script_full_dir(), f'{client_logger_name}.log')
20 | client_log_handler = logging.FileHandler(filename=client_log_file, delay=True)
21 | client_log_handler.setFormatter(log_format)
22 | client_logger = logging.getLogger(client_logger_name)
23 | client_logger.setLevel(logging.DEBUG)
24 | client_logger.addHandler(client_log_handler)
25 |
--------------------------------------------------------------------------------
/server/src/security.py:
--------------------------------------------------------------------------------
1 | import hashlib
2 | from os import urandom
3 | import hmac
4 |
5 | from helpers import bytes_to_hexstring, hexstring_to_bytes
6 |
7 | HASH_ALGORITHM = 'sha256'
8 | HASH_SALT = b'\xca\xfe\xbe\xef\xca\xfe\xbe\xef\xca\xfe\xbe\xef\xca\xfe\xbe\xef\xca\xfe\xbe\xef\xca\xfe\xbe\xef'
9 | HASH_ITERATIONS = 100000
10 | AUTH_TOKEN_LEN = 16
11 |
12 |
13 | def create_password_hash(password: str) -> str:
14 | if not password:
15 | raise RuntimeError('password value empty or incorrect')
16 | digest = hashlib.pbkdf2_hmac(HASH_ALGORITHM, password.encode('utf-8'), HASH_SALT, HASH_ITERATIONS)
17 | return bytes_to_hexstring(digest)
18 |
19 |
20 | def create_auth_token() -> str:
21 | return bytes_to_hexstring(urandom(AUTH_TOKEN_LEN))
22 |
23 |
24 | def create_auth_digest(secret: str, token: str) -> str:
25 | if not secret or not token:
26 | raise RuntimeError('secret or token value empty or incorrect')
27 | digest = hmac.new(hexstring_to_bytes(secret), hexstring_to_bytes(token)).digest()
28 | return bytes_to_hexstring(digest)
29 |
30 |
31 | def check_auth_digest_equal(digest_1: str, digest_2: str) -> bool:
32 | return hmac.compare_digest(digest_1, digest_2)
33 |
--------------------------------------------------------------------------------
/server/src/server.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | from socket import socket, AF_INET, SOCK_STREAM
3 | import sys
4 | import select
5 | import logging
6 | import inspect
7 | import os
8 | from time import sleep
9 | from threading import Thread
10 | from queue import Queue
11 |
12 | import helpers
13 | from jim import request_from_bytes, JimResponse, auth_server_message
14 | from storage import DBStorageServer
15 | import security
16 | import log_confing
17 |
18 | log = logging.getLogger(helpers.SERVER_LOGGER_NAME)
19 |
20 |
21 | def parse_commandline_args(cmd_args):
22 | parser = argparse.ArgumentParser()
23 | parser.add_argument('-a', dest='listen_address', type=str, default='',
24 | help='ip-address to listen on, default empty')
25 | parser.add_argument('-p', dest='listen_port', type=int, default=helpers.DEFAULT_SERVER_PORT,
26 | help=f'tcp port to listen on, default {str(helpers.DEFAULT_SERVER_PORT)}')
27 | return parser.parse_args(cmd_args)
28 |
29 |
30 | class ServerVerifierMeta(type):
31 | def __init__(cls, clsname, bases, clsdict):
32 | tcp_found = False
33 |
34 | for key, value in clsdict.items():
35 | if not hasattr(value, '__call__'): # we need only methods further
36 | continue
37 |
38 | source = inspect.getsource(value)
39 | if '.connect(' in source: # check there are no connect() socket calls
40 | raise RuntimeError('Server must not use connect for sockets')
41 |
42 | if 'SOCK_STREAM' in source: # check that TCP sockets are used
43 | tcp_found = True
44 |
45 | if not tcp_found:
46 | raise RuntimeError('Server must use only TCP sockets')
47 |
48 | type.__init__(cls, clsname, bases, clsdict)
49 |
50 |
51 | class Server(metaclass=ServerVerifierMeta):
52 | def __init__(self, host, port, storage,
53 | clients_limit=helpers.CLIENTS_COUNT_LIMIT, timeout=helpers.SERVER_SOCKET_TIMEOUT):
54 | self.__host = host
55 | self.__port = port
56 | self.__storage_name = storage
57 | self.__clients_limit = clients_limit
58 | self.__timeout = timeout
59 |
60 | self.__socket = None
61 | self.__storage = None
62 | self.__need_terminate = False
63 | self.__worker_thread = None
64 | self.__print_queue = Queue()
65 |
66 | def start(self):
67 | if self.__socket:
68 | raise RuntimeError('Already started')
69 | self.__socket = socket(AF_INET, SOCK_STREAM)
70 | self.__socket.bind((self.__host, self.__port))
71 | self.__socket.listen(self.__clients_limit)
72 | self.__socket.settimeout(self.__timeout)
73 | self.__worker_thread = Thread(target=self.worker_thread_function)
74 | self.__worker_thread.daemon = True
75 | self.__worker_thread.start()
76 |
77 | def close_server(self):
78 | if not self.__socket:
79 | raise RuntimeError('Not running')
80 | self.__socket.close()
81 | self.__socket = None
82 | self.__need_terminate = True
83 | self.__worker_thread.join()
84 | self.__worker_thread = None
85 |
86 | def worker_thread_function(self):
87 | self.__storage = DBStorageServer(self.__storage_name)
88 | self.mainloop()
89 | self.__storage = None
90 |
91 | @property
92 | def print_queue(self):
93 | return self.__print_queue
94 |
95 | @property
96 | def storage(self):
97 | return self.__storage
98 |
99 | def mainloop(self):
100 | clients = []
101 | logins = {}
102 | auth_tokens = {}
103 |
104 | while True:
105 | if self.__need_terminate:
106 | return
107 |
108 | try:
109 | conn, addr = self.__socket.accept() # check for new connections
110 | except OSError:
111 | pass # timeout, do nothing
112 | else:
113 | self.__print_queue.put(f'Client connected: {str(addr)}')
114 | clients.append(conn)
115 | finally: # check for incoming requests
116 | readable, writable, erroneous = [], [], []
117 | try:
118 | readable, writable, erroneous = select.select(clients, clients, clients, 0)
119 | except:
120 | pass # if some client unexpectedly disconnected, do nothing
121 |
122 | for client_socket in readable:
123 | try:
124 | if client_socket not in writable:
125 | continue
126 | request = request_from_bytes(client_socket.recv(helpers.TCP_MSG_BUFFER_SIZE))
127 | self.__print_queue.put(f'Request:\n{request}')
128 | responses = []
129 | if request.action == 'presence':
130 | client_login = request.datadict['user']['account_name']
131 | resp = JimResponse()
132 | if not self.storage.check_client_exists(client_login): # unknown client - error
133 | resp.response = 400
134 | resp.set_field('error', f'No such client: {client_login}')
135 | elif client_login not in logins.values(): # known client arrived - need auth
136 | token = security.create_auth_token()
137 | auth_tokens[client_socket] = token
138 | resp = auth_server_message(token)
139 | elif client_socket in logins.keys() and \
140 | logins[client_socket] == client_login: # existing client from same socket - ok
141 | client_time = request.datadict['time']
142 | client_ip = client_socket.getpeername()[0]
143 | self.storage.update_client(client_login, client_time, client_ip)
144 | resp.response = 200
145 | else: # existing client from different ip - not correct
146 | resp.response = 400
147 | resp.set_field('error', 'Client already online')
148 | responses.append(resp)
149 | elif request.action == 'authenticate':
150 | client_login = request.datadict['user']['account_name']
151 | client_hash = self.storage.get_client_hash(client_login)
152 | auth_token = auth_tokens[client_socket]
153 | del auth_tokens[client_socket]
154 | expected_digest = security.create_auth_digest(client_hash, auth_token)
155 | client_digest = request.datadict['user']['password']
156 | resp = JimResponse()
157 | if not security.check_auth_digest_equal(expected_digest, client_digest):
158 | resp.response = 402
159 | resp.set_field('error', 'Access denied')
160 | else: # add client login to dict, update client in database
161 | logins[client_socket] = client_login
162 | client_time = request.datadict['time']
163 | client_ip = client_socket.getpeername()[0]
164 | self.storage.update_client(client_login, client_time, client_ip)
165 | resp.response = 200
166 | responses.append(resp)
167 | elif request.action == 'add_contact':
168 | client_login = logins[client_socket]
169 | contact_login = request.datadict['user_id']
170 | resp = JimResponse()
171 | if not self.storage.check_client_exists(contact_login):
172 | resp.response = 400
173 | resp.set_field('error', f'No such client: {contact_login}')
174 | elif self.storage.check_client_in_contacts(client_login, contact_login):
175 | resp.response = 400
176 | resp.set_field('error', f'Client already in contacts: {contact_login}')
177 | else:
178 | self.storage.add_client_to_contacts(client_login, contact_login)
179 | resp.response = 200
180 | responses.append(resp)
181 | elif request.action == 'del_contact':
182 | client_login = logins[client_socket]
183 | contact_login = request.datadict['user_id']
184 | resp = JimResponse()
185 | if not self.storage.check_client_exists(contact_login):
186 | resp.response = 400
187 | resp.set_field('error', f'No such client: {contact_login}')
188 | elif not self.storage.check_client_in_contacts(client_login, contact_login):
189 | resp.response = 400
190 | resp.set_field('error', f'Client not in contacts: {contact_login}')
191 | else:
192 | self.storage.del_client_from_contacts(client_login, contact_login)
193 | resp.response = 200
194 | responses.append(resp)
195 | elif request.action == 'get_contacts':
196 | client_login = logins[client_socket]
197 | client_contacts = self.storage.get_client_contacts(client_login)
198 | quantity_resp = JimResponse()
199 | quantity_resp.response = 202
200 | quantity_resp.set_field('quantity', len(client_contacts))
201 | responses.append(quantity_resp)
202 | for contact in client_contacts:
203 | contact_resp = JimResponse()
204 | contact_resp.set_field('action', 'contact_list')
205 | contact_resp.set_field('user_id', contact)
206 | responses.append(contact_resp)
207 | elif request.action == 'msg':
208 | target_client_login = request.datadict['to']
209 | resp = JimResponse()
210 | for key, val in logins.items():
211 | if val == target_client_login:
212 | key.send(request.to_bytes())
213 | resp.response = 200
214 | break
215 | else:
216 | resp.response = 400
217 | resp.set_field('error', f'Client not online: {target_client_login}')
218 | responses.append(resp)
219 | else:
220 | raise RuntimeError(f'Unknown JIM action: {request.action}')
221 | self.__print_queue.put('Response:')
222 | for resp in responses:
223 | self.__print_queue.put(str(resp))
224 | sleep(0.001) # this magic solves problem with multiple jim messages in one socket message!!
225 | client_socket.send(resp.to_bytes())
226 | except BaseException as e:
227 | self.__print_queue.put(f'Client disconnected: {client_socket.getpeername()}, {e}')
228 | client_socket.close()
229 | clients.remove(client_socket)
230 | try:
231 | del logins[client_socket]
232 | except:
233 | pass
234 | if client_socket in writable:
235 | writable.remove(client_socket)
236 |
237 |
238 | def check_new_print_data_thread_function(print_queue: Queue):
239 | while True:
240 | if print_queue:
241 | print(print_queue.get())
242 |
243 |
244 | if __name__ == '__main__':
245 | try:
246 | args = parse_commandline_args(sys.argv[1:])
247 | storage_file = os.path.join(helpers.get_this_script_full_dir(), 'server.sqlite')
248 | server = Server(args.listen_address, args.listen_port, storage_file)
249 | print_monitor = Thread(target=check_new_print_data_thread_function,
250 | args=(server.print_queue,))
251 | print_monitor.daemon = True
252 | print_monitor.start()
253 | supported_commands = ['start', 'stop']
254 | main_menu = helpers.Menu(supported_commands)
255 | while True:
256 | user_choice = int(input(main_menu))
257 | command = main_menu.get_command(user_choice)
258 | if command == 'start':
259 | server.start()
260 | if command == 'stop':
261 | server.close_server()
262 | except BaseException as e:
263 | print(f'Error: {str(e)}')
264 | log.critical(str(e))
265 | raise e
266 |
--------------------------------------------------------------------------------
/server/src/server_gui.pyw:
--------------------------------------------------------------------------------
1 | import sys
2 | from PyQt5 import QtWidgets, QtGui
3 | from PyQt5.QtCore import QObject, QThread, pyqtSignal, pyqtSlot
4 | import os
5 | import traceback
6 | import logging
7 | import datetime
8 |
9 | import server_pyqt
10 | from server import Server
11 | import helpers
12 | from storage import DBStorageServer
13 | from security import create_password_hash
14 | import log_confing
15 |
16 | log = logging.getLogger(helpers.CLIENT_LOGGER_NAME)
17 |
18 |
19 | class ServerMonitor(QObject):
20 | gotPrintStr = pyqtSignal(str)
21 |
22 | def __init__(self, parent):
23 | super().__init__()
24 | self.parent = parent
25 | self._print_queue = None
26 |
27 | def set_queue(self, queue):
28 | self._print_queue = queue
29 |
30 | def check_new_data(self):
31 | while True:
32 | if self._print_queue:
33 | text = self._print_queue.get()
34 | if text is None:
35 | return
36 | self.gotPrintStr.emit(text)
37 |
38 |
39 | class MainWindow(QtWidgets.QMainWindow):
40 | def __init__(self, parent=None):
41 | QtWidgets.QWidget.__init__(self, parent)
42 | self.ui = server_pyqt.Ui_MainWindow()
43 | self.ui.setupUi(self)
44 | self.server = None
45 | self.listen_ip = None
46 | self.listen_port = None
47 | self.storage_name = os.path.join(helpers.get_this_script_full_dir(), 'server.sqlite')
48 | self.storage = DBStorageServer(self.storage_name)
49 |
50 | # connect slots
51 | self.ui.pushButton_start_server.clicked.connect(self.start_server_click)
52 | self.ui.pushButton_stop_server.clicked.connect(self.stop_server_click)
53 | self.ui.pushButton_add_new_client.clicked.connect(self.add_new_client_click)
54 |
55 | # create monitor and thread
56 | self.monitor = ServerMonitor(self)
57 | self.monitor_thread = QThread()
58 | self.monitor.moveToThread(self.monitor_thread)
59 | self.monitor.gotPrintStr.connect(self.new_print_data)
60 | self.monitor_thread.started.connect(self.monitor.check_new_data)
61 |
62 | # setup table widget parameters
63 | header = self.ui.tableWidget_clients.horizontalHeader()
64 | header.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch)
65 | header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents)
66 | header.setSectionResizeMode(2, QtWidgets.QHeaderView.Stretch)
67 | self.update_clients_table()
68 |
69 | @pyqtSlot(str)
70 | def new_print_data(self, text: str):
71 | if text.startswith('Client disconnected') or '"action": "get_contacts"' in text:
72 | self.update_clients_table()
73 | self.print_info(text)
74 |
75 | def update_clients_table(self):
76 | current_clients = self.storage.get_clients()
77 | self.ui.tableWidget_clients.setRowCount(len(current_clients))
78 | for index, client in enumerate(current_clients):
79 | self.ui.tableWidget_clients.setItem(index, 0, QtWidgets.QTableWidgetItem(client[0]))
80 | last_time = datetime.datetime.fromtimestamp(client[1]).strftime('%Y-%m-%d %H:%M:%S') if client[1] else None
81 | self.ui.tableWidget_clients.setItem(index, 1, QtWidgets.QTableWidgetItem(last_time))
82 | self.ui.tableWidget_clients.setItem(index, 2, QtWidgets.QTableWidgetItem((client[2])))
83 |
84 | def add_new_client_click(self):
85 | try:
86 | client_login = self.ui.lineEdit_add_new_client_login.text()
87 | client_password = self.ui.lineEdit_add_new_client_password.text()
88 | if not client_password or not client_password:
89 | self.print_info('Login and password must be non-empty')
90 | return
91 | if self.storage.check_client_exists(client_login):
92 | self.print_info(f'Client with this login already exists: {client_login}')
93 | return
94 | self.storage.add_client(client_login, create_password_hash(client_password))
95 | self.print_info(f'Client added: {client_login}')
96 | self.update_clients_table()
97 | except:
98 | self.print_info(traceback.format_exc())
99 |
100 | def start_server_click(self):
101 | try:
102 | if self.server:
103 | self.print_info('Already started')
104 | return
105 | self.print_info('Starting server')
106 | self.listen_ip = self.ui.lineEdit_ip.text()
107 | self.listen_port = int(self.ui.lineEdit_port.text())
108 | self.server = Server(self.listen_ip, self.listen_port, self.storage_name)
109 | self.server.start()
110 | self.monitor.set_queue(self.server.print_queue)
111 | self.monitor_thread.start()
112 | self.set_server_status_started(True)
113 | self.update_clients_table()
114 | except:
115 | self.print_info(traceback.format_exc())
116 |
117 | def stop_server_click(self):
118 | try:
119 | if not self.server:
120 | self.print_info('Not running')
121 | return
122 | self.print_info('Stopping server')
123 | self.server.print_queue.put(None)
124 | self.monitor_thread.terminate()
125 | self.server.close_server()
126 | self.server = None
127 | self.set_server_status_started(False)
128 | self.ui.tableWidget_clients.clearContents()
129 | self.ui.lineEdit_add_new_client_login.clear()
130 | self.ui.lineEdit_add_new_client_password.clear()
131 | except:
132 | self.print_info(traceback.format_exc())
133 |
134 | def print_info(self, info: str):
135 | current_text = self.ui.textBrowser_service_info.toPlainText()
136 | new_text = info if not current_text else f'{current_text}\n{info}'
137 | self.ui.textBrowser_service_info.setText(new_text)
138 | self.ui.textBrowser_service_info.moveCursor(QtGui.QTextCursor.End)
139 |
140 | def set_server_status_started(self, state: bool):
141 | self.ui.label_status_value.setText('Started' if state else 'Not started')
142 |
143 |
144 | if __name__ == '__main__':
145 | app = QtWidgets.QApplication(sys.argv)
146 | window = MainWindow()
147 | window.show()
148 | sys.exit(app.exec_())
149 |
--------------------------------------------------------------------------------
/server/src/server_gui.ui:
--------------------------------------------------------------------------------
1 |
2 |
3 | MainWindow
4 |
5 |
6 |
7 | 0
8 | 0
9 | 451
10 | 681
11 |
12 |
13 |
14 | Server
15 |
16 |
17 |
18 |
19 |
20 | 30
21 | 120
22 | 391
23 | 191
24 |
25 |
26 |
27 | Clients
28 |
29 |
30 |
31 |
32 | 10
33 | 20
34 | 371
35 | 161
36 |
37 |
38 |
39 |
40 | 0
41 | 0
42 |
43 |
44 |
45 | true
46 |
47 |
48 | false
49 |
50 |
51 |
52 | Login
53 |
54 |
55 |
56 |
57 | Last time
58 |
59 |
60 |
61 |
62 | Last IP
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 | 30
71 | 380
72 | 391
73 | 261
74 |
75 |
76 |
77 | Service info
78 |
79 |
80 |
81 |
82 | 10
83 | 20
84 | 371
85 | 231
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 | 30
94 | 10
95 | 391
96 | 101
97 |
98 |
99 |
100 | Parameters
101 |
102 |
103 |
104 |
105 | 270
106 | 30
107 | 61
108 | 16
109 |
110 |
111 |
112 | Status:
113 |
114 |
115 |
116 |
117 |
118 | 270
119 | 60
120 | 61
121 | 16
122 |
123 |
124 |
125 | Not started
126 |
127 |
128 |
129 |
130 |
131 | 30
132 | 30
133 | 111
134 | 20
135 |
136 |
137 |
138 | 127.0.0.1
139 |
140 |
141 | IP address to listen
142 |
143 |
144 |
145 |
146 |
147 | 30
148 | 60
149 | 111
150 | 20
151 |
152 |
153 |
154 | 7777
155 |
156 |
157 | Port to listen
158 |
159 |
160 |
161 |
162 |
163 | 160
164 | 60
165 | 71
166 | 21
167 |
168 |
169 |
170 | Stop server
171 |
172 |
173 |
174 |
175 |
176 | 160
177 | 30
178 | 71
179 | 21
180 |
181 |
182 |
183 | Start server
184 |
185 |
186 |
187 |
188 |
189 |
190 | 30
191 | 320
192 | 391
193 | 51
194 |
195 |
196 |
197 | Add new client
198 |
199 |
200 |
201 |
202 | 10
203 | 20
204 | 121
205 | 20
206 |
207 |
208 |
209 | Login
210 |
211 |
212 |
213 |
214 |
215 | 150
216 | 20
217 | 141
218 | 20
219 |
220 |
221 |
222 | Password
223 |
224 |
225 |
226 |
227 |
228 | 310
229 | 20
230 | 75
231 | 21
232 |
233 |
234 |
235 | Add client
236 |
237 |
238 |
239 |
240 |
250 |
251 |
252 |
253 |
254 |
255 |
--------------------------------------------------------------------------------
/server/src/server_pyqt.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | # Form implementation generated from reading ui file 'server_gui.ui'
4 | #
5 | # Created by: PyQt5 UI code generator 5.10.1
6 | #
7 | # WARNING! All changes made in this file will be lost!
8 |
9 | from PyQt5 import QtCore, QtGui, QtWidgets
10 |
11 | class Ui_MainWindow(object):
12 | def setupUi(self, MainWindow):
13 | MainWindow.setObjectName("MainWindow")
14 | MainWindow.resize(451, 681)
15 | self.centralwidget = QtWidgets.QWidget(MainWindow)
16 | self.centralwidget.setObjectName("centralwidget")
17 | self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
18 | self.groupBox.setGeometry(QtCore.QRect(30, 120, 391, 191))
19 | self.groupBox.setObjectName("groupBox")
20 | self.tableWidget_clients = QtWidgets.QTableWidget(self.groupBox)
21 | self.tableWidget_clients.setGeometry(QtCore.QRect(10, 20, 371, 161))
22 | sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
23 | sizePolicy.setHorizontalStretch(0)
24 | sizePolicy.setVerticalStretch(0)
25 | sizePolicy.setHeightForWidth(self.tableWidget_clients.sizePolicy().hasHeightForWidth())
26 | self.tableWidget_clients.setSizePolicy(sizePolicy)
27 | self.tableWidget_clients.setObjectName("tableWidget_clients")
28 | self.tableWidget_clients.setColumnCount(3)
29 | self.tableWidget_clients.setRowCount(0)
30 | item = QtWidgets.QTableWidgetItem()
31 | self.tableWidget_clients.setHorizontalHeaderItem(0, item)
32 | item = QtWidgets.QTableWidgetItem()
33 | self.tableWidget_clients.setHorizontalHeaderItem(1, item)
34 | item = QtWidgets.QTableWidgetItem()
35 | self.tableWidget_clients.setHorizontalHeaderItem(2, item)
36 | self.tableWidget_clients.horizontalHeader().setVisible(True)
37 | self.tableWidget_clients.verticalHeader().setVisible(False)
38 | self.groupBox_2 = QtWidgets.QGroupBox(self.centralwidget)
39 | self.groupBox_2.setGeometry(QtCore.QRect(30, 380, 391, 261))
40 | self.groupBox_2.setObjectName("groupBox_2")
41 | self.textBrowser_service_info = QtWidgets.QTextBrowser(self.groupBox_2)
42 | self.textBrowser_service_info.setGeometry(QtCore.QRect(10, 20, 371, 231))
43 | self.textBrowser_service_info.setObjectName("textBrowser_service_info")
44 | self.groupBox_3 = QtWidgets.QGroupBox(self.centralwidget)
45 | self.groupBox_3.setGeometry(QtCore.QRect(30, 10, 391, 101))
46 | self.groupBox_3.setObjectName("groupBox_3")
47 | self.label_status_key = QtWidgets.QLabel(self.groupBox_3)
48 | self.label_status_key.setGeometry(QtCore.QRect(270, 30, 61, 16))
49 | self.label_status_key.setObjectName("label_status_key")
50 | self.label_status_value = QtWidgets.QLabel(self.groupBox_3)
51 | self.label_status_value.setGeometry(QtCore.QRect(270, 60, 61, 16))
52 | self.label_status_value.setObjectName("label_status_value")
53 | self.lineEdit_ip = QtWidgets.QLineEdit(self.groupBox_3)
54 | self.lineEdit_ip.setGeometry(QtCore.QRect(30, 30, 111, 20))
55 | self.lineEdit_ip.setObjectName("lineEdit_ip")
56 | self.lineEdit_port = QtWidgets.QLineEdit(self.groupBox_3)
57 | self.lineEdit_port.setGeometry(QtCore.QRect(30, 60, 111, 20))
58 | self.lineEdit_port.setObjectName("lineEdit_port")
59 | self.pushButton_stop_server = QtWidgets.QPushButton(self.groupBox_3)
60 | self.pushButton_stop_server.setGeometry(QtCore.QRect(160, 60, 71, 21))
61 | self.pushButton_stop_server.setObjectName("pushButton_stop_server")
62 | self.pushButton_start_server = QtWidgets.QPushButton(self.groupBox_3)
63 | self.pushButton_start_server.setGeometry(QtCore.QRect(160, 30, 71, 21))
64 | self.pushButton_start_server.setObjectName("pushButton_start_server")
65 | self.groupBox_4 = QtWidgets.QGroupBox(self.centralwidget)
66 | self.groupBox_4.setGeometry(QtCore.QRect(30, 320, 391, 51))
67 | self.groupBox_4.setObjectName("groupBox_4")
68 | self.lineEdit_add_new_client_login = QtWidgets.QLineEdit(self.groupBox_4)
69 | self.lineEdit_add_new_client_login.setGeometry(QtCore.QRect(10, 20, 121, 20))
70 | self.lineEdit_add_new_client_login.setObjectName("lineEdit_add_new_client_login")
71 | self.lineEdit_add_new_client_password = QtWidgets.QLineEdit(self.groupBox_4)
72 | self.lineEdit_add_new_client_password.setGeometry(QtCore.QRect(150, 20, 141, 20))
73 | self.lineEdit_add_new_client_password.setObjectName("lineEdit_add_new_client_password")
74 | self.pushButton_add_new_client = QtWidgets.QPushButton(self.groupBox_4)
75 | self.pushButton_add_new_client.setGeometry(QtCore.QRect(310, 20, 75, 21))
76 | self.pushButton_add_new_client.setObjectName("pushButton_add_new_client")
77 | MainWindow.setCentralWidget(self.centralwidget)
78 | self.menubar = QtWidgets.QMenuBar(MainWindow)
79 | self.menubar.setGeometry(QtCore.QRect(0, 0, 451, 21))
80 | self.menubar.setObjectName("menubar")
81 | MainWindow.setMenuBar(self.menubar)
82 | self.statusbar = QtWidgets.QStatusBar(MainWindow)
83 | self.statusbar.setObjectName("statusbar")
84 | MainWindow.setStatusBar(self.statusbar)
85 |
86 | self.retranslateUi(MainWindow)
87 | QtCore.QMetaObject.connectSlotsByName(MainWindow)
88 |
89 | def retranslateUi(self, MainWindow):
90 | _translate = QtCore.QCoreApplication.translate
91 | MainWindow.setWindowTitle(_translate("MainWindow", "Server"))
92 | self.groupBox.setTitle(_translate("MainWindow", "Clients"))
93 | item = self.tableWidget_clients.horizontalHeaderItem(0)
94 | item.setText(_translate("MainWindow", "Login"))
95 | item = self.tableWidget_clients.horizontalHeaderItem(1)
96 | item.setText(_translate("MainWindow", "Last time"))
97 | item = self.tableWidget_clients.horizontalHeaderItem(2)
98 | item.setText(_translate("MainWindow", "Last IP"))
99 | self.groupBox_2.setTitle(_translate("MainWindow", "Service info"))
100 | self.groupBox_3.setTitle(_translate("MainWindow", "Parameters"))
101 | self.label_status_key.setText(_translate("MainWindow", "Status:"))
102 | self.label_status_value.setText(_translate("MainWindow", "Not started"))
103 | self.lineEdit_ip.setText(_translate("MainWindow", "127.0.0.1"))
104 | self.lineEdit_ip.setPlaceholderText(_translate("MainWindow", "IP address to listen"))
105 | self.lineEdit_port.setText(_translate("MainWindow", "7777"))
106 | self.lineEdit_port.setPlaceholderText(_translate("MainWindow", "Port to listen"))
107 | self.pushButton_stop_server.setText(_translate("MainWindow", "Stop server"))
108 | self.pushButton_start_server.setText(_translate("MainWindow", "Start server"))
109 | self.groupBox_4.setTitle(_translate("MainWindow", "Add new client"))
110 | self.lineEdit_add_new_client_login.setPlaceholderText(_translate("MainWindow", "Login"))
111 | self.lineEdit_add_new_client_password.setPlaceholderText(_translate("MainWindow", "Password"))
112 | self.pushButton_add_new_client.setText(_translate("MainWindow", "Add client"))
113 |
114 |
--------------------------------------------------------------------------------
/server/src/storage.py:
--------------------------------------------------------------------------------
1 | import sqlite3
2 |
3 |
4 | class DBStorage:
5 | def __init__(self, database):
6 | self._conn = sqlite3.connect(database)
7 | self._cursor = self._conn.cursor()
8 |
9 | def __del__(self):
10 | self._conn.close()
11 |
12 | @property
13 | def conn(self):
14 | return self._conn
15 |
16 | @property
17 | def cursor(self):
18 | return self._cursor
19 |
20 |
21 | class DBStorageServer(DBStorage):
22 | def __init__(self, database):
23 | super().__init__(database)
24 | self._cursor.executescript('''
25 | CREATE TABLE IF NOT EXISTS `Clients`(
26 | `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
27 | `login` TEXT NOT NULL UNIQUE,
28 | `info` TEXT,
29 | `last_connect_time` INTEGER,
30 | `last_connect_ip` TEXT
31 | );
32 | ''')
33 | self._cursor.execute('PRAGMA foreign_keys = ON;')
34 | self._cursor.executescript('''
35 | CREATE TABLE IF NOT EXISTS `ClientContacts` (
36 | `owner_id` INTEGER,
37 | `contact_id` INTEGER,
38 | PRIMARY KEY(`owner_id`,`contact_id`),
39 | FOREIGN KEY(`owner_id`) REFERENCES `Clients`(`id`),
40 | FOREIGN KEY(`contact_id`) REFERENCES `Clients`(`id`)
41 | );
42 | ''')
43 | self._conn.commit()
44 |
45 | def get_client_id(self, login: str):
46 | """ Returns client id by login from Clients table, or None if there is no such client """
47 | self._cursor.execute('SELECT `id` FROM `Clients` WHERE `login` == ?', (login,))
48 | return self._cursor.fetchall()[0][0]
49 |
50 | def get_clients(self):
51 | self._cursor.execute(
52 | '''
53 | SELECT `login`, `last_connect_time`, `last_connect_ip`
54 | FROM `Clients`
55 | ORDER BY `last_connect_time` DESC
56 | '''
57 | )
58 | result = self._cursor.fetchall()
59 | return result if result else []
60 |
61 | def get_client_hash(self, login: str) -> str:
62 | self._cursor.execute('SELECT `info` FROM `Clients` WHERE `login` == ?', (login,))
63 | return self._cursor.fetchall()[0][0]
64 |
65 | def check_client_exists(self, login: str) -> bool:
66 | try:
67 | self.get_client_id(login)
68 | return True
69 | except IndexError:
70 | return False
71 |
72 | def add_client(self, login: str, password_hash: str):
73 | if not login:
74 | raise ValueError('login cannot be None or empty')
75 | if not password_hash:
76 | raise ValueError('password hash cannot be None or empty')
77 | if self.check_client_exists(login) is True:
78 | raise RuntimeError(f'client with this login already exists: {login}')
79 | self._cursor.execute('INSERT INTO `Clients` VALUES (NULL, ?, ?, NULL, NULL)', (login, password_hash))
80 | self._conn.commit()
81 |
82 | def update_client(self, login: str, connection_time: float, connection_ip: str):
83 | client_id = self.get_client_id(login)
84 | self._cursor.execute(
85 | """
86 | UPDATE `Clients` SET
87 | `last_connect_time` = ?,
88 | `last_connect_ip` = ?
89 | WHERE `id` == ?;
90 | """, (connection_time, connection_ip, client_id)
91 | )
92 | self._conn.commit()
93 |
94 | def check_client_in_contacts(self, owner_login: str, client_login: str) -> bool:
95 | owner_id = self.get_client_id(owner_login)
96 | client_id = self.get_client_id(client_login)
97 | self._cursor.execute('SELECT COUNT() FROM `ClientContacts` WHERE `owner_id` == ? AND `contact_id` == ?;',
98 | (owner_id, client_id))
99 | return True if self._cursor.fetchall()[0][0] == 1 else False
100 |
101 | def add_client_to_contacts(self, owner_login: str, client_login: str):
102 | owner_id = self.get_client_id(owner_login)
103 | client_id = self.get_client_id(client_login)
104 | self._cursor.execute('INSERT INTO `ClientContacts` VALUES (?, ?);', (owner_id, client_id))
105 | self._conn.commit()
106 |
107 | def del_client_from_contacts(self, owner_login: str, client_login: str):
108 | owner_id = self.get_client_id(owner_login)
109 | client_id = self.get_client_id(client_login)
110 | self._cursor.execute('DELETE FROM `ClientContacts` WHERE `owner_id` == ? AND `contact_id` == ?',
111 | (owner_id, client_id))
112 | self._conn.commit()
113 |
114 | def get_client_contacts(self, client_login: str) -> list:
115 | client_id = self.get_client_id(client_login)
116 | query = '''select `Clients`.login from `ClientContacts` join `Clients`
117 | where (`ClientContacts`.contact_id == `Clients`.id and `ClientContacts`.owner_id == ?);'''
118 | self._cursor.execute(query, (client_id,))
119 | result = self._cursor.fetchall()
120 | return [item[0] for item in result] if result is not None else []
121 |
122 |
123 | class DBStorageClient(DBStorage):
124 | def __init__(self, database):
125 | # connect to database, create it if not exists,
126 | # create db schema if not exists (tables Contacts, Messages)
127 | super().__init__(database)
128 | self._cursor.executescript('''
129 | CREATE TABLE IF NOT EXISTS `Contacts`(
130 | `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
131 | `login` TEXT NOT NULL UNIQUE
132 | );
133 | ''')
134 | self._cursor.execute('PRAGMA foreign_keys = ON;')
135 | self._cursor.executescript('''
136 | CREATE TABLE IF NOT EXISTS `Messages` (
137 | `id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
138 | `contact_id` INTEGER NOT NULL,
139 | `incoming` INTEGER NOT NULL,
140 | `text` TEXT NOT NULL,
141 | FOREIGN KEY(`contact_id`) REFERENCES `Contacts`(`id`) ON DELETE CASCADE
142 | );
143 | ''')
144 | self._conn.commit()
145 |
146 | def add_contact(self, login: str):
147 | self._cursor.execute('INSERT INTO `Contacts` VALUES(NULL, ?)', (login,))
148 | self._conn.commit()
149 |
150 | def get_contact_id(self, login: str):
151 | self._cursor.execute('SELECT `id` FROM `Contacts` WHERE `login` == ?', (login,))
152 | try:
153 | return self._cursor.fetchall()[0][0]
154 | except IndexError:
155 | return None
156 |
157 | def add_message(self, login: str, text: str, incoming: bool=False):
158 | contact_id = self.get_contact_id(login)
159 | self._cursor.execute('INSERT INTO `Messages` VALUES (NULL, ?, ?, ?)', (contact_id, int(incoming), text))
160 | self._conn.commit()
161 |
162 | def get_messages(self, login: str):
163 | contact_id = self.get_contact_id(login)
164 | self.cursor.execute('''
165 | SELECT `text`, `incoming`
166 | FROM `Messages`
167 | WHERE `contact_id` == ?
168 | ORDER BY `id`
169 | ''', (contact_id,))
170 | return self._cursor.fetchall()
171 |
172 | def get_contacts(self) -> list:
173 | self._cursor.execute('SELECT `login` FROM `Contacts`')
174 | return [item[0] for item in self._cursor.fetchall()]
175 |
176 | def delete_contact(self, login: str):
177 | self._cursor.execute('DELETE FROM `Contacts` WHERE `login` == ?', (login,))
178 | self._conn.commit()
179 |
180 | def update_contacts(self, server_contacts: list):
181 | """
182 | If contact in client list, but not in server list - delete from client list
183 | If contact in server list, but not in client list - add to client list
184 | """
185 | client_contacts = self.get_contacts()
186 | for contact in client_contacts:
187 | if contact not in server_contacts:
188 | self.delete_contact(contact)
189 | for contact in server_contacts:
190 | if contact not in client_contacts:
191 | self.add_contact(contact)
192 |
193 |
194 | class FileStorage:
195 | pass
196 |
--------------------------------------------------------------------------------
/server/src/test_jim.py:
--------------------------------------------------------------------------------
1 | import pytest
2 |
3 | from jim import *
4 |
5 |
6 | class TestJimMessage:
7 | test = None
8 |
9 | def setup(self):
10 | self.test = JimMessage()
11 |
12 | def teardown(self):
13 | self.test = None
14 |
15 | def test_init__dictionary_empty(self):
16 | assert len(self.test.datadict) == 0
17 |
18 | def test_setfield__correct_data_added(self):
19 | testkey, testval = 'testkey', 'testval'
20 | self.test.set_field(testkey, testval)
21 | assert self.test.datadict[testkey] == testval
22 |
23 | def test_settime__time_field_added_positive_float(self):
24 | self.test.set_time()
25 | time_value = float(self.test.datadict['time'])
26 | assert time_value > 0
27 |
28 | def test_eq__two_empty_messages_return_true(self):
29 | assert JimMessage() == JimMessage()
30 |
31 | def test_eq__one_empty_other_not_empty_return_false(self):
32 | self.test.set_time()
33 | assert self.test != JimMessage()
34 |
35 | def test_eq__both_not_empty_not_equal_return_false(self):
36 | test1, test2 = JimMessage(), JimMessage()
37 | test1.set_field('key1', 'val1')
38 | test2.set_field('key2', 'val2')
39 | assert test1 != test2
40 |
41 | def test_eq__both_not_empty_equal_return_true(self):
42 | test1, test2 = JimMessage(), JimMessage()
43 | testkey, testval = 'key', 'val'
44 | test1.set_field(testkey, testval)
45 | test2.set_field(testkey, testval)
46 | assert test1 == test2
47 |
48 | def test_tobytes__result_not_empty(self):
49 | assert len(JimMessage().to_bytes()) > 0
50 |
51 | def test_frombytes__tobytes_then_frombytes_result_the_same(self):
52 | self.test.set_time()
53 | test_bytes = self.test.to_bytes()
54 | decoded = JimMessage()
55 | decoded.from_bytes(test_bytes)
56 | assert decoded == self.test
57 |
58 | def test_frombytes__incorrect_binary_data_raises(self):
59 | baddata = b'\xde\xad\xbe\xef'
60 | with pytest.raises(UnicodeDecodeError):
61 | self.test.from_bytes(baddata)
62 |
63 |
64 | # tests for: jim_request_from_bytes
65 | def test__jim_request_from_bytes__incorrect_input__raises():
66 | baddata = b'\xde\xad\xbe\xef'
67 | with pytest.raises(UnicodeDecodeError):
68 | request_from_bytes(baddata)
69 |
70 |
71 | def test__jim_request_from_bytes__correct_input__correct_empty_object_created():
72 | test = request_from_bytes(b'{}')
73 | assert len(test.datadict) == 0
74 |
75 |
76 | def test__jim_request_from_bytes__correct_input__correct_not_empty_object_created():
77 | test = request_from_bytes(b'{"key":"val"}')
78 | assert test.datadict['key'] == 'val'
79 |
80 |
81 | class TestJimResponse:
82 | test_response = 123
83 | test_alert = "Test alert"
84 | test_error = "Test error"
85 |
86 | def test_getters_setters__object_is_correct(self):
87 | test = JimResponse()
88 | test.response = self.test_response
89 | assert test.response == self.test_response
90 | assert test.datadict["response"] == self.test_response
91 |
92 | def test_tobytes_frombytes__result_the_same(self):
93 | test = JimResponse()
94 | test.response = self.test_response
95 | test_bytedata = test.to_bytes()
96 | test_from_bytes = JimResponse()
97 | test_from_bytes.from_bytes(test_bytedata)
98 | assert test == test_from_bytes
99 |
100 |
101 | # tests for: jim_response_from_bytes
102 | def test__jim_response_from_bytes__incorrect_input__raises():
103 | bad_data = b'\xde\xad\xbe\xef'
104 | with pytest.raises(UnicodeDecodeError):
105 | response_from_bytes(bad_data)
106 |
107 |
108 | def test__jim_response_from_bytes__input_is_not_response__result_response_is_none():
109 | test = JimRequest()
110 | test.set_field('test_key_1', 'test_val_1')
111 | test.set_field('test_key_2', 'test_val_2')
112 | byte_data = test.to_bytes()
113 | test_from_bytes = response_from_bytes(byte_data)
114 | assert test_from_bytes.response is None
115 |
116 |
117 | def test__jim_response_from_bytes__response_set__correct_result():
118 | test = JimResponse()
119 | test.response = 321
120 | byte_data = test.to_bytes()
121 | actual = response_from_bytes(byte_data)
122 | assert test == actual
123 |
--------------------------------------------------------------------------------
/server/src/test_security.py:
--------------------------------------------------------------------------------
1 | import pytest
2 |
3 | from security import *
4 |
5 |
6 | # tests for create_password_hash()
7 | def test__correct_input__correct_results():
8 | assert create_password_hash('test') is not None
9 | assert isinstance(create_password_hash('test'), str)
10 | assert create_password_hash('test') == create_password_hash('test')
11 | assert len(create_password_hash('test1')) == len(create_password_hash('test2'))
12 | assert create_password_hash('test1') != create_password_hash('test2')
13 | assert create_password_hash('test') != 'test'
14 |
15 |
16 | def test__empty_or_incorrect_input__raises():
17 | with pytest.raises(RuntimeError):
18 | create_password_hash('')
19 | with pytest.raises(RuntimeError):
20 | create_password_hash(None)
21 | with pytest.raises(AttributeError):
22 | create_password_hash(1)
23 | with pytest.raises(AttributeError):
24 | create_password_hash([1, 2, 3])
25 | with pytest.raises(AttributeError):
26 | create_password_hash({'key': 'value'})
27 | # end tests for create_password_hash()
28 |
29 |
30 | # tests for create_auth_token()
31 | def test__values_are_correct():
32 | assert create_auth_token() is not None
33 | assert isinstance(create_auth_token(), str)
34 | assert len(create_auth_token()) == AUTH_TOKEN_LEN * 2
35 | assert create_auth_token() != create_auth_token()
36 | # end tests for create_auth_token()
37 |
38 |
39 | test_secret = 'cafecafe'
40 | test_token = 'fefefefe'
41 |
42 |
43 | # tests for create_auth_digest()
44 | def test__correct_input__correct_output():
45 | assert create_auth_digest(test_secret, test_token) is not None
46 | assert isinstance(create_auth_digest(test_secret, test_token), str)
47 |
48 |
49 | def test__incorrect_input__raises():
50 | with pytest.raises(BaseException):
51 | create_auth_digest('not_hex_string', test_token)
52 | with pytest.raises(BaseException):
53 | create_auth_digest(test_secret, 'not_hex_string')
54 | with pytest.raises(RuntimeError):
55 | create_auth_digest(None, test_token)
56 | with pytest.raises(RuntimeError):
57 | create_auth_digest(test_secret, None)
58 | with pytest.raises(TypeError):
59 | create_auth_digest(1, test_token)
60 | with pytest.raises(TypeError):
61 | create_auth_digest(test_secret, 2)
62 | with pytest.raises(RuntimeError):
63 | create_auth_digest('', test_token)
64 | with pytest.raises(RuntimeError):
65 | create_auth_digest(test_secret, '')
66 | # end tests for create_auth_digest()
67 |
68 |
69 | test_digest = create_auth_digest(test_secret, test_token)
70 |
71 |
72 | # tests for check_auth_digest_equal()
73 | def test__equal_digests__return_true():
74 | digest2 = create_auth_digest(test_secret, test_token)
75 | assert check_auth_digest_equal(test_digest, digest2) is True
76 | assert check_auth_digest_equal(digest2, test_digest) is True
77 |
78 |
79 | def test__different_digests__return_false():
80 | another_secret = 'aabbccddeeff'
81 | another_token = 'ffeeddccbb'
82 | digest2 = create_auth_digest(another_secret, test_token)
83 | assert check_auth_digest_equal(test_digest, digest2) is False
84 | digest3 = create_auth_digest(test_secret, another_token)
85 | assert check_auth_digest_equal(test_digest, digest3) is False
86 | digest4 = create_auth_digest(another_secret, another_token)
87 | assert check_auth_digest_equal(test_digest, digest4) is False
88 | digest5 = create_auth_digest(test_token, test_secret)
89 | assert check_auth_digest_equal(test_digest, digest5) is False
90 |
91 |
92 | def test__input_empty__raises():
93 | with pytest.raises(TypeError):
94 | check_auth_digest_equal(None, test_digest)
95 | with pytest.raises(TypeError):
96 | check_auth_digest_equal(test_digest, None)
97 | # end tests for check_auth_digest_equal()
98 |
--------------------------------------------------------------------------------
/server/src/test_server.py:
--------------------------------------------------------------------------------
1 | import pytest
2 |
3 | from server import parse_commandline_args, Server
4 | from helpers import DEFAULT_SERVER_PORT
5 |
6 |
7 | # tests for: parse_commandline_args
8 | test_ip = '1.2.3.4'
9 | test_port = '55555'
10 |
11 |
12 | def test_none_args_set__results_are_default_values():
13 | args = parse_commandline_args([])
14 | assert args.listen_address == ''
15 | assert args.listen_port == DEFAULT_SERVER_PORT
16 |
17 |
18 | def test_address_arg_set__one_result_is_correct_other_is_default():
19 | args = parse_commandline_args(['-a', test_ip])
20 | assert args.listen_address == test_ip
21 | assert args.listen_port == DEFAULT_SERVER_PORT
22 |
23 |
24 | def test_port_arg_set__one_result_is_correct_other_is_default():
25 | args = parse_commandline_args(['-p', test_port])
26 | assert args.listen_address == ''
27 | assert args.listen_port == int(test_port)
28 |
29 |
30 | def test_two_args_set__both_results_are_correct():
31 | args = parse_commandline_args(['-a', test_ip, '-p', test_port])
32 | assert args.listen_address == test_ip
33 | assert args.listen_port == int(test_port)
34 |
35 |
36 | def test_unknown_args__raises():
37 | with pytest.raises(SystemExit):
38 | parse_commandline_args(['-z', 'zzz'])
39 |
40 |
41 | class TestServer:
42 | def test__init__no_errors(self):
43 | Server(':memory:')
44 |
45 | def test__set_settings__correct_settings_no_errors(self):
46 | test_server = Server(':memory:')
47 | test_server.set_settings('', int(test_port), clients_limit=1000, timeout=1)
48 |
--------------------------------------------------------------------------------
/server/src/test_storage.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | import sqlite3
3 |
4 | from storage import DBStorageServer, DBStorageClient
5 |
6 |
7 | class TestDBStorageServer:
8 | test_db = ':memory:'
9 | test_login = 'TestLogin'
10 | test_time = 123456
11 | test_ip = '1.2.3.4'
12 | test_info = 'test_info'
13 | test_second_login = 'TestLogin2'
14 |
15 | def setup(self):
16 | self.storage = DBStorageServer(self.test_db)
17 | self.conn = self.storage.conn
18 | self.cursor = self.storage.cursor
19 |
20 | def test__init__tables_created(self):
21 | self.cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
22 | table_names = [t[0] for t in self.cursor.fetchall()]
23 | assert 'Clients' in table_names
24 | assert 'ClientContacts' in table_names
25 |
26 | def test__get_client_id__client_exists__return_correct_id(self):
27 | self.cursor.execute(f'INSERT INTO `Clients` VALUES (NULL, ?, NULL, NULL, NULL)', (self.test_login,))
28 | self.conn.commit()
29 | actual = self.storage.get_client_id(self.test_login)
30 | assert actual == 1
31 |
32 | def test__get_client_id__no_such_client__raises(self):
33 | with pytest.raises(IndexError):
34 | self.storage.get_client_id(self.test_login)
35 | # assert self.storage.get_client_id(self.test_login) is None
36 |
37 | def test__get_client_id___input_none_or_empty__return_none(self):
38 | with pytest.raises(IndexError):
39 | self.storage.get_client_id(None)
40 | with pytest.raises(IndexError):
41 | self.storage.get_client_id('')
42 |
43 | def test__get_client_id__input_collection__raises(self):
44 | with pytest.raises(sqlite3.Error):
45 | self.storage.get_client_id([1, 2, 3])
46 | with pytest.raises(sqlite3.Error):
47 | self.storage.get_client_id({})
48 |
49 | def test__add_new_client__correct_input__can_find_client_by_login(self):
50 | self.storage.add_client(self.test_login)
51 | assert self.storage.get_client_id(self.test_login) == 1
52 |
53 | def test__add_new_client__already_exists__raises(self):
54 | with pytest.raises(sqlite3.Error):
55 | self.storage.add_client(self.test_login)
56 | self.storage.add_client(self.test_login)
57 |
58 | def test__add_new_client__login_none_or_empty__raises(self):
59 | with pytest.raises(ValueError):
60 | self.storage.add_client(None)
61 | with pytest.raises(ValueError):
62 | self.storage.add_client('')
63 |
64 | def test__add_new_client__login_not_str__raises(self):
65 | with pytest.raises(sqlite3.Error):
66 | self.storage.add_client([1, 2])
67 | with pytest.raises(ValueError):
68 | self.storage.add_client({})
69 |
70 | def test__update_client__client_exists__correct_parameters_in_table(self):
71 | self.storage.add_client(self.test_login)
72 | client_id = self.storage.get_client_id(self.test_login)
73 |
74 | self.storage.update_client(self.test_login, self.test_time, self.test_ip, self.test_info)
75 | self.cursor.execute('SELECT login, info, last_connect_time, last_connect_ip FROM Clients WHERE id == ?',
76 | (client_id,))
77 | actual_values = self.cursor.fetchall()
78 | assert actual_values[0] == (self.test_login, self.test_info, self.test_time, self.test_ip)
79 |
80 | def test__update_client__info_is_none__correct_parameters_in_table(self):
81 | self.storage.add_client(self.test_login)
82 | client_id = self.storage.get_client_id(self.test_login)
83 |
84 | self.storage.update_client(self.test_login, self.test_time, self.test_ip)
85 |
86 | self.cursor.execute('SELECT login, info, last_connect_time, last_connect_ip FROM Clients WHERE id == ?',
87 | (client_id,))
88 | actual_values = self.cursor.fetchall()
89 | assert actual_values[0] == (self.test_login, None, self.test_time, self.test_ip)
90 |
91 | def test__add_client_to_contacts__client_not_in_contacts__client_added(self):
92 | self.storage.add_client(self.test_login)
93 | self.storage.add_client(self.test_second_login)
94 | first_client_id = self.storage.get_client_id(self.test_login)
95 | second_client_id = self.storage.get_client_id(self.test_second_login)
96 |
97 | self.storage.add_client_to_contacts(self.test_login, self.test_second_login)
98 |
99 | self.cursor.execute('SELECT COUNT() FROM `ClientContacts` WHERE `owner_id` == ? AND `contact_id` == ?;',
100 | (first_client_id, second_client_id))
101 | assert self.cursor.fetchall()[0][0] == 1
102 |
103 | def test__add_client_to_contacts_clients_add_each_other__no_errors(self):
104 | self.storage.add_client(self.test_login)
105 | self.storage.add_client(self.test_second_login)
106 | self.storage.add_client_to_contacts(self.test_login, self.test_second_login)
107 | self.storage.add_client_to_contacts(self.test_second_login, self.test_login)
108 |
109 | def test__add_client_to_contacts__client_already_in_contacts__raises(self):
110 | self.storage.add_client(self.test_login)
111 | self.storage.add_client(self.test_second_login)
112 | self.storage.add_client_to_contacts(self.test_login, self.test_second_login)
113 | with pytest.raises(sqlite3.Error):
114 | self.storage.add_client_to_contacts(self.test_login, self.test_second_login)
115 |
116 | def test__add_client_to_contacts__incorrect_input__raises(self):
117 | with pytest.raises(IndexError):
118 | self.storage.add_client_to_contacts(None, {})
119 | with pytest.raises(sqlite3.InterfaceError):
120 | self.storage.add_client_to_contacts({}, None)
121 |
122 | def test__check_client_in_contacts__client_in_contacts__return_true(self):
123 | self.storage.add_client(self.test_login)
124 | self.storage.add_client(self.test_second_login)
125 | self.storage.add_client_to_contacts(self.test_login, self.test_second_login)
126 | assert self.storage.check_client_in_contacts(self.test_login, self.test_second_login) is True
127 |
128 | def test__check_client_in_contacts__client_not_in_contacts__return_false(self):
129 | self.storage.add_client(self.test_login)
130 | self.storage.add_client(self.test_second_login)
131 | assert self.storage.check_client_in_contacts(self.test_login, self.test_second_login) is False
132 |
133 | def test__check_client_in_contacts__incorrect_input__raises(self):
134 | with pytest.raises(IndexError):
135 | self.storage.check_client_in_contacts('qwerty', 'asdfgh')
136 | with pytest.raises(IndexError):
137 | self.storage.check_client_in_contacts(None, None)
138 |
139 |
140 | class TestDBStorageClient:
141 | test_db = ':memory:'
142 | test_login = 'TestLogin'
143 | test_second_login = 'TestLogin2'
144 | test_message = 'Test message'
145 |
146 | def setup(self):
147 | self.storage = DBStorageClient(self.test_db)
148 | self.conn = self.storage.conn
149 | self.cursor = self.storage.cursor
150 |
151 | def test__init__tables_created(self):
152 | self.cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
153 | table_names = [t[0] for t in self.cursor.fetchall()]
154 | assert 'Contacts' in table_names
155 | assert 'Messages' in table_names
156 |
157 | def test__add_new_contact__not_added_yet__correct_row_added(self):
158 | self.storage.add_contact(self.test_login)
159 | self.cursor.execute('SELECT `login` FROM `Contacts` WHERE `id` == 1')
160 | assert self.cursor.fetchall()[0][0] == self.test_login
161 |
162 | def test__add_new_contact__already_added__raises(self):
163 | self.storage.add_contact(self.test_login)
164 | with pytest.raises(sqlite3.Error):
165 | self.storage.add_contact(self.test_login)
166 |
167 | def test__add_new_contact__input_incorrect__raises(self):
168 | with pytest.raises(sqlite3.Error):
169 | self.storage.add_contact(None)
170 | with pytest.raises(sqlite3.Error):
171 | self.storage.add_contact({})
172 |
173 | def test__get_contact_id__contact_exists__return_correct_value(self):
174 | self.storage.add_contact(self.test_login)
175 | assert self.storage.get_contact_id(self.test_login) == 1
176 |
177 | def test__get_contact_id__no_such_contact__return_none(self):
178 | assert self.storage.get_contact_id(self.test_login) is None
179 |
180 | def test__get_contact_id__input_none__return_none(self):
181 | assert self.storage.get_contact_id(None) is None
182 |
183 | def test__add_new_message__input_ok_incoming__correct_row_added(self):
184 | self.storage.add_contact(self.test_login)
185 | self.storage.add_message(self.test_login, self.test_message, True)
186 | self.cursor.execute('SELECT * FROM `Messages`')
187 | result = self.cursor.fetchall()
188 | assert len(result) == 1
189 | assert result[0] == (1, 1, int(True), self.test_message)
190 |
191 | def test__add_new_message__input_ok_outcoming__correct_row_added(self):
192 | self.storage.add_contact(self.test_login)
193 | self.storage.add_message(self.test_login, self.test_message)
194 | self.cursor.execute('SELECT * FROM `Messages`')
195 | result = self.cursor.fetchall()
196 | assert len(result) == 1
197 | assert result[0] == (1, 1, int(False), self.test_message)
198 |
199 | def test__add_new_message__input_incorrect__raises(self):
200 | with pytest.raises(sqlite3.Error):
201 | self.storage.add_message(None, self.test_message, True)
202 |
203 | self.storage.add_contact(self.test_login)
204 | with pytest.raises(TypeError):
205 | self.storage.add_message(1, self.test_message, None)
206 | with pytest.raises(sqlite3.Error):
207 | self.storage.add_message(1, None, True)
208 | with pytest.raises(sqlite3.Error):
209 | self.storage.add_message(1, None, False)
210 |
--------------------------------------------------------------------------------
/server/src/update_ui.bat:
--------------------------------------------------------------------------------
1 | "c:\Program Files (x86)\Python36-32\Scripts\pyuic5.exe" server_gui.ui -o server_pyqt.py
--------------------------------------------------------------------------------