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

UESTC

3 |

UESTC-API

4 | 5 | > 👉 [https://uestc.ml](https://uestc.ml) 6 | 7 | [![node (tag)](https://img.shields.io/node/v/egg.svg?style=flat-square)](https://nodejs.org) [![](https://img.shields.io/travis/Vizards/uestc-api.svg?style=flat-square)](https://travis-ci.org/Vizards/uestc-api) [![Docker Cloud Automated build](https://img.shields.io/docker/cloud/automated/vizards/uestc-api.svg?style=flat-square)](https://hub.docker.com/r/vizards/uestc-api) [![Docker Cloud Build Status](https://img.shields.io/docker/cloud/build/vizards/uestc-api.svg?style=flat-square)](https://hub.docker.com/r/vizards/uestc-api/builds) [![](https://img.shields.io/codecov/c/github/Vizards/uestc-api.svg?style=flat-square)](https://codecov.io/gh/Vizards/uestc-api) [![Dependency Status](https://img.shields.io/david/Vizards/uestc-api.svg?style=flat-square)](https://david-dm.org/Vizards/uestc-api) [![](https://img.shields.io/badge/license-GPL-blue.svg?style=flat-square)](https://github.com/Vizards/uestc-api/blob/dev/LICENSE) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](https://github.com/Vizards/uestc-api/pulls) [![%e2%9d%a4](https://img.shields.io/badge/made%20with-%e2%9d%a4-ff69b4.svg?style=flat-square)](https://github.com/Vizards/uestc-api) 8 | 9 | ## 介绍 10 | 11 | UESTC-API 是电子科技大学部分网站功能的集成 API 接口,仅支持查询本科生数据 12 | 13 | ## 功能 14 | 15 | > 以下功能尚未完全接口化。3、4 中的功能均以 302 跳转到相关网页的方式完成(已经过处理使其支持 HTTPS 和移动端视图) 16 | > 17 | > 如果您有兴趣完善,欢迎 [Pull Request](https://github.com/Vizards/uestc-api/pulls) 18 | 19 | 20 | 1. 教务系统 21 | - [x] 统一身份认证系统登录/退出 22 | - [x] 按学期获取课程表信息 23 | - [x] 按学期获取考试安排信息 24 | - [x] 按学期获取课程成绩信息 25 | - [x] 获取所有课程成绩信息 26 | - [x] 获取成绩统计信息 27 | - [x] 获取平时成绩信息 28 | - [x] 获取和设置用户个人信息 29 | - [ ] 评教 30 | 31 | 2. 后勤综合服务 32 | - [x] 获取一卡通信息 33 | - [x] 一卡通挂失 34 | - [x] 获取一卡通和电费账单 35 | - [x] 获取宿舍电费信息 36 | 37 | 3. 校园实用工具 38 | - [x] 校园班车查询 39 | - [x] 空闲教室查询 40 | - [x] 当日课程查询 41 | - [x] 全校课程查询 42 | - [x] 教师信息查询 43 | 44 | 4. 公告与信息 45 | - [x] 学校办公室联系方式 46 | - [x] 教务服务指南 47 | - [x] 教学管理公告 48 | - [x] 教研教改公告 49 | - [x] 实践交流公告 50 | - [x] 教学新闻 51 | 52 | 5. 开发者服务 53 | - [x] 获取账户教务系统网站 cookies 54 | - [x] 获取账户一卡通网站 cookies 55 | 56 | ## 文档 57 | 58 | - API 接口文档: [GitHub Wiki](https://github.com/Vizards/uestc-api/wiki) 59 | 60 | - 开发者接口文档:[开发者 - GitHub Wiki](https://github.com/Vizards/uestc-api/wiki/%E5%BC%80%E5%8F%91%E8%80%85) 61 | 62 | - Egg 框架文档:[egg - 为企业级框架和应用而生](https://eggjs.org) 63 | 64 | ## 部署 65 | 66 | UESTC-API 现已提供 Docker 版本,但仍可灵活选择多种部署方式 67 | 68 | 详见:[部署 - GitHub Wiki](https://github.com/Vizards/uestc-api/wiki/%E9%83%A8%E7%BD%B2) 69 | 70 | ## 开发 71 | 72 | 在开始之前,请确认您的电子科技大学本科统一身份认证系统账户已完成初始设置 73 | 74 | #### 安装 75 | 76 | 项目框架为 [Egg](https://eggjs.org),`node` 版本需要高于 `v8.0.0` 77 | 78 | ```bash 79 | $ git clone && npm install 80 | ``` 81 | 82 | 83 | #### 安装全局依赖 84 | 85 | - [MongoDB](https://docs.mongodb.com/) 86 | 87 | - ~~[GraphicsMagick](http://www.graphicsmagick.org/):用于处理验证码~~ 88 | 89 | - ~~[Tesseract 3.01+](https://github.com/tesseract-ocr/tesseract):用于识别验证码~~ 90 | 91 | #### 开发环境运行 92 | 93 | **设置 `config.default.js` 和 `config.unittest.js` 中的密码、Key 等** 94 | 95 | ```bash 96 | $ npm run dev 97 | ``` 98 | 99 | > 参数说明 100 | 101 | 参数 | 是否必须 | 说明 102 | :---: | :---: | :---: 103 | `APP_KEY` | 是 | 自定义 104 | `JWT_SECRET` | 是 | 自定义,生成 `jwt-token` 的密钥 105 | `YOUR_STU_NUM`
`YOUR_STU_PASS` | 否(单元测试必须)| 学号
密码 106 | `YOUR_ROOM_ID` | 否(单元测试必须)| 宿舍房间号 107 | `ALINODE_APPID`
`ALINODE_SECRET` | 是 | 阿里云 Node.js 性能平台
`APPID`
`SECRET`
(需自行注册) 108 | `PROXY` | 否 | HTTP(S) 代理服务器地址和端口
格式 `http(s)://url:port` 109 | 110 | 或者可以将参数设置为环境变量,然后运行: 111 | 112 | **Linux, MacOS(Bash)** 113 | 114 | ```bash 115 | APP_KEY=xxx JWT_SECRET=xxx YOUR_STU_NUM=xxx YOUR_STU_PASS=xxx YOUR_ROOM_ID=xxx ALINODE_APPID=xxx ALINODE_SECRET=xxx PROXY=xxx npm run dev 116 | ``` 117 | 118 | **Windows(cmd.exe)** 119 | 120 | ```bash 121 | set APP_KEY=xxx && set JWT_SECRET=xxx && set YOUR_STU_NUM=xxx && set YOUR_STU_PASS=xxx && set YOUR_ROOM_ID=xxx && set ALINODE_APPID=xxx && set ALINODE_SECRET=xxx && set PROXY=xxx && npm run dev 122 | ``` 123 | 124 | **Windows(Powershell)** 125 | 126 | ```bash 127 | ($env:APP_KEY=xxx) -and ($env:JWT_SECRET=xxx) -and ($env:YOUR_STU_NUM=xxx) -and ($env:YOUR_STU_PASS=xxx) -and ($env:YOUR_ROOM_ID=xxx) -and ($env:ALINODE_APPID=xxx) -and ($env:ALINODE_SECRET=xxx) -and ($env:PROXY=xxx) -and npm run dev 128 | ``` 129 | 130 | 浏览器打开 `http://127.0.0.1:7001` 页面出现项目主页即为运行成功 131 | 132 | #### 单元测试 133 | 134 | > 运行测试需要配置上表中的参数,同时保证数据库可连接 135 | 136 | 单元测试受源站网络影响,如遇单元测试无法通过,请先确认 **[教务系统](http://portal.uestc.edu.cn)**、**[一卡通](http://ecard.uestc.edu.cn)**、**成电微教务(微信订阅号)** 是否可以正常使用 137 | 138 | ```bash 139 | $ npm run test 140 | ``` 141 | 142 | 目前只完成了 `Controller` 层简单的单元测试,如果您有兴趣完善,欢迎 [Pull Request](https://github.com/Vizards/uestc-api/pulls) 143 | 144 | #### 覆盖率测试 145 | 146 | ```bash 147 | $ npm run cov 148 | ``` 149 | 150 | #### 代码风格检查(ESLint) 151 | 152 | ```bash 153 | $ npm run lint 154 | ``` 155 | 156 | #### 检查依赖更新 157 | 158 | 请先删除 `package-lock.json` 或 `yarn.lock` 文件 159 | 160 | ```bash 161 | $ npm run autod 162 | ``` 163 | 164 | 参考:[autod](https://www.npmjs.com/package/autod) 165 | 166 | ## 合作产品 167 | 168 | 如果您的产品或服务接入了 UESTC-API,可通过 [New Issue](https://github.com/Vizards/uestc-api/issue) 或 [Pull Request](https://github.com/Vizards/uestc-api/pulls) 展示在此处 169 | 170 | 171 | 172 | 173 | 176 | 179 | 180 | 181 | 184 | 187 | 188 | 189 |
174 | UESTC 175 | 177 | 电子科技大学(UESTC)iOS 客户端 178 |
182 | UESTC 183 | 185 | iUESTC - 电子科技大学 Android 客户端 186 |
190 | 191 | ## 许可协议 192 | 193 | [GPL-3.0](https://github.com/Vizards/uestc-api/blob/dev/LICENSE) 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | -------------------------------------------------------------------------------- /app/controller/dev.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Controller = require('egg').Controller; 4 | 5 | class DevController extends Controller { 6 | constructor(ctx) { 7 | super(ctx); 8 | this.UserLoginTransfer = { 9 | username: { type: 'string', required: true, allowEmpty: false, format: /^[0-9]{13}$/ }, 10 | password: { type: 'password', required: true, allowEmpty: false, min: 6 }, 11 | }; 12 | } 13 | 14 | // 登录教务系统,返回 cookies 15 | async idas() { 16 | const { ctx, service } = this; 17 | ctx.validate(this.UserLoginTransfer); 18 | const payload = ctx.request.body || {}; 19 | const res = await service.dev.idas(payload); 20 | ctx.helper.postSuccess({ ctx, res }); 21 | } 22 | 23 | // 登录一卡通网站,返回 cookies 24 | async ecard() { 25 | const { ctx, service } = this; 26 | ctx.validate(this.UserLoginTransfer); 27 | const payload = ctx.request.body || {}; 28 | const res = await service.dev.ecard(payload); 29 | ctx.helper.postSuccess({ ctx, res }); 30 | } 31 | } 32 | 33 | module.exports = DevController; 34 | -------------------------------------------------------------------------------- /app/controller/extra.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Controller = require('egg').Controller; 4 | 5 | class ExtraController extends Controller { 6 | async traffic() { 7 | const { ctx } = this; 8 | ctx.status = 302; 9 | ctx.redirect('https://wx.uestc.ml/uestc-wxapp/?urlfrom=wx&myredirect=/busTime#/busTime'); 10 | } 11 | 12 | async contact() { 13 | const { ctx } = this; 14 | ctx.status = 302; 15 | ctx.redirect('https://wx.uestc.ml/uestc-wxapp/?urlfrom=wx&myredirect=%2FmobileM#/mobileM'); 16 | } 17 | 18 | async info() { 19 | const { ctx } = this; 20 | ctx.status = 302; 21 | ctx.redirect('https://jwc.uestc.ml/wx/toIndex.action'); 22 | } 23 | 24 | async stu() { 25 | const { ctx } = this; 26 | ctx.status = 302; 27 | ctx.redirect('https://jwc.uestc.ml/wx/SchAbout!findNewsInfo.action?partId=37,62,4028811d56bccc720156bcf9a16f0004,4028811d5688c21501568db010930007'); 28 | } 29 | 30 | async edu() { 31 | const { ctx } = this; 32 | ctx.status = 302; 33 | ctx.redirect('https://jwc.uestc.ml/wx/SchAbout!findNewsInfo.action?partId=4028811d54f83c720154ff69e1890002,39'); 34 | } 35 | 36 | async communication() { 37 | const { ctx } = this; 38 | ctx.status = 302; 39 | ctx.redirect('https://jwc.uestc.ml/wx/SchAbout!findNewsInfo.action?partId=38,4028811d5688c21501568daf83b20006'); 40 | } 41 | 42 | async news() { 43 | const { ctx } = this; 44 | ctx.status = 302; 45 | ctx.redirect('https://jwc.uestc.ml/wx/SchAbout!findNewsInfo.action?partId=40'); 46 | } 47 | 48 | async room() { 49 | const { ctx } = this; 50 | ctx.status = 302; 51 | ctx.redirect('https://jwc.uestc.ml/wx/SchAbout!toClassroom.action'); 52 | } 53 | 54 | async todayCourse() { 55 | const { ctx } = this; 56 | ctx.status = 302; 57 | ctx.redirect('https://jwc.uestc.ml/wx/CourseAbout!toTodayCourse.action'); 58 | } 59 | 60 | async searchCourse() { 61 | const { ctx } = this; 62 | ctx.status = 302; 63 | ctx.redirect('https://jwc.uestc.ml/wx/CourseAbout!toSearchCourse.action'); 64 | } 65 | 66 | async searchTeacher() { 67 | const { ctx } = this; 68 | ctx.status = 302; 69 | ctx.redirect('https://jwc.uestc.ml/wx/SchAbout!toSearchTeach.action'); 70 | } 71 | } 72 | 73 | module.exports = ExtraController; 74 | 75 | -------------------------------------------------------------------------------- /app/controller/home.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Controller = require('egg').Controller; 4 | 5 | class HomeController extends Controller { 6 | constructor(ctx) { 7 | super(ctx); 8 | 9 | this.calendarTranser = { 10 | year: { type: 'string', required: true, allowEmpty: false, format: /^[0-9]{4}$/ }, 11 | semester: { type: 'string', required: true, allowEmpty: false, format: /[1|2]$/ }, 12 | }; 13 | } 14 | 15 | async index() { 16 | const { ctx } = this; 17 | if (ctx.acceptJSON) { 18 | ctx.helper.getSuccess({ ctx, res: 'hi, uestc' }); 19 | } else { 20 | const result = await ctx.curl('https://qiniu.vizards.cc/uestc.ga/index.html'); 21 | ctx.status = result.status; 22 | ctx.set(result.headers); 23 | ctx.body = result.data; 24 | } 25 | } 26 | 27 | async calendar() { 28 | const { ctx, service } = this; 29 | ctx.validate(this.calendarTranser); 30 | const payload = ctx.request.body || {}; 31 | const res = await service.calendar.get(payload); 32 | ctx.helper.postSuccess({ ctx, res }); 33 | } 34 | } 35 | 36 | module.exports = HomeController; 37 | -------------------------------------------------------------------------------- /app/controller/living.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Controller = require('egg').Controller; 4 | 5 | class livingController extends Controller { 6 | constructor(ctx) { 7 | super(ctx); 8 | 9 | this.electricityTransfer = { 10 | room: { type: 'string', required: true, allowEmpty: true, format: /^[0-9]{6}$/ }, 11 | }; 12 | 13 | this.billTransfer = { 14 | day: { type: 'enum', required: true, allowEmpty: false, values: [ 7, 30, 90, 180 ] }, 15 | type: { type: 'enum', required: true, allowEmpty: false, values: [ 'all', 'cost', 'charge', 'electricity' ] }, 16 | }; 17 | } 18 | 19 | // 查询一卡通信息 20 | async ecard() { 21 | const { ctx, service } = this; 22 | const res = await service.ecard.query(); 23 | ctx.helper.getSuccess({ ctx, res }); 24 | } 25 | 26 | // 一卡通挂失 27 | async loss() { 28 | const { ctx, service } = this; 29 | const res = await service.loss.claim(); 30 | ctx.helper.postSuccess({ ctx, res }); 31 | } 32 | 33 | // 查询交易流水 34 | async bill() { 35 | const { ctx, service } = this; 36 | ctx.validate(this.billTransfer); 37 | const payload = ctx.request.body || {}; 38 | const res = await service.bill.query(payload); 39 | ctx.helper.postSuccess({ ctx, res }); 40 | } 41 | 42 | // 查询电费 43 | async electricity() { 44 | const { ctx, service } = this; 45 | ctx.validate(this.electricityTransfer); 46 | const payload = ctx.request.body || {}; 47 | const res = await service.electricity.query(payload); 48 | ctx.helper.postSuccess({ ctx, res }); 49 | } 50 | } 51 | 52 | module.exports = livingController; 53 | -------------------------------------------------------------------------------- /app/controller/user.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Controller = require('egg').Controller; 4 | 5 | 6 | class UserController extends Controller { 7 | constructor(ctx) { 8 | super(ctx); 9 | 10 | this.UserLoginTransfer = { 11 | username: { type: 'string', required: true, allowEmpty: false, format: /^[0-9]{13}$/ }, 12 | password: { type: 'password', required: true, allowEmpty: false, min: 6 }, 13 | }; 14 | 15 | this.courseTransfer = this.examTransfer = this.gradeTransfer = { 16 | year: { type: 'string', required: true, allowEmpty: false, format: /^[0-9]{4}$/ }, 17 | semester: { type: 'string', required: true, allowEmpty: false, format: /[1|2]$/ }, 18 | }; 19 | 20 | this.profileTransfer = { 21 | avatarUrl: { type: 'string', required: false, allowEmpty: false, format: /https:\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/ }, 22 | nickName: { type: 'string', required: false, allowEmpty: false, max: 50 }, 23 | bio: { type: 'string', required: false, allowEmpty: false, max: 50 }, 24 | }; 25 | } 26 | 27 | // 用户登录/创建 28 | async login() { 29 | const { ctx, service } = this; 30 | // 校验参数 31 | ctx.validate(this.UserLoginTransfer); 32 | // 组装参数 33 | const payload = ctx.request.body || {}; 34 | // 调用 Service 进行业务处理 35 | const res = await service.user.login(payload); 36 | // 设置响应内容和响应状态码 37 | ctx.helper.postSuccess({ ctx, res }); 38 | } 39 | 40 | // 退出统一身份认证系统的登录 41 | async exit() { 42 | const { ctx, service } = this; 43 | const res = await service.user.exit(); 44 | ctx.helper.postSuccess({ ctx, res }); 45 | } 46 | 47 | // 删除账户(删除数据库记录,不影响教务系统账户) 48 | async delete() { 49 | const { ctx, service } = this; 50 | ctx.validate(this.UserLoginTransfer); 51 | const payload = ctx.request.body || {}; 52 | const res = await service.user.delete(payload); 53 | ctx.helper.postSuccess({ ctx, res }); 54 | } 55 | 56 | // 获取个人信息 57 | async profile() { 58 | const { ctx, service } = this; 59 | const res = await service.profile.get(); 60 | ctx.helper.getSuccess({ ctx, res }); 61 | } 62 | 63 | // 修改头像 64 | async setProfile() { 65 | const { ctx, service } = this; 66 | ctx.validate(this.profileTransfer); 67 | const payload = ctx.request.body || {}; 68 | const res = await service.profile.set(payload); 69 | ctx.helper.postSuccess({ ctx, res }); 70 | } 71 | 72 | // 获取课程信息 73 | async course() { 74 | const { ctx, service } = this; 75 | ctx.validate(this.courseTransfer); 76 | const payload = ctx.request.body || {}; 77 | const res = await service.course.getCourse(payload); 78 | ctx.helper.postSuccess({ ctx, res }); 79 | } 80 | 81 | // 获取考试信息 82 | async exam() { 83 | const { ctx, service } = this; 84 | ctx.validate(this.examTransfer); 85 | const payload = ctx.request.body || {}; 86 | const res = await service.exam.getExam(payload); 87 | ctx.helper.postSuccess({ ctx, res }); 88 | } 89 | 90 | // 获取单学期成绩信息 91 | async grade() { 92 | const { ctx, service } = this; 93 | ctx.validate(this.gradeTransfer); 94 | const payload = ctx.request.body || {}; 95 | const res = await service.grade.getGrade(payload); 96 | ctx.helper.postSuccess({ ctx, res }); 97 | } 98 | 99 | // 获取所有学期成绩信息 100 | async allGrade() { 101 | const { ctx, service } = this; 102 | const res = await service.grade.allGrade(); 103 | ctx.helper.getSuccess({ ctx, res }); 104 | } 105 | 106 | // 获取平时成绩信息 107 | async usualGrade() { 108 | const { ctx, service } = this; 109 | ctx.validate(this.gradeTransfer); 110 | const payload = ctx.request.body || {}; 111 | const res = await service.grade.usualGrade(payload); 112 | ctx.helper.postSuccess({ ctx, res }); 113 | } 114 | 115 | // 获取 GPA 统计信息 116 | async gpa() { 117 | const { ctx, service } = this; 118 | const res = await service.grade.getGPA(); 119 | ctx.helper.getSuccess({ ctx, res }); 120 | } 121 | } 122 | 123 | module.exports = UserController; 124 | -------------------------------------------------------------------------------- /app/extend/RESTfulHTTPStatus.rec: -------------------------------------------------------------------------------- 1 | 200 OK - [GET]:服务器成功返回用户请求的数据,该操作是幂等的(Idempotent)。 2 | 201 CREATED - [POST/PUT/PATCH]:用户新建或修改数据成功。 3 | 202 Accepted - [*]:表示一个请求已经进入后台排队(异步任务) 4 | 204 NO CONTENT - [DELETE]:用户删除数据成功。 5 | 400 INVALID REQUEST - [POST/PUT/PATCH]:用户发出的请求有错误,服务器没有进行新建或修改数据的操作,该操作是幂等的。 6 | 401 Unauthorized - [*]:表示用户没有权限(令牌、用户名、密码错误)。 7 | 403 Forbidden - [*] 表示用户得到授权(与 401 错误相对),但是访问是被禁止的。 8 | 404 NOT FOUND - [*]:用户发出的请求针对的是不存在的记录,服务器没有进行操作,该操作是幂等的。 9 | 406 Not Acceptable - [GET]:用户请求的格式不可得(比如用户请求 JSON 格式,但是只有 XML 格式)。 10 | 410 Gone -[GET]:用户请求的资源被永久删除,且不会再得到的。 11 | 422 Unprocesable entity - [POST/PUT/PATCH] 当创建一个对象时,发生一个验证错误。 12 | 500 INTERNAL SERVER ERROR - [*]:服务器发生错误,用户将无法判断发出的请求是否成功 -------------------------------------------------------------------------------- /app/extend/helper.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const moment = require('moment'); 4 | const request = require('request-promise-native').defaults({ simple: false, resolveWithFullResponse: true }); 5 | const CryptoJS = require('crypto-js'); 6 | 7 | // 处理 POST 成功响应 8 | exports.postSuccess = ({ ctx, res, msg = 'Post Success' }) => { 9 | ctx.body = { 10 | code: 201, 11 | data: res, 12 | time: moment.utc().format(), 13 | msg, 14 | }; 15 | ctx.status = 200; 16 | }; 17 | 18 | // 处理 GET 成功响应 19 | exports.getSuccess = ({ ctx, res, msg = 'Get Success' }) => { 20 | ctx.body = { 21 | code: 200, 22 | data: res, 23 | time: moment.utc().format(), 24 | msg, 25 | }; 26 | ctx.status = 200; 27 | }; 28 | 29 | // 返回完整 HTML 数据 30 | exports.htmlSuccess = ({ ctx, res }) => { 31 | ctx.body = res; 32 | ctx.status = 200; 33 | }; 34 | 35 | // 封装单点登录 request 请求 36 | exports.checkSSO = (url, cookies, Host) => { 37 | try { 38 | const option = { 39 | url, 40 | method: 'GET', 41 | headers: { 42 | Cookie: cookies, 43 | 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1', 44 | }, 45 | Host, 46 | followRedirect: false, 47 | proxy: process.env.PROXY || null, 48 | }; 49 | const res = request(option); 50 | return Promise.resolve(res); 51 | } catch (err) { 52 | return Promise.reject(err); 53 | } 54 | }; 55 | 56 | // 封装生成 OPTIONS 57 | exports.options = (url, method, Cookie, form) => { 58 | return { 59 | url, 60 | method: method ? method : 'GET', 61 | headers: Cookie ? { 62 | Cookie, 63 | 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1', 64 | } : null, 65 | form: form ? form : null, 66 | followRedirect: false, 67 | proxy: process.env.PROXY || null, 68 | }; 69 | }; 70 | 71 | exports.encrypt = (data, aesKey) => { 72 | if (!aesKey) aesKey = 'rjBFAaHsNkKAhpoi'; // 没有什么用,需要从 HTML 解析得到真正的动态 key 73 | const $aes_chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; 74 | const aes_chars_len = $aes_chars.length; 75 | 76 | function getAesString(data, key0, iv0) { 77 | key0 = key0.replace(/(^\s+)|(\s+$)/g, ''); 78 | const key = CryptoJS.enc.Utf8.parse(key0); 79 | const iv = CryptoJS.enc.Utf8.parse(iv0); 80 | const encrypted = CryptoJS.AES.encrypt(data, key, { 81 | iv, 82 | mode: CryptoJS.mode.CBC, 83 | padding: CryptoJS.pad.Pkcs7, 84 | }); 85 | return encrypted.toString(); 86 | } 87 | 88 | function randomString(len) { 89 | let retStr = ''; 90 | for (let i = 0; i < len; i++) { 91 | retStr += $aes_chars.charAt(Math.floor(Math.random() * aes_chars_len)); 92 | } 93 | return retStr; 94 | } 95 | 96 | return getAesString(randomString(64) + data, aesKey, randomString(16)); 97 | }; 98 | 99 | exports.generateCookieString = (ctx, requiredKeys, customCookies) => { 100 | let generatedCookies = ''; 101 | const cookies = JSON.parse(customCookies ? customCookies : ctx.locals.user.data.cookies); 102 | requiredKeys = requiredKeys ? requiredKeys : Object.keys(cookies); 103 | 104 | requiredKeys.forEach(key => { 105 | generatedCookies += `${key}=${cookies[key]};`; 106 | }); 107 | return generatedCookies; 108 | }; 109 | 110 | exports.parseCookies = cookiesArray => { 111 | const cookies = {}; 112 | cookiesArray.forEach(item => { 113 | const splitLocation = item.indexOf('='); 114 | const key = item.substring(0, splitLocation); 115 | const value = item.substring(splitLocation + 1); 116 | cookies[key] = value; 117 | }); 118 | return cookies; 119 | }; 120 | -------------------------------------------------------------------------------- /app/middleware/cookies_handler.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports = () => { 4 | return async (ctx, next) => { 5 | if (ctx.locals.user.data.cookies !== undefined) return next(); 6 | try { 7 | const username = ctx.locals.user.data.username; 8 | const query = ctx.model.User.findOne({ username }); 9 | await query.select('finalCookies'); 10 | const data = await query.exec(); 11 | ctx.locals.user.data.cookies = data.finalCookies; 12 | return next(); 13 | } catch (err) { 14 | ctx.throw(err); 15 | } 16 | }; 17 | }; 18 | -------------------------------------------------------------------------------- /app/middleware/sso_handler.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | async function refresh(ctx) { 4 | const cookies = ctx.helper.generateCookieString(ctx, [ 5 | 'semester.id', 6 | 'JSESSIONID', 7 | 'sto-id-20480', 8 | 'iPlanetDirectoryPro', 9 | ]); 10 | 11 | try { 12 | const res = await ctx.helper.checkSSO('http://eams.uestc.edu.cn/eams/home.action', cookies); 13 | switch (res.statusCode) { 14 | case 200: 15 | if (res.body.includes('本次会话已经被过期(可能是由于重复登录)') || res.body.includes('当前用户存在重复登录的情况')) { 16 | await refresh(ctx); 17 | } 18 | return '已登录'; 19 | case 302: 20 | return res.headers.location; 21 | default: 22 | return ctx.throw(403, '无法重定向至指定页面,教务系统未按预期跳转'); 23 | } 24 | } catch (e) { 25 | return ctx.throw(500, e); 26 | } 27 | } 28 | 29 | async function getTicketUrl(ctx, url) { 30 | const cookies = ctx.helper.generateCookieString(ctx, [ 31 | 'CASTGC', 32 | 'route', 33 | 'JSESSIONID', 34 | 'iPlanetDirectoryPro', 35 | ]); 36 | try { 37 | const res = await ctx.helper.checkSSO(url, cookies, 'idas.uestc.edu.cn'); 38 | if (res.statusCode === 302 && res.headers.location.includes('ticket')) { 39 | return res.headers.location; 40 | } 41 | return ctx.throw(403, '统一身份认证系统登录失败,请尝试重新登录以避开单点登录限制'); 42 | } catch (e) { 43 | return ctx.throw(500, e); 44 | } 45 | } 46 | 47 | async function getNewCookies(ctx, ticketUrl) { 48 | const cookies = ctx.helper.generateCookieString(ctx, [ 49 | 'semester.id', 50 | 'JSESSIONID', 51 | 'sto-id-20480', 52 | 'iPlanetDirectoryPro', 53 | ]); 54 | 55 | try { 56 | const res = await ctx.helper.checkSSO(ticketUrl, cookies); 57 | if (res.headers['set-cookie'].length !== 0) { 58 | return res.headers['set-cookie']; 59 | } 60 | } catch (err) { 61 | return ctx.throw(500, err); 62 | } 63 | } 64 | 65 | async function updateCookies(ctx, newCookies) { 66 | try { 67 | const username = ctx.locals.user.data.username; 68 | const query = ctx.model.User.findOne({ username }); 69 | await query.select('finalCookies'); 70 | const data = await query.exec(); 71 | 72 | const finalCookies = JSON.parse(data.finalCookies); 73 | newCookies.forEach(item => { 74 | const splitLocation = item.indexOf('='); 75 | const key = item.substring(0, splitLocation); 76 | const value = item.substring(splitLocation + 1); 77 | finalCookies[key] = value; 78 | }); 79 | 80 | ctx.locals.user.data.cookies = finalCookies; 81 | 82 | await ctx.model.User.updateOne({ 83 | username, 84 | }, { 85 | updatedAt: Date.now(), 86 | finalCookies: JSON.stringify(finalCookies), 87 | }); 88 | 89 | } catch (e) { 90 | return ctx.throw(500, e); 91 | } 92 | } 93 | 94 | module.exports = () => { 95 | return async (ctx, next) => { 96 | const url = await refresh(ctx); 97 | if (url !== '已登录') { 98 | const ticketUrl = await getTicketUrl(ctx, url); 99 | const newCookies = await getNewCookies(ctx, ticketUrl); 100 | await updateCookies(ctx, newCookies); 101 | } 102 | return next(); 103 | }; 104 | }; 105 | -------------------------------------------------------------------------------- /app/model/user.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports = app => { 4 | const mongoose = app.mongoose; 5 | mongoose.set('useCreateIndex', true); 6 | const UserSchema = new mongoose.Schema({ 7 | username: { type: String, unique: true, required: true }, 8 | finalCookies: { type: String, unique: true, required: true }, 9 | avatarUrl: { type: String, unique: false, required: false }, 10 | nickName: { type: String, unique: false, required: false }, 11 | bio: { type: String, unique: false, required: false }, 12 | createdAt: { type: Date, default: Date.now }, 13 | updatedAt: { type: Date, default: Date.now }, 14 | }); 15 | return mongoose.model('User', UserSchema); 16 | }; 17 | -------------------------------------------------------------------------------- /app/public/calendar.json: -------------------------------------------------------------------------------- 1 | { 2 | "2014": { 3 | "1": { 4 | "startDate": "2014-09-01", 5 | "endDate": "2015-01-18", 6 | "holidays": [ 7 | { "name": "运动会", "date": ["2014-09-26", "2014-09-27"] }, 8 | { "name": "中秋节", "date": ["2014-09-06", "2014-09-07", "2014-09-08"] }, 9 | { "name": "国庆节", "date": ["2014-10-01", "2014-10-02", "2014-10-03", "2014-10-04", "2014-10-05", "2014-10-06", "2014-10-07"] }, 10 | { "name": "元旦节", "date": ["2015-01-01", "2015-01-02", "2015-01-03"] } 11 | ] 12 | }, 13 | "2": { 14 | "startDate": "2015-03-02", 15 | "endDate": "2015-07-19", 16 | "holidays": [ 17 | { "name": "清明节", "date": ["2015-04-04", "2015-04-05", "2015-04-06"] }, 18 | { "name": "劳动节", "date": ["2015-05-01", "2015-05-02", "2015-05-03"] }, 19 | { "name": "端午节", "date": ["2015-06-20", "2015-06-21", "2015-06-22"] } 20 | ] 21 | } 22 | }, 23 | "2015": { 24 | "1": { 25 | "startDate": "2015-08-31", 26 | "endDate": "2016-01-17", 27 | "holidays": [ 28 | { "name": "运动会", "date": ["2015-09-25", "2015-09-26"] }, 29 | { "name": "中秋节", "date": ["2015-09-26", "2015-09-27"] }, 30 | { "name": "国庆节", "date": ["2015-10-01", "2015-10-02", "2015-10-03", "2015-10-04", "2015-10-05", "2015-10-06", "2015-10-07"] }, 31 | { "name": "元旦节", "date": ["2016-01-01", "2016-01-02", "2016-01-03"] } 32 | ] 33 | }, 34 | "2": { 35 | "startDate": "2016-02-22", 36 | "endDate": "2016-07-10", 37 | "holidays": [ 38 | { "name": "清明节", "date": ["2016-04-02", "2016-04-03", "2016-04-04"] }, 39 | { "name": "劳动节", "date": ["2016-04-30", "2016-05-01", "2016-05-02"] }, 40 | { "name": "端午节", "date": ["2016-06-09", "2016-06-10", "2016-06-11"] } 41 | ] 42 | } 43 | }, 44 | "2016": { 45 | "1": { 46 | "startDate": "2016-08-29", 47 | "endDate": "2017-01-15", 48 | "holidays": [ 49 | { "name": "运动会", "date": ["2016-09-27", "2016-09-28"] }, 50 | { "name": "中秋节", "date": ["2016-09-15", "2016-09-16", "2016-09-17"] }, 51 | { "name": "国庆节", "date": ["2016-10-01", "2016-10-02", "2016-10-03", "2016-10-04", "2016-10-05", "2016-10-06", "2016-10-07"] }, 52 | { "name": "元旦节", "date": ["2016-12-31", "2017-01-01", "2017-01-02"] } 53 | ] 54 | }, 55 | "2": { 56 | "startDate": "2017-02-10", 57 | "endDate": "2017-07-09", 58 | "holidays": [ 59 | { "name": "清明节", "date": ["2017-04-02", "2017-04-03", "2017-04-04"] }, 60 | { "name": "劳动节", "date": ["2017-04-29", "2017-04-30", "2017-05-01"] }, 61 | { "name": "端午节", "date": ["2017-05-28", "2016-05-29", "2016-05-30"] } 62 | ] 63 | } 64 | }, 65 | "2017": { 66 | "1": { 67 | "startDate": "2017-09-04", 68 | "endDate": "2018-01-21", 69 | "holidays": [ 70 | { "name": "运动会", "date": ["2017-09-29", "2017-09-30"] }, 71 | { "name": "中秋节", "date": ["2016-10-04"] }, 72 | { "name": "国庆节", "date": ["2017-10-01", "2017-10-02", "2017-10-03", "2017-10-05", "2017-10-06", "2017-10-07", "2017-10-08"] }, 73 | { "name": "元旦节", "date": ["2017-12-30", "2017-12-31", "2018-01-01"] } 74 | ] 75 | }, 76 | "2": { 77 | "startDate": "2018-03-05", 78 | "endDate": "2018-07-22", 79 | "holidays": [ 80 | { "name": "清明节", "date": ["2018-04-05", "2018-04-06", "2018-04-07"] }, 81 | { "name": "劳动节", "date": ["2018-04-29", "2018-04-30", "2018-05-01"] }, 82 | { "name": "端午节", "date": ["2018-06-16", "2018-06-17", "2018-06-18"] } 83 | ] 84 | } 85 | }, 86 | "2018": { 87 | "1": { 88 | "startDate": "2018-09-03", 89 | "endDate": "2019-01-20", 90 | "holidays": [ 91 | { "name": "运动会", "date": ["2018-09-28", "2018-09-29"] }, 92 | { "name": "中秋节", "date": ["2018-09-22", "2018-09-23", "2018-09-24"] }, 93 | { "name": "国庆节", "date": ["2018-10-01", "2018-10-02", "2018-10-03", "2018-10-04", "2018-10-05", "2018-10-06", "2018-10-07"] }, 94 | { "name": "元旦节", "date": ["2018-12-30", "2018-12-31", "2018-01-01"] } 95 | ] 96 | }, 97 | "2": { 98 | "startDate": "2019-02-25", 99 | "endDate": "2019-07-14", 100 | "holidays": [ 101 | { "name": "清明节", "date": ["2019-04-05", "2019-04-06", "2019-04-07"] }, 102 | { "name": "劳动节", "date": ["2019-01-01"] }, 103 | { "name": "端午节", "date": ["2019-06-07", "2019-06-08", "2019-06-09"] } 104 | ] 105 | } 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /app/router.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * @param {Egg.Application} app - egg application 5 | */ 6 | module.exports = app => { 7 | const { router, controller } = app; 8 | const cookiesHandler = app.middleware.cookiesHandler(); 9 | const ssoHandler = app.middleware.ssoHandler(); 10 | router.get('/', controller.home.index); 11 | router.post('/api/home/calendar', controller.home.calendar); 12 | router.post('/api/dev/idas', controller.dev.idas); 13 | router.post('/api/dev/ecard', controller.dev.ecard); 14 | router.post('/api/user/login', controller.user.login); 15 | router.post('/api/user/exit', app.jwt, cookiesHandler, controller.user.exit); 16 | router.post('/api/user/delete', controller.user.delete); 17 | router.get('/api/user/profile', app.jwt, cookiesHandler, ssoHandler, controller.user.profile); 18 | router.post('/api/user/profile', app.jwt, cookiesHandler, ssoHandler, controller.user.setProfile); 19 | router.post('/api/user/course', app.jwt, cookiesHandler, ssoHandler, controller.user.course); 20 | router.post('/api/user/exam', app.jwt, cookiesHandler, ssoHandler, controller.user.exam); 21 | router.post('/api/user/grade', app.jwt, cookiesHandler, ssoHandler, controller.user.grade); 22 | router.get('/api/user/grade', app.jwt, cookiesHandler, ssoHandler, controller.user.allGrade); 23 | router.post('/api/user/usualGrade', app.jwt, cookiesHandler, ssoHandler, controller.user.usualGrade); 24 | router.get('/api/user/gpa', app.jwt, cookiesHandler, ssoHandler, controller.user.gpa); 25 | router.get('/api/living/ecard', app.jwt, cookiesHandler, controller.living.ecard); 26 | router.post('/api/living/loss', app.jwt, cookiesHandler, controller.living.loss); 27 | router.post('/api/living/bill', app.jwt, cookiesHandler, controller.living.bill); 28 | router.post('/api/living/electricity', controller.living.electricity); 29 | router.get('/api/extra/traffic', controller.extra.traffic); 30 | router.get('/api/extra/contact', controller.extra.contact); 31 | router.get('/api/extra/info', controller.extra.info); 32 | router.get('/api/extra/stu', controller.extra.stu); 33 | router.get('/api/extra/edu', controller.extra.edu); 34 | router.get('/api/extra/communication', controller.extra.communication); 35 | router.get('/api/extra/news', controller.extra.news); 36 | router.get('/api/extra/room', controller.extra.room); 37 | router.get('/api/extra/today-course', controller.extra.todayCourse); 38 | router.get('/api/extra/search-course', controller.extra.searchCourse); 39 | router.get('/api/extra/search-teacher', controller.extra.searchTeacher); 40 | }; 41 | -------------------------------------------------------------------------------- /app/service/actionToken.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Service = require('egg').Service; 4 | 5 | class ActionTokenService extends Service { 6 | async apply(username) { 7 | const { ctx } = this; 8 | return ctx.app.jwt.sign({ 9 | data: { username }, 10 | exp: Math.floor(Date.now() / 1000) + (60 * 60 * 24 * 7), 11 | }, ctx.app.config.jwt.secret); 12 | } 13 | } 14 | 15 | module.exports = ActionTokenService; 16 | -------------------------------------------------------------------------------- /app/service/bill.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Service = require('egg').Service; 4 | const request = require('request-promise-native').defaults({ simple: false, resolveWithFullResponse: true }); 5 | const moment = require('moment'); 6 | const billUrl = 'http://ecard.uestc.edu.cn/web/guest/personal?p_p_id=transDtl_WAR_ecardportlet&p_p_lifecycle=0&p_p_state=exclusive&p_p_mode=view&p_p_col_id=column-4&p_p_col_count=1&_transDtl_WAR_ecardportlet_action=dtlmoreview'; 7 | 8 | class billService extends Service { 9 | async parseSpecified(payload, cookies) { 10 | const hash = { 11 | charge: 1, 12 | cost: 2, 13 | electricity: 3, 14 | }; 15 | const option = await this.ctx.helper.options(billUrl, 'POST', cookies, { 16 | _transDtl_WAR_ecardportlet_qdate: payload.day, 17 | _transDtl_WAR_ecardportlet_qtype: hash[payload.type], 18 | }); 19 | 20 | try { 21 | const res = await request(option); 22 | const tradeSumData = await this.ctx.service.parser.parseTradeSum(res.body); 23 | return { payload, cookies, hash, tradeSumData }; 24 | } catch (e) { 25 | return this.ctx.throw(403, '解析账单信息失败'); 26 | } 27 | } 28 | 29 | async traversePage({ payload, cookies, hash, tradeSumData }) { 30 | const page_sum = tradeSumData.page_sum; 31 | let tradeDetailArray = []; 32 | for (let i = 1; i <= page_sum; i++) { 33 | const option = await this.ctx.helper.options(billUrl, 'POST', cookies, { 34 | _transDtl_WAR_ecardportlet_cur: i, 35 | _transDtl_WAR_ecardportlet_delta: 10, 36 | _transDtl_WAR_ecardportlet_qdate: payload.day, 37 | _transDtl_WAR_ecardportlet_qtype: hash[payload.type], 38 | }); 39 | 40 | try { 41 | const res = await request(option); 42 | const data = await this.ctx.service.parser.parseTradeInfo(res.body, payload.type); 43 | tradeDetailArray = tradeDetailArray.concat(data); 44 | } catch (e) { 45 | return this.ctx.throw(403, '解析账单列表失败'); 46 | } 47 | } 48 | if (tradeSumData.total_cost === undefined && tradeSumData.total_charge === undefined) { 49 | tradeSumData.total_cost = 0; 50 | tradeSumData.total_charge = 0; 51 | tradeDetailArray.forEach(tradeDetail => { 52 | if (+tradeDetail.transaction < 0) tradeSumData.total_cost += -tradeDetail.transaction; 53 | if (+tradeDetail.transaction > 0) tradeSumData.total_cost += +tradeDetail.transaction; 54 | }); 55 | } 56 | return { 57 | total_cost: tradeSumData.total_cost, 58 | total_charge: tradeSumData.total_charge, 59 | history: tradeDetailArray.map(detail => { 60 | detail.transaction = detail.transaction > 0 ? `+${detail.transaction}` : `${detail.transaction}`; 61 | return detail; 62 | }), 63 | }; 64 | } 65 | 66 | async parseAll(payload, cookies) { 67 | const obj = {}; 68 | let arr = []; 69 | await Promise.all([ 'charge', 'cost', 'electricity' ].map(async item => { 70 | const info = await this.parseSpecified({ 71 | day: payload.day, 72 | type: item, 73 | }, cookies); 74 | const data = await this.traversePage(info); 75 | arr = arr.concat(data.history); 76 | if (info.tradeSumData.total_cost && info.tradeSumData.total_charge) { 77 | obj.total_cost = data.total_cost; 78 | obj.total_charge = data.total_charge; 79 | } 80 | })); 81 | 82 | if (obj.total_cost === undefined && obj.total_charge === undefined) { 83 | let total_cost = 0; 84 | let total_charge = 0; 85 | arr.forEach(detail => { 86 | if (+detail.transaction < 0) total_cost += -detail.transaction; 87 | if (+detail.transaction > 0) total_charge += +detail.transaction; 88 | }); 89 | obj.total_cost = total_cost; 90 | obj.total_charge = total_charge; 91 | } 92 | 93 | arr.sort((a, b) => (moment(a.time).isBefore(moment(b.time)) ? 1 : -1)); 94 | obj.history = arr; 95 | return obj; 96 | } 97 | 98 | 99 | async query(payload) { 100 | const { ctx } = this; 101 | try { 102 | const cookiesObj = await ctx.service.ecard.cookies(); 103 | const cookies = await ctx.helper.generateCookieString(ctx, undefined, JSON.stringify(cookiesObj)); 104 | if (payload.type !== 'all') { 105 | const data = await this.parseSpecified(payload, cookies); 106 | return await this.traversePage(data); 107 | } 108 | 109 | return await this.parseAll(payload, cookies); 110 | } catch (err) { 111 | return ctx.throw(403, '查询账单信息失败'); 112 | } 113 | } 114 | } 115 | 116 | module.exports = billService; 117 | -------------------------------------------------------------------------------- /app/service/calendar.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * @desc 按学年学期获取校历 5 | * @param year [string] '2017-2018' = '2017' 6 | * @param semester [string] '1' or '2' 7 | * @type {Service} 8 | */ 9 | 10 | const Service = require('egg').Service; 11 | const fs = require('fs'); 12 | 13 | class calendarService extends Service { 14 | async get(payload) { 15 | const { ctx } = this; 16 | const calendarJson = await fs.readFileSync('app/public/calendar.json'); 17 | const calendarData = JSON.parse(calendarJson); 18 | 19 | try { 20 | return calendarData[payload.year][payload.semester]; 21 | } catch (e) { 22 | return ctx.throw(403, '获取校历信息失败'); 23 | } 24 | } 25 | } 26 | 27 | module.exports = calendarService; 28 | -------------------------------------------------------------------------------- /app/service/captcha.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Service = require('egg').Service; 4 | const request = require('request-promise-native').defaults({ simple: false, resolveWithFullResponse: true }); 5 | const tesseract = require('node-tesseract'); 6 | const gm = require('gm'); 7 | const captchaUrl = 'http://idas.uestc.edu.cn/authserver/captcha.html'; 8 | 9 | class CaptchaService extends Service { 10 | /* 11 | * 对图片进行阈值处理(默认55) 12 | */ 13 | async disposeImg(newPath, cookies) { 14 | const option = await this.ctx.helper.options(captchaUrl, 'GET', cookies); 15 | return new Promise((resolve, reject) => { 16 | gm(request(option)) 17 | .threshold(55, '%') 18 | .normalize() 19 | .monochrome() 20 | .despeckle() 21 | .write(newPath, err => { 22 | if (err) return reject(err); 23 | resolve(newPath); 24 | }); 25 | }); 26 | } 27 | 28 | /* 29 | * 识别阈值化后图片内容 30 | */ 31 | async recognizeImg(imgPath, options) { 32 | options = Object.assign({ l: 'eng', psm: 7 }, options); 33 | 34 | return new Promise((resolve, reject) => { 35 | tesseract 36 | .process(imgPath, options, (err, text) => { 37 | if (err) return reject(err); 38 | resolve(text.replace(/[\r\n\s'.‘“”’。\-]/gm, '')); // 去掉识别结果中的换行回车空格 39 | }); 40 | }); 41 | } 42 | 43 | async identify(cookies, username) { 44 | try { 45 | const newImgPath = await this.disposeImg(`/tmp/${username}.jpg`, cookies); 46 | return await this.recognizeImg(newImgPath); 47 | } catch (err) { 48 | await this.ctx.throw(`识别失败:${err}`); 49 | } 50 | } 51 | } 52 | 53 | module.exports = CaptchaService; 54 | -------------------------------------------------------------------------------- /app/service/course.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * @desc 按学年学期获取课程表数据 5 | * @param year [string] '2017-2018' = '2017' 6 | * @param semester [string] '1' or '2' 7 | * @type {Service} 8 | */ 9 | 10 | const Service = require('egg').Service; 11 | const request = require('request-promise-native').defaults({ simple: false, resolveWithFullResponse: true }); 12 | const courseUrl = 'http://eams.uestc.edu.cn/eams/'; 13 | 14 | class courseService extends Service { 15 | 16 | async getIds(finalCookies) { 17 | const option = await this.ctx.helper.options(`${courseUrl}courseTableForStd.action`, 'GET', finalCookies); 18 | try { 19 | const res = await request(option); 20 | return Promise.resolve(res.body.match(/ids.*\)/)[0].match(/\d+/)[0]); 21 | } catch (err) { 22 | return this.ctx.throw(403, '课程数据获取失败'); 23 | } 24 | } 25 | 26 | async getCourseTable(ids, semesterId, finalCookies) { 27 | const { ctx, service } = this; 28 | const option = await ctx.helper.options( 29 | `${courseUrl}courseTableForStd!courseTable.action`, 30 | 'POST', 31 | `${finalCookies};semester.id=${semesterId}`, 32 | { 33 | ignoreHead: 1, 34 | 'setting.kind': 'std', 35 | startWeek: 1, 36 | 'semester.id': semesterId, 37 | ids, 38 | } 39 | ); 40 | try { 41 | const res = await request(option); 42 | return Promise.resolve(service.parser.parseCourseData(res.body)); 43 | } catch (err) { 44 | return ctx.throw(403, '课程数据解析失败'); 45 | } 46 | } 47 | 48 | async getCourse(payload) { 49 | const { ctx, service } = this; 50 | try { 51 | const finalCookies = ctx.helper.generateCookieString(ctx, [ 52 | 'iPlanetDirectoryPro', 53 | 'JSESSIONID', 54 | 'sto-id-20480', 55 | ]); 56 | const ids = await this.getIds(finalCookies); 57 | const semesterId = await service.semester.getSemesterId(payload, finalCookies); 58 | return await this.getCourseTable(ids, semesterId, finalCookies); 59 | } catch (err) { 60 | ctx.throw(err); 61 | } 62 | } 63 | } 64 | 65 | module.exports = courseService; 66 | -------------------------------------------------------------------------------- /app/service/dev.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Service = require('egg').Service; 4 | 5 | class devService extends Service { 6 | async idas(payload) { 7 | const data = await this.ctx.service.idas.login(payload); 8 | return JSON.parse(data.finalCookies); 9 | } 10 | 11 | async ecard(payload) { 12 | const { ctx } = this; 13 | const data = await ctx.service.idas.login(payload); 14 | return await ctx.service.ecard.cookies(data.finalCookies); 15 | } 16 | } 17 | 18 | module.exports = devService; 19 | -------------------------------------------------------------------------------- /app/service/ecard.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Service = require('egg').Service; 4 | const request = require('request-promise-native').defaults({ simple: false, resolveWithFullResponse: true }); 5 | const ecardIndexUrl = 'http://ecard.uestc.edu.cn'; 6 | const unionAuthUrl = 'http://idas.uestc.edu.cn/authserver/login?service=http%3A%2F%2Fecard.uestc.edu.cn%2Fcaslogin.jsp'; 7 | const ecardLoginUrl = 'http://ecard.uestc.edu.cn/c/portal/login'; 8 | const ecardPersonalUrl = 'http://ecard.uestc.edu.cn/c/portal/render_portlet?p_l_id=10570&p_p_id=cardInfo_WAR_ecardportlet&p_p_lifecycle=0&p_t_lifecycle=0&p_p_state=normal&p_p_mode=view&p_p_col_id=null&p_p_col_pos=null&p_p_col_count=null&p_p_isolated=1¤tURL=%2Fweb%2Fguest%2Fpersonal'; 9 | 10 | class ecardService extends Service { 11 | async getCookies() { 12 | const option = await this.ctx.helper.options(ecardIndexUrl, 'GET'); 13 | try { 14 | const res = await request(option); 15 | if (res.headers['set-cookie'].length === 3) { 16 | return res.headers['set-cookie']; 17 | } 18 | return this.ctx.throw(403, '一卡通网站未按预期返回 set-cookie 值'); 19 | } catch (err) { 20 | return this.ctx.throw(403, '访问一卡通网站出现错误'); 21 | } 22 | } 23 | 24 | async getTicketInfo(finalCookies) { 25 | const option = await this.ctx.helper.options(unionAuthUrl, 'GET', finalCookies); 26 | try { 27 | const res = await request(option); 28 | if (res.headers.location.includes('ticket')) { 29 | return { url: res.headers.location, setCookie: res.headers['set-cookie'] }; 30 | } 31 | return this.ctx.throw(403, '统一身份认证系统认证失败,请检查 token 是否过期并尝试重新登录'); 32 | } catch (err) { 33 | return this.ctx.throw(403, '获取统一身份认证系统交换登录凭据失败'); 34 | } 35 | } 36 | 37 | // 一卡通登录需要提前访问这两个域名,否则在后续的 login 过程中无法获取新的 JSESSIONID 38 | async casLogin(ticketInfo, ecardCookies) { 39 | const cookies = `${ecardCookies.join(';')};${ticketInfo.setCookie.join(';')}`; 40 | const options = await this.ctx.helper.options(ticketInfo.url, 'GET', cookies); 41 | try { 42 | const res = await request(options); 43 | const options1 = await this.ctx.helper.options(res.headers.location, 'GET', cookies); 44 | return await request(options1); 45 | } catch (err) { 46 | return this.ctx.throw(403, 'casLogin 失败'); 47 | } 48 | } 49 | 50 | async login(ticketInfo, ecardCookies) { 51 | const cookies = `${ecardCookies.join(';')};${ticketInfo.setCookie.join(';')}`; 52 | const option = await this.ctx.helper.options(ecardLoginUrl, 'GET', cookies); 53 | try { 54 | const res = await request(option); 55 | if (res.headers['set-cookie'][0].includes('JSESSIONID')) { 56 | // 获取到更新后的 JSESSIONID 并加入 ecardCookies; 57 | const parsedEcardCookies = await this.ctx.helper.parseCookies(ecardCookies); 58 | const parsedNewEcardCookies = await this.ctx.helper.parseCookies(res.headers['set-cookie']); 59 | const parsedTicketInfoCookies = await this.ctx.helper.parseCookies(ticketInfo.setCookie); 60 | return Object.assign(parsedEcardCookies, parsedNewEcardCookies, parsedTicketInfoCookies); 61 | } 62 | return this.ctx.throw(403, '一卡通网站登录过程中未按预期更新 cookie'); 63 | } catch (err) { 64 | return this.ctx.throw(403, '登录一卡通网站失败'); 65 | } 66 | } 67 | 68 | async balance() { 69 | const payload = { day: 180, type: 'cost' }; 70 | const billData = await this.ctx.service.bill.query(payload); 71 | if (billData.history[0]) { 72 | return billData.history[0].balance; 73 | } 74 | return '180 天内没有消费,无法计算余额'; 75 | } 76 | 77 | async getPersonalInfo(cookies) { 78 | cookies = await this.ctx.helper.generateCookieString(this.ctx, undefined, JSON.stringify(cookies)); 79 | const option = await this.ctx.helper.options(ecardPersonalUrl, 'POST', cookies); 80 | try { 81 | const res = await request(option); 82 | const data = this.ctx.service.parser.parseECardInfo(res.body); 83 | data.balance = await this.balance(); 84 | return data; 85 | } catch (e) { 86 | return this.ctx.throw(403, '获取一卡通个人信息失败'); 87 | } 88 | } 89 | 90 | async cookies(cookies) { 91 | const { ctx } = this; 92 | try { 93 | const finalCookies = ctx.helper.generateCookieString(ctx, [ 94 | 'CASTGC', 95 | 'route', 96 | 'JSESSIONID', 97 | ], cookies); 98 | const ecardCookies = await this.getCookies(); 99 | const ticketInfo = await this.getTicketInfo(finalCookies); 100 | await this.casLogin(ticketInfo, ecardCookies); 101 | return await this.login(ticketInfo, ecardCookies); 102 | } catch (err) { 103 | return ctx.throw(403, err); 104 | } 105 | } 106 | 107 | async query() { 108 | const { ctx } = this; 109 | try { 110 | const finalCookies = ctx.helper.generateCookieString(ctx, [ 111 | 'CASTGC', 112 | 'route', 113 | 'JSESSIONID', 114 | ]); 115 | const ecardCookies = await this.getCookies(); 116 | const ticketInfo = await this.getTicketInfo(finalCookies); 117 | await this.casLogin(ticketInfo, ecardCookies); 118 | const cookies = await this.login(ticketInfo, ecardCookies); 119 | return await this.getPersonalInfo(cookies); 120 | } catch (err) { 121 | return ctx.throw(403, '查询一卡通信息失败'); 122 | } 123 | } 124 | } 125 | 126 | module.exports = ecardService; 127 | -------------------------------------------------------------------------------- /app/service/electricity.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Service = require('egg').Service; 4 | const request = require('request-promise-native').defaults({ simple: false, resolveWithFullResponse: true }); 5 | const getElectricityUrl = 'http://wx.uestc.edu.cn/oneCartoon/list'; 6 | 7 | class electricityService extends Service { 8 | async getElectricityInfo(roomCode) { 9 | const option = await this.ctx.helper.options( 10 | getElectricityUrl, 11 | 'POST', 12 | null, 13 | { roomCode } 14 | ); 15 | 16 | try { 17 | const res = await request(option); 18 | return JSON.parse(res.body).data; 19 | } catch (e) { 20 | return this.ctx.throw(403, e); 21 | } 22 | } 23 | 24 | async query(payload) { 25 | const { ctx } = this; 26 | try { 27 | return await this.getElectricityInfo(payload.room); 28 | } catch (err) { 29 | ctx.throw(err); 30 | } 31 | } 32 | } 33 | 34 | module.exports = electricityService; 35 | -------------------------------------------------------------------------------- /app/service/exam.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * @desc 按学年学期获取考试数据 5 | * @param year [number] 2017-2018 = 2017 6 | * @param semester [number] 1 or 2 7 | * @type {Service} 8 | */ 9 | 10 | const Service = require('egg').Service; 11 | const request = require('request-promise-native').defaults({ simple: false, resolveWithFullResponse: true }); 12 | const examUrl = 'http://eams.uestc.edu.cn/eams/stdExamTable'; 13 | 14 | class examService extends Service { 15 | 16 | async getSingleExam(finalCookies, semesterId, url) { 17 | const option = await this.ctx.helper.options(url, 'GET', `${finalCookies};semester.id=${semesterId}`); 18 | try { 19 | const res = await request(option); 20 | return Promise.resolve(res.body); 21 | } catch (err) { 22 | return this.ctx.throw(403, '获取学期成绩信息失败'); 23 | } 24 | } 25 | 26 | async getSemesterExamData(finalCookies, semesterId) { 27 | const { service } = this; 28 | const semesterExamData = []; 29 | for (let examType = 1; examType < 5; examType++) { 30 | const url = `${examUrl}!examTable.action?examType.id=${examType}&semester.id=${semesterId}`; 31 | const resText = await this.getSingleExam(finalCookies, semesterId, url); 32 | const examData = await service.parser.parseExamData(resText); 33 | await semesterExamData.push(examData.map(data => { 34 | // 为考试信息添加考试类型字段 35 | return Object.assign(data, { examType }); 36 | })); 37 | } 38 | return semesterExamData; 39 | } 40 | 41 | async getExam(payload) { 42 | const { ctx, service } = this; 43 | try { 44 | const finalCookies = ctx.helper.generateCookieString(ctx, [ 45 | 'iPlanetDirectoryPro', 46 | 'JSESSIONID', 47 | 'sto-id-20480', 48 | ]); 49 | const semesterId = await service.semester.getSemesterId(payload, finalCookies); 50 | return await this.getSemesterExamData(finalCookies, semesterId); 51 | } catch (err) { 52 | ctx.throw(err); 53 | } 54 | } 55 | } 56 | 57 | module.exports = examService; 58 | -------------------------------------------------------------------------------- /app/service/grade.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * @desc 获取成绩数据 5 | * @param year [string] '2017-2018' = '2017' 6 | * @param semester [string] '1' or '2' 7 | * @type {Service} 8 | */ 9 | 10 | const Service = require('egg').Service; 11 | const request = require('request-promise-native').defaults({ simple: false, resolveWithFullResponse: true }); 12 | const _ = require('underscore'); 13 | const gradeUrl = 'http://eams.uestc.edu.cn/eams/teach/grade/course/person'; 14 | const allGradeUrl = 'http://eams.uestc.edu.cn/eams/teach/grade/usual/usual-grade-std!search.action'; 15 | 16 | class gradeService extends Service { 17 | 18 | async getData(gradeOptions) { 19 | try { 20 | const res = await request(gradeOptions); 21 | return Promise.resolve(res.body); 22 | } catch (err) { 23 | return this.ctx.throw(403, '成绩数据获取失败'); 24 | } 25 | } 26 | 27 | async getGrade(payload) { 28 | const { ctx, service } = this; 29 | try { 30 | const finalCookies = ctx.helper.generateCookieString(ctx, [ 31 | 'iPlanetDirectoryPro', 32 | 'JSESSIONID', 33 | 'sto-id-20480', 34 | ]); 35 | const semesterId = await service.semester.getSemesterId(payload, finalCookies); 36 | const gradeOptions = await ctx.helper.options( 37 | `${gradeUrl}!search.action?semesterId=${semesterId}&projectType=`, 38 | 'GET', 39 | `${finalCookies};semester.id=${semesterId}` 40 | ); 41 | const gradeData = await this.getData(gradeOptions); 42 | return await service.parser.parseGradeData(gradeData); 43 | } catch (err) { 44 | ctx.throw(err); 45 | } 46 | } 47 | 48 | async allGrade() { 49 | const { ctx, service } = this; 50 | try { 51 | const finalCookies = ctx.helper.generateCookieString(ctx, [ 52 | 'iPlanetDirectoryPro', 53 | 'JSESSIONID', 54 | 'sto-id-20480', 55 | ]); 56 | const gradeOptions = await ctx.helper.options( 57 | `${gradeUrl}!historyCourseGrade.action?projectType=MAJOR`, 58 | 'GET', 59 | finalCookies 60 | ); 61 | const gradeData = await this.getData(gradeOptions); 62 | return await service.parser.parseGradeData(gradeData).map(item => { 63 | return _.omit(item, 'gpa'); 64 | }); 65 | } catch (err) { 66 | ctx.throw(err); 67 | } 68 | } 69 | 70 | async usualGrade(payload) { 71 | const { ctx, service } = this; 72 | try { 73 | const finalCookies = ctx.helper.generateCookieString(ctx, [ 74 | 'iPlanetDirectoryPro', 75 | 'JSESSIONID', 76 | 'sto-id-20480', 77 | ]); 78 | const semesterId = await service.semester.getSemesterId(payload, finalCookies); 79 | const usualGradeOptions = this.ctx.helper.options( 80 | allGradeUrl, 81 | 'POST', 82 | `semester.id=183;${finalCookies}`, 83 | { 84 | 'semester.id': semesterId, 85 | } 86 | ); 87 | const usualGradeData = await this.getData(usualGradeOptions); 88 | return await service.parser.parseUsualGradeData(usualGradeData); 89 | } catch (err) { 90 | ctx.throw(err); 91 | } 92 | } 93 | 94 | async getGPA() { 95 | const { ctx, service } = this; 96 | try { 97 | const finalCookies = ctx.helper.generateCookieString(ctx, [ 98 | 'iPlanetDirectoryPro', 99 | 'JSESSIONID', 100 | 'sto-id-20480', 101 | ]); 102 | const gradeOptions = await ctx.helper.options( 103 | `${gradeUrl}!historyCourseGrade.action?projectType=MAJOR`, 104 | 'GET', 105 | finalCookies 106 | ); 107 | const gradeData = await this.getData(gradeOptions); 108 | return await service.parser.parseGPAData(gradeData); 109 | } catch (err) { 110 | ctx.throw(err); 111 | } 112 | } 113 | } 114 | 115 | module.exports = gradeService; 116 | -------------------------------------------------------------------------------- /app/service/idas.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * @desc 登录统一身份认证系统,获取 Cookies 5 | * @param username [string] 学号 6 | * @param password [string] 密码 7 | * @type {Service} 8 | */ 9 | 10 | const Service = require('egg').Service; 11 | const _ = require('underscore'); 12 | const request = require('request-promise-native').defaults({ simple: false, resolveWithFullResponse: true }); 13 | const cheerio = require('cheerio'); 14 | const loginUrl = 'http://idas.uestc.edu.cn/authserver/login?service=http://eams.uestc.edu.cn/eams/home.action'; 15 | 16 | class IdasService extends Service { 17 | // 获取登录参数和 Cookie 18 | async getParams() { 19 | try { 20 | const option = await this.ctx.helper.options(loginUrl); 21 | const res = await request(option); 22 | const $ = await cheerio.load(res.body); 23 | // 前端加密密码的 aesKey,一般隐藏在 header 中,但是位置会发生变化,所以直接全局搜索吧 24 | const aesKey = res.body.match(/pwdDefaultEncryptSalt.*/)[0].split('"')[1]; 25 | const names = await $('#casLoginForm > input').map((i, el) => { 26 | return $(el).attr('name'); 27 | }).get(); 28 | 29 | const values = await $('#casLoginForm > input').map((i, el) => { 30 | return $(el).attr('value'); 31 | }).get(); 32 | 33 | const formData = await _.object(names, values); 34 | return { 35 | formData, 36 | cookies: res.headers['set-cookie'], 37 | // 教务系统前端密码加密的 aesKey,必须传入 38 | aesKey, 39 | }; 40 | } catch (err) { 41 | return this.ctx.throw(403, '暂时无法访问统一身份认证系统'); 42 | } 43 | } 44 | 45 | // 获取重定向地址 46 | // async getRedirectUrl(params, payload, captcha) { 47 | async getRedirectUrl(params, payload) { 48 | // 处理验证码 49 | // const option = await this.ctx.helper.options(loginUrl, 'POST', params.Cookies1, _.extend(_.omit(params, 'Cookies1'), payload, captcha, { rememberMe: 'on' })); 50 | // 处理密码,仅在教务系统开启加密时使用 51 | payload.password = this.ctx.helper.encrypt(payload.password, params.aesKey); 52 | const option = await this.ctx.helper.options(loginUrl, 'POST', params.cookies.join(';'), _.extend(params.formData, payload, { rememberMe: 'on' })); 53 | const res = await request(option); 54 | if (res.body.includes('您提供的用户名或者密码有误')) { 55 | return this.ctx.throw(403, '您提供的用户名或者密码有误'); 56 | } 57 | if (res.headers.location === undefined) { 58 | return false; 59 | } 60 | return { 61 | redirectUrl: res.headers.location, 62 | redirectCookies: res.headers['set-cookie'], 63 | }; 64 | } 65 | 66 | async returnCookies(redirectParams, keywords, cookies) { 67 | const option = await this.ctx.helper.options(redirectParams.redirectUrl, 'GET', `semester.id=183;JSESSIONID=00000000000000000;sto-id-20480=J${keywords}KEMFNOECBP;${redirectParams.redirectCookies.join(';')}`); 68 | const res = await request(option); 69 | const cookiesArray = [ 70 | 'semester.id=183', 71 | ].concat(cookies).concat(redirectParams.redirectCookies).concat(res.headers['set-cookie']); 72 | 73 | const finalCookies = await this.ctx.helper.parseCookies(cookiesArray); 74 | return Promise.resolve({ finalCookies: JSON.stringify(finalCookies) }); 75 | } 76 | 77 | // 目标地址 78 | async genCookies(redirectParams, cookies) { 79 | // JGKE or JHKE or JIKE 80 | try { 81 | return this.returnCookies(redirectParams, 'G', cookies); 82 | } catch (err) { 83 | try { 84 | return this.returnCookies(redirectParams, 'H', cookies); 85 | } catch (err) { 86 | try { 87 | return this.returnCookies(redirectParams, 'I', cookies); 88 | } catch (err) { 89 | return this.ctx.throw(403, '统一身份认证系统报告了一个错误'); 90 | } 91 | } 92 | } 93 | } 94 | 95 | // 登录 96 | async login(payload) { 97 | const { ctx } = this; 98 | // 这里是进行验证码错误自动重试 99 | // let success = false; 100 | // let redirectParams = null; 101 | try { 102 | // while (success === false) { 103 | // const params = await this.getParams(); 104 | // const captchaText = await ctx.service.captcha.identify(params.Cookies1, payload.username); 105 | // redirectParams = await this.getRedirectUrl(params, payload, { captchaResponse: captchaText }); 106 | // if (redirectParams) { 107 | // success = true; 108 | // break; 109 | // } 110 | // } 111 | const params = await this.getParams(); 112 | const redirectParams = await this.getRedirectUrl(params, payload); 113 | return await this.genCookies(redirectParams, params.cookies); 114 | } catch (err) { 115 | ctx.throw(err); 116 | } 117 | } 118 | } 119 | 120 | module.exports = IdasService; 121 | -------------------------------------------------------------------------------- /app/service/loss.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * @name loss.js 5 | * @desc 一卡通挂失 6 | */ 7 | 8 | const Service = require('egg').Service; 9 | const request = require('request-promise-native').defaults({ simple: false, resolveWithFullResponse: true }); 10 | const claimUrl = 'http://ecard.uestc.edu.cn/web/guest/personal?p_p_id=cardInfo_WAR_ecardportlet&p_p_lifecycle=2&p_p_state=normal&p_p_mode=view&p_p_resource_id=loseCard&p_p_cacheability=cacheLevelPage&p_p_col_id=column-2&p_p_col_count=1'; 11 | 12 | class lossService extends Service { 13 | async getECardInfo() { 14 | const { ctx } = this; 15 | try { 16 | const finalCookies = ctx.helper.generateCookieString(ctx, [ 17 | 'CASTGC', 18 | 'route', 19 | 'JSESSIONID', 20 | ]); 21 | const ecardCookies = await ctx.service.ecard.getCookies(); 22 | const ticketInfo = await ctx.service.ecard.getTicketInfo(finalCookies); 23 | await ctx.service.ecard.casLogin(ticketInfo, ecardCookies); 24 | const cookies = await ctx.service.ecard.login(ticketInfo, ecardCookies); 25 | const personalInfo = await ctx.service.ecard.getPersonalInfo(cookies); 26 | const cookieString = ctx.helper.generateCookieString(ctx, undefined, JSON.stringify(cookies)); 27 | return { cookies: cookieString, id: personalInfo.id }; 28 | } catch (e) { 29 | return ctx.throw(403, '获取一卡通信息失败'); 30 | } 31 | } 32 | 33 | async claim() { 34 | const { ctx } = this; 35 | try { 36 | const eCardInfo = await this.getECardInfo(); 37 | const option = await ctx.helper.options( 38 | claimUrl, 39 | 'POST', 40 | eCardInfo.cookies, 41 | { _cardInfo_WAR_ecardportlet_cardno: eCardInfo.id } 42 | ); 43 | const res = await request(option); 44 | const data = JSON.parse(res.body); 45 | if (data.retcode === 120) { data.retmsg = '挂失失败,挂失服务没有启动'; } 46 | if (data.retcode === 100 || data.retcode === 110) { data.retmsg = '该卡已经挂失或注销,请到卡务中心或线下圈存机处理'; } 47 | if (data.retcode === 0) { data.retmsg = '挂失成功'; } 48 | return data; 49 | } catch (e) { 50 | return ctx.throw(403, '挂失接口未按预期工作'); 51 | } 52 | } 53 | } 54 | 55 | module.exports = lossService; 56 | -------------------------------------------------------------------------------- /app/service/parser.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Service = require('egg').Service; 4 | const cheerio = require('cheerio'); 5 | const moment = require('moment'); 6 | 7 | class parserService extends Service { 8 | 9 | parseTime(str) { 10 | const res = []; 11 | const matchFullWeek = new RegExp(/1{2,}/g); // 匹配连续周 12 | const matchSingleWeek = new RegExp(/(10){2,}/g); // 匹配奇偶周 13 | const getZeroStr = num => { // 获取 num 个 0 的字符串 14 | return new Array(num).fill(0).join(''); 15 | }; 16 | const matchStr = (pattern, str) => { 17 | // 获取 str 中匹配 pattern 的所有字串 18 | const tmpRes = []; 19 | let tmp = null; 20 | let tmpStr = str; 21 | let cond = true; 22 | while (cond) { 23 | tmp = pattern.exec(tmpStr); 24 | if (tmp) { 25 | tmpRes.push(tmp); 26 | tmpStr = tmpStr.replace(tmp[0], getZeroStr(tmp[0].length)); // 将匹配到的字串位置清零 27 | } else { 28 | cond = false; 29 | } 30 | } 31 | return [ tmpRes, tmpStr ]; 32 | }; 33 | const fullWeek = matchStr(matchFullWeek, str); 34 | const singleWeek = matchStr(matchSingleWeek, fullWeek[1]); 35 | fullWeek[0].forEach(v => { 36 | const endWeek = v.index + v[0].length - 1; 37 | res.push(v.index + '-' + endWeek + '周'); // 处理连续周 38 | }); 39 | singleWeek[0].forEach(v => { 40 | const startWeek = v.index; 41 | const endWeek = v.index + v[0].length - 1; 42 | const attr = startWeek % 2 ? '单' : '双'; 43 | res.push(startWeek + '-' + endWeek + attr + '周'); // 处理奇偶周 44 | }); 45 | res.push(() => { 46 | const tmp = singleWeek[1].split('').map((v, i) => { 47 | return v === '1' ? i : 0; // 得到单周的索引 48 | }).filter(v => { 49 | return v !== 0; // 剔除无效值 50 | }) 51 | .join('/'); 52 | return tmp.length ? tmp + '周' : null; // 加壳处理 53 | }); // 处理单周 54 | 55 | return res.filter(v => { 56 | return isFinite(parseInt(v)); // 剔除无效值 57 | }); 58 | } 59 | 60 | parseCourseData(courseData) { 61 | const pHtml = JSON.stringify(courseData).match(/activity = new TaskActivity.*activity/g); 62 | if (!pHtml) return []; 63 | const tmp = pHtml && pHtml[0].split('activity ='); 64 | const data = []; 65 | tmp.forEach(value => { 66 | if (value.length) { 67 | const tmpTime = value.match(/index =.*?\;/g); 68 | const time = []; 69 | tmpTime.forEach(v => { 70 | time.push(v.match(/\d+/g)); 71 | }); 72 | data.push({ 73 | info: value.match(/TaskActivity\((.*)\)/)[1].replace(/\,/g, '').split('\\\"'), // 每个课程的详细信息, 74 | time, // 每节课的排课时间 75 | }); 76 | } 77 | }); 78 | return data.map(v => { 79 | return { 80 | courseName: v.info[7].split('(')[0], 81 | courseId: v.info[7].split('(')[1].replace(')', ''), 82 | teacher: v.info[3], 83 | room: v.info[11], 84 | time: v.time, 85 | date: this.parseTime(v.info[13]), 86 | }; 87 | }); 88 | } 89 | 90 | parseExamData(resText) { 91 | const $ = cheerio.load(resText.replace(/[\n\r\t]\s+/g, '')); 92 | if ($('.formTable > tbody').children().length === 1) return []; 93 | return $('.formTable > tbody').children().map((i, el) => { 94 | return $(el).children().length === 8 && i > 0 ? { 95 | name: $(el).children().get(1).children[0].data, 96 | date: $(el).children().get(2).children[0].data, 97 | detail: $(el).children().get(3).children[0].data.replace(/\(.*\)/, ''), 98 | address: $(el).children().get(4).children[0].data, 99 | seat: $(el).children().get(5).children[0].data, 100 | status: $(el).children().get(6).children[0].data, 101 | } : $(el).children().length === 7 && i > 0 ? { 102 | // 此处处理考试已经安排时间,但是座位号和考场教室尚未安排的情况 103 | name: $(el).children().get(1).children[0].data, 104 | date: $(el).children().get(2).children[0].data, 105 | detail: $(el).children().get(3).children[0].data.replace(/\(.*\)/, ''), 106 | address: $(el).children().get(4).children[0].children[0].data, 107 | seat: $(el).children().get(4).children[0].children[0].data, 108 | status: $(el).children().get(5).children[0].data, 109 | } : null; 110 | }) 111 | .get(); 112 | } 113 | 114 | parseGradeData(body) { 115 | const $ = cheerio.load(body); 116 | return $('.grid > table > tbody > tr').map((i, element) => { 117 | // 增加从未补考过的用户的总成绩表处理 118 | return element.children.length === 17 || element.children.length === 18 ? { 119 | name: $(element) 120 | .find('td:nth-of-type(4)') 121 | .text() 122 | .trim(), 123 | type: $(element) 124 | .find('td:nth-of-type(5)') 125 | .text() 126 | .trim(), 127 | credit: $(element) 128 | .find('td:nth-of-type(6)') 129 | .text() 130 | .trim(), 131 | overall: $(element) 132 | .find('td:nth-of-type(7)') 133 | .text() 134 | .trim(), 135 | resit: $(element) 136 | .find('td:nth-of-type(8)') 137 | .text() 138 | .trim(), 139 | final: $(element) 140 | .find('td:nth-of-type(9)') 141 | .text() 142 | .trim(), 143 | gpa: $(element) 144 | .find('td:nth-of-type(10)') 145 | .text() 146 | .trim(), 147 | } : { 148 | name: $(element) 149 | .find('td:nth-of-type(4)') 150 | .text() 151 | .trim(), 152 | type: $(element) 153 | .find('td:nth-of-type(5)') 154 | .text() 155 | .trim(), 156 | credit: $(element) 157 | .find('td:nth-of-type(6)') 158 | .text() 159 | .trim(), 160 | overall: $(element) 161 | .find('td:nth-of-type(7)') 162 | .text() 163 | .trim(), 164 | resit: '--', 165 | final: $(element) 166 | .find('td:nth-of-type(8)') 167 | .text() 168 | .trim(), 169 | gpa: $(element) 170 | .find('td:nth-of-type(9)') 171 | .text() 172 | .trim(), 173 | }; 174 | }).get(); 175 | } 176 | 177 | parseUsualGradeData(body) { 178 | const $ = cheerio.load(body); 179 | const tr = $('.grid > table > tbody > tr'); 180 | return tr.length === 1 ? [] : tr.map((i, element) => { 181 | return { 182 | name: $(element) 183 | .find('td:nth-of-type(4)') 184 | .text() 185 | .trim(), 186 | type: $(element) 187 | .find('td:nth-of-type(5)') 188 | .text() 189 | .trim(), 190 | credit: $(element) 191 | .find('td:nth-of-type(6)') 192 | .text() 193 | .trim(), 194 | grade: $(element) 195 | .find('td:nth-of-type(7)') 196 | .text() 197 | .trim(), 198 | }; 199 | }).get(); 200 | } 201 | 202 | parseGPAData(body) { 203 | const $ = cheerio.load(body); 204 | const arr = $('body > .gridtable > tbody > tr').map((i, element) => { 205 | const year = Number($(element) 206 | .find('td:nth-of-type(1)') 207 | .text() 208 | .trim() 209 | .substr(0, 4)); 210 | const semester = Number($(element) 211 | .find('td:nth-of-type(2)') 212 | .text() 213 | .trim()); 214 | 215 | return year === 0 && semester === 0 ? { 216 | year, 217 | semester, 218 | subject: $(element) 219 | .find('th:nth-of-type(2)') 220 | .text() 221 | .trim(), 222 | credit: $(element) 223 | .find('th:nth-of-type(3)') 224 | .text() 225 | .trim(), 226 | gpa: $(element) 227 | .find('th:nth-of-type(4)') 228 | .text() 229 | .trim(), 230 | } : { 231 | year, 232 | semester, 233 | subject: $(element) 234 | .find('td:nth-of-type(3)') 235 | .text() 236 | .trim(), 237 | credit: $(element) 238 | .find('td:nth-of-type(4)') 239 | .text() 240 | .trim(), 241 | gpa: $(element) 242 | .find('td:nth-of-type(5)') 243 | .text() 244 | .trim(), 245 | }; 246 | }).get(); 247 | arr.pop(); // 处理掉最后一行的空数据 248 | // 多条件排序 249 | arr.sort((a, b) => { 250 | if (a.year === b.year) { 251 | return a.semester - b.semester; 252 | } 253 | return a.year - b.year; 254 | }); 255 | return arr; 256 | } 257 | 258 | parseProfile(body) { 259 | const $ = cheerio.load(body); 260 | const tr = $('#studentInfoTb > tbody > tr'); 261 | const obj = {}; 262 | const attrArr = [ 263 | [], 264 | [ 'stuID', 'stuName' ], 265 | [ 'enName', 'gender' ], 266 | [ 'grade', 'plan' ], 267 | [ 'project', 'level' ], 268 | [ 'category', 'department' ], 269 | [ 'profession', 'direction' ], 270 | [ '', '' ], 271 | [ 'enrollDate', 'graduateDate' ], 272 | [ 'manager', 'waysOfLearning' ], 273 | [ 'eduForm', 'status' ], 274 | [ 'registered', 'atSchool' ], 275 | [ 'class', 'campus' ], 276 | ]; 277 | tr.map((i, element) => { 278 | if (i !== 0 && element.children.length !== 1) { 279 | obj[attrArr[i][0]] = $(element).find('td:nth-of-type(2)').text() 280 | .trim(); 281 | obj[attrArr[i][1]] = $(element).find('td:nth-of-type(4)').text() 282 | .trim(); 283 | } 284 | return false; 285 | }).get(); 286 | return obj; 287 | } 288 | 289 | parseECardInfo(body) { 290 | const $ = cheerio.load(body); 291 | const tr = $('.card-info > tbody > tr'); 292 | const obj = {}; 293 | tr.map((i, element) => { 294 | const text = $(element).find('td:nth-of-type(1)').text(); 295 | if (text.includes('卡号')) obj.id = +text.split(':')[1]; 296 | if (text.includes('卡状态')) obj.status = text.split(':')[1]; 297 | if (text.includes('卡余额')) obj.balance = +text.split(':')[1].substring(0, text.split(':')[1].length - 1); 298 | if (text.includes('卡有效期')) obj.expirationTime = text.split(':')[1]; 299 | if (text.includes('充值未领取')) obj.unClaimed = +text.split(':')[1].substring(0, text.split(':')[1].length - 1); 300 | return false; 301 | }).get(); 302 | 303 | const tradeTr = $('.trade_table > tbody > tr'); 304 | 305 | tradeTr.map((i, element) => { 306 | const text = +$(element).find('td:nth-of-type(5)').text(); 307 | obj.balance = text; 308 | return false; 309 | }).get(); 310 | return obj; 311 | } 312 | 313 | parseTradeSum(body) { 314 | const $ = cheerio.load(body); 315 | const data = {}; 316 | 317 | const value = $('#_transDtl_WAR_ecardportlet_pageCount').attr('value'); 318 | data.page_sum = value === undefined ? 1 : +value; 319 | 320 | $('p').map((i, el) => { 321 | const total_cost = +$(el).find('span:nth-of-type(1)').text(); 322 | const total_charge = +$(el).find('span:nth-of-type(2)').text(); 323 | data.total_cost = total_cost; 324 | data.total_charge = total_charge; 325 | return false; 326 | }); 327 | 328 | return data; 329 | } 330 | 331 | parseTradeInfo(body, type) { 332 | const $ = cheerio.load(body); 333 | const history = $('.trade_table > tbody > tr').map((i, el) => { 334 | const date = $(el).find('td:nth-of-type(1)').text(); 335 | const time = $(el).find('td:nth-of-type(2)').text(); 336 | const device = $(el).find('td:nth-of-type(3)').text() === '易支付' ? '电费充值' : $(el).find('td:nth-of-type(3)').text(); 337 | const transaction = type === 'charge' ? +$(el).find('td:nth-of-type(4) > span').text() : type === 'cost' ? -$(el).find('td:nth-of-type(4) > span').text() : +$(el).find('td:nth-of-type(4) > span').text(); 338 | const balance = +$(el).find('td:nth-of-type(5)').text(); 339 | return device !== '电费充值' ? { 340 | time: moment(`${date} ${time}`, 'YYYYMMDD HHmmss').format('YYYY-MM-DD HH:mm:ss'), 341 | device, transaction, balance, 342 | } : { 343 | time: moment(`${date} ${time}`, 'YYYYMMDD HHmmss').format('YYYY-MM-DD HH:mm:ss'), 344 | device, 345 | transaction: balance, 346 | roomId: transaction, 347 | }; 348 | }).get(); 349 | history.shift(); 350 | return history; 351 | } 352 | } 353 | 354 | module.exports = parserService; 355 | -------------------------------------------------------------------------------- /app/service/profile.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Service = require('egg').Service; 4 | const request = require('request-promise-native').defaults({ simple: false, resolveWithFullResponse: true }); 5 | const profileUrl = 'http://eams.uestc.edu.cn/eams/stdDetail.action'; 6 | 7 | class ProfileService extends Service { 8 | async queryProfile() { 9 | const { ctx } = this; 10 | const username = ctx.locals.user.data.username; 11 | const query = ctx.model.User.findOne({ username }); 12 | await query.select('avatarUrl nickName bio'); 13 | const data = await query.exec(); 14 | return { 15 | avatarUrl: data._doc.avatarUrl, 16 | nickName: data._doc.nickName, 17 | bio: data._doc.bio, 18 | }; 19 | } 20 | 21 | async set(payload) { 22 | const { ctx } = this; 23 | const username = ctx.locals.user.data.username; 24 | await this.ctx.model.User.updateOne({ username }, Object.assign(payload, { updatedAt: Date.now() })); 25 | return await this.get(); 26 | } 27 | 28 | async get() { 29 | const { ctx } = this; 30 | const finalCookies = ctx.helper.generateCookieString(ctx, [ 31 | 'iPlanetDirectoryPro', 32 | 'JSESSIONID', 33 | 'sto-id-20480', 34 | ]); 35 | const options = await ctx.helper.options(profileUrl, 'GET', finalCookies); 36 | try { 37 | const res = await request(options); 38 | const profile = await this.queryProfile(); 39 | const parsedProfile = await ctx.service.parser.parseProfile(res.body); 40 | return Object.assign(profile, parsedProfile); 41 | } catch (err) { 42 | ctx.throw(403, '拉取学籍信息失败'); 43 | } 44 | } 45 | } 46 | 47 | module.exports = ProfileService; 48 | -------------------------------------------------------------------------------- /app/service/semester.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * @desc 解析学期代码 5 | * @extends Service.course 6 | * @type {Service} 7 | */ 8 | 9 | const Service = require('egg').Service; 10 | const request = require('request-promise-native').defaults({ simple: false, resolveWithFullResponse: true }); 11 | const courseUrl = 'http://eams.uestc.edu.cn/eams/'; 12 | 13 | class semesterService extends Service { 14 | async getId(payload, finalCookies) { 15 | const option = await this.ctx.helper.options( 16 | `${courseUrl}dataQuery.action`, 17 | 'POST', 18 | `semester.id=183;${finalCookies}`, 19 | { 20 | tagId: 'semesterBar00000000000Semester', 21 | dataType: 'semesterCalendar', 22 | value: 183, // 仅做获取用,可在已有学期 code 范围内随意取值 23 | empty: false, 24 | } 25 | ); 26 | 27 | try { 28 | const res = await request(option); 29 | const Obj = {}; 30 | // 迫不得已,只能用 eval 解析 31 | /* eslint-disable */ 32 | Object.values(eval('(' + res.body + ')').semesters).forEach(item => { 33 | /* eslint-enable */ 34 | // 处理一个学年内只发布了第一个学期课程 semester_id 的情况 35 | item.length === 2 ? Object.assign(Obj, { [item[0].schoolYear.substr(0, 4)]: { [item[0].name]: item[0].id, [item[1].name]: item[1].id } }) : Object.assign(Obj, { [item[0].schoolYear.substr(0, 4)]: { [item[0].name]: item[0].id } }); 36 | }); 37 | return Promise.resolve(Obj[payload.year][payload.semester]); 38 | } catch (err) { 39 | return this.ctx.throw(403, '获取学期信息对应表失败'); 40 | } 41 | } 42 | 43 | async getSemesterId(payload, finalCookies) { 44 | const { ctx } = this; 45 | try { 46 | return await this.getId(payload, finalCookies); 47 | } catch (err) { 48 | ctx.throw(err); 49 | } 50 | } 51 | } 52 | 53 | module.exports = semesterService; 54 | -------------------------------------------------------------------------------- /app/service/user.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const Service = require('egg').Service; 4 | const request = require('request-promise-native').defaults({ simple: false, resolveWithFullResponse: true }); 5 | const exitUrl = 'http://idas.uestc.edu.cn/authserver/logout?service=/authserver/login'; 6 | 7 | class UserService extends Service { 8 | 9 | // 当前用户不存在时, 调用注册 10 | async databaseSignUpUser(payload, finalCookies) { 11 | return await this.ctx.model.User.create({ 12 | username: payload.username, 13 | finalCookies: finalCookies.finalCookies, 14 | createdAt: Date.now(), 15 | updatedAt: Date.now(), 16 | }); 17 | } 18 | 19 | // 用户存在时,更新数据库 Cookies 20 | async databaseUpdateUser(loggedUser, finalCookies) { 21 | return await this.ctx.model.User.updateOne({ username: loggedUser.username }, { updatedAt: Date.now(), finalCookies: finalCookies.finalCookies }); 22 | } 23 | 24 | // 尝试登录教务系统,判断当前用户是否已经存在 25 | async login(payload) { 26 | const { ctx, service } = this; 27 | const finalCookies = await ctx.service.idas.login(payload); 28 | try { 29 | await this.databaseSignUpUser(payload, finalCookies); 30 | return { token: await service.actionToken.apply(payload.username) }; 31 | } catch (err) { 32 | if (err.code === 11000) { 33 | await this.databaseUpdateUser(payload, finalCookies); 34 | return { token: await service.actionToken.apply(payload.username) }; 35 | } 36 | return ctx.throw(err); 37 | } 38 | } 39 | 40 | async exit() { 41 | const { ctx } = this; 42 | const finalCookies = ctx.helper.generateCookieString(ctx, [ 43 | 'iPlanetDirectoryPro', 44 | 'JSESSIONID', 45 | 'sto-id-20480', 46 | ]); 47 | const options = await ctx.helper.options(exitUrl, 'GET', finalCookies); 48 | try { 49 | const res = await request(options); 50 | if (res.statusCode === 200 && res.body.includes('注销成功')) { 51 | return Promise.resolve('已成功退出统一身份认证系统'); 52 | } 53 | } catch (err) { 54 | return ctx.throw(403, '退出教务系统失败'); 55 | } 56 | } 57 | 58 | async delete(payload) { 59 | const { ctx } = this; 60 | try { 61 | const finalCookies = await ctx.service.idas.login(payload); 62 | await this.databaseUpdateUser(payload, finalCookies); 63 | // 稳妥起见,根据 finalCookies 去删除用户 64 | await ctx.model.User.remove({ finalCookies: finalCookies.finalCookies }); 65 | // 根据用户名删除喜付用户 66 | await ctx.model.Xifu.remove({ username: payload.username }); 67 | return `已删除账户 ${payload.username}`; 68 | } catch (err) { 69 | ctx.throw(err); 70 | } 71 | } 72 | } 73 | 74 | module.exports = UserService; 75 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | environment: 2 | matrix: 3 | - nodejs_version: '8' 4 | 5 | install: 6 | - ps: Install-Product node $env:nodejs_version 7 | - npm i npminstall && node_modules\.bin\npminstall 8 | 9 | test_script: 10 | - node --version 11 | - npm --version 12 | - npm run test 13 | 14 | build: off 15 | -------------------------------------------------------------------------------- /config/config.default.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | const moment = require('moment'); 3 | 4 | module.exports = appInfo => { 5 | const config = exports = {}; 6 | 7 | // use for cookie sign key, should change to your own and keep security 8 | config.keys = appInfo.name + process.env.APP_KEY; 9 | 10 | // add your config here 11 | config.middleware = []; 12 | 13 | config.security = { 14 | csrf: { 15 | enable: false, 16 | }, 17 | }; 18 | 19 | config.jwt = { 20 | secret: process.env.JWT_SECRET, 21 | enable: true, // default is false 22 | match: '/jwt', // optional 23 | }; 24 | 25 | config.mongoose = { 26 | url: `mongodb://${process.env.DB_URL ? process.env.DB_URL : '127.0.0.1'}:27017/uestc`, 27 | options: { 28 | autoReconnect: true, 29 | reconnectTries: Number.MAX_VALUE, 30 | bufferMaxEntries: 0, 31 | useNewUrlParser: true, 32 | }, 33 | }; 34 | 35 | config.alinode = { 36 | // 从 `Node.js 性能平台` 获取对应的接入参数 37 | appid: process.env.ALINODE_APPID, 38 | secret: process.env.ALINODE_SECRET, 39 | }; 40 | 41 | config.onerror = { 42 | accepts() { 43 | return 'json'; 44 | }, 45 | 46 | json(err, ctx) { 47 | // 从 error 对象上读出各个属性,设置到响应中 48 | ctx.body = { 49 | code: err.status, 50 | err: err.message, 51 | time: moment.utc().format(), 52 | }; 53 | // 处理 Validation Failed 错误,提供提示 54 | if (err.status === 422) { 55 | ctx.body.detail = err.errors; 56 | } 57 | if (err.status === 401) { 58 | ctx.body.err = err.message.substr(0, err.message.length - 1); 59 | } 60 | ctx.status = 200; 61 | }, 62 | 63 | }; 64 | 65 | 66 | return config; 67 | }; 68 | -------------------------------------------------------------------------------- /config/config.prod.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports = { 4 | alinode: { 5 | // 从 `Node.js 性能平台` 获取对应的接入参数 6 | appid: process.env.ALINODE_APPID, 7 | secret: process.env.ALINODE_SECRET, 8 | }, 9 | }; 10 | -------------------------------------------------------------------------------- /config/config.unittest.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | module.exports = { 4 | user: { 5 | username: process.env.YOUR_STU_NUM, 6 | password: process.env.YOUR_STU_PASS, 7 | year: '2017', 8 | semester: '2', 9 | }, 10 | 11 | living: { 12 | roomId: process.env.YOUR_ROOM_ID, 13 | }, 14 | 15 | alinode: { 16 | // 从 `Node.js 性能平台` 获取对应的接入参数 17 | appid: process.env.ALINODE_APPID, 18 | secret: process.env.ALINODE_SECRET, 19 | }, 20 | }; 21 | -------------------------------------------------------------------------------- /config/plugin.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | // had enabled by egg 4 | // exports.static = true; 5 | 6 | exports.mongoose = { 7 | enable: true, 8 | package: 'egg-mongoose', 9 | }; 10 | 11 | exports.validate = { 12 | enable: true, 13 | package: 'egg-validate', 14 | }; 15 | 16 | exports.jwt = { 17 | enable: true, 18 | package: 'egg-jwt', 19 | }; 20 | 21 | exports.cors = { 22 | enable: true, 23 | package: 'egg-cors', 24 | }; 25 | 26 | exports.alinode = { 27 | enable: true, 28 | package: 'egg-alinode', 29 | }; 30 | -------------------------------------------------------------------------------- /docker-compose.yaml: -------------------------------------------------------------------------------- 1 | version: "3" 2 | 3 | services: 4 | mongo: 5 | image: mongo 6 | container_name: mongodb 7 | restart: always 8 | ports: 9 | - "27017:27017" 10 | networks: 11 | - docker_db_network 12 | volumes: 13 | - ${HOME}/docker/mongo:/data/db 14 | 15 | uestc-api: 16 | image: vizards/uestc-api 17 | container_name: uestc-api 18 | restart: always 19 | ports: 20 | - "7001:7001" 21 | expose: 22 | - "7001" 23 | networks: 24 | - docker_db_network 25 | - docker_front_network 26 | environment: 27 | - APP_KEY=${APP_KEY} 28 | - JWT_SECRET=${JWT_SECRET} 29 | - ALINODE_APPID=${ALINODE_APPID} 30 | - ALINODE_SECRET=${ALINODE_SECRET} 31 | - DB_URL=mongo 32 | - WAIT_HOSTS=mongo:27017 33 | depends_on: 34 | - "mongo" 35 | 36 | networks: 37 | docker_db_network: 38 | docker_front_network: 39 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "uestc-api", 3 | "version": "1.0.0", 4 | "description": "Intergrated REST API for UESTC", 5 | "private": true, 6 | "dependencies": { 7 | "cheerio": "^1.0.0-rc.2", 8 | "crypto-js": "^3.1.9-1", 9 | "egg": "^2.11.0", 10 | "egg-alinode": "^2.0.1", 11 | "egg-cors": "^2.1.0", 12 | "egg-jwt": "^3.1.2", 13 | "egg-mongoose": "^3.1.0", 14 | "egg-scripts": "^2.9.1", 15 | "egg-validate": "^2.0.1", 16 | "gm": "^1.23.1", 17 | "moment": "^2.22.2", 18 | "node-tesseract": "^0.2.7", 19 | "request": "^2.88.0", 20 | "request-promise-native": "^1.0.5", 21 | "underscore": "^1.9.1" 22 | }, 23 | "devDependencies": { 24 | "autod": "^3.0.1", 25 | "autod-egg": "^1.1.0", 26 | "egg-bin": "^4.8.5", 27 | "egg-ci": "^1.8.0", 28 | "egg-mock": "^3.20.0", 29 | "eslint": "^5.5.0", 30 | "eslint-config-egg": "^7.1.0", 31 | "webstorm-disable-index": "^1.2.0" 32 | }, 33 | "engines": { 34 | "node": ">=8.9.0" 35 | }, 36 | "scripts": { 37 | "start": "egg-scripts start", 38 | "stop": "egg-scripts stop", 39 | "dev": "egg-bin dev", 40 | "debug": "egg-bin debug", 41 | "test": "npm run lint -- --fix && npm run test-local", 42 | "test-local": "egg-bin test", 43 | "cov": "egg-bin cov", 44 | "lint": "eslint .", 45 | "ci": "npm run lint && npm run cov", 46 | "autod": "autod" 47 | }, 48 | "ci": { 49 | "version": "8" 50 | }, 51 | "repository": { 52 | "type": "git", 53 | "url": "https://github.com/Vizards/uestc-api" 54 | }, 55 | "author": "Vizards ", 56 | "license": "GPL-3.0" 57 | } 58 | -------------------------------------------------------------------------------- /test/app/controller/dev.test.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { app, assert } = require('egg-mock/bootstrap'); 4 | 5 | describe('test/app/controller/dev.test.js', () => { 6 | it('should get idas cookies', async () => { 7 | const body = { 8 | username: app.config.user.username, 9 | password: app.config.user.password, 10 | }; 11 | 12 | const res = await app.httpRequest() 13 | .post('/api/dev/idas') 14 | .set('Accept', 'application/json') 15 | .send(body) 16 | .expect('Content-Type', /json/) 17 | .expect(200); 18 | assert(res.body.code === 201); 19 | assert(res.body.data.JSESSIONID !== undefined); 20 | }); 21 | 22 | it('should get ecard cookies', async () => { 23 | const body = { 24 | username: app.config.user.username, 25 | password: app.config.user.password, 26 | }; 27 | 28 | const res = await app.httpRequest() 29 | .post('/api/dev/ecard') 30 | .set('Accept', 'application/json') 31 | .send(body) 32 | .expect('Content-Type', /json/) 33 | .expect(200); 34 | assert(res.body.code === 201); 35 | assert(res.body.data.JSESSIONID !== undefined); 36 | }); 37 | }); 38 | -------------------------------------------------------------------------------- /test/app/controller/extra.test.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { app } = require('egg-mock/bootstrap'); 4 | 5 | describe('test/app/controller/extra.test.js', () => { 6 | it('should get traffic info', async () => { 7 | await app.httpRequest() 8 | .get('/api/extra/traffic') 9 | .set('Accept', 'text/html') 10 | .expect(302); 11 | }); 12 | 13 | it('should get department contact info', async () => { 14 | await app.httpRequest() 15 | .get('/api/extra/contact') 16 | .set('Accept', 'text/html') 17 | .expect(302); 18 | }); 19 | 20 | it('should get info', async () => { 21 | await app.httpRequest() 22 | .get('/api/extra/info') 23 | .set('Accept', 'text/html') 24 | .expect(302); 25 | }); 26 | 27 | it('should get student announcement', async () => { 28 | await app.httpRequest() 29 | .get('/api/extra/stu') 30 | .set('Accept', 'text/html') 31 | .expect(302); 32 | }); 33 | 34 | it('should get education announcement', async () => { 35 | await app.httpRequest() 36 | .get('/api/extra/edu') 37 | .set('Accept', 'text/html') 38 | .expect(302); 39 | }); 40 | 41 | it('should get communication announcement', async () => { 42 | await app.httpRequest() 43 | .get('/api/extra/communication') 44 | .set('Accept', 'text/html') 45 | .expect(302); 46 | }); 47 | 48 | it('should get news', async () => { 49 | await app.httpRequest() 50 | .get('/api/extra/news') 51 | .set('Accept', 'text/html') 52 | .expect(302); 53 | }); 54 | 55 | it('should get classroom info', async () => { 56 | await app.httpRequest() 57 | .get('/api/extra/room') 58 | .set('Accept', 'text/html') 59 | .expect(302); 60 | }); 61 | 62 | it('should get today course info', async () => { 63 | await app.httpRequest() 64 | .get('/api/extra/today-course') 65 | .set('Accept', 'text/html') 66 | .expect(302); 67 | }); 68 | 69 | it('should get search-course page', async () => { 70 | await app.httpRequest() 71 | .get('/api/extra/search-course') 72 | .set('Accept', 'text/html') 73 | .expect(302); 74 | }); 75 | 76 | it('should get search-teacher page', async () => { 77 | await app.httpRequest() 78 | .get('/api/extra/search-teacher') 79 | .set('Accept', 'text/html') 80 | .expect(302); 81 | }); 82 | }); 83 | -------------------------------------------------------------------------------- /test/app/controller/home.test.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { app, assert } = require('egg-mock/bootstrap'); 4 | 5 | describe('test/app/controller/home.test.js', () => { 6 | 7 | it('should assert', function* () { 8 | const pkg = require('../../../package.json'); 9 | assert(app.config.keys.startsWith(pkg.name)); 10 | 11 | // const ctx = app.mockContext({}); 12 | // yield ctx.service.xx(); 13 | }); 14 | 15 | it('should get text response', () => { 16 | return app.httpRequest() 17 | .get('/') 18 | .expect(200); 19 | }); 20 | 21 | it('should get json response', async () => { 22 | const res = await app.httpRequest() 23 | .get('/') 24 | .set('Accept', 'application/json') 25 | .expect(200); 26 | assert(res.body.data === 'hi, uestc'); 27 | }); 28 | 29 | it('should get school calendar', async () => { 30 | const body = { 31 | year: app.config.user.year, 32 | semester: app.config.user.semester, 33 | }; 34 | const res = await app.httpRequest() 35 | .post('/api/home/calendar') 36 | .set('Accept', 'application/json') 37 | .send(body) 38 | .expect('Content-Type', /json/) 39 | .expect(200); 40 | assert(res.body.code === 201); 41 | assert(res.body.data.hasOwnProperty('startDate') === true); 42 | assert(res.body.data.hasOwnProperty('endDate') === true); 43 | assert(res.body.data.holidays[0].hasOwnProperty('name') === true); 44 | assert(res.body.data.holidays[0].date.length !== 0); 45 | }); 46 | }); 47 | -------------------------------------------------------------------------------- /test/app/controller/living.test.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { app, assert } = require('egg-mock/bootstrap'); 4 | let token = ''; 5 | 6 | describe('test/app/controller/living.test.js', () => { 7 | it('should login', async () => { 8 | const body = { 9 | username: app.config.user.username, 10 | password: app.config.user.password, 11 | }; 12 | const res = await app.httpRequest() 13 | .post('/api/user/login') 14 | .set('Accept', 'application/json') 15 | .send(body) 16 | .expect('Content-Type', /json/) 17 | .expect(200); 18 | assert(res.body.code === 201); 19 | assert(res.body.data.token.length !== 0); 20 | token = res.body.data.token; 21 | }); 22 | 23 | it('should get ecard info', async () => { 24 | const res = await app.httpRequest() 25 | .get('/api/living/ecard') 26 | .set('Accept', 'application/json') 27 | .set('Authorization', `Bearer ${token}`) 28 | .expect('Content-Type', /json/) 29 | .expect(200); 30 | assert(res.body.code === 200); 31 | assert(res.body.data.id.toString().length === 6); 32 | assert(res.body.data.hasOwnProperty('status') === true); 33 | }); 34 | 35 | it('report the loss of ecard', async () => { 36 | const res = await app.httpRequest() 37 | .post('/api/living/loss') 38 | .set('Accept', 'application/json') 39 | .set('Authorization', `Bearer ${token}`) 40 | .expect('Content-Type', /json/) 41 | .expect(200); 42 | assert(res.body.code === 201); 43 | assert(res.body.data.retcode === 0 || res.body.data.retcode === 100 || res.body.data.retcode === 110 || res.body.data.retcode === 120); 44 | assert(res.body.data.hasOwnProperty('retmsg') === true); 45 | }); 46 | 47 | it('should get specified bill', async () => { 48 | const body = { 49 | day: 180, 50 | type: 'cost', 51 | }; 52 | const res = await app.httpRequest() 53 | .post('/api/living/bill') 54 | .set('Accept', 'application/json') 55 | .set('Authorization', `Bearer ${token}`) 56 | .send(body) 57 | .expect('Content-Type', /json/) 58 | .expect(200); 59 | assert(res.body.code === 201); 60 | assert(res.body.data.hasOwnProperty('total_cost') === true); 61 | assert(res.body.data.hasOwnProperty('total_charge') === true); 62 | }); 63 | 64 | it('should get electricity with room_id', async () => { 65 | const body = { room: app.config.living.roomId }; 66 | const res = await app.httpRequest() 67 | .post('/api/living/electricity') 68 | .set('Accept', 'application/json') 69 | .set('Authorization', `Bearer ${token}`) 70 | .send(body) 71 | .expect('Content-Type', /json/) 72 | .expect(200); 73 | assert(res.body.code === 201); 74 | assert(res.body.data.roomName === app.config.living.roomId); 75 | }); 76 | }); 77 | -------------------------------------------------------------------------------- /test/app/controller/user.test.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | const { app, assert } = require('egg-mock/bootstrap'); 4 | let token = ''; 5 | 6 | describe('test/app/controller/user.test.js', () => { 7 | it('should login', async () => { 8 | const body = { 9 | username: app.config.user.username, 10 | password: app.config.user.password, 11 | }; 12 | const res = await app.httpRequest() 13 | .post('/api/user/login') 14 | .set('Accept', 'application/json') 15 | .send(body) 16 | .expect('Content-Type', /json/) 17 | .expect(200); 18 | assert(res.body.code === 201); 19 | assert(res.body.data.token.length !== 0); 20 | token = res.body.data.token; 21 | }); 22 | 23 | it('should get profile', async () => { 24 | const res = await app.httpRequest() 25 | .get('/api/user/profile') 26 | .set('Accept', 'application/json') 27 | .set('Authorization', `Bearer ${token}`) 28 | .expect('Content-Type', /json/) 29 | .expect(200); 30 | assert(res.body.code === 200); 31 | assert(res.body.data.length !== 0); 32 | assert(res.body.data.stuID === app.config.user.username); 33 | }); 34 | 35 | it('should set profile', async () => { 36 | const body = { 37 | nickName: 'Vizards', 38 | }; 39 | const res = await app.httpRequest() 40 | .post('/api/user/profile') 41 | .set('Accept', 'application/json') 42 | .set('Authorization', `Bearer ${token}`) 43 | .send(body) 44 | .expect('Content-Type', /json/) 45 | .expect(200); 46 | assert(res.body.code === 201); 47 | assert(res.body.data.length !== 0); 48 | assert(res.body.data.stuID === app.config.user.username); 49 | }); 50 | 51 | it('should get course', async () => { 52 | const body = { 53 | year: app.config.user.year, 54 | semester: app.config.user.semester, 55 | }; 56 | const res = await app.httpRequest() 57 | .post('/api/user/course') 58 | .set('Accept', 'application/json') 59 | .set('Authorization', `Bearer ${token}`) 60 | .send(body) 61 | .expect('Content-Type', /json/) 62 | .expect(200); 63 | assert(res.body.code === 201); 64 | assert(res.body.data.length !== 0); 65 | assert(res.body.data[0].hasOwnProperty('courseName') === true); 66 | }); 67 | 68 | it('should get exam', async () => { 69 | const body = { 70 | year: app.config.user.year, 71 | semester: app.config.user.semester, 72 | }; 73 | const res = await app.httpRequest() 74 | .post('/api/user/exam') 75 | .set('Accept', 'application/json') 76 | .set('Authorization', `Bearer ${token}`) 77 | .send(body) 78 | .expect('Content-Type', /json/) 79 | .expect(200); 80 | assert(res.body.code === 201); 81 | assert(res.body.data.length === 4); 82 | assert(res.body.data[0][0].examType === 1); 83 | }); 84 | 85 | it('should get semester grade', async () => { 86 | const body = { 87 | year: app.config.user.year, 88 | semester: app.config.user.semester, 89 | }; 90 | const res = await app.httpRequest() 91 | .post('/api/user/grade') 92 | .set('Accept', 'application/json') 93 | .set('Authorization', `Bearer ${token}`) 94 | .send(body) 95 | .expect('Content-Type', /json/) 96 | .expect(200); 97 | assert(res.body.code === 201); 98 | assert(res.body.data.length !== 0); 99 | assert(res.body.data[0].hasOwnProperty('gpa') === true); 100 | }); 101 | 102 | it('should get semester usual grade', async () => { 103 | const body = { 104 | year: app.config.user.year, 105 | semester: app.config.user.semester, 106 | }; 107 | const res = await app.httpRequest() 108 | .post('/api/user/usualGrade') 109 | .set('Accept', 'application/json') 110 | .set('Authorization', `Bearer ${token}`) 111 | .send(body) 112 | .expect('Content-Type', /json/) 113 | .expect(200); 114 | assert(res.body.code === 201); 115 | assert(res.body.data.length !== 0); 116 | assert(res.body.data[0].hasOwnProperty('grade') === true); 117 | }); 118 | 119 | it('should get all grade', async () => { 120 | const res = await app.httpRequest() 121 | .get('/api/user/grade') 122 | .set('Accept', 'application/json') 123 | .set('Authorization', `Bearer ${token}`) 124 | .expect('Content-Type', /json/) 125 | .expect(200); 126 | assert(res.body.code === 200); 127 | assert(res.body.data.length !== 0); 128 | assert(res.body.data[0].hasOwnProperty('final') === true); 129 | }); 130 | 131 | it('should get GPA', async () => { 132 | const res = await app.httpRequest() 133 | .get('/api/user/gpa') 134 | .set('Accept', 'application/json') 135 | .set('Authorization', `Bearer ${token}`) 136 | .expect('Content-Type', /json/) 137 | .expect(200); 138 | assert(res.body.code === 200); 139 | assert(res.body.data[0].year === 0); 140 | assert(res.body.data[0].semester === 0); 141 | assert(res.body.data[0].hasOwnProperty('gpa') === true); 142 | }); 143 | 144 | it('should exit', async () => { 145 | const res = await app.httpRequest() 146 | .post('/api/user/exit') 147 | .set('Accept', 'application/json') 148 | .set('Authorization', `Bearer ${token}`) 149 | .expect('Content-Type', /json/) 150 | .expect(200); 151 | assert(res.body.code === 201); 152 | assert(res.body.data === '已成功退出统一身份认证系统'); 153 | }); 154 | 155 | }); 156 | --------------------------------------------------------------------------------