├── .gitignore
├── CHANGELOG.md
├── LICENSE
├── README.md
├── data.db
├── example.config.toml
├── module
├── __init__.py
├── aiodb.py
├── aioitad.py
├── aiokeylol.py
├── aionet.py
├── aiosteam.py
├── config.py
├── crawer.py
├── filter.py
├── handlers
│ ├── __init__.py
│ ├── bbcode.py
│ ├── console.py
│ ├── excel.py
│ ├── json.py
│ └── markdown.py
├── log.py
├── sort.py
├── static.py
├── utils.py
└── version.py
├── requirements.txt
└── run.py
/.gitignore:
--------------------------------------------------------------------------------
1 | *.pyc
2 | __pycache__
3 | config.toml
4 | output/
5 | .vscode/
6 | build/
7 | release/
8 | test.py
9 | filter.toml
10 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # 更新日志
2 |
3 | ## 2020.11.26 v1.11
4 |
5 | 修复因为拼写错误导致无法显示原价的bug
6 |
7 | ## 2020.11.15 v1.10
8 |
9 | 加入过滤器功能
10 | 支持导出为json
11 | 修改数据储存格式,优化性能
12 | 修复一些小错误
13 |
14 | ## 2020.11.9 v1.03
15 |
16 | 修改了配置文件格式,建议重新配置一遍
17 | 现在代理选项同时作用于itad和steam模块
18 | 暂时禁用console输出功能,因为打包后的程序一直出错
19 | 预计下个版本加入过滤器和排序功能
20 |
21 | ## 2020.11.8 v1.01
22 |
23 | 修改了几处代码风格问题
24 | 执行结束以后等待键盘输入,而不是直接退出
25 |
26 | ## 2020.11.8 v1.00
27 |
28 | 支持 BBCode xlsx markdown 以及直接在控制台输出(打包版不可用)
29 | 支持本地缓存,加快查询速度
30 | 暂不支持过滤器和排序,可以导出为xlsx再使用excel进行数据操作
31 | 当前版本多线程并发做的比较辣鸡,愿望单数量超过2000条可能会被当成网络攻击导致后面的数据获取失败
32 |
33 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | # Steam Wishlist Helper
3 |
4 | [![Codacy Badge][b1]][b2] [![Release][b5]][b4] [![Download][b3]][b4] [![License][b7]][b6]
5 |
6 | 结合ITAD的价格查询功能, 生成一份自己的游戏折扣列表
7 |
8 | 需要Python3.8及以上
9 |
10 | > [蓝奏云镜像][2] 密码:cg84
11 |
12 | ## 使用方法
13 |
14 | * 从[发布页][0]或者[蓝奏云][2] (密码:cg84) 下载最新版本并解压
15 | * pip install -r requirements.txt
16 | * 将 example.config.toml 重命名为 config.toml
17 | * 修改 config.toml , 填入自己的API Token([申请地址][1])
18 | * python3 run.py
19 |
20 | ## TODO
21 |
22 | - [x] 加入过滤器
23 | - [ ] 加入排序功能
24 | - [ ] 加一个GUI
25 |
26 | [b1]:https://app.codacy.com/project/badge/Grade/d295529050004976aa50252d61eda98e
27 | [b2]:https://www.codacy.com/gh/chr233/steam_wishlist_helper/dashboard?utm_source=github.com&utm_medium=referral&utm_content=chr233/steam_wishlist_helper&utm_campaign=Badge_Grade
28 | [b3]: https://img.shields.io/github/downloads/chr233/steam_wishlist_helper/total
29 | [b4]: https://github.com/chr233/steam_wishlist_helper/releases
30 | [b5]: https://img.shields.io/github/v/release/chr233/steam_wishlist_helper
31 | [b6]: https://github.com/chr233/steam_wishlist_helper/blob/master/license
32 | [b7]: https://img.shields.io/github/license/chr233/steam_wishlist_helper
33 | [0]: https://github.com/chr233/steam_wishlist_helper/releases
34 | [1]: https://new.isthereanydeal.com/apps/mine/
35 | [2]: https://wws.lanzous.com/b01nqwxta
36 |
--------------------------------------------------------------------------------
/data.db:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/chr233/steam_wishlist_helper/aedf568d83336d035dc8fec494639b3854d5f8c7/data.db
--------------------------------------------------------------------------------
/example.config.toml:
--------------------------------------------------------------------------------
1 | [auto] # 可选配置
2 | # 如果配置了下面的值,脚本将会自动代入配置的值
3 | # 如果没有配置,脚本将会要求你输入对应项目
4 |
5 | # Steam64位ID,只能为64位ID
6 | steamid = 0
7 | # 如果有多个账号,也可以这这么配置
8 | # steamid = [11111,22222,33333]
9 |
10 | [other] # 其他设置
11 | # 是否在运行结束后显示等待屏幕, 如果是在终端中运行可以禁用
12 | # true: 显示等待屏幕, false: 不显示等待屏幕,直接退出
13 | wait_screen = true
14 |
15 | [itad] # itad模块设置,用于获取价格信息
16 | # API Token, 必填
17 | # 申请地址: https://new.isthereanydeal.com/apps/mine/
18 | token = ""
19 |
20 | # 价格区域
21 | # 设置值参考: https://blog.chrxw.com/archives/2020/11/08/1411.html
22 | country = "CN"
23 | region = "cn"
24 | # 货币符号
25 | currency_symbol = '¥'
26 |
27 | [keylol] # keylol模块设置,用于获取游戏标签,卡牌等信息
28 | # 是否启用keylol模块,禁用的话将使用itad模块替代
29 | # true:启用, false:禁用
30 | enable = false
31 |
32 | [steam] # Steam网页端语言选项
33 | # schinese代表简中, english代表英文
34 | language = "schinese"
35 | # 是否使用小尺寸的游戏图片,改为false将会使用大一些的图片
36 | small_game_pic = true
37 |
38 | [net] # 代理设置,只支持http协议(不支持socks5)
39 | # 如果使用全局模式应该不需要设置
40 | # 非空值: 启用代理, false: 禁用代理
41 | proxy = false
42 | # proxy = 'http://127.0.0.1:1081'
43 |
44 | [output] #输出配置
45 | # 直接在控制台显示
46 | console = true # 打包出了点问题暂时不可用
47 |
48 | # markdown格式的输出文件(Typora等软件可以打开)
49 | markdown = true
50 |
51 | # xlsx格式的输出文件(Excel可以打开)
52 | xlsx = true
53 |
54 | # 论坛使用的BBCODE
55 | bbcode = true
56 |
57 | # 导出Json,方便二次开发
58 | json = true
59 |
60 | [sort] # 排序设置
61 | ###################
62 | # 排序功能暂未实装 #
63 | ###################
64 |
65 | # 使用数字表示排序方式,负数表示逆向排序
66 | # 例如:
67 | # 1: appid 从小到大
68 | # -1: appid 从大到小 (以下类似)
69 |
70 | # 0: 不排序 (按照Steam返回的顺序输出)
71 | # 1: appid 从小到大
72 | # 2: 史低 -> 近史低 -> 未达史低 ,没有价格的项目始终放在最下面
73 | # 3: 折扣幅度 从小到大 ,没有价格的项目始终放在最下面
74 | # 4: 现价 从低到高 ,没有价格的项目始终放在最下面
75 | # 5: 原价 从低到高 ,没有价格的项目始终放在最下面
76 | # 6: 好评率 从低到高
77 | # 7: 类型 游戏 -> 软件 -> DLC -> 视频
78 |
79 | # [0-7]:选择排序依据,如果排名相同会按照appid从小到大排序
80 | index = 1
81 |
82 | [filter] # 过滤器设置
83 | # 错误的配置有可能得到意外的结果
84 |
85 | # 类似于白名单,【过滤掉】的意思是【删掉】
86 |
87 | # 任意规则的值设置为 -1 代表禁用该条规则
88 |
89 | # -----其他过滤器---------------------------------------
90 | # true:过滤掉 没有 卡牌的游戏, false/-1:禁用
91 | has_card = -1
92 |
93 | # -----价格过滤器---------------------------------------
94 | # 如果游戏未发售,视为 没有价格
95 | # 如果价格获取出错,视为 没有价格
96 | # 免费游戏价格视为 0,但是既不算有价格也不算没有价格
97 |
98 | # false:过滤掉 免费 的游戏, true/-1:禁用
99 | price_free = -1
100 | # false:过滤掉 有价格 的游戏, true/-1:禁用
101 | price_set = -1
102 | # false:过滤掉 没有价格 的游戏, true/-1:禁用
103 | price_noset = -1
104 |
105 | # 下面的价格过滤器只对有价格的游戏有效,忽略没有价格和免费的游戏
106 |
107 | # 任意数值:过滤掉当前价格 低于 设定值的游戏, -1:禁用
108 | price_higher = -1
109 | # 任意数值:过滤掉当前价格 高于 设定值的游戏, -1:禁用
110 | price_lower = -1
111 |
112 | # -----折扣过滤器---------------------------------------
113 | # 折扣过滤器只对有价格的游戏有效,忽略没有价格和免费的游戏
114 |
115 | # 折扣计算方法: (原价 - 现价) / 原价 * 100
116 | # 免费游戏和没有价格的游戏折扣视为 0
117 | # 未打折折扣视为 0, 限免折扣视为 100
118 |
119 | # false:过滤掉 未打折 的游戏, true/-1:禁用
120 | discount_no = -1
121 |
122 | # 下面的折扣过滤器只对有折扣的游戏有效,忽略未打折的游戏
123 |
124 | # [1-100]:过滤掉当前折扣 低于 设定值的游戏, -1:禁用
125 | discount_higher = -1
126 | # [1-100]:过滤掉当前折扣 高于 设定值的游戏, -1:禁用
127 | discount_lower = -1
128 |
129 | # 近史低条件: (现价-史低价) / 原价 <= 5%
130 | # 一个游戏只有一种状态,要么是史低,要么是近史低,要么是非史低
131 |
132 | # false:过滤掉 未达到 史低或近史低的游戏, true/-1:禁用
133 | discount_not_lowest = -1
134 | # false:过滤掉 达到 史低的游戏, true/-1:禁用
135 | discount_is_lowest = -1
136 | # false:过滤掉 达到 近史低的游戏, true/-1:禁用
137 | discount_almost_lowest = -1
138 |
139 | # -----评测过滤器---------------------------------------
140 | # 评价等级说明:
141 | # 0:评测数量不足 (未发售和预售游戏会显示这个)
142 | # 1->4:差评如潮 -> 特别差评 -> 差评 -> 多半差评
143 | # 5:褒贬不一
144 | # 6->9:多半好评 -> 好评 -> 特别好评 -> 好评如潮
145 |
146 | # false:过滤掉 评测数量不足(等级0) 的游戏, true/-1: 禁用
147 | review_no_score = -1
148 |
149 | # 下面的过滤器都会 忽略 评测数量不足 的游戏
150 |
151 | # [1-9]:过滤掉评价等级 低于 设定值的游戏, 0和-1:禁用
152 | review_score_higher = -1
153 | # [1-9]:过滤掉评价等级 高于 设定值的游戏, 0和-1:禁用
154 | review_score_lower = -1
155 |
156 | # [0-100]:过滤掉好评率 低于 设定值的游戏, -1:禁用
157 | review_percent_higher = -1
158 | # [0-100]:过滤掉好评率 高于 设定值的游戏, -1:禁用
159 | review_percent_lower = -1
160 |
161 | # 任意数值:过滤掉总评价数 低于 设定值的游戏, -1:禁用
162 | review_total_higher = -1
163 | # 任意数值:过滤掉总评价数 高于 设定值的游戏, -1:禁用
164 | review_total_lower = -1
165 |
166 | # -----平台过滤器---------------------------------------
167 | # true: 过滤掉 不支持 Windows的游戏, false: 不过滤, -1: 禁用
168 | platform_windows = -1
169 | # true: 过滤掉 不支持 Mac的游戏, false: 不过滤, -1: 禁用
170 | platform_mac = -1
171 | # true: 过滤掉 不支持 Linux的游戏, false: 不过滤, -1: 禁用
172 | platform_linux = -1
173 |
174 | # PS: Steam上真的有不支持Windows的游戏吗?
175 |
176 | # -----标签过滤器---------------------------------------
177 | # 游戏标签名称由Steam语言决定,不同的语言会获取到不同的标签
178 |
179 | # false: 过滤掉 没有 标签的游戏, true/-1:禁用
180 | tags_enpty = -1
181 |
182 | # 下面的过滤器都会 忽略 没有 标签的游戏
183 |
184 | # 过滤规则示例:
185 | # 游戏A: '射击','动漫','动作','弹幕射击'
186 | # 游戏B: '视觉小说','动漫','女性主角','冒险','独立'
187 | # 游戏C: '休闲','冒险','独立'
188 |
189 | # tags_include = ['动漫'] -> 过滤后 -> 游戏A,游戏B
190 | # tags_include = ['动漫','射击'] -> 过滤后 -> 游戏A
191 | # tags_exclude = ['休闲'] -> 过滤后 -> 游戏C
192 | # tags_exclude = ['冒险','独立'] -> 过滤后 -> 游戏B,游戏C
193 |
194 | # 可以只写标签名称的一部分,只要标签中包含设置值就算匹配
195 | # 如果设置了多个标签,则需要每个设置值都被匹配才算通过匹配
196 |
197 | # 错误的配置可能得到空结果,例如:
198 | # tags_include = ['射击游戏'] -> 过滤后 -> 无匹配
199 | # 得到空结果的原因是没有游戏有'射击游戏'这个标签
200 |
201 | # 任意文本:过滤掉标签 不匹配 规则的游戏, -1: 禁用
202 | tags_include = -1
203 | # tags_include = ['标签1']
204 | # tags_include = ['标签1','标签2']
205 |
206 | # 任意文本:过滤掉标签 匹配 规则的游戏, -1: 禁用
207 | tags_exclude = -1
208 | # tags_exclude = ['标签1']
209 | # tags_exclude = ['标签1','标签2']
210 |
211 | # 可以设置更多标签,比如['标签1','标签2','标签3','标签4']
212 |
--------------------------------------------------------------------------------
/module/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 | '''
3 | # @Author : Chr_
4 | # @Date : 2020-11-01 00:02:11
5 | # @LastEditors : Chr_
6 | # @LastEditTime : 2020-11-12 21:07:27
7 | # @Description : 功能模块
8 | '''
9 | __all__ = ['crawer']
--------------------------------------------------------------------------------
/module/aiodb.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 | '''
3 | # @Author : Chr_
4 | # @Date : 2020-07-08 10:42:53
5 | # @LastEditors : Chr_
6 | # @LastEditTime : 2020-11-08 20:12:14
7 | # @Description : 读写缓存数据库
8 | '''
9 |
10 | from .log import get_logger
11 | from aiosqlite import DatabaseError, OperationalError, NotSupportedError,Connection
12 |
13 | logger = get_logger('Db')
14 |
15 |
16 | async def init_db(conn: Connection, drop_if_exist: bool = False):
17 | '''
18 | 初始化数据库
19 |
20 | 参数:
21 | conn: 数据库连接对象
22 | drop_if_exit: 如果数据表已存在是否先删表
23 | '''
24 | sql = ('PRAGMA foreign_keys = false;'
25 | f'{"""DROP TABLE IF EXISTS "plains";""" if drop_if_exist else ""}'
26 | 'CREATE TABLE "plains" ('
27 | '"id" INTEGER NOT NULL COLLATE BINARY,'
28 | '"plain" TEXT NOT NULL,'
29 | 'PRIMARY KEY ("id"));'
30 | 'CREATE UNIQUE INDEX "id" ON "plains" ("id" COLLATE BINARY ASC);'
31 | 'PRAGMA foreign_keys = true;')
32 | if drop_if_exist:
33 | logger.warning('即将清除原数据表')
34 | else:
35 | logger.warning('即将初始化数据库')
36 | try:
37 | await conn.executescript(sql)
38 | await conn.commit()
39 | logger.warning('初始化数据库完成')
40 | except (DatabaseError, OperationalError, NotSupportedError) as e:
41 | logger.warning(f'数据库读写失败 - {e}')
42 |
43 |
44 | async def set_plain(conn: Connection, id_: int, plain: str):
45 | '''
46 | 向数据库写入id和plain
47 |
48 | 参数:
49 | conn: 数据库连接对象
50 | id: appid或者subid,需为数字
51 | plain: itad使用的游戏标识
52 | '''
53 | sql = 'INSERT INTO "main"."plains"("id", "plain") VALUES (?,?);'
54 | try:
55 | await conn.execute(sql, (str(id_), plain))
56 | await conn.commit()
57 | except (DatabaseError, OperationalError, NotSupportedError) as e:
58 | logger.warning(f'操作数据库失败 {e}')
59 |
60 |
61 | async def get_plain(conn: Connection, id_: int) -> str:
62 | '''
63 | 使用id向数据库查询plain
64 |
65 | 参数:
66 | conn: 数据库连接对象
67 | id: appid或者subid,需为数字
68 | '''
69 | sql = 'SELECT "plain" From "main"."plains" WHERE "id" = ?;'
70 | try:
71 | cur = await conn.cursor()
72 | await cur.execute(sql, (str(id_),))
73 | result = await cur.fetchone()
74 | if result:
75 | plain, = result
76 | else:
77 | plain = None
78 | return (plain)
79 | except (DatabaseError, OperationalError, NotSupportedError) as e:
80 | logger.warning(f'操作数据库失败 {e}')
81 |
82 |
83 | async def del_plain(conn: Connection, id_: int) -> str:
84 | '''
85 | 删除指定id,仅供测试
86 |
87 | 参数:
88 | conn: 数据库连接对象
89 | id: appid或者subid,需为数字
90 | '''
91 | sql = 'DELETE FROM "main"."plains" WHERE "id" = ?;'
92 | try:
93 | await conn.execute(sql, (str(id_),))
94 | await conn.commit()
95 | except (DatabaseError, OperationalError, NotSupportedError) as e:
96 | logger.warning(f'操作数据库失败 {e}')
97 |
--------------------------------------------------------------------------------
/module/aioitad.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 | '''
3 | # @Author : Chr_
4 | # @Date : 2020-07-08 19:48:26
5 | # @LastEditors : Chr_
6 | # @LastEditTime : 2020-11-16 18:16:20
7 | # @Description : 对接ITAD的API【异步】
8 | '''
9 |
10 | import asyncio
11 | import aiosqlite
12 |
13 | from os import path
14 | from httpx import AsyncClient
15 | from json import JSONDecodeError
16 |
17 | from .aiodb import get_plain, set_plain, init_db
18 | from .log import get_logger
19 | from .aionet import adv_http_get
20 | from .static import URLs, DB_NAME
21 |
22 | logger = get_logger('ITAD')
23 |
24 |
25 | async def get_plains(ids: list, token: str, use_cache: bool = True,
26 | proxy: dict = None) -> dict:
27 | '''
28 | 把appid或subid转换成IsThereAnyDeal使用的plainid
29 |
30 | 参数:
31 | ids: appid列表,例如[730]
32 | token: ITAD的API token
33 | [use_cache]: 是否使用缓存,开启后优先读取本地数据库,默认为True
34 |
35 | 返回:
36 | dict: {id:plain} (如果id有误则返回None)
37 | '''
38 | if not path.exists(DB_NAME):
39 | logger.warning('缓存数据库不存在,创建data.db')
40 | async with aiosqlite.connect(DB_NAME) as conn:
41 | await init_db(conn, True)
42 |
43 | params = {'key': token, 'shop': 'steam', 'ids': ''}
44 | id2pdict = {}
45 | if use_cache: # 如果启用缓存则优先从本地读取plain
46 | async with aiosqlite.connect(DB_NAME) as conn:
47 | ncache = []
48 | for id_ in ids:
49 | plain = await get_plain(conn, id_)
50 | if not plain:
51 | ncache.append(id_)
52 | else:
53 | id2pdict[id_] = plain
54 | else:
55 | ncache = ids
56 | async with AsyncClient(proxies=proxy) as client:
57 | max_ = len(ncache)
58 | if max_:
59 | tasks = set()
60 | for i in range(0, max_, 30):
61 | part = ncache[i:i+30]
62 | tasks.add(asyncio.create_task(
63 | _get_plain(client, params, part)))
64 | await asyncio.wait(tasks)
65 |
66 | for task in tasks:
67 | dic = task.result()
68 | if use_cache: # 如果启用缓存则将结果写入数据库
69 | async with aiosqlite.connect(DB_NAME) as conn:
70 | for key in dic.keys():
71 | if dic[key]:
72 | await set_plain(conn, key, dic[key])
73 | id2pdict.update(dic)
74 | return (id2pdict)
75 |
76 |
77 | async def _get_plain(client: AsyncClient, params: dict, ids: list) -> str:
78 | '''
79 | 把appid或subid转换成IsThereAnyDeal使用的plainid
80 |
81 | 参数:
82 | client: httpx Client对象
83 | params: 参考get_plain里的用法
84 | 返回:
85 | dict: {id:plain} (如果id有误则返回None)
86 | '''
87 | url = URLs.ITAD_ID_To_Plain
88 | params['ids'] = ','.join([f'app/{x}' for x in ids])
89 | resp = await adv_http_get(client=client, url=url, params=params)
90 | result = {}
91 | if resp:
92 | try:
93 | data = resp.json().get('data', {})
94 | except (JSONDecodeError, AttributeError) as e:
95 | logger.error(f'解析json出错 - {e}')
96 | data = {}
97 | for id_ in ids:
98 | plain = data.get(f'app/{id_}', None)
99 | if not plain:
100 | logger.warning(f'读取App{id_}出错,忽略该App')
101 | else:
102 | result[id_] = plain
103 | return (result)
104 |
105 |
106 | async def get_current_price(plains: list, token: str, region: str, country: str,
107 | proxy: dict = None) -> dict:
108 | '''
109 | 使用plainid获取当前价格
110 |
111 | 参数:
112 | plains: plain列表,例如['counterstrikeglobaloffensive']
113 | token: ITAD的API token
114 | region: 地区
115 | country: 国家
116 | 返回:
117 | dict: 价格字典,以plain为键名,每个键是(现价,原价,折扣)
118 | '''
119 | params = {'key': token, 'plains': '', 'region': region,
120 | 'country': country, 'shops': 'steam'}
121 | pricedict = {}
122 | if plains:
123 | async with AsyncClient(proxies=proxy) as client:
124 | max_ = len(plains)
125 | tasks = set()
126 | for i in range(0, max_, 5):
127 | part = plains[i:i+5]
128 | tasks.add(asyncio.create_task(
129 | _get_current_price(client, params, part)))
130 | await asyncio.wait(tasks)
131 | for task in tasks:
132 | dic = task.result()
133 | pricedict.update(dic)
134 | return (pricedict)
135 |
136 |
137 | async def _get_current_price(client: AsyncClient, params: dict, plains: list) -> dict:
138 | '''
139 | 获取Steam商店当前价格
140 |
141 | 参数:
142 | client: httpx Client对象
143 | params: 参考get_current_price里的用法
144 | 返回:
145 | dict: 价格字典,以plain为键名,每个键是(现价,原价,折扣)
146 | '''
147 | url = URLs.ITAD_Get_Current_Prices
148 | params['plains'] = ','.join(plains)
149 | resp = await adv_http_get(client=client, url=url, params=params)
150 | pricedict = {}
151 | if resp:
152 | try:
153 | data = resp.json().get('data', {})
154 | except (JSONDecodeError, AttributeError):
155 | logger.error('json解析失败')
156 | data = {}
157 | for plain in data.keys():
158 | d = data[plain].get('list', None)
159 | if len(d) > 1:
160 | logger.debug(f'{plain} {d}')
161 | if d:
162 | p_new = d[0]['price_new']
163 | p_old = d[0]['price_old']
164 | p_cut = d[0]['price_cut']
165 | else:
166 | # 未发售游戏,没有价格,标记为-1
167 | p_new, p_old, p_cut = -1, -1, 0
168 | pricedict[plain] = (p_new, p_old, p_cut)
169 | return (pricedict)
170 |
171 |
172 | async def get_lowest_price(plains: list, token: str, region: str, country: str,
173 | proxy: dict = None) -> dict:
174 | '''
175 | 获取Steam商店史低价格
176 |
177 | 参数:
178 | plains: plain列表,例如['counterstrikeglobaloffensive']
179 | token: ITAD的API token
180 | region: 地区
181 | country: 国家
182 | 返回:
183 | dict: 价格字典,以plain为键名,每个键是(史低,史低折扣,史低时间)
184 | '''
185 | params = {'key': token, 'plains': '', 'region': region,
186 | 'country': country, 'shops': 'steam'}
187 | pricedict = {}
188 | if plains:
189 | async with AsyncClient(proxies=proxy) as client:
190 | max_ = len(plains)
191 | tasks = set()
192 | for i in range(0, max_, 5):
193 | part = plains[i:i+5]
194 | tasks.add(asyncio.create_task(
195 | _get_lowest_price(client, params, part)))
196 | await asyncio.wait(tasks)
197 | for task in tasks:
198 | dic = task.result()
199 | pricedict.update(dic)
200 | return (pricedict)
201 |
202 |
203 | async def _get_lowest_price(client: AsyncClient, params: dict, plains: list) -> dict:
204 | '''
205 | 获取Steam商店史低价格
206 |
207 | 参数:
208 | client: httpx Client对象
209 | params: 参考get_lowest_price里的用法
210 | plains: plains列表
211 | 返回:
212 | dict: 价格字典,以plain为键名,每个键是(史低,史低折扣,史低时间)
213 | '''
214 | url = URLs.ITAD_Get_Lowest_Prices
215 | params['plains'] = ','.join(plains)
216 | resp = await adv_http_get(client=client, url=url, params=params)
217 | pricedict = {}
218 | if resp:
219 | try:
220 | data = resp.json().get('data', {})
221 | except (JSONDecodeError, AttributeError):
222 | logger.error('json解析失败')
223 | data = {}
224 | for plain in data.keys():
225 | d = data[plain]
226 | if 'price' in d:
227 | p_low = d['price']
228 | p_cut = d['cut']
229 | p_time = d['added']
230 | else:
231 | # 未发售游戏,没有价格,标记为-1
232 | p_low, p_cut, p_time = -1, 0, 0
233 | pricedict[plain] = (p_low, p_cut, p_time)
234 | return (pricedict)
235 |
236 |
237 | async def get_base_info(plains: list, token: str, proxy: dict = None) -> dict:
238 | '''
239 | 获取Steam商店游戏信息【只能获取2个属性,不建议使用】
240 |
241 | 参数:
242 | plains: plain列表,例如['counterstrikeglobaloffensive']
243 | token: ITAD的API token
244 | 返回:
245 | dict: 游戏信息字典,(有成就,有卡牌)
246 | '''
247 | params = {'key': token, 'plains': ''}
248 | infodict = {}
249 | if plains:
250 | async with AsyncClient(proxies=proxy) as client:
251 | max_ = len(plains)
252 | tasks = set()
253 | for i in range(0, max_, 5):
254 | part = plains[i:i+5]
255 | tasks.add(asyncio.create_task(
256 | _get_base_info(client, params, part)))
257 | await asyncio.wait(tasks)
258 | for task in tasks:
259 | dic = task.result()
260 | infodict.update(dic)
261 | return (infodict)
262 |
263 |
264 | async def _get_base_info(client: AsyncClient, params: dict, plains: list) -> dict:
265 | '''
266 | 获取Steam商店史低价格
267 |
268 | 参数:
269 | client: httpx Client对象
270 | params: 参考get_base_info里的用法
271 | plains: plains列表
272 | 返回:
273 | dict: 游戏信息字典
274 | '''
275 | url = URLs.ITAD_Get_Game_Info
276 | params['plains'] = ','.join(plains)
277 | resp = await adv_http_get(client=client, url=url, params=params)
278 | infodict = {}
279 | if resp:
280 | try:
281 | data = resp.json().get('data', {})
282 | except (JSONDecodeError, AttributeError):
283 | logger.error(f'json解析失败')
284 | data = {}
285 | for plain in data.keys():
286 | d = data[plain]
287 | # has_achi = d.get('achievements', False)
288 | has_card = d.get('trading_cards', False)
289 | infodict[plain] = has_card
290 | return (infodict)
291 |
--------------------------------------------------------------------------------
/module/aiokeylol.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 | '''
3 | # @Author : Chr_
4 | # @Date : 2020-06-30 05:08:57
5 | # @LastEditors : Chr_
6 | # @LastEditTime : 2020-11-14 23:46:41
7 | # @Description : 对接Keylol的API【异步】
8 | '''
9 |
10 | import asyncio
11 | from httpx import AsyncClient
12 |
13 | from .log import get_logger
14 | from .static import URLs
15 | from .aionet import adv_http_get_keylol
16 |
17 |
18 | logger = get_logger('Keylol')
19 |
20 |
21 | async def get_games_tags(appids: list) -> dict:
22 | '''
23 | 异步读取Steam愿望单
24 |
25 | 参数:
26 | appids: appid列表
27 | 返回:
28 | dict: 游戏信息字典
29 | '''
30 | gameinfo = {}
31 | if appids:
32 | async with AsyncClient() as client:
33 | tasks = {
34 | asyncio.create_task(_get_game_tags(client=client, appid=i)) for i in appids
35 | }
36 | await asyncio.wait(tasks)
37 | for task in tasks:
38 | gameinfo.update(task.result())
39 | return (gameinfo)
40 |
41 |
42 | async def _get_game_tags(client: AsyncClient, appid: int) -> dict:
43 | '''
44 | 其乐API,读取steam游戏信息
45 |
46 | 参数:
47 | appid: appid
48 | 返回:
49 | dict: 包含游戏附加信息的dict
50 | '''
51 | url = URLs.Keylol_Get_Game_Info % appid
52 | async with AsyncClient() as client:
53 | jd = await adv_http_get_keylol(client=client,
54 | url=url,
55 | retrys=3)
56 | result = {}
57 | if jd:
58 | result[appid] = {
59 | # 'tags': set(jd.get('tags', []) + jd.get('genre', [])),
60 | # 'categories': [(int(x[0]), x[1])for x in raw.get('categories', [])],
61 | 'card': len(jd.get('card', [])) > 0,
62 | # 'description': jd.get('description', '')
63 | }
64 | return (result)
65 |
--------------------------------------------------------------------------------
/module/aionet.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 | '''
3 | # @Author : Chr_
4 | # @Date : 2020-07-11 12:25:45
5 | # @LastEditors : Chr_
6 | # @LastEditTime : 2020-11-09 19:49:21
7 | # @Description : 网络请求模块
8 | '''
9 | import re
10 | import json
11 | import asyncio
12 |
13 | from httpx import Response, AsyncClient
14 |
15 | from .log import get_logger
16 | from .static import TREAD_CD,TIMEOUT,HEADERS
17 |
18 | logger = get_logger('Net')
19 |
20 |
21 | async def adv_http_get(client: AsyncClient, url: str, params: dict = None,
22 | headers: dict = None, retrys: int = 3) -> Response:
23 | '''
24 | 出错自动重试的请求器
25 |
26 | 参数:
27 | client: httpx对象
28 | url: url
29 | params: params
30 | headers: headers
31 | [retrys]: 重试次数,默认为3
32 | 返回:
33 | Response: 请求结果
34 | '''
35 | if not headers :
36 | headers=HEADERS
37 | for _ in range(0, retrys):
38 | try:
39 | resp = await client.get(url=url, params=params, headers=headers,timeout=TIMEOUT)
40 | print('.', end='')
41 | await asyncio.sleep(TREAD_CD)
42 | return (resp)
43 | except Exception:
44 | if _ == 0:
45 | logger.debug('网络错误,暂停5秒')
46 | await asyncio.sleep(5)
47 | else:
48 | logger.warning('网络错误,暂停15秒')
49 | await asyncio.sleep(15)
50 |
51 | logger.error('网络错误,请求失败')
52 | return (None)
53 |
54 |
55 | async def adv_http_get_keylol(client: AsyncClient, url: str, params: dict = None,
56 | headers: dict = None, retrys: int = 3) -> Response:
57 | '''
58 | 出错自动重试的请求器
59 |
60 | 参数:
61 | client: httpx对象
62 | url: url
63 | params: params
64 | headers: headers
65 | [retrys]: 重试次数,默认为3
66 | 返回:
67 | Response: 请求结果
68 | '''
69 | if not headers :
70 | headers=HEADERS
71 | for _ in range(0, retrys):
72 | try:
73 | resp = await client.get(url=url, params=params, headers=headers,timeout=TIMEOUT)
74 | print('.', end='')
75 | pattern = re.compile(r'(\{.+\})', re.MULTILINE)
76 | matchobj = pattern.search(resp.text)
77 | jd = json.loads(matchobj.group(1))
78 | await asyncio.sleep(TREAD_CD)
79 | return (jd)
80 | except Exception:
81 | if _ == 0:
82 | logger.debug('网络错误,暂停8秒')
83 | await asyncio.sleep(8)
84 | else:
85 | logger.warning('网络错误,暂停30秒')
86 | await asyncio.sleep(30)
87 | logger.error('网络错误,请求失败')
88 | return {}
89 |
--------------------------------------------------------------------------------
/module/aiosteam.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 | '''
3 | # @Author : Chr_
4 | # @Date : 2020-06-21 15:41:24
5 | # @LastEditors : Chr_
6 | # @LastEditTime : 2020-11-14 23:58:09
7 | # @Description : 读取Steam愿望单信息【异步】
8 | '''
9 |
10 | import asyncio
11 | import re
12 | from json import JSONDecodeError
13 |
14 | from httpx import AsyncClient
15 | from .static import URLs, GameType2Num, Num2Review
16 | from .log import get_logger
17 | from .aionet import adv_http_get
18 |
19 | logger = get_logger('Steam')
20 |
21 | PIC_URL = URLs.Steam_Game_Pic_SM
22 |
23 |
24 | async def get_wishlish(steamid: int, settings: dict, proxy: dict = None) -> dict:
25 | '''
26 | 异步读取Steam愿望单
27 |
28 | 参数:
29 | steamid: 64位SteamID
30 | settings: 配置字典
31 | 返回:
32 | dict: {appid:{游戏详情}}
33 | '''
34 | global PIC_URL
35 |
36 | steam = settings.get('steam', {})
37 |
38 | lang = steam.get('lang', 'schinese')
39 | sm_pic = steam.get('small_game_pic', True)
40 | PIC_URL = URLs.Steam_Game_Pic_SM if sm_pic else URLs.Steam_Game_Pic_MD
41 |
42 | async with AsyncClient(proxies=proxy) as client:
43 | client.cookies = {
44 | 'Cookie': f'wants_mature_content=1;Steam_Language={lang}'
45 | }
46 | try:
47 | count = await _get_page_count(client=client, steamid=steamid)
48 | except ValueError as e:
49 | logger.warning(f'{e}')
50 | return ({})
51 | tasks = {
52 | asyncio.create_task(_get_single_page(client=client, steamid=steamid, page=p)) for p in range(0, count)
53 | }
54 | await asyncio.wait(tasks)
55 | wishlist = {}
56 | for task in tasks:
57 | wishlist.update(task.result())
58 | return (wishlist)
59 |
60 |
61 | async def _get_page_count(client: AsyncClient, steamid: int) -> int:
62 | '''
63 | 获取steam愿望单页数
64 |
65 | 参数:
66 | client: httpx异步client对象
67 | steamid: 64位steamid
68 | 返回:
69 | int: 愿望单页数
70 | '''
71 | url = URLs.Steam_Wishlist % (steamid, 'order')
72 | resp = await adv_http_get(client=client, url=url)
73 | if not resp:
74 | raise ValueError('网络错误,拉取失败')
75 |
76 | pattern = re.compile(r'nAdditionalPages\s=\s(\d+)')
77 | matchobj = pattern.search(resp.text)
78 | count = 0
79 | if matchobj:
80 | count = int(matchobj.group(1))
81 | else:
82 | raise ValueError(f'读取用户{steamid}的愿望单失败,请检查SteamID')
83 | if count == 0:
84 | raise ValueError(f'用户{steamid}愿望单为空,请检查是否将愿望单公开')
85 | return (count)
86 |
87 |
88 | async def _get_single_page(client: AsyncClient, steamid: int, page: int = 0) -> dict:
89 | '''
90 | 获取steam愿望单单页详情
91 |
92 | 参数:
93 | client: httpx异步client对象
94 | steamid: 64位steamid
95 | page: 页码
96 | 返回:
97 | dict: 愿望单信息字典,key:{游戏信息}
98 | '''
99 | url = URLs.Steam_Wishlist_XHR % (steamid, page)
100 | headers = {
101 | 'Referer': URLs.Steam_Wishlist % (steamid, 'order')
102 | }
103 | resp = await adv_http_get(client=client, url=url, headers=headers)
104 | wishlist = {}
105 | if resp:
106 | try:
107 | datajson = resp.json()
108 | except (JSONDecodeError, AttributeError):
109 | logger.error('Json解析失败')
110 | logger.error(resp.content)
111 | return {}
112 |
113 | for key in datajson.keys():
114 | data = datajson[key]
115 | review_score = int(data.get('review_score', -1))
116 | key = int(key)
117 | wishlist[key] = {
118 | 'name': data.get('name', '【解析出错】'),
119 | 'picture': PIC_URL % key,
120 | 'review': {
121 | 'score': review_score,
122 | 'result': Num2Review.get(review_score, 'Error'),
123 | 'total': int(data.get('reviews_total', '0').replace(',', '')),
124 | 'percent': int(data.get('reviews_percent', 0)),
125 | },
126 | 'release_date': int(data.get('release_date', 0)),
127 | 'subs': [s['id'] for s in data.get('subs', [])],
128 | 'free': data.get('is_free_game', False),
129 | 'type': GameType2Num.get(data.get('type', 'Error'), 0),
130 | 'priority': data.get('priority', 0),
131 | 'tags': data.get('tags', []),
132 | 'add_date': int(data.get('added', 0)),
133 | # 'rank': int(data.get('rank', 0)),
134 | 'price': {},
135 | 'platform': (
136 | data.get('win', 0) == 1,
137 | data.get('mac', 0) == 1,
138 | data.get('linux', 0) == 1
139 | ),
140 | "card": False
141 | }
142 | if wishlist[key]['name'] == '【解析出错】':
143 | logger.debug(f'数据解析失败 {data}')
144 | return (wishlist)
145 |
--------------------------------------------------------------------------------
/module/config.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 | '''
3 | # @Author : Chr_
4 | # @Date : 2020-06-30 17:32:56
5 | # @LastEditors : Chr_
6 | # @LastEditTime : 2020-11-15 02:38:55
7 | # @Description : 读取并验证配置
8 | '''
9 |
10 | from os import getcwd, path
11 |
12 | import toml
13 |
14 | from .log import get_logger
15 | from .utils import dint, fint, fbool, flist
16 | from .static import SORT_TYPE
17 |
18 | logger = get_logger('Config')
19 | default_path = path.join(getcwd(), 'config.toml')
20 |
21 |
22 | def get_config(path: str = default_path) -> dict:
23 | '''
24 | 读取并验证配置
25 |
26 | 参数:
27 | [path]:配置文件路径,默认为config.toml
28 | 返回:
29 | dict:验证过的配置字典,如果读取出错则返回None
30 | '''
31 | try:
32 | logger.info('开始读取配置')
33 | raw_cfg = dict(toml.load(path))
34 | cfg = verify_config(raw_cfg)
35 | logger.info('配置验证通过')
36 | return (cfg)
37 |
38 | except FileNotFoundError:
39 | logger.error(f'配置文件[{path}]不存在')
40 | with open(path, 'w+', encoding='utf-8') as f:
41 | toml.dump(verify_config({}), f)
42 | logger.error('已生成默认配置,请重新运行程序')
43 |
44 | except ValueError as e:
45 | logger.error(f'配置文件验证失败[{e}]')
46 |
47 |
48 | def verify_config(cfg: dict) -> dict:
49 | '''
50 | 验证配置
51 |
52 | 参数:
53 | cfg:配置字典
54 | 返回:
55 | dict:验证过的配置字典,剔除错误的和不必要的项目
56 | '''
57 | auto = __verify_auto(cfg.get('auto', {}))
58 |
59 | other = __verify_other(cfg.get('other', {}))
60 |
61 | itad = __verify_itad(cfg.get('itad', {}))
62 | if not itad['token'] and cfg:
63 | raise ValueError('未设置API token,可以自行申请或者使用文档中的公共token')
64 |
65 | keylol = __verify_keylol(cfg.get('keylol', {}))
66 |
67 | steam = __verify_steam(cfg.get('steam', {}))
68 |
69 | net = __verify_net(cfg.get('net', {}))
70 |
71 | output = __verify_output(cfg.get('output', {}))
72 |
73 | sort = __verify_sort(cfg.get('sort', {}))
74 |
75 | filter = __verify_filter(cfg.get('filter', {}))
76 |
77 | vcfg = {'auto': auto, 'other': other, 'itad': itad,
78 | 'keylol': keylol, 'steam': steam, 'net': net,
79 | 'output': output, 'sort': sort, 'filter': filter}
80 |
81 | return (vcfg)
82 |
83 |
84 | def __verify_auto(auto: dict) -> dict:
85 | '''
86 | 验证auto节
87 | '''
88 | steamid = auto.get('steamid', None)
89 | if (steamid and not isinstance(steamid, list)):
90 | steamid = [steamid]
91 |
92 | vsteamid = []
93 | if steamid:
94 | for i in range(0, len(steamid)):
95 | try:
96 | vsteamid.append(int(steamid[i]))
97 | except ValueError:
98 | logger.warning(f'错误的steamid: [{steamid[i]}]')
99 | auto = {'steamid': steamid}
100 | return (auto)
101 |
102 |
103 | def __verify_other(other: dict) -> dict:
104 | '''
105 | 验证other节
106 | '''
107 | wait_screen = bool(other.get('wait_screen', True))
108 | other = {'wait_screen': wait_screen}
109 | return (other)
110 |
111 |
112 | def __verify_itad(itad: dict) -> dict:
113 | '''
114 | 验证itad节
115 | '''
116 | token = itad.get('token', '')
117 | region = itad.get('region', 'cn')
118 | country = itad.get('country', 'CN')
119 | symbol = itad.get('currency_symbol', '¥')
120 | itad = {'token': token,
121 | 'region': region,
122 | 'country': country,
123 | 'currency_symbol': symbol}
124 | return (itad)
125 |
126 |
127 | def __verify_keylol(keylol: dict) -> dict:
128 | '''
129 | 验证keylol节
130 | '''
131 | enable = bool(keylol.get('enable', True))
132 | keylol = {'enable': enable}
133 | return (keylol)
134 |
135 |
136 | def __verify_steam(steam: dict) -> dict:
137 | '''
138 | 验证steam节
139 | '''
140 | language = steam.get('language', 'schinese')
141 | small_game_pic = bool(steam.get('small_game_pic', True))
142 | steam = {'language': language,
143 | 'small_game_pic': small_game_pic}
144 | return (steam)
145 |
146 |
147 | def __verify_net(net: dict) -> dict:
148 | '''
149 | 验证net节
150 | '''
151 | proxy = net.get('proxy', None)
152 | p = {"http://": proxy, "https://": proxy} if proxy else None
153 | net = {'proxy': p}
154 | return (net)
155 |
156 |
157 | def __verify_output(output: dict) -> dict:
158 | '''
159 | 验证output节
160 | '''
161 | console = bool(output.get('console', False))
162 | markdown = bool(output.get('markdown', True))
163 | xlsx = bool(output.get('xlsx', True))
164 | bbcode = bool(output.get('bbcode', False))
165 | json = bool(output.get('json', False))
166 |
167 | output = {'console': console, 'markdown': markdown,
168 | 'xlsx': xlsx, 'bbcode': bbcode, 'json': json}
169 | return (output)
170 |
171 |
172 | def __verify_sort(sort: dict) -> dict:
173 | '''
174 | 验证sort节
175 | '''
176 | index = dint(sort.get('index', 0), 0)
177 | if(abs(index) > SORT_TYPE):
178 | index = 0
179 | logger.warning(f'[filter]节 index 设置有误 (index = {index})')
180 | sort = {'index': index}
181 | return (sort)
182 |
183 |
184 | def __verify_filter(filter: dict) -> dict:
185 | '''
186 | 验证filter节
187 | '''
188 | has_card = fbool(filter.get('has_card', -1))
189 |
190 | price_set = fbool(filter.get('price_set', -1))
191 | price_noset = fbool(filter.get('price_noset', -1))
192 | price_free = fbool(filter.get('price_free', -1))
193 | price_higher = fint(filter.get('price_higher', -1), 0)
194 | price_lower = fint(filter.get('price_lower', -1), 0)
195 |
196 | discount_no = fbool(filter.get('discount_no', -1))
197 | discount_higher = fint(filter.get('discount_higher', -1), 100)
198 | discount_lower = fint(filter.get('discount_lower', -1), 100)
199 | discount_not_lowest = fbool(filter.get('discount_not_lowest', -1))
200 | discount_is_lowest = fbool(filter.get('discount_is_lowest', -1))
201 | discount_almost_lowest = fbool(filter.get('discount_almost_lowest', -1))
202 |
203 | review_score_higher = fint(filter.get('review_score_higher', -1), 9)
204 | review_score_lower = fint(filter.get('review_score_lower', -1), 9)
205 | review_no_score = fbool(filter.get('review_no_score', -1))
206 |
207 | review_percent_higher = fint(filter.get('review_percent_higher', -1), 100)
208 | review_percent_lower = fint(filter.get('review_percent_lower', -1), 100)
209 | review_total_higher = fint(filter.get('review_total_higher', -1), 0)
210 | review_total_lower = fint(filter.get('review_total_lower', -1), 0)
211 |
212 | platform_windows = fbool(filter.get('platform_windows', -1))
213 | platform_mac = fbool(filter.get('platform_mac', -1))
214 | platform_linux = fbool(filter.get('platform_linux', -1))
215 |
216 | tags_enpty = fbool(filter.get('tags_enpty', -1))
217 | tags_include = flist(filter.get('tags_include', -1))
218 | tags_exclude = flist(filter.get('tags_exclude', -1))
219 |
220 | filter = {
221 | 'has_card': has_card,
222 |
223 | 'price_set': price_set,
224 | 'price_noset': price_noset,
225 | 'price_free': price_free,
226 | 'price_higher': price_higher,
227 | 'price_lower': price_lower,
228 |
229 | 'discount_no': discount_no,
230 | 'discount_higher': discount_higher,
231 | 'discount_lower': discount_lower,
232 | 'discount_not_lowest': discount_not_lowest,
233 | 'discount_is_lowest': discount_is_lowest,
234 | 'discount_almost_lowest': discount_almost_lowest,
235 |
236 | 'review_score_higher': review_score_higher,
237 | 'review_score_lower': review_score_lower,
238 | 'review_no_score': review_no_score,
239 | 'review_percent_higher': review_percent_higher,
240 | 'review_percent_lower': review_percent_lower,
241 | 'review_total_higher': review_total_higher,
242 | 'review_total_lower': review_total_lower,
243 |
244 | 'platform_windows': platform_windows,
245 | 'platform_mac': platform_mac,
246 | 'platform_linux': platform_linux,
247 |
248 | 'tags_enpty': tags_enpty,
249 | 'tags_include': tags_include,
250 | 'tags_exclude': tags_exclude
251 | }
252 | return (filter)
253 |
--------------------------------------------------------------------------------
/module/crawer.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 | '''
3 | # @Author : Chr_
4 | # @Date : 2020-11-02 20:56:28
5 | # @LastEditors : Chr_
6 | # @LastEditTime : 2020-11-15 03:08:44
7 | # @Description : 抓取模块
8 | '''
9 | from asyncio import Semaphore
10 |
11 | from .log import get_logger
12 | from .aiosteam import get_wishlish
13 | from .aioitad import get_plains, get_lowest_price, get_current_price, get_base_info
14 | from .aiokeylol import get_games_tags
15 | from .handlers import bbcode, markdown, excel, json # , console
16 | from .sort import get_index
17 | from .filter import Filter
18 | from .utils import is_lowest
19 |
20 |
21 | class Crawer(object):
22 |
23 | wishdict = {} # {appid: {游戏详情}}
24 | steamids = {} # steam账号列表
25 | setting = {} # 配置
26 | index = [] # 索引
27 |
28 | def __init__(self, setting: dict, steamids: list, tag: str = None) -> None:
29 | '''
30 | 初始化抓取器
31 |
32 | 参数:
33 | config: 调用module.config.get_config()获取
34 | steamids: steamid列表
35 | '''
36 | try:
37 | steamids = set(steamids)
38 | except TypeError:
39 | raise ValueError('steam ID必须为非空列表')
40 |
41 | if steamids:
42 | self.steamids = steamids
43 | self.setting = setting
44 |
45 | self.logger = get_logger(f'Crawer *{len(steamids)}')
46 | self.logger.debug(f'共有{len(steamids)}个账号')
47 | else:
48 | raise ValueError('steam ID必须为非空列表')
49 |
50 | async def start(self):
51 | async with Semaphore(3): # 最大并发数
52 | await self.get_wishlist()
53 | await self.add_price()
54 | await self.add_addition()
55 | self.filter()
56 | # self.sort()
57 | self.output()
58 |
59 | async def get_wishlist(self):
60 | '''
61 | 从steam读取愿望单
62 | '''
63 | wishdict = self.wishdict
64 | setting = self.setting
65 | steamids = self.steamids
66 |
67 | net = setting.get('net', {})
68 | proxy = net.get('proxy', None)
69 |
70 | self.logger.info('开始读取愿望单,如果一直报错请配置proxy')
71 | for i, sid in enumerate(steamids, 1):
72 | self.logger.info(f'开始读取 {steamids} 的愿望单 {i}')
73 | dic = await get_wishlish(sid, setting, proxy)
74 | self.logger.info(f'读取完毕,愿望单中共有{len(dic)}个游戏')
75 | wishdict.update(dic)
76 | self.logger.info(f'愿望单读取完毕,合并后共有{len(wishdict)}个游戏')
77 |
78 | async def add_price(self):
79 | '''
80 | 获取游戏价格信息
81 | '''
82 | wishlist = self.wishdict
83 | setting = self.setting
84 |
85 | itad = setting.get('itad', {})
86 | net = setting.get('net', {})
87 |
88 | proxy = net.get('proxy', None)
89 | token = itad.get('token')
90 | region = itad.get('region', 'cn')
91 | country = itad.get('country', 'CN')
92 |
93 | ids = list(wishlist.keys())
94 | self.logger.info('开始获取游戏ID,第一次耗时会比较久')
95 | plaindict = await get_plains(ids, token, True, proxy)
96 | self.logger.info(f'游戏ID读取完毕,共{len(plaindict)}条')
97 |
98 | plains = list(plaindict.values())
99 | self.logger.info('开始获取游戏价格信息,可能会比较久')
100 | current_dict = await get_current_price(plains, token, region, country, proxy)
101 | lowest_dict = await get_lowest_price(plains, token, region, country, proxy)
102 | print('')
103 | self.logger.info('整理游戏价格数据')
104 | for key in wishlist.keys():
105 | try:
106 | plain = plaindict[key]
107 | except KeyError:
108 | self.logger.debug(f'未找到ID为{key}的plain,已忽略')
109 | continue
110 |
111 | obj = wishlist[key]
112 |
113 | if not obj['free']:
114 | try:
115 | p_now, p_old, p_cut = current_dict[plain]
116 | except KeyError:
117 | # 没有当前价格数据
118 | p_now, p_old, p_cut = -1, -1, 0
119 | try:
120 | p_low, p_low_cut, p_low_time = lowest_dict[plain]
121 | except KeyError:
122 | # 没有史低价格数据
123 | p_low, p_low_cut, p_low_time = -1, 0, 0
124 | else:
125 | # 免费游戏
126 | p_now, p_old, p_cut = 0, 0, 0
127 | p_low, p_low_cut, p_low_time = 0, 0, 0
128 |
129 | obj['price'] = {
130 | 'current': p_now,
131 | 'origin': p_old,
132 | 'current_cut': p_cut,
133 | 'lowest': p_low,
134 | 'low_cut': p_low_cut,
135 | 'low_time': p_low_time,
136 | 'is_lowest': is_lowest(p_old, p_now, p_low, p_cut)
137 | }
138 | # obj['price_current'] = p_now
139 | # obj['price_origin'] = p_old
140 | # obj['price_cut'] = p_cut
141 | # obj['price_lowest'] = p_low
142 | # obj['price_low_cut'] = p_low_cut
143 | # obj['price_low_time'] = p_low_time
144 | self.logger.info('价格数据整理完成')
145 |
146 | async def add_addition(self):
147 | '''
148 | 获取游戏附加信息
149 | '''
150 | wishdict = self.wishdict
151 | setting = self.setting
152 | net = setting.get('net', {})
153 | proxy = net.get('proxy', None)
154 |
155 | ids = list(wishdict.keys())
156 | errors = 0
157 | if setting['keylol']['enable']:
158 | self.logger.info('使用Keylol模块获取附加信息,可能会比较久')
159 | additiondict = await get_games_tags(ids)
160 | for key in wishdict.keys():
161 | try:
162 | obj = wishdict[key]
163 | add = additiondict[key]
164 | # obj['tags'] = add['tags']
165 | obj['card'] = add['card']
166 | # obj['name_cn'] = add['name_cn']
167 | except KeyError:
168 | errors += 1
169 | self.logger.debug(f'ID {key}处理失败')
170 | else:
171 | self.logger.info('使用ITAD模块获取附加信息,可能会比较久')
172 | token = setting['itad']['token']
173 | plaindict = await get_plains(ids, token, True, proxy)
174 | self.logger.info(f'ID读取完毕,共{len(plaindict)}条')
175 | plains = list(plaindict.values())
176 | additiondict = await get_base_info(plains, token, proxy)
177 | for key in wishdict.keys():
178 | try:
179 | plain = plaindict[key]
180 | obj = wishdict[key]
181 | obj['card'] = additiondict[plain]
182 | # obj['tags'] = None
183 | # obj['name_cn'] = None
184 | except KeyError:
185 | errors += 1
186 | self.logger.debug(f'ID {key}处理失败')
187 | print('')
188 | self.logger.debug(f'总计{errors}个错误')
189 | self.logger.info('附加信息读取完成')
190 |
191 | def filter(self):
192 | '''
193 | 按照配置过滤愿望单
194 | '''
195 | wishdict = self.wishdict
196 | filter = self.setting['filter']
197 | f = Filter(filter)
198 | wishdict = {k: v for k, v in wishdict.items() if f.filter(v)}
199 | self.logger.info(f'过滤后共有{len(wishdict)}个游戏')
200 | self.wishdict = wishdict
201 |
202 | def sort(self):
203 | '''
204 | 按照配置过滤愿望单
205 | '''
206 | wishdict = self.wishdict
207 | sort = self.setting['sort']
208 | self.index = get_index(wishdict, sort)
209 |
210 | def output(self):
211 | '''
212 | 按照配置输出到文件
213 | '''
214 | wishdict = self.wishdict
215 | index = self.index
216 | symbol = self.setting['itad']['currency_symbol']
217 | setting = self.setting['output']
218 |
219 | cmd = setting.get('console', False)
220 | md = setting.get('markdown', False)
221 | xlsx = setting.get('xlsx', False)
222 | bbc = setting.get('bbcode', False)
223 | jsn = setting.get('json', False)
224 |
225 | if not index:
226 | index = wishdict.keys()
227 |
228 | self.logger.info('开始输出')
229 | if md:
230 | try:
231 | markdown.handler(wishdict, index, symbol)
232 | except Exception as e:
233 | self.logger.error(f'遇到错误: {e}')
234 | if xlsx:
235 | try:
236 | excel.handler(wishdict, index, symbol)
237 | except Exception as e:
238 | self.logger.error(f'遇到错误: {e}')
239 | if bbc:
240 | try:
241 | bbcode.handler(wishdict, index, symbol)
242 | except Exception as e:
243 | self.logger.error(f'遇到错误: {e}')
244 | if cmd:
245 | try:
246 | self.logger.warning('因为打包程序有问题,暂时禁用控制台输出的功能')
247 | # console.handler(wishdict, index, symbol)
248 | except Exception as e:
249 | self.logger.error(f'遇到错误: {e}')
250 | if jsn:
251 | try:
252 | json.handler(wishdict, index, symbol)
253 | except Exception as e:
254 | self.logger.error(f'遇到错误: {e}')
255 |
256 | self.logger.info('输出完成')
257 |
--------------------------------------------------------------------------------
/module/filter.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 | '''
3 | # @Author : Chr_
4 | # @Date : 2020-11-07 21:12:39
5 | # @LastEditors : Chr_
6 | # @LastEditTime : 2020-11-15 03:00:52
7 | # @Description : 过滤器模块【TODO】
8 | '''
9 |
10 | class Filter(object):
11 | '''
12 | 过滤器类
13 | '''
14 | price_higher = 0
15 | price_lower = 0
16 | discount_higher = 0
17 | discount_lower = 0
18 | review_score_higher = 0
19 | review_score_lower = 0
20 | review_percent_higher = 0
21 | review_percent_lower = 0
22 | review_total_higher = 0
23 | review_total_lower = 0
24 | tags_include = []
25 | tags_exclude = []
26 |
27 | def __init__(self, setting: dict) -> None:
28 | '''
29 | 初始化
30 |
31 | 参数:
32 | setting: get_cfg()得到的配置字典
33 | '''
34 | def disable(x):
35 | return True
36 |
37 | has_card = setting.get('has_card', -1)
38 |
39 | price_set = setting.get('price_set', -1)
40 | price_noset = setting.get('price_noset', -1)
41 | price_free = setting.get('price_free', -1)
42 | price_higher = setting.get('price_higher', -1)
43 | price_lower = setting.get('price_lower', -1)
44 |
45 | discount_no = setting.get('discount_no', -1)
46 | discount_higher = setting.get('discount_higher', -1)
47 | discount_lower = setting.get('discount_lower', -1)
48 | discount_not_lowest = setting.get('discount_not_lowest', -1)
49 | discount_is_lowest = setting.get('discount_is_lowest', -1)
50 | discount_almost_lowest = setting.get('discount_almost_lowest', -1)
51 |
52 | review_score_higher = setting.get('review_score_higher', -1)
53 | review_score_lower = setting.get('review_score_lower', -1)
54 | review_no_score = setting.get('review_no_score', -1)
55 | review_percent_higher = setting.get('review_percent_higher', -1)
56 | review_percent_lower = setting.get('review_percent_lower', -1)
57 | review_total_higher = setting.get('review_total_higher', -1)
58 | review_total_lower = setting.get('review_total_lower', -1)
59 |
60 | platform_windows = setting.get('platform_windows', -1)
61 | platform_mac = setting.get('platform_mac', -1)
62 | platform_linux = setting.get('platform_linux', -1)
63 |
64 | tags_enpty = setting.get('tags_enpty', -1)
65 | tags_include = setting.get('tags_include', -1)
66 | tags_exclude = setting.get('tags_exclude', -1)
67 |
68 | if not has_card or has_card == -1: # 果过滤没有卡牌
69 | self.__o_has_card = disable
70 |
71 | if price_set or price_set == -1: # 过滤有价格
72 | self.__p_set = disable
73 | if price_noset or price_noset == -1: # 过滤无价格
74 | self.__p_noset = disable
75 | if price_free or price_free == -1: # 过滤免费
76 | self.__p_free = disable
77 | if price_higher == -1: # 过滤价格低于
78 | self.__p_higher = disable
79 | else:
80 | self.price_higher = price_higher
81 | if price_lower == -1: # 过滤价格高于
82 | self.__p_lower = disable
83 | else:
84 | self.price_lower = price_lower
85 |
86 | if discount_no or discount_no == -1: # 过滤未打折
87 | self.__d_no = disable
88 | if discount_higher == -1: # 过滤折扣低于
89 | self.__d_higher = disable
90 | else:
91 | self.discount_higher = discount_higher
92 | if discount_lower == -1: # 过滤折扣高于
93 | self.__d_lower = disable
94 | else:
95 | self.discount_lower = discount_lower
96 | if discount_not_lowest or discount_not_lowest == -1: # 过滤非史低和非近史低
97 | self.__d_not_lowest = disable
98 | if discount_is_lowest or discount_is_lowest == -1: # 过滤史低
99 | self.__d_is_lowest = disable
100 | if discount_almost_lowest or discount_is_lowest == -1: # 过滤近史低
101 | self.__d_almost_lowest = disable
102 |
103 | if review_no_score or review_no_score == -1: # 过滤无评测结果
104 | self.__r_no_score = disable
105 | if review_score_higher <= 0: # 过滤评测等级低于
106 | self.__r_score_higher = disable
107 | else:
108 | self.review_score_higher = review_score_higher
109 | if review_score_lower <= 0: # 过滤评测等级高于
110 | self.__r_score_lower = disable
111 | else:
112 | self.review_score_lower = review_score_lower
113 | if review_percent_higher == -1: # 过滤好评率低于
114 | self.__r_percent_higher = disable
115 | else:
116 | self.review_percent_higher = review_percent_higher
117 | if review_percent_lower == -1: # 过滤好评率高于
118 | self.__r_percent_lower = disable
119 | else:
120 | self.review_percent_lower = review_percent_lower
121 | if review_total_higher == -1: # 过滤评测总数低于
122 | self.__r_total_higher = disable
123 | else:
124 | self.review_total_higher = review_total_higher
125 | if review_total_lower == -1: # 过滤评测总数高于
126 | self.__r_total_lower = disable
127 | else:
128 | self.review_total_lower = review_total_lower
129 |
130 | if not platform_windows or platform_windows == -1: # 过滤不支持win
131 | self.__p_windows = disable
132 | if not platform_mac or platform_mac == -1: # 过滤不支持mac
133 | self.__p_mac = disable
134 | if not platform_linux or platform_linux == -1: # 过滤不支持linux
135 | self.__p_linux = disable
136 |
137 | if tags_enpty or tags_enpty == -1: # 过滤空标签
138 | self.__t_empty = disable
139 | if not tags_include or tags_include == -1: # 过滤不包含指定标签
140 | self.__t_include = disable
141 | else:
142 | self.tags_include = tags_include
143 | if not tags_exclude or tags_exclude == -1: # 过滤包含指定标签
144 | self.__t_exclude = disable
145 | else:
146 | self.tags_exclude = tags_exclude
147 |
148 | def filter(self, d: dict) -> bool:
149 | '''
150 | 根据配置过滤愿望单列表
151 | '''
152 | result = (self.__o_has_card(d) and
153 | self.__p_set(d) and
154 | self.__p_noset(d) and self.__p_free(d) and
155 | self.__p_higher(d) and self.__p_lower(d) and
156 | self.__d_no(d) and
157 | self.__d_higher(d) and self.__d_lower(d) and
158 | self.__d_not_lowest(d) and
159 | self.__d_is_lowest(d) and self.__d_almost_lowest(d) and
160 | self.__r_no_score(d) and
161 | self.__r_score_higher(d) and self.__r_score_lower(d) and
162 | self.__r_percent_higher(d) and self.__r_percent_lower(d) and
163 | self.__r_total_higher(d) and self.__r_total_lower(d) and
164 | self.__p_windows(d) and
165 | self.__p_mac(d) and self.__p_linux(d) and
166 | self.__t_empty(d) and
167 | self.__t_include(d) and self.__t_exclude(d))
168 | return result
169 |
170 | def __o_has_card(self, d: dict) -> bool:
171 | '''
172 | 过滤掉 没有 卡牌的游戏
173 | '''
174 | card = d.get('card', False)
175 | return card # 有卡有效
176 |
177 | def __p_set(self, d: dict) -> bool:
178 | '''
179 | 忽略免费游戏
180 | 过滤掉 有价格 的游戏
181 | '''
182 | price = d.get('price', {})
183 | p_now = price.get('current', -1)
184 | return p_now <= 0 # 免费或者无价格有效
185 |
186 | def __p_noset(self, d: dict) -> bool:
187 | '''
188 | 忽略免费游戏
189 | 过滤掉 没有价格 的游戏
190 | '''
191 | price = d.get('price', {})
192 | p_now = price.get('current', -1)
193 | return p_now >= 0 # 免费或者有价格有效
194 |
195 | def __p_free(self, d: dict) -> bool:
196 | '''
197 | 过滤掉 免费 的游戏
198 | '''
199 | free = d.get('free', False)
200 | return not free # 非免费有效
201 |
202 | def __p_higher(self, d: dict) -> bool:
203 | '''
204 | 忽略免费和无价格的游戏
205 | 过滤掉当前价格 低于 设定值的游戏
206 | '''
207 | price = d.get('price', {})
208 | p_now = price.get('current', -1)
209 | if p_now <= -0:
210 | return True # 忽略免费或无价格
211 | else:
212 | return p_now >= self.price_higher # 价格高于设定有效
213 |
214 | def __p_lower(self, d: dict) -> bool:
215 | '''
216 | 忽略免费和无价格的游戏
217 | 过滤掉当前价格 高于 设定值的游戏
218 | '''
219 | price = d.get('price', {})
220 | p_now = price.get('current', -1)
221 | if p_now <= 0:
222 | return True # 忽略免费或无价格
223 | else:
224 | return p_now <= self.price_lower # 价格低于设定有效
225 |
226 | def __d_no(self, d: dict) -> bool:
227 | '''
228 | 过滤掉 未打折 的游戏
229 | '''
230 | price = d.get('price', {})
231 | p_cut = price.get('current_cut', -1)
232 | return p_cut > 0 # 打折有效
233 |
234 | def __d_higher(self, d: dict) -> bool:
235 | '''
236 | 忽略未打折游戏
237 | 过滤掉当前折扣 低于 设定值 的游戏
238 | '''
239 | price = d.get('price', {})
240 | p_cut = price.get('current_cut', -1)
241 | if p_cut == 0:
242 | return True # 忽略未打折
243 | else:
244 | return p_cut >= self.discount_higher # 折扣高于设定有效
245 |
246 | def __d_lower(self, d: dict) -> bool:
247 | '''
248 | 忽略未打折游戏
249 | 过滤掉当前折扣 高于 设定值 的游戏
250 | '''
251 | price = d.get('price', {})
252 | p_cut = price.get('current_cut', -1)
253 | if p_cut == 0:
254 | return True # 忽略未打折
255 | else:
256 | return p_cut <= self.discount_lower # 折扣低于设定有效
257 |
258 | def __d_not_lowest(self, d: dict) -> bool:
259 | '''
260 | 忽略未打折游戏
261 | 过滤掉 未达到 史低和近史低的游戏
262 | '''
263 | price = d.get('price', {})
264 | p_cut = price.get('current_cut', -1)
265 | if p_cut == 0:
266 | return True # 忽略未打折
267 | else:
268 | is_lowest = price.get('is_lowest', 0)
269 | return is_lowest != 0 # 史低或近史低有效
270 |
271 | def __d_is_lowest(self, d: dict) -> bool:
272 | '''
273 | 忽略未打折游戏
274 | 过滤掉 达到 史低的游戏
275 | '''
276 | price = d.get('price', {})
277 | p_cut = price.get('current_cut', -1)
278 | if p_cut == 0:
279 | return True # 忽略未打折
280 | else:
281 | is_lowest = price.get('is_lowest', 0)
282 | return is_lowest != 1 # 非史低或近史低有效
283 |
284 | def __d_almost_lowest(self, d: dict) -> bool:
285 | '''
286 | 忽略未打折游戏
287 | 过滤掉 达到 近史低的游戏
288 | '''
289 | price = d.get('price', {})
290 | p_cut = price.get('current_cut', -1)
291 | if p_cut == 0:
292 | return True # 忽略未打折
293 | else:
294 | is_lowest = price.get('is_lowest', 0)
295 | return is_lowest != -1 # 非史低或史低有效
296 |
297 | def __r_no_score(self, d: dict) -> bool:
298 | '''
299 | 过滤掉 评价等级 = 0 的游戏
300 | '''
301 | review = d.get('review', {})
302 | score = review.get('score', -1)
303 | return score > 0 # 评分低于0有效
304 |
305 | def __r_score_higher(self, d: dict) -> bool:
306 | '''
307 | 忽略评价等级 = 0 的游戏
308 | 过滤掉评价等级 低于 设定值的游戏
309 | '''
310 | review = d.get('review', {})
311 | score = review.get('score', -1)
312 |
313 | if score <= 0:
314 | return True # 忽略没评价或出错
315 | else:
316 | return score >= self.review_score_higher # 评分高于设定有效
317 |
318 | def __r_score_lower(self, d: dict) -> bool:
319 | '''
320 | 忽略评价等级 = 0 的游戏
321 | 过滤掉评价等级 高于 设定值的游戏
322 | '''
323 | review = d.get('review', {})
324 | score = review.get('score', -1)
325 |
326 | if score <= 0:
327 | return True # 忽略没评价或出错
328 | else:
329 | return score <= self.review_score_lower # 评分低于设定有效
330 |
331 | def __r_percent_higher(self, d: dict) -> bool:
332 | '''
333 | 过滤掉好评率 低于 设定值的游戏
334 | '''
335 | review = d.get('review', {})
336 | score = review.get('score', -1)
337 |
338 | if score <= 0:
339 | return True # 忽略没评价或出错
340 | else:
341 | percent = review.get('percent', -1)
342 | return percent >= self.review_percent_higher # 评分低于设定有效
343 |
344 | def __r_percent_lower(self, d: dict) -> bool:
345 | '''
346 | 过滤掉好评率 低于 设定值的游戏
347 | '''
348 | review = d.get('review', {})
349 | score = review.get('score', -1)
350 |
351 | if score <= 0:
352 | return True # 忽略没评价或出错
353 | else:
354 | percent = review.get('percent', -1)
355 | return percent <= self.review_percent_lower # 评分低于设定有效
356 |
357 | def __r_total_higher(self, d: dict) -> bool:
358 | '''
359 | 过滤掉评价总数 低于 设定值的游戏
360 | '''
361 | review = d.get('review', {})
362 | score = review.get('score', -1)
363 |
364 | if score <= 0:
365 | return True # 忽略没评价或出错
366 | else:
367 | total = review.get('total', -1)
368 | return total >= self.review_total_higher # 评价总数低于设定有效
369 |
370 | def __r_total_lower(self, d: dict) -> bool:
371 | '''
372 | 过滤掉评价总数 低于 设定值的游戏
373 | '''
374 | review = d.get('review', {})
375 | score = review.get('score', -1)
376 |
377 | if score <= 0:
378 | return True # 忽略没评价或出错
379 | else:
380 | total = review.get('total', -1)
381 | return total <= self.review_total_lower # 评价总数低于设定有效
382 |
383 | def __p_windows(self, d: dict) -> bool:
384 | '''
385 | 过滤掉 不支持 Windows的游戏
386 | '''
387 | windows, _, _ = d.get('platform', (False, False, False))
388 | return windows # 支持win有效
389 |
390 | def __p_mac(self, d: dict) -> bool:
391 | '''
392 | 过滤掉 不支持 Mac的游戏
393 | '''
394 | _, macos, _ = d.get('platform', (False, False, False))
395 | return macos # 支持mac有效
396 |
397 | def __p_linux(self, d: dict) -> bool:
398 | '''
399 | 过滤掉 不支持 Linux的游戏
400 | '''
401 | _, _, linux = d.get('platform', (False, False, False))
402 | return linux # 支持linux有效
403 |
404 | def __t_empty(self, d: dict) -> bool:
405 | '''
406 | 过滤掉 没有 标签的游戏
407 | '''
408 | tags = d.get('tags', [])
409 | return bool(tags) # 含有标签有效
410 |
411 | def __t_include(self, d: dict) -> bool:
412 | '''
413 | 忽略没有标签的游戏
414 | 过滤掉标签 不匹配 规则的游戏
415 | '''
416 | itags = self.tags_include
417 | tags = d.get('tags', [])
418 | if not tags:
419 | return True # 含有标签有效
420 | for it in itags:
421 | flag = False
422 | for t in tags:
423 | if it in t:
424 | flag = True
425 | break
426 | if not flag:
427 | return False
428 | return True # 包含全部标签有效
429 |
430 | def __t_exclude(self, d: dict) -> bool:
431 | '''
432 | 忽略没有标签的游戏
433 | 过滤掉标签 匹配 规则的游戏
434 | '''
435 | itags = self.tags_include
436 | tags = d.get('tags', [])
437 | if not tags:
438 | return True # 含有标签有效
439 | for it in itags:
440 | flag = False
441 | for t in tags:
442 | if it in t:
443 | flag = True
444 | break
445 | if flag:
446 | return False
447 | return True # 不包含全部标签有效
448 |
--------------------------------------------------------------------------------
/module/handlers/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 | '''
3 | # @Author : Chr_
4 | # @Date : 2020-11-07 18:59:53
5 | # @LastEditors : Chr_
6 | # @LastEditTime : 2020-11-12 21:08:22
7 | # @Description : 处理输出的函数
8 | '''
9 | __all__ = ['bbcode', 'console', 'excel', 'json', 'markdown']
10 |
--------------------------------------------------------------------------------
/module/handlers/bbcode.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 | '''
3 | # @Author : Chr_
4 | # @Date : 2020-07-06 18:22:37
5 | # @LastEditors : Chr_
6 | # @LastEditTime : 2020-11-26 16:01:47
7 | # @Description : 输出BBCode格式的文件
8 | '''
9 |
10 | from ..log import get_logger
11 | from ..utils import is_lowest_str, get_output_path
12 |
13 | logger = get_logger('BBCode')
14 |
15 |
16 | def handler(wishdict: dict, index: list, symbol: str):
17 | '''
18 | 这个函数将会被crawer调用
19 |
20 | 参数:
21 | wishdict: 愿望单字典
22 | '''
23 | data = formater(wishdict, index, symbol)
24 | p = get_output_path('swh-bbcode.txt')
25 | with open(p, 'w+', encoding='utf-8') as f:
26 | f.write(data)
27 | logger.info(f'写入文件到 {p}')
28 |
29 |
30 | def formater(wishdict: dict, index: list, symbol: str) -> str:
31 | '''
32 | 这个函数用于从愿望单字典中提取数据
33 |
34 | 参数:
35 | wishdict: 愿望单字典
36 | 返回:
37 | str: 生成的结果
38 | '''
39 | result = []
40 | if wishdict:
41 | result.append(f'[table][tr][td]预览图[/td][td]游戏名称[/td][td]卡牌[/td]'
42 | f'[td]现价({symbol})[/td][td]原价({symbol})[/td]'
43 | f'[td]折扣[/td][td]史低({symbol})[/td][td]史低[/td][td]评测[/td][/tr]')
44 | for appid, detail in wishdict.items():
45 | link = f'https://store.steampowered.com/app/{appid}'
46 | name = detail.get('name', '')
47 | pic = detail.get('picture', '#')
48 | card = '有' if detail.get('card', False) else '无'
49 | if 'price' in detail:
50 | price = detail['price']
51 | p_now = price.get('current')
52 | p_old = price.get('origin')
53 | p_cut = price.get('current_cut')
54 | p_low = price.get('lowest')
55 | shidi = is_lowest_str(price.get('is_lowest',0))
56 | discount = f'-{p_cut}%'
57 | else:
58 | shidi = '-'
59 | discount = '-'
60 | p_now = '-'
61 | p_low = '-'
62 | p_old = '-'
63 | if detail['free']:
64 | p_now = '免费'
65 | shidi = '免费'
66 | p_low = '免费'
67 | p_old = '免费'
68 | if p_now == -1:
69 | p_now = '-'
70 | p_low = '-'
71 | p_old = '-'
72 |
73 | review = detail['review']
74 | r_result = review['result']
75 | r_total = review['total']
76 | # r_percent = review['percent']
77 | review_str = f'{r_result} ({r_total})'
78 | # review_str = f'{r_result} {r_percent}%好评/({r_total})'
79 |
80 | result.append((f'[tr][td][url={link}][img]{pic}[/img][/url][/td]'
81 | f'[td][url={link}]{name}[/url][/td]'
82 | f'[td]{card}[/td]'
83 | f'[td]{p_now}[/td]'
84 | f'[td]{p_old}[/td]'
85 | f'[td]{discount}[/td]'
86 | f'[td]{p_low}[/td]'
87 | f'[td]{shidi}[/td]'
88 | f'[td]{review_str}[/td][/tr]'))
89 | result.append('[/table]')
90 | else:
91 | result.append('游戏列表空,请检查过滤器设置以及是否将愿望单公开')
92 | return ('\n'.join(result))
93 |
--------------------------------------------------------------------------------
/module/handlers/console.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 | '''
3 | # @Author : Chr_
4 | # @Date : 2020-07-05 12:43:38
5 | # @LastEditors : Chr_
6 | # @LastEditTime : 2020-11-14 14:40:50
7 | # @Description : 在控制台输出
8 | '''
9 |
10 | from prettytable import PrettyTable
11 |
12 | from ..log import get_logger
13 | from ..utils import is_lowest_str
14 |
15 | logger = get_logger('Console')
16 |
17 |
18 | def handler(wishdict: dict, index: list, symbol: str) -> str:
19 | '''
20 | 这个函数将会被crawer调用
21 |
22 | 参数:
23 | wishdict: 愿望单字典
24 | '''
25 | logger.info('开始打印'.center(50, '='))
26 | data = formater(wishdict, index, symbol)
27 | print(data)
28 | logger.info('打印结束'.center(50, '='))
29 |
30 |
31 | def formater(wishdict: dict, index: list, symbol: str) -> PrettyTable:
32 | '''
33 | 这个函数用于从愿望单字典中提取数据
34 |
35 | 参数:
36 | wishdict: 愿望单字典
37 | 返回:
38 | str: 生成的结果
39 | '''
40 | table = PrettyTable(
41 | ['游戏名称', '卡牌', f'现价({symbol})', f'原价({symbol})', '折扣', '史低', '评测结果'])
42 | if wishdict:
43 | for appid, detail in wishdict.items():
44 | # link = f'https://store.steampowered.com/app/{appid}'
45 | name = str(detail.get('name', ''))
46 | # pic = detail.get('picture', '#')
47 | card = '有' if detail.get('card', False) else '无'
48 | if 'price' in detail:
49 | price = detail['price']
50 | p_now = price.get('current')
51 | p_old = price.get('origin')
52 | p_cut = price.get('current_cut')
53 | p_low = price.get('lowest')
54 | shidi = is_lowest_str(price.get('is_lowest', 0))
55 | discount = f'-{p_cut}%'
56 | else:
57 | shidi = '-'
58 | discount = '-'
59 | p_now = '-'
60 | p_low = '-'
61 | p_old = '-'
62 | if detail['free']:
63 | p_now = '免费'
64 | shidi = '免费'
65 | p_low = '免费'
66 | p_old = '免费'
67 | if p_now == -1:
68 | p_now = '-'
69 | p_low = '-'
70 | p_old = '-'
71 |
72 | review = detail['review']
73 | r_result = review['result']
74 | # r_total = review['total']
75 | # r_percent = review['percent']
76 | # review_str = f'{r_result} ({r_total})'
77 | # review_str = f'{r_result} {r_percent}%好评/({r_total})'
78 | if '史低' in shidi:
79 | table.add_row([name, card, p_now, p_old,
80 | discount, shidi, r_result])
81 | else:
82 | table.add_row(['游戏列表空,请检查过滤器设置以及是否将愿望单公开', '', '', ''])
83 | return (table)
84 |
--------------------------------------------------------------------------------
/module/handlers/excel.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 | '''
3 | # @Author : Chr_
4 | # @Date : 2020-07-06 18:22:37
5 | # @LastEditors : Chr_
6 | # @LastEditTime : 2020-11-14 23:48:51
7 | # @Description : 输出Xlsx文件
8 | '''
9 |
10 | from xlsxwriter import Workbook
11 |
12 | from ..log import get_logger
13 | from ..utils import is_lowest_str, get_output_path
14 |
15 | logger = get_logger('Excel')
16 |
17 |
18 | def handler(wishdict: dict, index: list, symbol: str):
19 | '''
20 | 这个函数将会被crawer调用
21 |
22 | 参数:
23 | wishdict: 愿望单字典
24 | '''
25 | p = get_output_path('swh-excel.xlsx')
26 | try:
27 | wb = Workbook(p)
28 | formater(wishdict, index, symbol, wb)
29 | wb.close()
30 | except Exception as e:
31 | logger.error(f'遇到意外错误 {e}')
32 |
33 | logger.info(f'写入文件到 {p}')
34 |
35 |
36 | def formater(wishdict: dict, index: list, symbol: str, wb: Workbook):
37 | '''
38 | 这个函数用于从愿望单字典中提取数据
39 |
40 | 参数:
41 | wishdict: 愿望单字典
42 | '''
43 |
44 | fmt = wb.add_format({'font_name': '微软雅黑', 'align': 'center'})
45 |
46 | ws = wb.add_worksheet(name='Steam Wishlist Helper')
47 | ws.set_column('A:A', 10, fmt)
48 | ws.set_column('B:B', 60, fmt)
49 | ws.set_column('C:C', 7, fmt)
50 | ws.set_column('D:D', 8, fmt)
51 | ws.set_column('E:E', 8, fmt)
52 | ws.set_column('F:F', 7, fmt)
53 | ws.set_column('G:G', 8, fmt)
54 | ws.set_column('H:H', 8, fmt)
55 | ws.set_column('I:I', 12, fmt)
56 | ws.set_column('J:J', 7, fmt)
57 | ws.set_column('K:K', 9, fmt)
58 | ws.write(0, 0, '商店链接')
59 | ws.write(0, 1, '游戏名')
60 | ws.write(0, 2, '卡牌')
61 | ws.write(0, 3, f'现价({symbol})')
62 | ws.write(0, 4, f'原价({symbol})')
63 | ws.write(0, 5, '折扣')
64 | ws.write(0, 6, f'史低({symbol})')
65 | ws.write(0, 7, '史低')
66 | ws.write(0, 8, '评测结果')
67 | ws.write(0, 9, '好评率')
68 | ws.write(0, 10, '评测总数')
69 | if wishdict:
70 | for col, (appid, detail) in enumerate(wishdict.items(), 1):
71 | link = f'https://store.steampowered.com/app/{appid}'
72 | name = detail.get('name', '')
73 | card = '有' if detail.get('card', False) else '无'
74 | # pic = detail.get('picture', '#')
75 | if 'price' in detail:
76 | price = detail['price']
77 | p_now = price.get('current')
78 | p_old = price.get('origin')
79 | p_cut = price.get('current_cut')
80 | p_low = price.get('lowest')
81 | shidi = is_lowest_str(price.get('is_lowest',0))
82 | discount = f'-{p_cut}%'
83 | else:
84 | shidi = '-'
85 | discount = '-'
86 | p_now = '-'
87 | p_low = '-'
88 | p_old = '-'
89 | if detail['free']:
90 | p_now = '免费'
91 | shidi = '免费'
92 | p_low = '免费'
93 | p_old = '免费'
94 | if p_now == -1:
95 | p_now = '-'
96 | p_old = '-'
97 | p_low = '-'
98 |
99 |
100 | review = detail['review']
101 | r_result = review['result']
102 | r_total = review['total']
103 | r_percent = review['percent']
104 | # review_str = f'{r_result} ({r_total})'
105 |
106 | ws.write(col, 0, link)
107 | ws.write(col, 1, name)
108 | ws.write(col, 2, card)
109 | ws.write(col, 3, p_now)
110 | ws.write(col, 4, p_old)
111 | ws.write(col, 5, discount)
112 | ws.write(col, 6, p_low)
113 | ws.write(col, 7, shidi)
114 | ws.write(col, 8, r_result)
115 | ws.write(col, 9, f'{r_percent}%')
116 | ws.write(col, 10, r_total)
117 | else:
118 | ws.write(1, 1, '游戏列表空,请检查过滤器设置以及是否将愿望单公开')
119 |
--------------------------------------------------------------------------------
/module/handlers/json.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 | '''
3 | # @Author : Chr_
4 | # @Date : 2020-07-06 18:22:37
5 | # @LastEditors : Chr_
6 | # @LastEditTime : 2020-11-26 16:00:05
7 | # @Description : 输出Json文件
8 | '''
9 | from json import dumps
10 |
11 | from ..log import get_logger
12 | from ..utils import get_output_path
13 |
14 | logger = get_logger('Markdown')
15 |
16 |
17 | def handler(wishdict: dict, index: list, symbol: str):
18 | '''
19 | 这个函数将会被crawer调用
20 |
21 | 参数:
22 | wishdict: 愿望单字典
23 | '''
24 | data = formater(wishdict, index, symbol)
25 | p = get_output_path('swh-json.json')
26 | with open(p, 'w+', encoding='utf-8') as f:
27 | f.write(data)
28 | logger.info(f'写入文件到 {p}')
29 |
30 |
31 | def formater(wishdict: dict, index: list, symbol: str) -> str:
32 | '''
33 | 这个函数用于从愿望单字典中提取数据
34 |
35 | 参数:
36 | wishdict: 愿望单字典
37 | 返回:
38 | str: 生成的结果
39 | '''
40 | if wishdict:
41 | pass
42 | else:
43 | wishdict['error']=('游戏列表空,请检查过滤器设置以及是否将愿望单公开')
44 | return dumps(wishdict,ensure_ascii=False)
45 |
--------------------------------------------------------------------------------
/module/handlers/markdown.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 | '''
3 | # @Author : Chr_
4 | # @Date : 2020-07-06 18:22:37
5 | # @LastEditors : Chr_
6 | # @LastEditTime : 2020-11-14 23:49:15
7 | # @Description : 输出Markdown文件
8 | '''
9 |
10 | from ..log import get_logger
11 | from ..utils import is_lowest_str, get_output_path
12 |
13 | logger = get_logger('Markdown')
14 |
15 |
16 | def handler(wishdict: dict, index: list, symbol: str):
17 | '''
18 | 这个函数将会被crawer调用
19 |
20 | 参数:
21 | wishdict: 愿望单字典
22 | '''
23 | data = formater(wishdict, index, symbol)
24 | p = get_output_path('swh-markdown.md')
25 | with open(p, 'w+', encoding='utf-8') as f:
26 | f.write(data)
27 | logger.info(f'写入文件到 {p}')
28 |
29 |
30 | def formater(wishdict: dict, index: list, symbol: str) -> str:
31 | '''
32 | 这个函数用于从愿望单字典中提取数据
33 |
34 | 参数:
35 | wishdict: 愿望单字典
36 | 返回:
37 | str: 生成的结果
38 | '''
39 | result = []
40 | result.append(
41 | f'|预览图|游戏名称|卡牌|现价({symbol})|原价({symbol})|折扣|史低({symbol})|史低|评测|')
42 | result.append('|-|-|-|-|-|-|-|-|-|')
43 | if wishdict:
44 | for appid, detail in wishdict.items():
45 | link = f'https://store.steampowered.com/app/{appid}'
46 | name = detail.get('name', '')
47 | pic = detail.get('picture', '#')
48 | card = '有' if detail.get('card', False) else '无'
49 | if 'price' in detail:
50 | price = detail['price']
51 | p_now = price.get('current')
52 | p_old = price.get('origin')
53 | p_cut = price.get('current_cut')
54 | p_low = price.get('lowest')
55 | shidi = is_lowest_str(price.get('is_lowest', 0))
56 | discount = f'-{p_cut}%'
57 | else:
58 | shidi = '-'
59 | discount = '-'
60 | p_now = '-'
61 | p_low = '-'
62 | p_old = '-'
63 | if detail['free']:
64 | p_now = '免费'
65 | shidi = '免费'
66 | p_low = '免费'
67 | p_old = '免费'
68 | if p_now == -1:
69 | p_now = '-'
70 | p_low = '-'
71 | p_old = '-'
72 |
73 | review = detail['review']
74 | r_result = review['result']
75 | r_total = review['total']
76 | # r_percent = review['percent']
77 | review_str = f'{r_result} ({r_total})'
78 |
79 | result.append((f'|[]({link})|[{name}]({link})|{card}|'
80 | f'{p_now}|{p_old}|{discount}|{p_low}|{shidi}|{review_str}|'))
81 | else:
82 | result.append('游戏列表空,请检查过滤器设置以及是否将愿望单公开')
83 | return ('\n'.join(result))
84 |
--------------------------------------------------------------------------------
/module/log.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 | '''
3 | # @Author : Chr_
4 | # @Date : 2020-06-21 15:46:23
5 | # @LastEditors : Chr_
6 | # @LastEditTime : 2020-11-14 14:20:39
7 | # @Description : 日志模块
8 | '''
9 |
10 | import logging
11 | import os
12 |
13 | debug = (os.getenv('mode', '').lower() == 'debug')
14 |
15 | log_level = logging.DEBUG if debug else logging.INFO
16 | log_format = '%(asctime)s %(levelname)s %(name)s %(message)s'
17 | log_data = '%H:%M:%S' # '%m-%d %H:%M:%S'
18 |
19 | logging.basicConfig(level=log_level,
20 | format=log_format,
21 | datefmt=log_data)
22 |
23 |
24 | def get_logger(tag: str = '-'):
25 | return (logging.getLogger(tag))
--------------------------------------------------------------------------------
/module/sort.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 | '''
3 | # @Author : Chr_
4 | # @Date : 2020-11-10 13:54:21
5 | # @LastEditors : Chr_
6 | # @LastEditTime : 2020-11-10 19:03:20
7 | # @Description : 生成索引
8 | '''
9 |
10 |
11 | def get_index(wishdict: dict, setting: dict) -> list:
12 | '''
13 | 根据设置生成排序后的key索引
14 |
15 | 参数:
16 | wishdict: 愿望单字典
17 | setting: 设置字典
18 | 返回:
19 | list: wishdict排序后的key列表
20 | '''
21 | # TODO
22 | return wishdict.keys()
23 |
--------------------------------------------------------------------------------
/module/static.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 | '''
3 | # @Author : Chr_
4 | # @Date : 2020-05-03 23:20:00
5 | # @LastEditors : Chr_
6 | # @LastEditTime : 2020-11-26 16:02:27
7 | # @Description : 静态常量
8 | '''
9 |
10 | # 脚本版本
11 | SCRIPT_VERSION = '1.11'
12 |
13 | # 缓存数据库名称
14 | DB_NAME = 'data.db'
15 |
16 | # 输出文件夹名称
17 | OP_PATH = 'output'
18 |
19 | # 可用排序种类
20 | SORT_TYPE = 7
21 |
22 | # 网络超时时间
23 | TIMEOUT = 10
24 |
25 | # 每个线程的等待时间
26 | TREAD_CD = 0.8
27 |
28 | # 近史低标准
29 | ALMOST_LOWEST = 0.05
30 |
31 |
32 | class URLs():
33 | '''
34 | URL常量
35 | '''
36 |
37 | Steam_Store = 'https://store.steampowered.com/'
38 | Steam_Wishlist = 'https://store.steampowered.com/wishlist/profiles/%s/#sort=%s'
39 | Steam_Wishlist_XHR = 'https://store.steampowered.com/wishlist/profiles/%s/wishlistdata/?p=%s'
40 | Steam_Game_Pic_SM = 'https://steamcdn-a.akamaihd.net/steam/apps/%s/capsule_sm_120.jpg'
41 | Steam_Game_Pic_MD = 'https://steamcdn-a.akamaihd.net/steam/apps/%s/header_292x136.jpg'
42 |
43 | ITAD_ID_To_Plain = 'https://api.isthereanydeal.com/v01/game/plain/id/'
44 | ITAD_Get_Current_Prices = 'https://api.isthereanydeal.com/v01/game/prices/'
45 | ITAD_Get_Lowest_Prices = 'https://api.isthereanydeal.com/v01/game/lowest/'
46 | ITAD_Get_Game_Info = 'https://api.isthereanydeal.com/v01/game/info/'
47 | ITAD_Get_Overview_Prices = 'https://api.isthereanydeal.com/v01/game/overview/'
48 |
49 | Keylol_Get_Game_Info = 'https://steamdb.keylol.com/app/%s/data.js?v=38'
50 |
51 | Github_Releases = 'https://github.com/chr233/steam_wishlist_helper/releases'
52 | Github_Releases_API = 'https://api.github.com/repos/chr233/steam_wishlist_helper/releases/latest'
53 |
54 |
55 | HEADERS = {
56 | "Accept": "application/json",
57 | "Accept-Encoding": "gzip",
58 | "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
59 | "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36 Steam_Wishlist_Helper",
60 | }
61 |
62 | Review2Num = {
63 | 'Error': -1,
64 | 'No user reviews': 0,
65 | 'Overwhelmingly Negative': 1,
66 | 'Very Negative': 2,
67 | 'Negative': 3,
68 | 'Mostly Negative': 4,
69 | 'Mixed': 5,
70 | 'Mostly Positive': 6,
71 | 'Positive': 7,
72 | 'Very Positive': 8,
73 | 'Overwhelmingly Positive': 9
74 | }
75 |
76 | Num2Review = {
77 | -1: '【解析出错】',
78 | 0: '评测数量不足',
79 | 1: '差评如潮',
80 | 2: '特别差评',
81 | 3: '差评',
82 | 4: '多半差评',
83 | 5: '褒贬不一',
84 | 6: '多半好评',
85 | 7: '好评',
86 | 8: '特别好评',
87 | 9: '好评如潮'
88 | }
89 |
90 | GameType2Num = {
91 | 'Error': 0,
92 | 'Game': 1,
93 | 'Application': 2,
94 | 'DLC': 3,
95 | 'Video': 4
96 | }
97 | Num2GameType = {
98 | 0: '【解析错误】',
99 | 1: '游戏',
100 | 2: '软件',
101 | 3: 'DLC',
102 | 4: '视频'
103 | }
104 |
--------------------------------------------------------------------------------
/module/utils.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 | '''
3 | # @Author : Chr_
4 | # @Date : 2020-11-07 18:16:37
5 | # @LastEditors : Chr_
6 | # @LastEditTime : 2020-11-15 02:34:13
7 | # @Description : 一些公共函数
8 | '''
9 |
10 | from os import path, makedirs, getcwd
11 |
12 | from .static import OP_PATH, ALMOST_LOWEST
13 |
14 |
15 | def is_lowest(origin: int, current: int, lowest: int, cut: int) -> int:
16 | '''
17 | 检查价格是否为史低
18 |
19 | 参数:
20 | origin: 无折扣原价
21 | current: 现价
22 | lowest: 史低价
23 | 返回:
24 | int: 1-史低,0-未达史低也不是近史低,-1-近史低
25 | '''
26 | if (cut > 0):
27 | if (current <= lowest): # 史低
28 | return 1
29 | elif ((current - lowest) / origin <= ALMOST_LOWEST): # 近史低
30 | return -1
31 | return 0
32 |
33 |
34 | def is_lowest_str(r: int) -> int:
35 | '''
36 | 检查价格是否为史低
37 |
38 | 参数:
39 | origin: 无折扣原价
40 | current: 现价
41 | lowest: 史低价
42 | 返回:
43 | str: 史低/近史低/空文本
44 | '''
45 | if (r > 0):
46 | return "史低"
47 | elif (r < 0):
48 | return "近史低"
49 | return "-"
50 |
51 |
52 | def get_output_path(name: str) -> str:
53 | '''
54 | 获取输出文件路径
55 |
56 | 参数:
57 | name: 文件名
58 | 返回:
59 | str: 文件路径
60 | '''
61 | if not path.exists(OP_PATH):
62 | makedirs(OP_PATH)
63 | p = path.join(getcwd(), OP_PATH, name)
64 | return str(p)
65 |
66 |
67 | def dint(value: all, default: int = -1) -> int:
68 | '''
69 | 带默认值的int()
70 |
71 | 参数:
72 | value: 待转换值
73 | default: 默认值
74 | 返回:
75 | int
76 | '''
77 | try:
78 | r = int(value)
79 | except (ValueError, TypeError):
80 | r = default
81 | return r
82 |
83 |
84 | def fbool(value: all) -> bool:
85 | '''
86 | 根据value,返回True,False或者-1
87 |
88 | 参数:
89 | value: 待转换值
90 | 返回:
91 | int
92 | '''
93 | value = dint(value, value)
94 |
95 | if value <= -1:
96 | return -1
97 | else:
98 | return bool(value)
99 |
100 |
101 | def fint(value: all, max_: int = 0) -> int:
102 | '''
103 | 根据value,返回大于0的整数,或者-1
104 |
105 | 参数:
106 | value: 待转换值
107 | max_: 默认值
108 | 返回:
109 | int
110 | '''
111 | value = dint(value, -1)
112 |
113 | if max_ > 0 and 0 <= value <= max_:
114 | return value
115 | elif max_ == 0 and 0 <= value:
116 | return value
117 | else:
118 | return -1
119 |
120 |
121 | def flist(value: all) -> int:
122 | '''
123 | 根据value,返回字符串列表
124 |
125 | 参数:
126 | value: 待转换值
127 | 返回:
128 | int
129 | '''
130 | value = dint(value, value)
131 |
132 | if value != -1:
133 | if isinstance(value, list):
134 | value = [str(x) for x in value]
135 | else:
136 | value = [str(value)]
137 | return value
138 |
--------------------------------------------------------------------------------
/module/version.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 | '''
3 | # @Author : Chr_
4 | # @Date : 2020-11-08 10:11:20
5 | # @LastEditors : Chr_
6 | # @LastEditTime : 2020-11-26 16:02:20
7 | # @Description : 版本管理
8 | '''
9 |
10 | from httpx import AsyncClient
11 | from typing import Tuple
12 |
13 | from .log import get_logger
14 | from .aionet import adv_http_get
15 | from .static import SCRIPT_VERSION, URLs
16 |
17 | logger = get_logger('Version')
18 |
19 |
20 | async def check_update(setting: dict):
21 | '''
22 | 检查脚本更新
23 | '''
24 | vc, vl, i, u = await __check_update(setting)
25 | # 检查脚本更新
26 | if (vc == vl):
27 | logger.info(f'已经是最新版本,当前版本 [{vc}]')
28 | elif (vc > vl):
29 | logger.info(f'已经是最新版本,当前版本 [{vc}] , 最新发布版本 [{vl}]')
30 | else:
31 | print('\n'*2)
32 | logger.info((f'[*] 脚本有更新,最新发布版本 [{vl}]\n'
33 | '更新内容:\n'
34 | f'{i}\n'
35 | f'{u}'))
36 | print('\n'*2)
37 |
38 |
39 | async def __check_update(setting: dict) -> Tuple[str, str, str, str]:
40 | '''
41 | 检查脚本版本
42 | '''
43 | logger.debug('正在后台检查更新')
44 | net = setting.get('net', {})
45 | proxy = net.get('proxy', None)
46 | async with AsyncClient(proxies=proxy) as client:
47 | url = URLs.Github_Releases_API
48 | resp = await adv_http_get(client=client, url=url)
49 | current_version = float(SCRIPT_VERSION)
50 | if resp:
51 | try:
52 | jd = resp.json()
53 | latest_version = float(str(jd['tag_name']))
54 | update_info = jd['body']
55 | download_url = jd['assets'][0]['browser_download_url']
56 | if (current_version == latest_version):
57 | logger.debug(f'当前为最新版本 [{current_version}]')
58 | elif (current_version > latest_version):
59 | logger.debug(
60 | f'当前版本号比发行版高 [{current_version}<-{latest_version}]')
61 | else:
62 | logger.debug(
63 | f'脚本有更新 [{current_version}->{latest_version}]')
64 | return ((current_version, latest_version, update_info, download_url))
65 | except Exception:
66 | logger.debug('检查最新版本出错')
67 | return ((current_version, current_version, '检查更新出错', URLs.Github_Releases))
68 | else:
69 | logger.debug('检查最新版本出错')
70 | return ((current_version, current_version, '检查更新出错', URLs.Github_Releases))
71 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | XlsxWriter>=1.3.7
2 | httpx>=0.14.3
3 | toml>=0.10.1
4 | aiosqlite>=0.16.0
5 | prettytable>=1.0.1
--------------------------------------------------------------------------------
/run.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 | '''
3 | # @Author : Chr_
4 | # @Date : 2020-11-01 00:00:47
5 | # @LastEditors : Chr_
6 | # @LastEditTime : 2020-11-10 19:03:04
7 | # @Description : 启动入口
8 | '''
9 |
10 | import asyncio
11 |
12 | from module.config import get_config
13 | from module.crawer import Crawer
14 | from module.log import get_logger
15 | from module.version import check_update
16 |
17 | logger = get_logger('Main')
18 |
19 |
20 | async def main():
21 | cfg = get_config()
22 | if cfg:
23 | steamid = cfg['auto']['steamid'] or [input('请输入64位steam ID: ')]
24 | c = Crawer(cfg, steamid)
25 |
26 | tasks = [
27 | asyncio.create_task(check_update(cfg)), # 异步检查更新
28 | asyncio.create_task(c.start())
29 | ]
30 | await asyncio.wait(tasks)
31 |
32 | try:
33 | if (cfg['other']['wait_screen']):
34 | input('运行结束,按回车键退出……')
35 | else:
36 | print('运行结束,程序退出')
37 | except KeyboardInterrupt:
38 | pass
39 | else:
40 | logger.info('读取配置文件失败')
41 | input('运行结束,按回车键退出……')
42 |
43 | loop = asyncio.get_event_loop()
44 | loop.run_until_complete(main())
45 |
--------------------------------------------------------------------------------