├── .gitignore
├── .vscode
└── launch.json
├── LICENSE
├── README.md
├── analysis_options.yaml
├── bin
├── config
│ └── example.env.config.json
├── libs
│ ├── sqlite3.dll
│ └── sqlite3.so
└── suai_leetcode_bot.dart
├── build.bat
├── build.sh
├── build.yaml
├── lib
├── bot
│ ├── repositories
│ │ ├── runtime_repository.dart
│ │ └── telegram_state_repository.dart
│ ├── scopes
│ │ ├── admin
│ │ │ ├── admin_query_event.dart
│ │ │ ├── admin_scope.dart
│ │ │ └── admin_state.dart
│ │ ├── register
│ │ │ ├── register_query_event.dart
│ │ │ ├── register_scope.dart
│ │ │ └── register_state.dart
│ │ ├── telegram_scope.dart
│ │ └── user
│ │ │ ├── user_query_event.dart
│ │ │ ├── user_scope.dart
│ │ │ └── user_state.dart
│ └── telegram_bot.dart
├── config
│ └── config.dart
├── constants
│ ├── crud.dart
│ └── group_numbers.dart
├── data
│ ├── api
│ │ └── leetcode_api.dart
│ ├── database
│ │ └── database.dart
│ └── repositories
│ │ └── leetcode_repository.dart
├── extensions
│ ├── file_extensions.dart
│ ├── int_extensions.dart
│ └── string_extensions.dart
└── service
│ ├── leetcode_service.dart
│ └── logger_service.dart
└── pubspec.yaml
/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://www.dartlang.org/guides/libraries/private-files
2 |
3 | # Files and directories created by pub
4 | .dart_tool/
5 | .packages
6 | build/
7 | # If you're building an application, you may want to check-in your pubspec.lock
8 | pubspec.lock
9 |
10 | # Directory created by dartdoc
11 | # If you don't generate documentation locally you can remove this line.
12 | doc/api/
13 |
14 | # Database
15 | *.sqlite
16 | db/
17 |
18 | # Codegen
19 | *.g.dart
20 |
21 | # Logs
22 | *.log
23 | *.logs
24 |
25 | # dotenv environment variables file
26 | .env*
27 | env.*
28 |
29 | # Avoid committing generated Javascript files:
30 | *.dart.js
31 | *.info.json # Produced by the --dump-info flag.
32 | *.js # When generated by dart2js. Don't specify *.js if your
33 | # project includes source files written in JavaScript.
34 | *.js_
35 | *.js.deps
36 | *.js.map
37 |
38 | .flutter-plugins
39 | .flutter-plugins-dependencies
40 |
--------------------------------------------------------------------------------
/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | // Use IntelliSense to learn about possible attributes.
3 | // Hover to view descriptions of existing attributes.
4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5 | "version": "0.2.0",
6 | "configurations": [
7 | {
8 | "name": "suai_leetcode_bot",
9 | "request": "launch",
10 | "type": "dart",
11 | "program": "${workspaceFolder}\\bin\\suai_leetcode_bot.dart",
12 | }
13 | ]
14 | }
15 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # SUAI Leetcode Bot
2 |
3 | ## Overview
4 | The "SUAI Leetcode Bot" is a Telegram bot designed for the sport programming club of the SUAI University. This project aims to facilitate an interactive and efficient way for club members to engage with programming challenges on Leetcode.
5 |
6 | ## Features
7 | - **Challenge Tracking**: Users can track which problems from a predefined list have been solved or are still pending.
8 | - **Progress Monitoring**: The bot allows the administration to monitor the number of problems solved by each member, enhancing the ability to track individual progress.
9 | - **Statistics and Reporting**: Administrators can access detailed statistics about the problems, including the ability to export data in table format for further analysis.
10 |
11 | ## Usage
12 | 1. **For Users**
13 | - View the list of assigned Leetcode problems.
14 | - Check off problems as you solve them.
15 | - Track your progress and compare with peers.
16 |
17 | 2. **For Administrators**
18 | - Monitor overall progress of all members.
19 | - Access detailed statistics and insights on problem-solving trends.
20 | - Export data for record-keeping and detailed analysis.
21 |
22 | ## Build
23 | To build and run the SUAI Leetcode Bot:
24 | 1. Clone this repository.
25 | 2. Install the Dart SDK if you haven't already: [Get Dart](https://dart.dev/get-dart)
26 | 3. In the cloned repository's folder, run `build.bat` (for Windows) or `build.sh` (for Linux) as an administrator.
27 | 4. The compiled project will be available in the `build` folder.
28 | 5. In the `build/config` folder, set your Telegram bot token.
29 | 6. The project is now ready to run.
30 |
31 | ## Support and Contact
32 | For support or inquiries about the SUAI Leetcode Bot, please reach out to us via [Telegram](https://t.me/cocahonka).
33 |
34 | ## License
35 | This project is licensed under the [AGPL License](LICENSE).
36 |
--------------------------------------------------------------------------------
/analysis_options.yaml:
--------------------------------------------------------------------------------
1 | include: package:very_good_analysis/analysis_options.yaml
2 | linter:
3 | rules:
4 | public_member_api_docs: false
5 | lines_longer_than_80_chars: false
6 | library_private_types_in_public_api: false
7 |
--------------------------------------------------------------------------------
/bin/config/example.env.config.json:
--------------------------------------------------------------------------------
1 | {
2 | "telegramToken": "YOUR_BOT_TOKEN",
3 | "leetCodeUpdateIntervalInSeconds": 900,
4 | "leetCodeUpdateCoolingTimeInSeconds": 150,
5 | "leetCodeBatchRequestSize": 1,
6 | "messages": {
7 | "register": {
8 | "onStart": "Привет! На связи бот для кружка АиСД. Я буду следить за твоей домашкой.",
9 | "requestName": "Введите ваше реальное имя и фамилию через пробел",
10 | "invalidName": "Имя и фамилия должны быть написаны на русском языке и разделены одним пробелом",
11 | "requestGroupNumber": "Введите номер группы в ВУЗе",
12 | "invalidGroupNumber": "Неверный номер группы",
13 | "requestLeetCodeNickname": "Введите никнейм литкода",
14 | "invalidLeetCodeNickname": "Неверный никнейм",
15 | "leetCodeNicknameIsAlreadyTaken": "Данный никнейм уже зарегистрирован в боте",
16 | "leetCodeNicknameNotExist": "Такого никнейма не существует",
17 | "successfulRegistration": "Аккаунт успешно создан!",
18 | "restartRegistration": "Регистрация успешно сброшена",
19 | "leetCodeNicknameGetError": "Произошла ошибка при попытке обратиться к LeetCode, сообщите об этом Булату"
20 | },
21 | "user": {
22 | "chooseMenuItem": "Выберите действие",
23 | "aboutClubCaption": "О кружке",
24 | "aboutClubLink": "https://vk.com/suai_it",
25 | "olympiadsCaption": "Олимпиады",
26 | "olympiadsLink": "https://vk.com/@suai_it-olimpiady",
27 | "joinClubCaption": "Записаться",
28 | "joinClubLink": "https://vk.com/write-224458729",
29 | "categoryListCaption": "Список категорий",
30 | "backToMenu": "Назад в меню",
31 | "backToCategories": "Назад в категории",
32 | "chooseCategory": "Выберите категорию",
33 | "taskLinkCaption": "ссылка",
34 | "howItWorks": "1) Бот обновляется раз в 32.5 минуты\n2) Старые решенные задачи нужно отправить еще раз\n3) За раз бот может считать только 10 последних попыток",
35 | "whenNextUpdate": "Следующее обновление решенных заданий будет $"
36 | },
37 | "admin": {
38 | "logsIsEmpty": "Файл логов пустой!",
39 | "exportLogs": "Выгрузить логи",
40 | "chooseMenuItem": "Выберите действие",
41 | "exportRating": "Выгрузить рейтинг",
42 | "exportRatingFilename": "Rating $.xlsx",
43 | "exportRatingSaveFail": "Не удалось составить таблицу :(",
44 | "exportRatingUnknownUsername": "unknown",
45 | "exportCategories": "Выгрузить категории",
46 | "exportCategoriesFilename": "Categories $.json",
47 | "crudCategories": "Внести изменения",
48 | "crudCancel": "Назад",
49 | "crudInvalidMimeType": "Нужно прислать файл .json, попробуйте еще раз!",
50 | "crudFileDownloadError": "Произошла ошибка при скачивании файла",
51 | "crudFileFormatError": "Файл не соответсвует формату example.json или не выполнены условия из правил, попробуйте еще раз!",
52 | "crudDatabaseUnknownError": "Произошла ошибка: $\n, попробуйте еще раз",
53 | "crudSuccessful": "Изменения успешно внесены!",
54 | "crudHelpMessage": "Если вы хотите внести изменения в категории или задачи то отправьте заполненный json файл или отмените операцию.\nПравила:\n1. В прикрепленном файле (example.json) содержится пример заполнения изменений.\n2. В прикрепленном файле (form.json) содержится форма для заполнения.\n3. При создании следует указать все поля.\n4. При обновлении следует следует указать id или slug, другие поля опциональны.\n5. При удалении следует указать только id или slug.\n6. При создании заданий необходимо знать id категории, для этого сначала создайте категорию, а потом выгрузите категорию, в выгруженном файле будут id категорий.",
55 | "exit": "Выход"
56 | }
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/bin/libs/sqlite3.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cocahonka/suai-leetcode-bot/a7617206765dcb5482894d659ad08cc6b3588521/bin/libs/sqlite3.dll
--------------------------------------------------------------------------------
/bin/libs/sqlite3.so:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cocahonka/suai-leetcode-bot/a7617206765dcb5482894d659ad08cc6b3588521/bin/libs/sqlite3.so
--------------------------------------------------------------------------------
/bin/suai_leetcode_bot.dart:
--------------------------------------------------------------------------------
1 | import 'dart:convert';
2 | import 'dart:ffi';
3 | import 'dart:io';
4 |
5 | import 'package:http/http.dart' as http;
6 | import 'package:path/path.dart' as path;
7 | import 'package:sqlite3/open.dart' as sqlite;
8 | import 'package:suai_leetcode_bot/bot/repositories/runtime_repository.dart';
9 | import 'package:suai_leetcode_bot/bot/scopes/admin/admin_scope.dart';
10 | import 'package:suai_leetcode_bot/bot/scopes/admin/admin_state.dart';
11 | import 'package:suai_leetcode_bot/bot/scopes/register/register_scope.dart';
12 | import 'package:suai_leetcode_bot/bot/scopes/register/register_state.dart';
13 | import 'package:suai_leetcode_bot/bot/scopes/telegram_scope.dart';
14 | import 'package:suai_leetcode_bot/bot/scopes/user/user_scope.dart';
15 | import 'package:suai_leetcode_bot/bot/scopes/user/user_state.dart';
16 | import 'package:suai_leetcode_bot/bot/telegram_bot.dart';
17 | import 'package:suai_leetcode_bot/config/config.dart';
18 | import 'package:suai_leetcode_bot/data/api/leetcode_api.dart';
19 | import 'package:suai_leetcode_bot/data/database/database.dart';
20 | import 'package:suai_leetcode_bot/data/repositories/leetcode_repository.dart';
21 | import 'package:suai_leetcode_bot/service/leetcode_service.dart';
22 |
23 | void main() async {
24 | sqlite.open
25 | ..overrideFor(sqlite.OperatingSystem.linux, _openOnLinux)
26 | ..overrideFor(sqlite.OperatingSystem.windows, _openOnWindows);
27 |
28 | final database = AppDatabase();
29 | final config = _readConfig();
30 | final httpClient = http.Client();
31 |
32 | final leetCodeRepository = HttpLeetCodeRepository(
33 | api: const LeetCodeApi(),
34 | client: httpClient,
35 | );
36 |
37 | final registerRepository = RuntimeRepository(initialState: const RegisterInitial());
38 | for (final User(:telegramId) in await database.authorizedUsers) {
39 | registerRepository.setState(chatId: telegramId, state: const RegisterCompleted());
40 | }
41 |
42 | final userScope = UserScope(
43 | messages: config.userMessages,
44 | database: database,
45 | repository: RuntimeRepository(initialState: const UserInitial()),
46 | );
47 |
48 | final registerScope = RegisterScope(
49 | messages: config.registerMessages,
50 | database: database,
51 | repository: registerRepository,
52 | leetCodeRepository: leetCodeRepository,
53 | onStateComplete: userScope.executeInitialStatePoint,
54 | );
55 |
56 | final adminScope = AdminScope(
57 | database: database,
58 | messages: config.adminMessages,
59 | repository: RuntimeRepository(initialState: const AdminInitial()),
60 | registerRepository: registerRepository,
61 | onStateComplete: userScope.executeInitialStatePoint,
62 | );
63 |
64 | final scopes = >[userScope, adminScope, registerScope];
65 |
66 | TelegramBot(
67 | config: config,
68 | scopes: scopes,
69 | ).start();
70 |
71 | LeetCodeService(
72 | leetCodeUpdateIntervalInSeconds: config.leetCodeUpdateIntervalInSeconds,
73 | leetCodeUpdateCoolingTimeInSeconds: config.leetCodeUpdateCoolingTimeInSeconds,
74 | leetCodeBatchRequestSize: config.leetCodeBatchRequestSize,
75 | database: database,
76 | leetCodeRepository: leetCodeRepository,
77 | ).start();
78 | }
79 |
80 | Config _readConfig() {
81 | final scriptFolderPath = File(Platform.script.toFilePath()).parent.path;
82 | final configFolderPath = path.join(scriptFolderPath, 'config');
83 | final jsonConfig = File(path.join(configFolderPath, 'env.config.json'));
84 |
85 | final content = jsonConfig.readAsStringSync();
86 | final json = jsonDecode(content) as Map;
87 | return Config.fromJson(json);
88 | }
89 |
90 | DynamicLibrary _openOnLinux() {
91 | final scriptFolderPath = File(Platform.script.toFilePath()).parent.path;
92 | final libsFolderPath = path.join(scriptFolderPath, 'libs');
93 | final libraryNextToDatabase = path.join(libsFolderPath, 'sqlite3.so');
94 | return DynamicLibrary.open(libraryNextToDatabase);
95 | }
96 |
97 | DynamicLibrary _openOnWindows() {
98 | final scriptFolderPath = File(Platform.script.toFilePath()).parent.path;
99 | final libsFolderPath = path.join(scriptFolderPath, 'libs');
100 | final libraryNextToDatabase = path.join(libsFolderPath, 'sqlite3.dll');
101 | return DynamicLibrary.open(libraryNextToDatabase);
102 | }
103 |
--------------------------------------------------------------------------------
/build.bat:
--------------------------------------------------------------------------------
1 | @echo off
2 | echo Building SUAI LeetCode Bot
3 |
4 | md build
5 | md build\config
6 | md build\libs
7 | md build\db
8 | md build\logs
9 |
10 | dart pub get
11 | dart pub run build_runner build --delete-conflicting-outputs
12 | dart compile exe bin/suai_leetcode_bot.dart -o build/suai_leetcode_bot.exe
13 |
14 | copy bin\config\example.env.config.json build\config\env.config.json
15 | copy bin\libs\sqlite3.dll build\libs\sqlite3.dll
16 |
17 | echo Build complete
18 |
--------------------------------------------------------------------------------
/build.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | echo "Building SUAI LeetCode Bot"
4 |
5 | mkdir -p build/config
6 | mkdir -p build/libs
7 | mkdir -p build/db
8 | mkdir -p build/logs
9 |
10 | dart pub get
11 | dart pub run build_runner build --delete-conflicting-outputs
12 | dart compile exe bin/suai_leetcode_bot.dart -o build/suai_leetcode_bot
13 |
14 | cp bin/config/example.env.config.json build/config/env.config.json
15 | cp bin/libs/sqlite3.so build/libs/sqlite3.so
16 |
17 | echo "Build complete"
18 |
--------------------------------------------------------------------------------
/build.yaml:
--------------------------------------------------------------------------------
1 | targets:
2 | $default:
3 | builders:
4 | drift_dev:
5 | generate_for:
6 | - lib/data/database/*.dart
7 |
--------------------------------------------------------------------------------
/lib/bot/repositories/runtime_repository.dart:
--------------------------------------------------------------------------------
1 | import 'package:suai_leetcode_bot/bot/repositories/telegram_state_repository.dart';
2 |
3 | final class RuntimeRepository extends TelegramStateRepository {
4 | RuntimeRepository({required super.initialState});
5 |
6 | final Map _states = {};
7 |
8 | @override
9 | State getState({required int chatId}) => _states.putIfAbsent(chatId, () => super.initialState);
10 |
11 | @override
12 | void setState({required int chatId, required State state}) => _states[chatId] = state;
13 | }
14 |
--------------------------------------------------------------------------------
/lib/bot/repositories/telegram_state_repository.dart:
--------------------------------------------------------------------------------
1 | abstract base class TelegramStateRepository {
2 | const TelegramStateRepository({required this.initialState});
3 |
4 | final State initialState;
5 |
6 | State getState({required int chatId});
7 | void setState({required int chatId, required State state});
8 | }
9 |
--------------------------------------------------------------------------------
/lib/bot/scopes/admin/admin_query_event.dart:
--------------------------------------------------------------------------------
1 | enum AdminQueryEvent {
2 | exportRating(),
3 | exportCategories(),
4 | exportLogs(),
5 | requestCRUD(),
6 | cancelCRUD(),
7 | exit();
8 |
9 | const AdminQueryEvent();
10 | }
11 |
--------------------------------------------------------------------------------
/lib/bot/scopes/admin/admin_scope.dart:
--------------------------------------------------------------------------------
1 | import 'dart:async';
2 | import 'dart:collection';
3 | import 'dart:convert';
4 | import 'dart:typed_data';
5 |
6 | import 'package:collection/collection.dart';
7 | import 'package:excel/excel.dart';
8 | import 'package:suai_leetcode_bot/bot/repositories/telegram_state_repository.dart';
9 | import 'package:suai_leetcode_bot/bot/scopes/admin/admin_query_event.dart';
10 | import 'package:suai_leetcode_bot/bot/scopes/admin/admin_state.dart';
11 | import 'package:suai_leetcode_bot/bot/scopes/register/register_state.dart';
12 | import 'package:suai_leetcode_bot/bot/scopes/telegram_scope.dart';
13 | import 'package:suai_leetcode_bot/config/config.dart';
14 | import 'package:suai_leetcode_bot/constants/crud.dart';
15 | import 'package:suai_leetcode_bot/data/database/database.dart';
16 | import 'package:suai_leetcode_bot/extensions/file_extensions.dart';
17 | import 'package:suai_leetcode_bot/service/logger_service.dart';
18 | import 'package:televerse/telegram.dart';
19 | import 'package:televerse/televerse.dart';
20 |
21 | final class AdminScope extends TelegramScope {
22 | const AdminScope({
23 | required AppDatabase database,
24 | required AdminMessages messages,
25 | required TelegramStateRepository registerRepository,
26 | required super.repository,
27 | required super.onStateComplete,
28 | }) : _database = database,
29 | _messages = messages,
30 | _registerRepository = registerRepository;
31 |
32 | final AppDatabase _database;
33 | final AdminMessages _messages;
34 | final TelegramStateRepository _registerRepository;
35 |
36 | @override
37 | String get identificator => 'admin_scope';
38 |
39 | @override
40 | RegExp get commands => RegExp(r'^\/admin$');
41 |
42 | Future _isAdmin(int chatId) async {
43 | return _registerRepository.getState(chatId: chatId) is RegisterCompleted && await _database.isAdmin(chatId);
44 | }
45 |
46 | @override
47 | FutureOr callbackOnCommand(Context context) async {
48 | if (context.chat?.isForum ?? false) return;
49 |
50 | final chatId = context.chat!.id;
51 | final command = context.message!.text!;
52 |
53 | if (!await _isAdmin(chatId)) return;
54 |
55 | if (RegExp('admin').hasMatch(command)) {
56 | repository.setState(chatId: chatId, state: const AdminWork());
57 | await callbackOnMessage(context);
58 | }
59 | }
60 |
61 | @override
62 | bool predicate(Context context) {
63 | if (context.chat?.isForum ?? false) return false;
64 |
65 | final chatId = context.chat?.id;
66 | final message = context.message;
67 |
68 | if (chatId == null || message == null) return false;
69 | return repository.getState(chatId: chatId) is! AdminInitial;
70 | }
71 |
72 | @override
73 | FutureOr callbackOnMessage(Context context) async {
74 | final chatId = context.chat!.id;
75 |
76 | if (!await _isAdmin(chatId)) return;
77 |
78 | switch (repository.getState(chatId: chatId)) {
79 | case AdminWaitForCRUD():
80 | await _takeCRUDForm(context);
81 | case AdminWork():
82 | await context.reply(
83 | _messages.chooseMenuItem,
84 | replyMarkup: InlineKeyboard()
85 | .add(_messages.exportRating, '${identificator}_${AdminQueryEvent.exportRating.name}')
86 | .row()
87 | .add(_messages.exportCategories, '${identificator}_${AdminQueryEvent.exportCategories.name}')
88 | .row()
89 | .add(_messages.crudCategories, '${identificator}_${AdminQueryEvent.requestCRUD.name}')
90 | .row()
91 | .add(_messages.exportLogs, '${identificator}_${AdminQueryEvent.exportLogs.name}')
92 | .row()
93 | .add(_messages.exit, '${identificator}_${AdminQueryEvent.exit.name}')
94 | .row(),
95 | );
96 | case AdminInitial():
97 | }
98 | }
99 |
100 | @override
101 | FutureOr callbackOnQuery(Context context) async {
102 | if (context.chat?.isForum ?? false) return;
103 |
104 | final chatId = context.chat!.id;
105 | if (!await _isAdmin(chatId)) return;
106 |
107 | await context.answerCallbackQuery();
108 |
109 | final queryData = context.callbackQuery!.data!;
110 | final queryEventIdentificator = queryPattern.firstMatch(queryData)!.group(1)!;
111 | final queryEvent = AdminQueryEvent.values.firstWhereOrNull((value) => value.name == queryEventIdentificator);
112 |
113 | switch (queryEvent) {
114 | case AdminQueryEvent.exportRating:
115 | await _exportRating(context);
116 | case AdminQueryEvent.exportCategories:
117 | await _exportCategories(context);
118 | case AdminQueryEvent.exportLogs:
119 | await _exportLogs(context);
120 | case AdminQueryEvent.requestCRUD:
121 | await _requestCRUD(context);
122 | case AdminQueryEvent.cancelCRUD:
123 | await _cancelCRUD(context);
124 | case AdminQueryEvent.exit:
125 | await _exit(context);
126 | case null:
127 | }
128 | }
129 |
130 | Future _takeCRUDForm(Context context) async {
131 | final chatId = context.chat!.id;
132 | final document = context.message!.document;
133 |
134 | if (document == null && document?.mimeType != 'application/json') {
135 | await context.reply(
136 | _messages.crudInvalidMimeType,
137 | replyMarkup: InlineKeyboard()
138 | .add(
139 | _messages.crudCancel,
140 | '${identificator}_${AdminQueryEvent.cancelCRUD.name}',
141 | )
142 | .row(),
143 | );
144 | return;
145 | }
146 |
147 | const jsonDecoder = JsonDecoder();
148 | const utf8Decoder = Utf8Decoder();
149 |
150 | final Map json;
151 |
152 | try {
153 | final file = await context.getFile();
154 | final fileBytes = (await file.getBytes())!.toList();
155 | final fileContent = utf8Decoder.convert(fileBytes);
156 | json = jsonDecoder.convert(fileContent) as Map;
157 | } on Exception catch (e, s) {
158 | LoggerService().writeError(e, s);
159 | await context.reply(_messages.crudFileDownloadError);
160 | repository.setState(chatId: chatId, state: const AdminWork());
161 | callbackOnMessage(context);
162 | return;
163 | }
164 |
165 | final operations = _getParsedCRUD(json);
166 |
167 | if (operations == null) {
168 | await context.reply(
169 | _messages.crudFileFormatError,
170 | replyMarkup:
171 | InlineKeyboard().add(_messages.crudCancel, '${identificator}_${AdminQueryEvent.cancelCRUD.name}').row(),
172 | );
173 | return;
174 | }
175 |
176 | final result = await _database.processCRUD(operations);
177 | if (result != null) {
178 | final (e, s) = result;
179 | await context.reply(
180 | _messages.crudDatabaseUnknownError.replaceFirst(r'$', e.toString()),
181 | replyMarkup: InlineKeyboard()
182 | .add(
183 | _messages.crudCancel,
184 | '${identificator}_${AdminQueryEvent.cancelCRUD.name}',
185 | )
186 | .row(),
187 | );
188 |
189 | LoggerService().writeError(e is Exception ? e : Exception(e), s);
190 | return;
191 | }
192 |
193 | await context.reply(_messages.crudSuccessful);
194 | repository.setState(chatId: chatId, state: const AdminWork());
195 | callbackOnMessage(context);
196 | }
197 |
198 | CRUDOperations? _getParsedCRUD(Map json) {
199 | switch (json) {
200 | case {
201 | 'categories': {
202 | 'operations': {
203 | 'create': final List categoriesCreate,
204 | 'update': final List categoriesUpdate,
205 | 'delete': final List categoriesDelete,
206 | },
207 | },
208 | 'tasks': {
209 | 'operations': {
210 | 'create': final List tasksCreate,
211 | 'update': final List tasksUpdate,
212 | 'delete': final List tasksDelete,
213 | },
214 | },
215 | }:
216 | {
217 | return (
218 | categories: CRUD(
219 | create: categoriesCreate,
220 | update: categoriesUpdate,
221 | delete: categoriesDelete,
222 | ),
223 | tasks: CRUD(
224 | create: tasksCreate,
225 | update: tasksUpdate,
226 | delete: tasksDelete,
227 | )
228 | );
229 | }
230 | }
231 |
232 | return null;
233 | }
234 |
235 | Future _exit(Context context) async {
236 | final chatId = context.chat!.id;
237 | repository.setState(chatId: chatId, state: const AdminInitial());
238 | onStateComplete?.call(context);
239 | }
240 |
241 | Future _cancelCRUD(Context context) async {
242 | final chatId = context.chat!.id;
243 |
244 | repository.setState(chatId: chatId, state: const AdminWork());
245 |
246 | await callbackOnMessage(context);
247 | }
248 |
249 | Future _requestCRUD(Context context) async {
250 | final chatId = context.chat!.id;
251 | const jsonEncoder = JsonEncoder.withIndent(' ');
252 | const utf8Encoder = Utf8Encoder();
253 |
254 | final exampleCrudBytes = utf8Encoder.convert(jsonEncoder.convert(kCrudExample));
255 | final emptyCrudBytes = utf8Encoder.convert(jsonEncoder.convert(kCrudEmpty));
256 |
257 | await context.reply(
258 | _messages.crudHelpMessage,
259 | replyMarkup: InlineKeyboard()
260 | .add(
261 | _messages.crudCancel,
262 | '${identificator}_${AdminQueryEvent.cancelCRUD.name}',
263 | )
264 | .row(),
265 | );
266 |
267 | await context.replyWithMediaGroup(
268 | [
269 | InputMediaDocument(media: InputFile.fromBytes(exampleCrudBytes, name: 'example.json')),
270 | InputMediaDocument(media: InputFile.fromBytes(emptyCrudBytes, name: 'form.json')),
271 | ],
272 | protectContent: true,
273 | );
274 |
275 | repository.setState(chatId: chatId, state: const AdminWaitForCRUD());
276 | }
277 |
278 | Future _exportCategories(Context context) async {
279 | final tasksByCategories = await _database.tasksByCategories;
280 | final json = jsonDecode(jsonEncode(kCrudEmpty)) as Map;
281 |
282 | for (final (:category, :tasks) in tasksByCategories) {
283 | final categoryJson = category.toJson();
284 | // ignore: avoid_dynamic_calls
285 | json['categories']['operations']['create'].add(categoryJson);
286 | // ignore: avoid_dynamic_calls
287 | json['tasks']['operations']['create'].addAll(tasks.map((t) => t.toJson()));
288 | }
289 |
290 | const jsonEncoder = JsonEncoder.withIndent(' ');
291 | const utf8Encoder = Utf8Encoder();
292 |
293 | final bytes = utf8Encoder.convert(jsonEncoder.convert(json));
294 |
295 | await context.replyWithDocument(
296 | InputFile.fromBytes(
297 | bytes,
298 | name: _messages.exportCategoriesFilename.replaceFirst(
299 | r'$',
300 | DateTime.now().toString().split(' ').first,
301 | ),
302 | ),
303 | );
304 | }
305 |
306 | Future _exportRating(Context context) async {
307 | final excel = Excel.createExcel();
308 |
309 | await _database.deleteSolvedDuplications();
310 | final ratingPerCategory = await _database.getRatingPerCategory();
311 |
312 | final globalRatingSheet = excel[excel.getDefaultSheet() ?? 'Global Rating']
313 | ..appendRow(const [
314 | TextCellValue('Место'),
315 | TextCellValue('Никнейм'),
316 | TextCellValue('Задачи'),
317 | ]);
318 | final globalSubmissions =
319 | ratingPerCategory.map((categoriesRating) => categoriesRating.usersSubmissions).flattened.toList();
320 | final groupedSubmissions = _groupSubmissionsByUser(globalSubmissions)
321 | ..sort(
322 | (a, b) => b.solvedTasks.length.compareTo(a.solvedTasks.length),
323 | );
324 |
325 | var lastPlaceByCount = (place: 0, count: -1);
326 | for (final UserLeetCodeSubmissions(:account, :solvedTasks) in groupedSubmissions) {
327 | lastPlaceByCount = solvedTasks.length == lastPlaceByCount.count
328 | ? lastPlaceByCount
329 | : (place: lastPlaceByCount.place + 1, count: solvedTasks.length);
330 |
331 | globalRatingSheet.appendRow([
332 | TextCellValue(lastPlaceByCount.place.toString()),
333 | TextCellValue(account.nickname),
334 | TextCellValue(solvedTasks.length.toString()),
335 | ]);
336 | }
337 |
338 | for (final CategoryRating(:category, :tasks, :usersSubmissions) in ratingPerCategory) {
339 | final sheet = excel[category.shortTitle]
340 | ..merge(
341 | CellIndex.indexByString('A1'),
342 | CellIndex.indexByColumnRow(columnIndex: tasks.length + 4, rowIndex: 0),
343 | customValue: TextCellValue(category.title),
344 | )
345 | ..updateCell(CellIndex.indexByString('A2'), const TextCellValue('№'))
346 | ..updateCell(CellIndex.indexByString('B2'), const TextCellValue('Имя'))
347 | ..updateCell(CellIndex.indexByString('C2'), const TextCellValue('Ник'))
348 | ..updateCell(CellIndex.indexByString('D2'), const TextCellValue('Решено'));
349 |
350 | for (final (index, leetCodeTask) in tasks.indexed) {
351 | sheet.updateCell(
352 | CellIndex.indexByColumnRow(columnIndex: index + 4, rowIndex: 1),
353 | TextCellValue('${leetCodeTask.complexity.cutName} ${leetCodeTask.title}'),
354 | );
355 | }
356 |
357 | for (final (index, submissions) in usersSubmissions.indexed) {
358 | final markers = [];
359 | for (final leetCodeTask in tasks) {
360 | final isSolved = submissions.solvedTasks.any((solvedTask) {
361 | return leetCodeTask.id == solvedTask.task;
362 | });
363 |
364 | markers.add(isSolved ? const TextCellValue('+') : const TextCellValue(''));
365 | }
366 |
367 | sheet.appendRow([
368 | TextCellValue('${index + 1}'),
369 | TextCellValue(submissions.user.name ?? _messages.exportRatingUnknownUsername),
370 | TextCellValue(submissions.account.nickname),
371 | TextCellValue(submissions.solvedTasks.length.toString()),
372 | ...markers,
373 | ]);
374 | }
375 | }
376 |
377 | final bytes = excel.save();
378 | if (bytes == null) {
379 | await context.reply(_messages.exportRatingSaveFail);
380 | return;
381 | }
382 |
383 | await context.replyWithDocument(
384 | InputFile.fromBytes(
385 | Uint8List.fromList(bytes),
386 | name: _messages.exportRatingFilename.replaceFirst(
387 | r'$',
388 | DateTime.now().toString().split(' ').first,
389 | ),
390 | ),
391 | );
392 | }
393 |
394 | Future _exportLogs(Context context) async {
395 | final logsFile = LoggerService().file;
396 |
397 | if (logsFile.isEmptySync) {
398 | await context.reply(_messages.logsIsEmpty);
399 | return;
400 | }
401 |
402 | await context.replyWithDocument(InputFile.fromFile(logsFile, name: 'logs.logs'));
403 | }
404 |
405 | List _groupSubmissionsByUser(List globalSubmissions) {
406 | final groupedSubmissions = {};
407 | for (final submissions in globalSubmissions) {
408 | groupedSubmissions.update(
409 | submissions.user.id,
410 | (value) => value.copyWith(
411 | solvedTasks: value.solvedTasks + submissions.solvedTasks,
412 | ),
413 | ifAbsent: () => submissions,
414 | );
415 | }
416 |
417 | return groupedSubmissions.values.toList();
418 | }
419 | }
420 |
421 | typedef CRUDOperations = ({CRUD categories, CRUD tasks});
422 |
423 | final class CRUD {
424 | const CRUD({
425 | required this.create,
426 | required this.update,
427 | required this.delete,
428 | });
429 | final List create;
430 | final List update;
431 | final List delete;
432 | }
433 |
--------------------------------------------------------------------------------
/lib/bot/scopes/admin/admin_state.dart:
--------------------------------------------------------------------------------
1 | sealed class AdminState {
2 | const AdminState();
3 | }
4 |
5 | class AdminInitial extends AdminState {
6 | const AdminInitial();
7 | }
8 |
9 | class AdminWork extends AdminState {
10 | const AdminWork();
11 | }
12 |
13 | class AdminWaitForCRUD extends AdminState {
14 | const AdminWaitForCRUD();
15 | }
16 |
--------------------------------------------------------------------------------
/lib/bot/scopes/register/register_query_event.dart:
--------------------------------------------------------------------------------
1 | enum RegisterQueryEvent {
2 | restart();
3 |
4 | const RegisterQueryEvent();
5 | }
6 |
--------------------------------------------------------------------------------
/lib/bot/scopes/register/register_scope.dart:
--------------------------------------------------------------------------------
1 | import 'dart:async';
2 |
3 | import 'package:collection/collection.dart';
4 | import 'package:suai_leetcode_bot/bot/scopes/register/register_query_event.dart';
5 | import 'package:suai_leetcode_bot/bot/scopes/register/register_state.dart';
6 | import 'package:suai_leetcode_bot/bot/scopes/telegram_scope.dart';
7 | import 'package:suai_leetcode_bot/config/config.dart';
8 | import 'package:suai_leetcode_bot/constants/group_numbers.dart';
9 | import 'package:suai_leetcode_bot/data/database/database.dart';
10 | import 'package:suai_leetcode_bot/data/repositories/leetcode_repository.dart';
11 | import 'package:suai_leetcode_bot/extensions/int_extensions.dart';
12 | import 'package:suai_leetcode_bot/extensions/string_extensions.dart';
13 | import 'package:televerse/televerse.dart';
14 |
15 | final class RegisterScope extends TelegramScope {
16 | RegisterScope({
17 | required RegisterMessages messages,
18 | required AppDatabase database,
19 | required HttpLeetCodeRepository leetCodeRepository,
20 | required super.onStateComplete,
21 | required super.repository,
22 | }) : _messages = messages,
23 | _database = database,
24 | _leetCodeRepository = leetCodeRepository;
25 |
26 | final RegisterMessages _messages;
27 | final AppDatabase _database;
28 | final HttpLeetCodeRepository _leetCodeRepository;
29 |
30 | late final InlineKeyboard _restartKeyboard = InlineKeyboard()
31 | .add(
32 | 'Начать с начала',
33 | '${identificator}_${RegisterQueryEvent.restart.name}',
34 | )
35 | .row();
36 |
37 | @override
38 | String get identificator => 'register_scope';
39 |
40 | @override
41 | RegExp get commands => RegExp(r'^\/start$');
42 |
43 | @override
44 | FutureOr callbackOnCommand(Context context) async {
45 | if (context.chat?.isForum ?? false) return;
46 |
47 | final chatId = context.chat!.id;
48 | final command = context.message!.text!;
49 | final state = repository.getState(chatId: chatId);
50 |
51 | if (RegExp('start').hasMatch(command)) {
52 | if (state case RegisterInitial()) {
53 | await context.reply(_messages.onStart);
54 | }
55 | }
56 |
57 | await callbackOnMessage(context);
58 | }
59 |
60 | @override
61 | bool predicate(Context context) {
62 | if (context.chat?.isForum ?? false) return false;
63 |
64 | final chatId = context.chat?.id;
65 | final message = context.message;
66 |
67 | if (chatId == null || message == null) return false;
68 |
69 | final state = repository.getState(chatId: chatId);
70 | return state is! RegisterCompleted;
71 | }
72 |
73 | @override
74 | FutureOr callbackOnMessage(Context context) async {
75 | final chatId = context.chat!.id;
76 | final state = repository.getState(chatId: chatId);
77 |
78 | await switch (state) {
79 | RegisterInitial() => _requestName(context, chatId, state),
80 | RegisterWaitingForName() => _takeName(context, chatId, state),
81 | RegisterWaitingForGroupNumber() => _takeGroupNumber(context, chatId, state),
82 | RegisterWaitingForLeetCodeNickname() => _takeLeetCodeNickname(context, chatId, state),
83 | RegisterCompleted() => Future.value(),
84 | };
85 | }
86 |
87 | @override
88 | FutureOr callbackOnQuery(Context context) async {
89 | if (context.chat?.isForum ?? false) return;
90 |
91 | final chatId = context.chat!.id;
92 | final state = repository.getState(chatId: chatId);
93 |
94 | if (state is RegisterCompleted) return;
95 |
96 | final queryData = context.callbackQuery!.data!;
97 | final queryEventIdentificator = queryPattern.firstMatch(queryData)!.group(1)!;
98 | final queryEvent = RegisterQueryEvent.values.firstWhereOrNull(
99 | (value) => value.name == queryEventIdentificator,
100 | );
101 |
102 | switch (queryEvent) {
103 | case RegisterQueryEvent.restart:
104 | repository.setState(
105 | chatId: chatId,
106 | state: const RegisterInitial(),
107 | );
108 | await context.editMessageText(_messages.restartRegistration);
109 | case null:
110 | }
111 |
112 | await callbackOnMessage(context);
113 | }
114 |
115 | Future _requestName(
116 | Context context,
117 | int chatId,
118 | RegisterInitial state,
119 | ) async {
120 | await context.reply(_messages.requestName);
121 |
122 | repository.setState(
123 | chatId: chatId,
124 | state: const RegisterWaitingForName(),
125 | );
126 | }
127 |
128 | Future _takeName(
129 | Context context,
130 | int chatId,
131 | RegisterWaitingForName state,
132 | ) async {
133 | final name = context.message!.text?.trim().toLowerCase().eachCapitalize();
134 | final validateRegex = RegExp(r'^[а-яА-ЯёЁ]{2,32} [а-яА-ЯёЁ]{2,32}$');
135 |
136 | if (name == null || !validateRegex.hasMatch(name)) {
137 | await context.reply(_messages.invalidName);
138 | return;
139 | }
140 |
141 | await context.reply(_messages.requestGroupNumber, replyMarkup: _restartKeyboard);
142 |
143 | repository.setState(
144 | chatId: chatId,
145 | state: RegisterWaitingForGroupNumber(name: name),
146 | );
147 | }
148 |
149 | Future _takeGroupNumber(
150 | Context context,
151 | int chatId,
152 | RegisterWaitingForGroupNumber state,
153 | ) async {
154 | final groupNumber = context.message!.text?.trim().toUpperCase();
155 |
156 | if (groupNumber == null || !kGroupNumbers.contains(groupNumber)) {
157 | await context.reply(_messages.invalidGroupNumber, replyMarkup: _restartKeyboard);
158 | return;
159 | }
160 |
161 | await context.reply(_messages.requestLeetCodeNickname, replyMarkup: _restartKeyboard);
162 |
163 | repository.setState(
164 | chatId: chatId,
165 | state: RegisterWaitingForLeetCodeNickname(name: state.name, groupNumber: groupNumber),
166 | );
167 | }
168 |
169 | Future _takeLeetCodeNickname(
170 | Context context,
171 | int chatId,
172 | RegisterWaitingForLeetCodeNickname state,
173 | ) async {
174 | final leetCodeNickname = context.message!.text?.trim();
175 |
176 | if (leetCodeNickname == null || !leetCodeNickname.length.inRange(3, 32)) {
177 | await context.reply(_messages.invalidLeetCodeNickname, replyMarkup: _restartKeyboard);
178 | return;
179 | }
180 |
181 | final isLeetCodeNicknameAlreadyTaken = await _database.isLeetCodeNicknameAlreadyTaken(leetCodeNickname);
182 |
183 | if (isLeetCodeNicknameAlreadyTaken) {
184 | await context.reply(_messages.leetCodeNicknameIsAlreadyTaken, replyMarkup: _restartKeyboard);
185 | return;
186 | }
187 |
188 | final isLeetCodeNicknameExist = await _leetCodeRepository.isUserExist(leetCodeNickname);
189 |
190 | if (isLeetCodeNicknameExist == null) {
191 | await context.reply(_messages.leetCodeNicknameGetError, replyMarkup: _restartKeyboard);
192 | return;
193 | }
194 |
195 | if (!isLeetCodeNicknameExist) {
196 | await context.reply(_messages.leetCodeNicknameNotExist, replyMarkup: _restartKeyboard);
197 | return;
198 | }
199 |
200 | await _database.createUserWithLeetCodeAccount(
201 | telegramId: chatId,
202 | name: state.name,
203 | groupNumber: state.groupNumber,
204 | leetCodeNickname: leetCodeNickname,
205 | );
206 | await context.reply(_messages.successfulRegistration);
207 |
208 | repository.setState(chatId: chatId, state: const RegisterCompleted());
209 |
210 | onStateComplete?.call(context);
211 | }
212 | }
213 |
--------------------------------------------------------------------------------
/lib/bot/scopes/register/register_state.dart:
--------------------------------------------------------------------------------
1 | sealed class RegisterState {
2 | const RegisterState();
3 | }
4 |
5 | class RegisterInitial extends RegisterState {
6 | const RegisterInitial();
7 | }
8 |
9 | class RegisterWaitingForName extends RegisterState {
10 | const RegisterWaitingForName();
11 | }
12 |
13 | class RegisterWaitingForGroupNumber extends RegisterState {
14 | const RegisterWaitingForGroupNumber({required this.name});
15 |
16 | final String name;
17 | }
18 |
19 | class RegisterWaitingForLeetCodeNickname extends RegisterState {
20 | const RegisterWaitingForLeetCodeNickname({
21 | required this.name,
22 | required this.groupNumber,
23 | });
24 |
25 | final String name;
26 | final String groupNumber;
27 | }
28 |
29 | class RegisterCompleted extends RegisterState {
30 | const RegisterCompleted();
31 | }
32 |
--------------------------------------------------------------------------------
/lib/bot/scopes/telegram_scope.dart:
--------------------------------------------------------------------------------
1 | import 'dart:async';
2 |
3 | import 'package:suai_leetcode_bot/bot/repositories/telegram_state_repository.dart';
4 | import 'package:televerse/televerse.dart';
5 |
6 | abstract base class TelegramScope {
7 | const TelegramScope({
8 | required this.repository,
9 | this.onStateComplete,
10 | });
11 |
12 | abstract final String identificator;
13 | final TelegramStateRepository repository;
14 |
15 | final FutureOr Function(Context context)? onStateComplete;
16 | FutureOr executeInitialStatePoint(Context context) {}
17 |
18 | RegExp get commands;
19 | FutureOr callbackOnCommand(Context context);
20 |
21 | bool predicate(Context context);
22 | FutureOr callbackOnMessage(Context context);
23 |
24 | RegExp get queryPattern => RegExp('^${identificator}_' r'(\w+)');
25 |
26 | FutureOr callbackOnQuery(Context context);
27 | }
28 |
--------------------------------------------------------------------------------
/lib/bot/scopes/user/user_query_event.dart:
--------------------------------------------------------------------------------
1 | enum UserQueryEvent {
2 | showCategories(),
3 | showCategoryDetails(),
4 |
5 | backToMenu(),
6 | backToCategories();
7 |
8 | const UserQueryEvent();
9 | }
10 |
--------------------------------------------------------------------------------
/lib/bot/scopes/user/user_scope.dart:
--------------------------------------------------------------------------------
1 | import 'dart:async';
2 |
3 | import 'package:collection/collection.dart';
4 | import 'package:suai_leetcode_bot/bot/scopes/telegram_scope.dart';
5 | import 'package:suai_leetcode_bot/bot/scopes/user/user_query_event.dart';
6 | import 'package:suai_leetcode_bot/bot/scopes/user/user_state.dart';
7 | import 'package:suai_leetcode_bot/config/config.dart';
8 | import 'package:suai_leetcode_bot/data/database/database.dart';
9 | import 'package:suai_leetcode_bot/service/leetcode_service.dart';
10 | import 'package:televerse/telegram.dart';
11 | import 'package:televerse/televerse.dart';
12 |
13 | final class UserScope extends TelegramScope {
14 | UserScope({
15 | required AppDatabase database,
16 | required UserMessages messages,
17 | required super.repository,
18 | }) : _database = database,
19 | _messages = messages {
20 | LeetCodeService.nextTimerRun.listen((time) => nextTimerRun = time);
21 | }
22 |
23 | final AppDatabase _database;
24 | final UserMessages _messages;
25 | DateTime? nextTimerRun;
26 |
27 | @override
28 | String get identificator => 'user_scope';
29 |
30 | @override
31 | RegExp get commands => RegExp(r'^(\/help|\/info|\/update)$');
32 |
33 | @override
34 | FutureOr callbackOnCommand(Context context) async {
35 | if (context.chat?.isForum ?? false) return;
36 |
37 | final command = context.message!.text!;
38 |
39 | if (RegExp('help').hasMatch(command)) {
40 | await context.reply(_messages.howItWorks);
41 | return;
42 | }
43 |
44 | if (RegExp('info').hasMatch(command)) {
45 | await context.reply(_messages.howItWorks);
46 | return;
47 | }
48 |
49 | if (RegExp('update').hasMatch(command)) {
50 | if (nextTimerRun case final time?) {
51 | final differenceTime = time.difference(DateTime.now());
52 | final (hour, minute, seconds) = (differenceTime.inHours, differenceTime.inMinutes, differenceTime.inSeconds);
53 | await context.reply(
54 | _messages.whenNextUpdate.replaceFirst(r'$', '\nчерез $hour ч. ${minute % 60} м. ${seconds % 60} с.'),
55 | );
56 | return;
57 | }
58 |
59 | await context.reply('Время неизвестно, попробуйте позже');
60 |
61 | return;
62 | }
63 | }
64 |
65 | @override
66 | bool predicate(Context context) {
67 | if (context.chat?.isForum ?? false) return false;
68 |
69 | final chatId = context.chat?.id;
70 | final message = context.message;
71 |
72 | if (chatId == null || message == null) return false;
73 |
74 | return true;
75 | }
76 |
77 | @override
78 | FutureOr callbackOnMessage(Context context) async {
79 | await context.reply(
80 | _messages.chooseMenuItem,
81 | replyMarkup: InlineKeyboard()
82 | .addUrl(_messages.aboutClubCaption, _messages.aboutClubLink)
83 | .row()
84 | .addUrl(_messages.olympiadsCaption, _messages.olympiadsLink)
85 | .row()
86 | .addUrl(_messages.joinClubCaption, _messages.joinClubLink)
87 | .row()
88 | .add(_messages.categoryListCaption, '${identificator}_${UserQueryEvent.showCategories.name}')
89 | .row(),
90 | );
91 | }
92 |
93 | @override
94 | FutureOr callbackOnQuery(Context context) async {
95 | if (context.chat?.isForum ?? false) return;
96 |
97 | await context.answerCallbackQuery();
98 |
99 | final queryData = context.callbackQuery!.data!;
100 | final queryEventIdentificator = queryPattern.firstMatch(queryData)!.group(1)!;
101 | final queryEvent = UserQueryEvent.values.firstWhereOrNull((value) => value.name == queryEventIdentificator);
102 |
103 | switch (queryEvent) {
104 | case UserQueryEvent.showCategories:
105 | await _showCategories(context);
106 | case UserQueryEvent.showCategoryDetails:
107 | final categoryUri = Uri.parse(queryData);
108 | final categoryId = categoryUri.queryParameters['id']!;
109 | await _showCategory(context, int.parse(categoryId));
110 | case UserQueryEvent.backToMenu:
111 | await callbackOnMessage(context);
112 | case UserQueryEvent.backToCategories:
113 | await _showCategories(context);
114 | case null:
115 | }
116 | }
117 |
118 | Future _showCategories(Context context) async {
119 | final categories = await _database.allCategories;
120 | final keyboard = InlineKeyboard();
121 | for (final Category(:id, :shortTitle) in categories) {
122 | keyboard
123 | ..add(shortTitle, '${identificator}_${UserQueryEvent.showCategoryDetails.name}?id=$id')
124 | ..row();
125 | }
126 |
127 | keyboard
128 | ..add(_messages.backToMenu, '${identificator}_${UserQueryEvent.backToMenu.name}')
129 | ..row();
130 |
131 | await context.reply(_messages.chooseCategory, replyMarkup: keyboard);
132 | }
133 |
134 | Future _showCategory(Context context, int categoryId) async {
135 | final chatId = context.chat!.id;
136 | final category = await _database.getCategory(categoryId);
137 | final tasks = await _database.getTasksWithUserSolutions(categoryId: categoryId, telegramId: chatId);
138 |
139 | final keyboard = InlineKeyboard().add(
140 | _messages.backToCategories,
141 | '${identificator}_${UserQueryEvent.backToCategories.name}',
142 | );
143 |
144 | final content = StringBuffer()
145 | ..writeln(category.title)
146 | ..writeln(category.description)
147 | ..writeln();
148 |
149 | for (final (:task, :isSolved) in tasks) {
150 | final taskMarker = isSolved ? '✅' : '❌';
151 | content
152 | ..write(taskMarker)
153 | ..write(' ${task.complexity.cutName}')
154 | ..write(' ${task.title}')
155 | ..write(' ${_messages.taskLinkCaption}')
156 | ..writeln();
157 | }
158 |
159 | await context.reply(
160 | content.toString(),
161 | replyMarkup: keyboard,
162 | parseMode: ParseMode.html,
163 | linkPreviewOptions: const LinkPreviewOptions(isDisabled: true),
164 | );
165 | }
166 |
167 | @override
168 | FutureOr executeInitialStatePoint(Context context) async {
169 | await callbackOnMessage(context);
170 | }
171 | }
172 |
--------------------------------------------------------------------------------
/lib/bot/scopes/user/user_state.dart:
--------------------------------------------------------------------------------
1 | sealed class UserState {
2 | const UserState();
3 | }
4 |
5 | class UserInitial extends UserState {
6 | const UserInitial();
7 | }
8 |
--------------------------------------------------------------------------------
/lib/bot/telegram_bot.dart:
--------------------------------------------------------------------------------
1 | import 'dart:async';
2 |
3 | import 'package:suai_leetcode_bot/bot/scopes/telegram_scope.dart';
4 | import 'package:suai_leetcode_bot/config/config.dart';
5 | import 'package:suai_leetcode_bot/service/logger_service.dart';
6 | import 'package:televerse/televerse.dart';
7 |
8 | class TelegramBot {
9 | TelegramBot({
10 | required this.config,
11 | required List> scopes,
12 | }) : _bot = Bot(config.telegramToken),
13 | _scopes = scopes;
14 |
15 | final Config config;
16 | final List> _scopes;
17 | final Bot _bot;
18 |
19 | void start() {
20 | runZonedGuarded(() {
21 | _bot.start();
22 | for (final TelegramScope(
23 | :commands,
24 | :callbackOnCommand,
25 | :predicate,
26 | :callbackOnMessage,
27 | :identificator,
28 | :queryPattern,
29 | :callbackOnQuery,
30 | ) in _scopes) {
31 | _bot
32 | ..command(commands, callbackOnCommand)
33 | ..filter(predicate, callbackOnMessage, name: identificator)
34 | ..callbackQuery(queryPattern, callbackOnQuery);
35 | }
36 | }, (error, stack) {
37 | LoggerService().writeError(error, stack);
38 | // ignore: avoid_print
39 | print('Error $error, with stackTrace $stack');
40 | });
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/lib/config/config.dart:
--------------------------------------------------------------------------------
1 | import 'package:meta/meta.dart';
2 |
3 | @immutable
4 | class Config {
5 | const Config({
6 | required this.telegramToken,
7 | required this.leetCodeUpdateIntervalInSeconds,
8 | required this.leetCodeUpdateCoolingTimeInSeconds,
9 | required this.leetCodeBatchRequestSize,
10 | required this.registerMessages,
11 | required this.userMessages,
12 | required this.adminMessages,
13 | });
14 |
15 | factory Config.fromJson(Map json) {
16 | return switch (json) {
17 | {
18 | 'telegramToken': final String telegramToken,
19 | 'leetCodeUpdateIntervalInSeconds': final int leetCodeUpdateIntervalInSeconds,
20 | 'leetCodeUpdateCoolingTimeInSeconds': final int leetCodeUpdateCoolingTimeInSeconds,
21 | 'leetCodeBatchRequestSize': final int leetCodeBatchRequestSize,
22 | 'messages': {
23 | 'register': {
24 | 'onStart': final String onStart,
25 | 'requestName': final String requestName,
26 | 'invalidName': final String invalidName,
27 | 'requestGroupNumber': final String requestGroupNumber,
28 | 'invalidGroupNumber': final String invalidGroupNumber,
29 | 'requestLeetCodeNickname': final String requestLeetCodeNickname,
30 | 'invalidLeetCodeNickname': final String invalidLeetCodeNickname,
31 | 'leetCodeNicknameIsAlreadyTaken': final String leetCodeNicknameIsAlreadyTaken,
32 | 'leetCodeNicknameNotExist': final String leetCodeNicknameNotExist,
33 | 'successfulRegistration': final String successfulRegistration,
34 | 'restartRegistration': final String restartRegistration,
35 | 'leetCodeNicknameGetError': final String leetCodeNicknameGetError,
36 | },
37 | 'user': {
38 | 'chooseMenuItem': final String $userChooseMenuItem,
39 | 'aboutClubCaption': final String aboutClubCaption,
40 | 'aboutClubLink': final String aboutClubLink,
41 | 'olympiadsCaption': final String olympiadsCaption,
42 | 'olympiadsLink': final String olympiadsLink,
43 | 'joinClubCaption': final String joinClubCaption,
44 | 'joinClubLink': final String joinClubLink,
45 | 'categoryListCaption': final String categoryListCaption,
46 | 'backToMenu': final String backToMenu,
47 | 'backToCategories': final String backToCategories,
48 | 'chooseCategory': final String chooseCategory,
49 | 'taskLinkCaption': final String taskLinkCaption,
50 | 'howItWorks': final String howItWorks,
51 | 'whenNextUpdate': final String whenNextUpdate,
52 | },
53 | 'admin': {
54 | 'logsIsEmpty': final String logsIsEmpty,
55 | 'exportLogs': final String exportLogs,
56 | 'chooseMenuItem': final String $adminChooseMenuItem,
57 | 'exportRating': final String exportRating,
58 | 'exportRatingFilename': final String exportRatingFilename,
59 | 'exportRatingSaveFail': final String exportRatingSaveFail,
60 | 'exportRatingUnknownUsername': final String exportRatingUnknownUsername,
61 | 'exportCategories': final String exportCategories,
62 | 'exportCategoriesFilename': final String exportCategoriesFilename,
63 | 'crudCategories': final String crudCategories,
64 | 'crudCancel': final String crudCancel,
65 | 'crudInvalidMimeType': final String crudInvalidMimeType,
66 | 'crudFileDownloadError': final String crudFileDownloadError,
67 | 'crudFileFormatError': final String crudFileFormatError,
68 | 'crudDatabaseUnknownError': final String crudDatabaseUnknownError,
69 | 'crudSuccessful': final String crudSuccessful,
70 | 'crudHelpMessage': final String crudHelpMessage,
71 | 'exit': final String exit,
72 | }
73 | },
74 | } =>
75 | Config(
76 | telegramToken: telegramToken,
77 | leetCodeUpdateIntervalInSeconds: leetCodeUpdateIntervalInSeconds,
78 | leetCodeUpdateCoolingTimeInSeconds: leetCodeUpdateCoolingTimeInSeconds,
79 | leetCodeBatchRequestSize: leetCodeBatchRequestSize,
80 | registerMessages: RegisterMessages(
81 | onStart: onStart,
82 | requestName: requestName,
83 | invalidName: invalidName,
84 | requestGroupNumber: requestGroupNumber,
85 | invalidGroupNumber: invalidGroupNumber,
86 | requestLeetCodeNickname: requestLeetCodeNickname,
87 | invalidLeetCodeNickname: invalidLeetCodeNickname,
88 | leetCodeNicknameIsAlreadyTaken: leetCodeNicknameIsAlreadyTaken,
89 | leetCodeNicknameNotExist: leetCodeNicknameNotExist,
90 | successfulRegistration: successfulRegistration,
91 | restartRegistration: restartRegistration,
92 | leetCodeNicknameGetError: leetCodeNicknameGetError,
93 | ),
94 | userMessages: UserMessages(
95 | chooseMenuItem: $userChooseMenuItem,
96 | aboutClubCaption: aboutClubCaption,
97 | aboutClubLink: aboutClubLink,
98 | olympiadsCaption: olympiadsCaption,
99 | olympiadsLink: olympiadsLink,
100 | joinClubCaption: joinClubCaption,
101 | joinClubLink: joinClubLink,
102 | categoryListCaption: categoryListCaption,
103 | backToMenu: backToMenu,
104 | backToCategories: backToCategories,
105 | chooseCategory: chooseCategory,
106 | taskLinkCaption: taskLinkCaption,
107 | howItWorks: howItWorks,
108 | whenNextUpdate: whenNextUpdate,
109 | ),
110 | adminMessages: AdminMessages(
111 | logsIsEmpty: logsIsEmpty,
112 | exportLogs: exportLogs,
113 | chooseMenuItem: $adminChooseMenuItem,
114 | exportRating: exportRating,
115 | exportRatingFilename: exportRatingFilename,
116 | exportRatingSaveFail: exportRatingSaveFail,
117 | exportRatingUnknownUsername: exportRatingUnknownUsername,
118 | exportCategories: exportCategories,
119 | exportCategoriesFilename: exportCategoriesFilename,
120 | crudCategories: crudCategories,
121 | crudCancel: crudCancel,
122 | crudInvalidMimeType: crudInvalidMimeType,
123 | crudFileDownloadError: crudFileDownloadError,
124 | crudFileFormatError: crudFileFormatError,
125 | crudDatabaseUnknownError: crudDatabaseUnknownError,
126 | crudSuccessful: crudSuccessful,
127 | crudHelpMessage: crudHelpMessage,
128 | exit: exit,
129 | ),
130 | ),
131 | _ => throw const FormatException('The configuration file does not match the template')
132 | };
133 | }
134 |
135 | final String telegramToken;
136 | final int leetCodeUpdateIntervalInSeconds;
137 | final int leetCodeUpdateCoolingTimeInSeconds;
138 | final int leetCodeBatchRequestSize;
139 | final RegisterMessages registerMessages;
140 | final UserMessages userMessages;
141 | final AdminMessages adminMessages;
142 | }
143 |
144 | sealed class Messages {
145 | const Messages();
146 | }
147 |
148 | class RegisterMessages extends Messages {
149 | const RegisterMessages({
150 | required this.onStart,
151 | required this.requestName,
152 | required this.invalidName,
153 | required this.requestGroupNumber,
154 | required this.invalidGroupNumber,
155 | required this.requestLeetCodeNickname,
156 | required this.invalidLeetCodeNickname,
157 | required this.leetCodeNicknameIsAlreadyTaken,
158 | required this.leetCodeNicknameNotExist,
159 | required this.successfulRegistration,
160 | required this.restartRegistration,
161 | required this.leetCodeNicknameGetError,
162 | });
163 |
164 | final String onStart;
165 | final String requestName;
166 | final String invalidName;
167 | final String requestGroupNumber;
168 | final String invalidGroupNumber;
169 | final String requestLeetCodeNickname;
170 | final String invalidLeetCodeNickname;
171 | final String leetCodeNicknameIsAlreadyTaken;
172 | final String leetCodeNicknameNotExist;
173 | final String successfulRegistration;
174 | final String restartRegistration;
175 | final String leetCodeNicknameGetError;
176 | }
177 |
178 | class UserMessages extends Messages {
179 | const UserMessages({
180 | required this.chooseMenuItem,
181 | required this.aboutClubCaption,
182 | required this.aboutClubLink,
183 | required this.olympiadsCaption,
184 | required this.olympiadsLink,
185 | required this.joinClubCaption,
186 | required this.joinClubLink,
187 | required this.categoryListCaption,
188 | required this.backToMenu,
189 | required this.backToCategories,
190 | required this.chooseCategory,
191 | required this.taskLinkCaption,
192 | required this.howItWorks,
193 | required this.whenNextUpdate,
194 | });
195 |
196 | final String chooseMenuItem;
197 | final String aboutClubCaption;
198 | final String aboutClubLink;
199 | final String olympiadsCaption;
200 | final String olympiadsLink;
201 | final String joinClubCaption;
202 | final String joinClubLink;
203 | final String categoryListCaption;
204 | final String backToMenu;
205 | final String backToCategories;
206 | final String chooseCategory;
207 | final String taskLinkCaption;
208 | final String howItWorks;
209 | final String whenNextUpdate;
210 | }
211 |
212 | class AdminMessages extends Messages {
213 | AdminMessages({
214 | required this.logsIsEmpty,
215 | required this.exportLogs,
216 | required this.chooseMenuItem,
217 | required this.exportRating,
218 | required this.exportRatingFilename,
219 | required this.exportRatingSaveFail,
220 | required this.exportRatingUnknownUsername,
221 | required this.exportCategories,
222 | required this.exportCategoriesFilename,
223 | required this.crudCategories,
224 | required this.crudCancel,
225 | required this.crudInvalidMimeType,
226 | required this.crudFileDownloadError,
227 | required this.crudFileFormatError,
228 | required this.crudDatabaseUnknownError,
229 | required this.crudSuccessful,
230 | required this.crudHelpMessage,
231 | required this.exit,
232 | });
233 |
234 | final String logsIsEmpty;
235 | final String exportLogs;
236 | final String chooseMenuItem;
237 | final String exportRating;
238 | final String exportRatingFilename;
239 | final String exportRatingSaveFail;
240 | final String exportRatingUnknownUsername;
241 | final String exportCategories;
242 | final String exportCategoriesFilename;
243 | final String crudCategories;
244 | final String crudCancel;
245 | final String crudInvalidMimeType;
246 | final String crudFileDownloadError;
247 | final String crudFileFormatError;
248 | final String crudDatabaseUnknownError;
249 | final String crudSuccessful;
250 | final String crudHelpMessage;
251 | final String exit;
252 | }
253 |
--------------------------------------------------------------------------------
/lib/constants/crud.dart:
--------------------------------------------------------------------------------
1 | // ignore_for_file: inference_failure_on_collection_literal
2 |
3 | const Map kCrudEmpty = {
4 | 'categories': {
5 | 'operations': {
6 | 'create': [],
7 | 'update': [],
8 | 'delete': [],
9 | },
10 | },
11 | 'tasks': {
12 | 'operations': {
13 | 'create': [],
14 | 'update': [],
15 | 'delete': [],
16 | },
17 | },
18 | };
19 |
20 | const Map kCrudExample = {
21 | 'categories': {
22 | 'operations': {
23 | 'create': [
24 | {
25 | 'title': 'Неделя 1: Сортировка',
26 | 'shortTitle': 'Сортировка',
27 | 'description': 'example description',
28 | 'sortingNumber': 1,
29 | }
30 | ],
31 | 'update': [
32 | {
33 | 'id': 0,
34 | 'title': 'example title',
35 | 'shortTitle': 'example shortTitle',
36 | 'description': 'example description',
37 | 'sortingNumber': 1,
38 | }
39 | ],
40 | 'delete': [
41 | {
42 | 'id': 0,
43 | }
44 | ],
45 | },
46 | },
47 | 'tasks': {
48 | 'operations': {
49 | 'create': [
50 | {
51 | 'slug': 'decode-ways',
52 | 'category': 0,
53 | 'title': '91. Decode Ways',
54 | 'link': 'https://leetcode.com/problems/decode-ways/description/',
55 | 'complexity': 'easy|medium|hard',
56 | }
57 | ],
58 | 'update': [
59 | {
60 | 'slug': 'decode-ways',
61 | 'category': 0,
62 | 'title': '91. Decode Ways',
63 | 'link': 'https://leetcode.com/problems/decode-ways/description/',
64 | 'complexity': 'hard',
65 | }
66 | ],
67 | 'delete': [
68 | {
69 | 'slug': 'decode-ways',
70 | }
71 | ],
72 | },
73 | },
74 | };
75 |
--------------------------------------------------------------------------------
/lib/constants/group_numbers.dart:
--------------------------------------------------------------------------------
1 | const kGroupNumbers = [
2 | '1011',
3 | '1012',
4 | '1021',
5 | '1022',
6 | '1031',
7 | '1032',
8 | '1035',
9 | '1036',
10 | '1041',
11 | '1042',
12 | '1043',
13 | '1044',
14 | '1045',
15 | '1111',
16 | '1112',
17 | '1121',
18 | '1122',
19 | '1123',
20 | '1131',
21 | '1132',
22 | '1133',
23 | '1135',
24 | '1136',
25 | '1137',
26 | '1141',
27 | '1142',
28 | '1144',
29 | '1145',
30 | '1211',
31 | '1212',
32 | '1213',
33 | '1221',
34 | '1222',
35 | '1223',
36 | '1224',
37 | '1231',
38 | '1232',
39 | '1233',
40 | '1241',
41 | '1242',
42 | '1243',
43 | '1245',
44 | '1310М',
45 | '1311',
46 | '1312',
47 | '1313',
48 | '1321',
49 | '1322',
50 | '1323',
51 | '1323М',
52 | '1324',
53 | '1324М',
54 | '1326М',
55 | '1330М',
56 | '1331',
57 | '1332',
58 | '1333',
59 | '1334',
60 | '1335',
61 | '1337',
62 | '1338',
63 | '1340М',
64 | '1341',
65 | '1342',
66 | '1343',
67 | '1346',
68 | '2010',
69 | '2011',
70 | '2015',
71 | '2022',
72 | '2031',
73 | '2033',
74 | '2035',
75 | '2037',
76 | '2040',
77 | '2043',
78 | '2046',
79 | '2051',
80 | '2052',
81 | '2055',
82 | '2056',
83 | '2110',
84 | '2111',
85 | '2115',
86 | '2121',
87 | '2131',
88 | '2133',
89 | '2135',
90 | '2137',
91 | '2138',
92 | '2140',
93 | '2144',
94 | '2146',
95 | '2151',
96 | '2152',
97 | '2154',
98 | '2155',
99 | '2156',
100 | '2210',
101 | '2211',
102 | '2212',
103 | '2213',
104 | '2215',
105 | '2221',
106 | '2222',
107 | '2223',
108 | '2233',
109 | '2235',
110 | '2237',
111 | '2240',
112 | '2243',
113 | '2246',
114 | '2247',
115 | '2251',
116 | '2252',
117 | '2253',
118 | '2254',
119 | '2255',
120 | '2310',
121 | '2311',
122 | '2315',
123 | '2321',
124 | '2322',
125 | '2323',
126 | '2330М',
127 | '2333',
128 | '2335',
129 | '2335М',
130 | '2337',
131 | '2337М',
132 | '2338',
133 | '2340',
134 | '2343',
135 | '2346',
136 | '2346М',
137 | '2350М',
138 | '2351',
139 | '2351М',
140 | '2352',
141 | '2353',
142 | '2354',
143 | '2354М',
144 | '2355',
145 | '2910',
146 | '3011',
147 | '3013КС',
148 | '3014',
149 | '3015',
150 | '3021',
151 | '3023',
152 | '3026',
153 | '3026КС',
154 | '3031',
155 | '3032',
156 | '3033',
157 | '3035',
158 | '3111',
159 | '3112',
160 | '3113КС',
161 | '3115',
162 | '3121',
163 | '3122К',
164 | '3123',
165 | '3127КС',
166 | '3131',
167 | '3132',
168 | '3133',
169 | '3135',
170 | '3136',
171 | '3211',
172 | '3212',
173 | '3215',
174 | '3216',
175 | '3218КС',
176 | '3221',
177 | '3222КС',
178 | '3223',
179 | '3226',
180 | '3231',
181 | '3233',
182 | '3234К',
183 | '3235',
184 | '3236',
185 | '3237',
186 | '3238К',
187 | '3310М',
188 | '3311',
189 | '3312',
190 | '3313К',
191 | '3315',
192 | '3316',
193 | '3320М',
194 | '3321',
195 | '3323',
196 | '3324М',
197 | '3326',
198 | '3328',
199 | '3331',
200 | '3333',
201 | '3335',
202 | '3335М',
203 | '3336',
204 | '3337',
205 | '3338К',
206 | '3923',
207 | '3933',
208 | '3935',
209 | '4016',
210 | '4017',
211 | '4021',
212 | '4026',
213 | '4027',
214 | '4028',
215 | '4031',
216 | '4032',
217 | '4036',
218 | '4041',
219 | '4042',
220 | '4116',
221 | '4117',
222 | '4118',
223 | '4121',
224 | '4126',
225 | '4127',
226 | '4128',
227 | '4131',
228 | '4132',
229 | '4133К',
230 | '4134К',
231 | '4136',
232 | '4141',
233 | '4142',
234 | '4143',
235 | '4215',
236 | '4216',
237 | '4217',
238 | '4218',
239 | '4219',
240 | '4221',
241 | '4226',
242 | '4227',
243 | '4228',
244 | '4231',
245 | '4232',
246 | '4233К',
247 | '4236',
248 | '4241',
249 | '4242',
250 | '4243',
251 | '4313М',
252 | '4314',
253 | '4315',
254 | '4316',
255 | '4317',
256 | '4318',
257 | '4319',
258 | '4320М',
259 | '4321',
260 | '4326',
261 | '4327',
262 | '4328',
263 | '4329',
264 | '4330М',
265 | '4331',
266 | '4332',
267 | '4333К',
268 | '4340М',
269 | '4341',
270 | '4342',
271 | '4342М',
272 | '4343',
273 | '6029К',
274 | '6031',
275 | '6032К',
276 | '6033К',
277 | '6034К',
278 | '6121К',
279 | '6122К',
280 | '6127К',
281 | '6131',
282 | '6132К',
283 | '6133',
284 | '6134К',
285 | '6136К',
286 | '6137К',
287 | '6221К',
288 | '6222К',
289 | '6227К',
290 | '6231',
291 | '6232К',
292 | '6234К',
293 | '6235К',
294 | '6236К',
295 | '6320МК',
296 | '6321К',
297 | '6331К',
298 | '6332К',
299 | '7041',
300 | '7141',
301 | '7241',
302 | '7341',
303 | '8011К',
304 | '8016К',
305 | '8021К',
306 | '8026',
307 | '8027',
308 | '8028К',
309 | '8031К',
310 | '8033К',
311 | '8035',
312 | '8036К',
313 | '8038К',
314 | '8039К',
315 | '8043К',
316 | '8044К',
317 | '8051КВ',
318 | '8051КС',
319 | '8053К',
320 | '8054К',
321 | '8111К',
322 | '8112КВ',
323 | '8114КВ',
324 | '8116К',
325 | '8121К',
326 | '8122К',
327 | '8124К',
328 | '8124КВ',
329 | '8126',
330 | '8133К',
331 | '8135К',
332 | '8136К',
333 | '8138К',
334 | '8141К',
335 | '8143К',
336 | '8151КС',
337 | '8152КС',
338 | '8153К',
339 | '8211К',
340 | '8212КВ',
341 | '8214КВ',
342 | '8221К',
343 | '8224КВ',
344 | '8226',
345 | '8227К',
346 | '8233К',
347 | '8235К',
348 | '8236К',
349 | '8241К',
350 | '8243К',
351 | '8251КС',
352 | '8251КСВ',
353 | '8253К',
354 | '8254К',
355 | '8311К',
356 | '8312КВ',
357 | '8314КВ',
358 | '8314МК',
359 | '8315М',
360 | '8316К',
361 | '8321К',
362 | '8324К',
363 | '8324КВ',
364 | '8326',
365 | '8326КВ',
366 | '8326М',
367 | '8327К',
368 | '8335К',
369 | '8335МК',
370 | '8341К',
371 | '8343К',
372 | '8345МК',
373 | '8351КВ',
374 | '8353К',
375 | '8353МК',
376 | '8354К',
377 | '8916К',
378 | '8917К',
379 | '8933К',
380 | '8938К',
381 | 'А3111',
382 | 'А3121',
383 | 'А3131',
384 | 'А3141',
385 | 'А3211',
386 | 'А3214',
387 | 'А3221',
388 | 'А3231',
389 | 'А3251',
390 | 'А3311',
391 | 'А3321',
392 | 'А3331',
393 | 'А3441',
394 | 'А3442',
395 | 'А3611К',
396 | 'А3621К',
397 | 'А3641К',
398 | 'А3811К',
399 | 'А3831К',
400 | 'А3841К',
401 | 'А3851К',
402 | 'А3М11',
403 | 'А3М52',
404 | 'В0326',
405 | 'В0441',
406 | 'В1326',
407 | 'В1441',
408 | 'В1821К',
409 | 'В2326',
410 | 'В2441',
411 | 'В2821К',
412 | 'В3326',
413 | 'В3441',
414 | 'В9326',
415 | 'В9441',
416 | 'И0824К',
417 | 'И1824К',
418 | 'И3131К',
419 | 'И3620МК',
420 | 'И3812КВ',
421 | 'И3824МК',
422 | 'М011',
423 | 'М021',
424 | 'М022',
425 | 'М050',
426 | 'М051',
427 | 'М053КС',
428 | 'М054КС',
429 | 'М056',
430 | 'М061',
431 | 'М062',
432 | 'М111',
433 | 'М112',
434 | 'М121',
435 | 'М122',
436 | 'М131К',
437 | 'М150',
438 | 'М151',
439 | 'М153КС',
440 | 'М154КС',
441 | 'М156',
442 | 'М157',
443 | 'М161',
444 | 'М211',
445 | 'М221',
446 | 'М222',
447 | 'М250',
448 | 'М251',
449 | 'М253КС',
450 | 'М256',
451 | 'М257',
452 | 'М261',
453 | 'М311',
454 | 'М320М',
455 | 'М321',
456 | 'М350',
457 | 'М351',
458 | 'М352',
459 | 'М355М',
460 | 'М357М',
461 | 'М358М',
462 | 'М361',
463 | 'М361М',
464 | 'М362',
465 | ];
466 |
--------------------------------------------------------------------------------
/lib/data/api/leetcode_api.dart:
--------------------------------------------------------------------------------
1 | import 'package:http/http.dart' as http;
2 |
3 | final class LeetCodeApi {
4 | const LeetCodeApi();
5 |
6 | static const String _apiBaseUrl = 'leetcode.com';
7 | static const String _grapqlPath = '/graphql';
8 |
9 | Uri user(String nickname) {
10 | return Uri(
11 | scheme: 'https',
12 | host: _apiBaseUrl,
13 | path: '/$nickname/',
14 | );
15 | }
16 |
17 | Uri userSubmissions() {
18 | return Uri(
19 | scheme: 'https',
20 | host: _apiBaseUrl,
21 | path: _grapqlPath,
22 | );
23 | }
24 | }
25 |
26 | sealed class LeetCodeApiException implements Exception {
27 | const LeetCodeApiException(this.message);
28 | final String message;
29 | }
30 |
31 | class UnknownCodeException extends LeetCodeApiException {
32 | const UnknownCodeException(this.statusCode, this.response) : super('Unknow code $statusCode');
33 |
34 | final int statusCode;
35 | final http.Response response;
36 | }
37 |
--------------------------------------------------------------------------------
/lib/data/database/database.dart:
--------------------------------------------------------------------------------
1 | import 'dart:io';
2 |
3 | import 'package:drift/drift.dart';
4 | import 'package:drift/native.dart';
5 | import 'package:meta/meta.dart';
6 | import 'package:path/path.dart' as path;
7 | import 'package:sqlite3/sqlite3.dart';
8 | import 'package:suai_leetcode_bot/bot/scopes/admin/admin_scope.dart';
9 |
10 | part 'database.g.dart';
11 |
12 | class Users extends Table {
13 | IntColumn get id => integer().autoIncrement()();
14 | IntColumn get telegramId => integer().unique()();
15 | BoolColumn get isAdmin => boolean().withDefault(const Constant(false))();
16 |
17 | TextColumn get name => text().nullable().withLength(min: 5, max: 32)();
18 | TextColumn get groupNumber => text().nullable()();
19 | }
20 |
21 | class LeetCodeAccounts extends Table {
22 | IntColumn get id => integer().autoIncrement()();
23 | IntColumn get user => integer().unique().references(Users, #id)();
24 | TextColumn get nickname => text().unique().withLength(min: 3, max: 32)();
25 | DateTimeColumn get dateOfAddition => dateTime().withDefault(currentDateAndTime)();
26 | BoolColumn get isGraduated => boolean().withDefault(const Constant(false))();
27 | }
28 |
29 | class Categories extends Table {
30 | IntColumn get id => integer().autoIncrement()();
31 | TextColumn get title => text().withLength(min: 1, max: 128)();
32 | TextColumn get shortTitle => text().withLength(min: 1, max: 16)();
33 | TextColumn get description => text().withLength(min: 1, max: 1024)();
34 | IntColumn get sortingNumber => integer()();
35 | DateTimeColumn get deadline => dateTime()();
36 | }
37 |
38 | enum LeetCodeTaskComplexity {
39 | easy,
40 | medium,
41 | hard;
42 |
43 | String get cutName => name[0].toUpperCase();
44 | }
45 |
46 | class LeetCodeTasks extends Table {
47 | IntColumn get id => integer().autoIncrement()();
48 | TextColumn get slug => text().unique()();
49 | IntColumn get category => integer().references(Categories, #id, onDelete: KeyAction.cascade)();
50 | TextColumn get title => text().withLength(min: 1, max: 128)();
51 | TextColumn get link => text().withLength(min: 1, max: 512)();
52 | TextColumn get complexity => textEnum()();
53 | }
54 |
55 | class SolvedLeetCodeTasks extends Table {
56 | IntColumn get id => integer().autoIncrement()();
57 | IntColumn get user => integer().references(Users, #id)();
58 | IntColumn get task => integer().references(LeetCodeTasks, #id, onDelete: KeyAction.cascade)();
59 | DateTimeColumn get date => dateTime()();
60 | }
61 |
62 | @DriftDatabase(
63 | tables: [
64 | Users,
65 | LeetCodeAccounts,
66 | Categories,
67 | LeetCodeTasks,
68 | SolvedLeetCodeTasks,
69 | ],
70 | )
71 | class AppDatabase extends _$AppDatabase {
72 | AppDatabase() : super(_openConnection());
73 |
74 | static LazyDatabase _openConnection() {
75 | return LazyDatabase(() async {
76 | final scriptFolderPath = File(Platform.script.toFilePath()).parent.path;
77 | final dbFolderPath = path.join(scriptFolderPath, 'db');
78 |
79 | final file = File(path.join(dbFolderPath, 'db.sqlite'));
80 | final cachebase = path.join(dbFolderPath, 'cache');
81 |
82 | sqlite3.tempDirectory = cachebase;
83 |
84 | return NativeDatabase.createInBackground(file);
85 | });
86 | }
87 |
88 | @override
89 | int get schemaVersion => 1;
90 |
91 | @override
92 | MigrationStrategy get migration {
93 | return MigrationStrategy(
94 | beforeOpen: (details) async {
95 | await customStatement('PRAGMA foreign_keys = ON');
96 | },
97 | );
98 | }
99 |
100 | Future isAdmin(int telegramId) async {
101 | final user = await (select(users)
102 | ..where((usr) => usr.telegramId.equals(telegramId))
103 | ..limit(1))
104 | .getSingleOrNull();
105 | return user?.isAdmin ?? false;
106 | }
107 |
108 | Future isLeetCodeNicknameAlreadyTaken(String leetCodeNickname) async {
109 | final leetCodeAccount = await (select(leetCodeAccounts)
110 | ..where((l) => l.nickname.equals(leetCodeNickname))
111 | ..limit(1))
112 | .getSingleOrNull();
113 |
114 | return leetCodeAccount != null;
115 | }
116 |
117 | Future> get authorizedUsers => select(users).get();
118 |
119 | Future> get activeLeetCodeAccounts =>
120 | (select(leetCodeAccounts)..where((l) => l.isGraduated.equals(false))).get();
121 |
122 | Future> get allCategories => (select(categories)
123 | ..orderBy([
124 | (c) => OrderingTerm.asc(c.sortingNumber),
125 | ]))
126 | .get();
127 |
128 | Future tasks})>> get tasksByCategories async {
129 | final categories = await allCategories;
130 | return Future.wait(
131 | List.generate(categories.length, (index) async {
132 | return (
133 | category: categories[index],
134 | tasks: await getTasks(categories[index].id),
135 | );
136 | }),
137 | );
138 | }
139 |
140 | Future getCategory(int id) => (select(categories)..where((c) => c.id.equals(id))).getSingle();
141 |
142 | Future> getTasks(int categoryId) =>
143 | (select(leetCodeTasks)..where((l) => l.category.equals(categoryId))).get();
144 |
145 | Future updateUserSubmissions({
146 | required int userId,
147 | required List<({String slug, int timestamp})> submissions,
148 | }) async {
149 | await batch((batch) async {
150 | for (final (:slug, :timestamp) in submissions) {
151 | final taskQuery = select(leetCodeTasks)
152 | ..where((l) => l.slug.equals(slug))
153 | ..limit(1);
154 | final task = await taskQuery.getSingleOrNull();
155 |
156 | if (task == null) return;
157 |
158 | final solvedTaskQuery = select(solvedLeetCodeTasks)
159 | ..where((st) => st.task.equals(task.id) & st.user.equals(userId))
160 | ..limit(1);
161 | final solvedTask = await solvedTaskQuery.getSingleOrNull();
162 |
163 | if (solvedTask != null) return;
164 |
165 | batch.insert(
166 | solvedLeetCodeTasks,
167 | SolvedLeetCodeTasksCompanion.insert(
168 | user: userId,
169 | task: task.id,
170 | date: DateTime.fromMillisecondsSinceEpoch(timestamp),
171 | ),
172 | );
173 | }
174 | });
175 | await deleteSolvedDuplications();
176 | }
177 |
178 | Future> getTasksWithUserSolutions({
179 | required int categoryId,
180 | required int telegramId,
181 | }) async {
182 | final tasksInCategory = await (select(leetCodeTasks)..where((t) => t.category.equals(categoryId))).get();
183 |
184 | final user = await (select(users)
185 | ..where((u) => u.telegramId.equals(telegramId))
186 | ..limit(1))
187 | .getSingle();
188 |
189 | final solvedTaskIds =
190 | await (select(solvedLeetCodeTasks)..where((st) => st.user.equals(user.id))).map((row) => row.task).get();
191 |
192 | return tasksInCategory.map((task) {
193 | final isSolved = solvedTaskIds.contains(task.id);
194 | return (task: task, isSolved: isSolved);
195 | }).toList();
196 | }
197 |
198 | Future deleteSolvedDuplications() async {
199 | final allEntries = await select(solvedLeetCodeTasks).get();
200 |
201 | final groupedEntries = <(int, int), List>{};
202 | for (final entry in allEntries) {
203 | final key = (entry.user, entry.task);
204 | groupedEntries.putIfAbsent(key, () => []).add(entry);
205 | }
206 |
207 | final idsToDelete = [];
208 | for (final group in groupedEntries.values) {
209 | if (group.length > 1) {
210 | group.sort((a, b) => a.date.compareTo(b.date));
211 | idsToDelete.addAll(group.skip(1).map((e) => e.id));
212 | }
213 | }
214 |
215 | for (final id in idsToDelete) {
216 | await (delete(solvedLeetCodeTasks)..where((t) => t.id.equals(id))).go();
217 | }
218 | }
219 |
220 | Future> getRatingPerCategory() async {
221 | final nonEmptyCategories = await (select(categories)
222 | ..where(
223 | (cat) => existsQuery(
224 | select(leetCodeTasks)
225 | ..where((task) => task.category.equalsExp(cat.id))
226 | ..limit(1),
227 | ),
228 | )
229 | ..orderBy([
230 | (cat) => OrderingTerm.asc(cat.sortingNumber),
231 | ]))
232 | .get();
233 |
234 | final categoriesTasks = >[];
235 | final usersWithProgress = >[];
236 | for (final cat in nonEmptyCategories) {
237 | categoriesTasks.add(
238 | await (select(leetCodeTasks)..where((lct) => lct.category.equals(cat.id))).get(),
239 | );
240 |
241 | final categoriesTasksIds = categoriesTasks.last.map((c) => c.id).toList();
242 |
243 | usersWithProgress.add(
244 | await (select(users)
245 | ..where(
246 | (usr) => existsQuery(
247 | select(solvedLeetCodeTasks)
248 | ..where((slv) => slv.user.equalsExp(usr.id) & slv.task.isIn(categoriesTasksIds)),
249 | ),
250 | ))
251 | .get(),
252 | );
253 | }
254 |
255 | final categoriesRating = [];
256 | for (final (catIndex, cat) in nonEmptyCategories.indexed) {
257 | final tasks = categoriesTasks[catIndex];
258 | final tasksIds = tasks.map((t) => t.id).toList();
259 | final usersSubmissions = await Future.wait(
260 | List.generate(usersWithProgress[catIndex].length, (usrIndex) async {
261 | final userWithProgress = usersWithProgress[catIndex][usrIndex];
262 | final account = await (select(leetCodeAccounts)
263 | ..where((lca) => lca.user.equals(userWithProgress.id))
264 | ..limit(1))
265 | .getSingle();
266 | final solvedTasks = await (select(solvedLeetCodeTasks)
267 | ..where(
268 | (slv) => slv.user.equals(userWithProgress.id) & slv.task.isIn(tasksIds),
269 | ))
270 | .get();
271 | return UserLeetCodeSubmissions(
272 | user: userWithProgress,
273 | account: account,
274 | solvedTasks: solvedTasks,
275 | );
276 | }),
277 | );
278 |
279 | categoriesRating.add(
280 | CategoryRating(
281 | category: cat,
282 | tasks: tasks,
283 | usersSubmissions: usersSubmissions
284 | ..sort(
285 | (a, b) => b.solvedTasks.length.compareTo(a.solvedTasks.length),
286 | ),
287 | ),
288 | );
289 | }
290 |
291 | return categoriesRating;
292 | }
293 |
294 | Future createUserWithLeetCodeAccount({
295 | required int telegramId,
296 | required String name,
297 | required String groupNumber,
298 | required String leetCodeNickname,
299 | }) async {
300 | await transaction(() async {
301 | final userId = await into(users).insert(
302 | UsersCompanion.insert(
303 | telegramId: telegramId,
304 | name: Value(name),
305 | groupNumber: Value(groupNumber),
306 | ),
307 | );
308 | await into(leetCodeAccounts).insert(
309 | LeetCodeAccountsCompanion.insert(
310 | user: userId,
311 | nickname: leetCodeNickname,
312 | ),
313 | );
314 | });
315 | }
316 |
317 | Future<(Object e, StackTrace s)?> processCRUD(CRUDOperations operations) async {
318 | try {
319 | await transaction(() async {
320 | final (categories: categoriesOperations, tasks: tasksOperations) = operations;
321 |
322 | for (final categoryCreate in categoriesOperations.create) {
323 | categoryCreate as Map;
324 | final title = categoryCreate['title'] as String;
325 | final shortTitle = categoryCreate['shortTitle'] as String;
326 | final description = categoryCreate['description'] as String;
327 | final sortingNumber = categoryCreate['sortingNumber'] as int;
328 |
329 | await into(categories).insert(
330 | CategoriesCompanion.insert(
331 | title: title,
332 | shortTitle: shortTitle,
333 | description: description,
334 | sortingNumber: sortingNumber,
335 | deadline: DateTime.fromMillisecondsSinceEpoch(0),
336 | ),
337 | );
338 | }
339 |
340 | for (final categoryUpdate in categoriesOperations.update) {
341 | categoryUpdate as Map;
342 | final id = categoryUpdate['id'] as int;
343 | final title = categoryUpdate['title'] as String?;
344 | final shortTitle = categoryUpdate['shortTitle'] as String?;
345 | final description = categoryUpdate['description'] as String?;
346 | final sortingNumber = categoryUpdate['sortingNumber'] as int?;
347 |
348 | final oldValue = await (select(categories)
349 | ..where((c) => c.id.equals(id))
350 | ..limit(1))
351 | .getSingle();
352 |
353 | final newValue = oldValue.copyWith(
354 | title: title,
355 | shortTitle: shortTitle,
356 | description: description,
357 | sortingNumber: sortingNumber,
358 | );
359 |
360 | await update(categories).replace(newValue);
361 | }
362 |
363 | for (final categoryDelete in categoriesOperations.delete) {
364 | categoryDelete as Map;
365 | final id = categoryDelete['id'] as int;
366 |
367 | await (delete(categories)..where((c) => c.id.equals(id))).go();
368 | }
369 |
370 | for (final taskCreate in tasksOperations.create) {
371 | taskCreate as Map;
372 | final slug = taskCreate['slug'] as String;
373 | final category = taskCreate['category'] as int;
374 | final title = taskCreate['title'] as String;
375 | final link = taskCreate['link'] as String;
376 | final complexity = taskCreate['complexity'] as String;
377 |
378 | await into(leetCodeTasks).insert(
379 | LeetCodeTasksCompanion.insert(
380 | slug: slug,
381 | category: category,
382 | title: title,
383 | link: link,
384 | complexity: LeetCodeTaskComplexity.values.firstWhere(
385 | (e) => e.name.toLowerCase() == complexity.toLowerCase(),
386 | ),
387 | ),
388 | );
389 | }
390 |
391 | for (final taskUpdate in tasksOperations.update) {
392 | taskUpdate as Map;
393 | final slug = taskUpdate['slug'] as String;
394 | final category = taskUpdate['category'] as int?;
395 | final title = taskUpdate['title'] as String?;
396 | final link = taskUpdate['link'] as String?;
397 | final complexity = taskUpdate['complexity'] as String?;
398 |
399 | final oldValue = await (select(leetCodeTasks)
400 | ..where((l) => l.slug.equals(slug))
401 | ..limit(1))
402 | .getSingle();
403 |
404 | final newValue = oldValue.copyWith(
405 | category: category,
406 | title: title,
407 | link: link,
408 | complexity: complexity == null
409 | ? null
410 | : LeetCodeTaskComplexity.values.firstWhere(
411 | (e) => e.name.toLowerCase() == complexity.toLowerCase(),
412 | ),
413 | );
414 |
415 | await update(leetCodeTasks).replace(newValue);
416 | }
417 |
418 | for (final taskDelete in tasksOperations.delete) {
419 | taskDelete as Map;
420 | final slug = taskDelete['slug'] as String;
421 |
422 | await (delete(leetCodeTasks)..where((l) => l.slug.equals(slug))).go();
423 | }
424 | });
425 | } on Object catch (e, s) {
426 | return (e, s);
427 | }
428 | return null;
429 | }
430 | }
431 |
432 | @immutable
433 | final class CategoryRating {
434 | const CategoryRating({
435 | required this.category,
436 | required this.tasks,
437 | required this.usersSubmissions,
438 | });
439 |
440 | final Category category;
441 | final List tasks;
442 | final List usersSubmissions;
443 | }
444 |
445 | @immutable
446 | final class UserLeetCodeSubmissions {
447 | const UserLeetCodeSubmissions({
448 | required this.user,
449 | required this.account,
450 | required this.solvedTasks,
451 | });
452 | final User user;
453 | final LeetCodeAccount account;
454 | final List solvedTasks;
455 |
456 | UserLeetCodeSubmissions copyWith({
457 | User? user,
458 | LeetCodeAccount? account,
459 | List? solvedTasks,
460 | }) =>
461 | UserLeetCodeSubmissions(
462 | user: user ?? this.user,
463 | account: account ?? this.account,
464 | solvedTasks: solvedTasks ?? this.solvedTasks,
465 | );
466 | }
467 |
--------------------------------------------------------------------------------
/lib/data/repositories/leetcode_repository.dart:
--------------------------------------------------------------------------------
1 | import 'dart:convert';
2 | import 'dart:io';
3 |
4 | import 'package:http/http.dart' as http;
5 | import 'package:suai_leetcode_bot/data/api/leetcode_api.dart';
6 | import 'package:suai_leetcode_bot/service/logger_service.dart';
7 |
8 | final class HttpLeetCodeRepository {
9 | const HttpLeetCodeRepository({
10 | required LeetCodeApi api,
11 | required http.Client client,
12 | }) : _api = api,
13 | _client = client;
14 |
15 | final LeetCodeApi _api;
16 | final http.Client _client;
17 |
18 | Future isUserExist(String nickname) async {
19 | try {
20 | final response = await _client.get(_api.user(nickname));
21 | return switch (response.statusCode) {
22 | 200 => true,
23 | 404 => false,
24 | final unknownCode => throw UnknownCodeException(unknownCode, response),
25 | };
26 | } on UnknownCodeException catch (e, s) {
27 | LoggerService().writeError(e, s);
28 | return null;
29 | }
30 | }
31 |
32 | Future?> getRecentUserSubmission(String nickname, [int limit = 10]) async {
33 | final data = {
34 | 'query': r'''
35 | query recentAcSubmissions($username: String!, $limit: Int!) {
36 | recentAcSubmissionList(username: $username, limit: $limit) {
37 | id
38 | title
39 | titleSlug
40 | timestamp
41 | }
42 | }
43 | ''',
44 | 'variables': {'username': nickname, 'limit': limit},
45 | };
46 |
47 | try {
48 | final response = await _client.post(
49 | _api.userSubmissions(),
50 | headers: {
51 | 'Content-Type': 'application/json',
52 | 'User-Agent': 'Mozilla/5.0',
53 | },
54 | body: jsonEncode(data),
55 | );
56 |
57 | if (response.statusCode == 403) {
58 | throw HttpException('Leetcode forbidden error per user $nickname\nBody:\n${response.body}');
59 | }
60 |
61 | if (response.statusCode != 200) {
62 | throw HttpException('Error ${response.statusCode}: ${response.body}');
63 | }
64 |
65 | final json = jsonDecode(response.body) as Map;
66 |
67 | if (json case {'data': {'recentAcSubmissionList': final List recentAcSubmissionList}}) {
68 | final result = recentAcSubmissionList.map((entry) {
69 | final map = entry as Map;
70 | return (
71 | slug: map['titleSlug'] as String,
72 | timestamp: int.parse(map['timestamp'] as String),
73 | );
74 | });
75 |
76 | return result.toList();
77 | } else {
78 | throw FormatException('Leetcode graphql dont match the format ($json)');
79 | }
80 | } on Exception catch (e, s) {
81 | LoggerService().writeError(e, s);
82 | return null;
83 | }
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/lib/extensions/file_extensions.dart:
--------------------------------------------------------------------------------
1 | import 'dart:io';
2 |
3 | extension FileX on File {
4 | Future get isEmpty async => (await readAsBytes()).isEmpty;
5 |
6 | bool get isEmptySync => readAsBytesSync().isEmpty;
7 | }
8 |
--------------------------------------------------------------------------------
/lib/extensions/int_extensions.dart:
--------------------------------------------------------------------------------
1 | extension IntX on int {
2 | bool inRange(int start, int end) => this >= start && this <= end;
3 | }
4 |
--------------------------------------------------------------------------------
/lib/extensions/string_extensions.dart:
--------------------------------------------------------------------------------
1 | extension StringX on String {
2 | String capitalize() => length > 0 ? this[0].toUpperCase() + substring(1) : this;
3 |
4 | String eachCapitalize([String separator = ' ']) => split(separator)
5 | .map(
6 | (word) => word.capitalize(),
7 | )
8 | .join(separator);
9 | }
10 |
--------------------------------------------------------------------------------
/lib/service/leetcode_service.dart:
--------------------------------------------------------------------------------
1 | import 'dart:async';
2 |
3 | import 'package:suai_leetcode_bot/data/database/database.dart';
4 | import 'package:suai_leetcode_bot/data/repositories/leetcode_repository.dart';
5 |
6 | final class LeetCodeService {
7 | const LeetCodeService({
8 | required int leetCodeUpdateIntervalInSeconds,
9 | required int leetCodeBatchRequestSize,
10 | required int leetCodeUpdateCoolingTimeInSeconds,
11 | required AppDatabase database,
12 | required HttpLeetCodeRepository leetCodeRepository,
13 | }) : _leetCodeUpdateIntervalInSeconds = leetCodeUpdateIntervalInSeconds,
14 | _leetCodeBatchRequestSize = leetCodeBatchRequestSize,
15 | _leetCodeUpdateCoolingTimeInSeconds = leetCodeUpdateCoolingTimeInSeconds,
16 | _leetCodeRepository = leetCodeRepository,
17 | _database = database;
18 |
19 | static final StreamController _nextTimerRunStreamController = StreamController.broadcast();
20 | static Stream get nextTimerRun => _nextTimerRunStreamController.stream;
21 |
22 | final int _leetCodeBatchRequestSize;
23 | final int _leetCodeUpdateIntervalInSeconds;
24 | final int _leetCodeUpdateCoolingTimeInSeconds;
25 | final AppDatabase _database;
26 | final HttpLeetCodeRepository _leetCodeRepository;
27 |
28 | void start() {
29 | final updateDuration = Duration(seconds: _leetCodeUpdateIntervalInSeconds + _leetCodeUpdateCoolingTimeInSeconds);
30 | _nextTimerRunStreamController.add(DateTime.now().add(updateDuration));
31 |
32 | Timer.periodic(updateDuration, (timer) {
33 | _nextTimerRunStreamController.add(DateTime.now().add(updateDuration));
34 | _updateAccountsPeriodically();
35 | });
36 | }
37 |
38 | Future _updateAccountsPeriodically() async {
39 | final accounts = await _database.activeLeetCodeAccounts;
40 | final totalBatches = (accounts.length / _leetCodeBatchRequestSize).ceil();
41 | final delayBetweenBatches = _leetCodeUpdateIntervalInSeconds ~/ totalBatches;
42 |
43 | for (var i = 0; i < accounts.length; i += _leetCodeBatchRequestSize) {
44 | final batch = accounts.skip(i).take(_leetCodeBatchRequestSize);
45 | await _updateBatch(batch.toList());
46 | if (i + _leetCodeBatchRequestSize < accounts.length) {
47 | await Future.delayed(Duration(seconds: delayBetweenBatches));
48 | }
49 | }
50 | }
51 |
52 | Future _updateBatch(List accounts) async {
53 | for (final account in accounts) {
54 | final submissions = await _leetCodeRepository.getRecentUserSubmission(account.nickname);
55 | if (submissions != null) {
56 | await _database.updateUserSubmissions(userId: account.user, submissions: submissions);
57 | }
58 | }
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/lib/service/logger_service.dart:
--------------------------------------------------------------------------------
1 | import 'dart:io';
2 |
3 | import 'package:path/path.dart' as path;
4 |
5 | final class LoggerService {
6 | factory LoggerService() => _instance;
7 |
8 | LoggerService._internal();
9 |
10 | static final LoggerService _instance = LoggerService._internal();
11 |
12 | File get file {
13 | final scriptFolderPath = File(Platform.script.toFilePath()).parent.path;
14 | final logsFolderPath = path.join(scriptFolderPath, 'logs');
15 | final logsFile = File(path.join(logsFolderPath, 'logs.logs'))..createSync(recursive: true);
16 | return logsFile;
17 | }
18 |
19 | void writeError(Object e, StackTrace s) {
20 | final moscowTime = DateTime.now().add(const Duration(hours: 3));
21 |
22 | final buffer = StringBuffer()
23 | ..writeln('${"-" * 10} BEGIN OF ERROR ${"-" * 10}')
24 | ..writeln('With time (UTC+3): $moscowTime')
25 | ..writeln('Error $e with StackTrace \n$s')
26 | ..writeln('${"-" * 10} END OF ERROR ${"-" * 10}')
27 | ..writeln('\n');
28 |
29 | file.writeAsStringSync(buffer.toString(), mode: FileMode.append);
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/pubspec.yaml:
--------------------------------------------------------------------------------
1 | name: suai_leetcode_bot
2 | version: 1.1.0
3 | repository: https://github.com/cocahonka/suai-leetcode-bot
4 |
5 | environment:
6 | sdk: ^3.2.6
7 |
8 | dependencies:
9 | collection: ^1.18.0
10 | drift: ^2.15.0
11 | excel: ^4.0.2
12 | http: ^1.2.0
13 | meta: ^1.12.0
14 | path: ^1.8.0
15 | sqlite3: ^2.4.0
16 | televerse: ^1.13.1
17 |
18 | dev_dependencies:
19 | build_runner: ^2.4.8
20 | drift_dev: ^2.15.0
21 | very_good_analysis: ^5.1.0
22 |
--------------------------------------------------------------------------------