├── .gitignore
├── LICENSE
├── README.md
├── lectureDL.py
├── other
├── heads_up_2017-07-29.md
├── initial_differences.md
├── subj_list_screenshot.png
└── todo.md
├── requirements.txt
├── settings.py
├── settings_base.py
├── settings_example.py
└── util.py
/.gitignore:
--------------------------------------------------------------------------------
1 | __pycache__
2 | *.pyc
3 | /myvenv/
4 | .DS_Store
5 | get-pip.py
6 | gui.py
7 | /mysettings/
8 | mysettings.py
9 | notetoselfREADMEPLEASE.txt
10 | chromedriver*
11 | /ChromeDriver
12 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Unimelb Lecture Downloader
2 |
3 | This is a program that allows you to easily download all your lectures for
4 | all your subjects. It does this by piloting the browser and navigating
5 | through the LMS on your behalf.
6 |
7 | ## What it does:
8 | - Logs in to the Unimelb LMS.
9 | - Builds a list of the subjects.
10 | - For each subject, navigates through to the Echocenter (Lecture Capture System).
11 | - Builds a list of the lectures.
12 | - For each lecture, queue up a download. The lectures are downloaded in a separate thread while the main thread continues to collect links by navigating through the LMS.
13 | - Downloads all of the queued downloads to the appropriate folders.
14 |
15 | ## Features
16 | The lecture downloader is able to:
17 |
18 | - ~ Download only some of your subjects.
19 | - ~ Download video or audio copies of the lectures.
20 | - ~ Download specific weeks.
21 | - ~ Download from the current week onwards.
22 | - ~ Choose where to download the lectures to.
23 | - ~ Autogenerate folders for each subject.
24 | - ~ Assign week numbers based on date and appends lecture numbers if there are more than one lecture per week - formatted eg. "LING30001 Week 1 Lecture 02.m4v"
25 | - Find pre-existing folders for each subject (given appropriate naming, pretty much just make sure that your subject folder names have the subject code in them).
26 | - Skip lectures that you've already downloaded.
27 | - Resume downloads that were cancelled partway through.
28 | - Display a progress bar as you download each lecture.
29 | - ~ Read the username and password from the settings file.
30 | - ~ Run in headless mode (where the Chrome window is hidden).
31 | - ~ Run with different settings files with minimal modification, for example if you are both a student and a tutor and you want to download the lectures for both.
32 |
33 | The features with the `~` are configurable through the settings file(s).
34 |
35 | **Note that you do *not* need to use a settings file, you can run the program
36 | without the settings file and it will just fall back to defaults and ask you
37 | for any required information.**
38 |
39 | ## Setup:
40 | lectureDL is written in [Python 3](http://python.org/downloads) and uses [Selenium](http://selenium-python.readthedocs.io), coupled with [ChromeDriver](https://sites.google.com/a/chromium.org/chromedriver/).
41 |
42 | Clone or download the zip of this repo to get started.
43 |
44 | ### Pre-installation steps
45 | - Make sure you have Chrome installed and updated.
46 | - Get the latest Chromedriver for your system from [here.](https://sites.google.com/a/chromium.org/chromedriver/downloads) For some easy instructions:
47 | - Download Chromedriver, unzip it, and drag the contents into this folder. It should just be a single binary file.
48 | - If your download isn't called `chromedriver`, you'll have to go to `setting_base.py` and change the value for `'driver_relative_path'` to the name of your chromedriver download.
49 | - In the future you might need to download a new Chromedriver, so make sure you keep track of which is which (perhaps by renaming it to `chromedriver `, like `chromedriver2.32`).
50 | - Edit the settings, see the **Configuration** section. Or just delete `settings.py` and let it ask you for the information that it needs.
51 | - Make sure your clock is correct. If it's the wrong date, the script will crash.
52 |
53 | **Now before moving on, make sure to modify the settings files (username, password, etc.). If this sounds too hard, just rename `settings.py` (e.g. `mv settings.py settings.py.bak`) and the script will prompt you for the required information as it goes.**
54 |
55 | ### MacOS
56 | Prerequsities:
57 |
58 | - You probably want to have [brew](https://brew.sh) installed.
59 | - Python 3.6 or greater. Install this with brew if possible, though it's also fine to use the installer from [https://www.python.org](https://www.python.org).
60 |
61 | Setup instructions:
62 | ```
63 | python3.6 -m venv myvenv
64 | source myvenv/bin/activate
65 | pip install --upgrade pip
66 | pip install -r requirements.txt
67 | python lectureDL.py # Success!!!
68 | ```
69 |
70 | ### Linux
71 | These steps have been tested on Ubuntu 16.04, adapt accordingly to your system.
72 |
73 | Prerequsities:
74 | - Python 3.6 or greater. Follow the instructions in [this](https://askubuntu.com/questions/865554/how-do-i-install-python-3-6-using-apt-get) Stack Overflow article.
75 |
76 | Setup instructions:
77 | ```
78 | # Install Python 3.6 virtualenv stuff
79 | sudo apt-get install python3.6-venv
80 | # Now just follow the MacOS instructions
81 | ```
82 |
83 | ### Windows 10 with bash (WSL)
84 | - Don't work from the subsystem's filesystem, it doesn't play too nice with Windows explorer or anything. Instead, move into the Windows file system, e.g. `cd /mnt/c/Users//Desktop`.
85 | - Clone or unzip the lectureDL repo here.
86 | - Copy chromedriver into lectureDL (it'll just be on the Desktop) and cd there from bash, e.g. `cd /mnt/c/Users//Desktop/lectureDL`.
87 | - Follow the Linux instructions for installing Python 3.6 (with venv), as well as the MacOS instructions afterwards to set up the venv. Don't run `lectureDL.py` yet though, it won't work.
88 |
89 | Here you have two options:
90 | 1. Change the `'uni_location'` option in `settings_example.py` to the folder that you want. If you aren't using a settings file then this of course won't work.
91 | 2. Create the folder `~/Downloads` or make it a symbolic link to somewhere else, e.g. `cd ~ && ln -s /mnt/c/Users//Downloads Downloads`.
92 |
93 | After this you should **finally** be good to go. Good luck!
94 |
95 | ## How to use
96 | TODO youtube tutorial vid maybe.
97 |
98 | Emphasise that you need to bring the terminal back up to the front. Don't enter the password manually, but do it through the terminal window.
99 |
100 | ## Configuration
101 | You'll notice there are 3 settings files.
102 |
103 | ### `settings_base.py`
104 | This file is for storing settings that you want for all your different downloading
105 | profiles. This is only really relevant if you want to download from different LMS
106 | accounts, for example if you're both a tutor and a student.
107 |
108 | ### `settings_example.py`
109 | This is where settings specific to a particular login go. Besides your username
110 | and password, there are other settings here. All the settings options are commented,
111 | so it should be pretty easy to change them to what you want.
112 |
113 | `settings_example.py` imports the settings from `settings_base.py` first, and
114 | then applies the settings from itself, overwriting the `settings_base.py` settings
115 | if there are clashes. If you only had one login, you could just put all your
116 | settings in this file and do away with `settings_base.py`.
117 |
118 | ### `settings.py`
119 | This is the file that `lectureDL.py` looks for when it starts. If you had two
120 | settings files called `settings_tutoring.py` and `settings_personal.py`, you
121 | could select which one you want to use here by changing the first line to
122 | `from settings_tutoring import *` or `from settings_personal import *` accordingly.
123 |
124 | ## Additional notes
125 |
126 | ### Differences in this fork from original
127 | See the file `other/initial_differences.md`. There have been many more improvements since that markdown file was written.
128 |
129 | ### To do list
130 | ~See the file `other/todo.md`.~ See the Issues tab.
131 |
132 | ### Setup for a new semester
133 | See the file `other/heads_up_2017_07_29.md`.
134 |
135 | ### Improving reliability
136 | Note: I'd recommend hiding subjects that are not active this semester because
137 | the script may try to find lecture recordings for past semesters. These days
138 | this is probably not necessary, but if you're having issues this might help.
139 |
140 | 
141 |
142 | Note: For selecting the weeks, the only thing that is verified as working right
143 | now is the `-` option, like `8-12`. The `,` or `/` may or may not work.
144 |
--------------------------------------------------------------------------------
/lectureDL.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # lectureDL.py by Larry Hudson
3 | # Python script to download all lecture files, either video or audio
4 | # What it does:
5 | # Logs in to Unimelb LMS system
6 | # Builds list of subjects
7 | # For each subject, navigate through to echo system
8 | # Builds list of lectures
9 | # For each lecture, builds filename based on subject number and date and downloads
10 | # Features:
11 | # Assigns week numbers based on date - formatted eg. "LING30001 Week 1 Lecture 2.m4a"
12 | # Support for subjects with single or multiple lectures per week
13 | # Skips if file already exists
14 | # Can download either video files or audio files
15 | # Allows user to choose specific subjects and to only download lectures newer than a specific date
16 | # To do list:
17 | # Allow user to choose download folder
18 | # Replace list system (eg. to_download) with class and attributes?
19 | # Change Week numbering from Week 1 to Week 01 (yeah yeah) - best boy Astrid xox
20 |
21 | # READ ME (Update as of 2017-07-29):
22 | # If you're modifying this in the future, know first off that the code was
23 | # not designed with easy future use, nor abstraction in general, in mind.
24 | # I've made it a bit better but it's still messy. Assuming you've got the
25 | # required directory structure in place (check out the uni_folder variable),
26 | # you'll have to:
27 | # 1. Change the current year and semester if necessary.
28 | # 2. Change the variables representing the start of the semester (such as
29 | # start_week0 and current_date) for this semester.
30 | # 3. Manually download the latest ChromeDriver and change the driver variable
31 | # accordingly.
32 | # 4. Perhaps change settings.py.
33 | # While it might be worth it, I feel like it'd be a fair bit of work to
34 | # refactor this project to be "Good TM", after which you could start adding
35 | # extra features. Like imagine trying to catch a selenium error and closing
36 | # chrome if one is encountered, it'd be like a million try/excepts.
37 | # So yeah, maybe one day. Still it wasn't too hard to get it working again.
38 |
39 | # UPDATE (As of 2017-10-07) - David Stern
40 | # Updates:
41 | # (1) Lecture Class Created & Implemented
42 | # (2) Scrolling Bug Fixed (Long lists of lectures weren't clickable)
43 | # (3) Fixed some constants
44 | # (4) Simplified getSubjectList()
45 | # (5) Require user to re-input choice of subjects, if invalid.
46 | # As a part of this, broke determine_subjects_to_download() down to
47 | # include:
48 | # - getValidUserChoice() Requests input until valid selection obtained
49 | # - getSubjects() Takes the list of subjects, returns only those
50 | # selected by the user.
51 | # (6) Switched to f-strings to improve clarity.
52 | # (7) Created and implemented Subject() Class.
53 | # (8) Other unlisted changes.
54 | #
55 | # TODO:
56 | # Implement Graphical Folder Selection
57 | # Implement full GUI
58 | # Fix Dates (Think of a better way to select dates)
59 | # Save file sizes in a .pickle file
60 | # Shorten Scrolling Function (Line 561 in download_lectures_for_subject())
61 |
62 |
63 | from selenium import webdriver
64 | from selenium.webdriver.chrome.options import Options
65 | from selenium.webdriver.common.keys import Keys
66 | from selenium.common.exceptions import (
67 | NoSuchElementException,
68 | ElementNotVisibleException,
69 | StaleElementReferenceException,
70 | WebDriverException,
71 | )
72 |
73 | import datetime
74 | import functools
75 | import getpass
76 | import os
77 | import os.path
78 | import random
79 | import re
80 | import sys
81 | import time
82 | import urllib
83 |
84 | from collections import defaultdict
85 | from contextlib import suppress
86 | from queue import Queue
87 | from threading import Thread
88 | from util import (
89 | retry_until_result,
90 | show_progress,
91 | StdoutSpace,
92 | )
93 |
94 | # To revert to regular stdout, just comment out this line.
95 | # The file=sys.__stdout__ part in util.show_progress could then also be removed.
96 | sys.stdout = StdoutSpace(sys.stdout)
97 |
98 | # Try to read in a settings file.
99 | try:
100 | from settings import (
101 | settings,
102 | getLectureName,
103 | )
104 | except ImportError as e:
105 | print(f'Couldn\'t import a settings file: {str(e)}')
106 | settings = defaultdict(lambda: None, {
107 | # These are the defaults for when settings isn't defined.
108 | 'uni_location': os.path.join(os.path.expanduser('~'), 'Downloads'),
109 | 'lecture_subfolder_name': 'Lectures',
110 | 'auto_create_subfolders': True,
111 | 'default_auto_create_format': '{code} - {name}',
112 | 'driver_relative_path': 'chromedriver',
113 | })
114 | getLectureName = lambda lec: f'{lec.subjCode} Week {lec.week:02} Lecture {lec.lecOfWeek}'
115 | print('Will download to ' + str(settings['uni_location']))
116 | print('Will automatically create the subject folders.')
117 | print('Default folder and lecture names will be used.')
118 |
119 | # These are partial matches, so the best matches should appear first:
120 | LECTURE_TAB_STRINGS = ["Lecture Recordings", "Lecture Capture", "Lectures",
121 | "lectures", "Lecture capture", "Recordings",
122 | "recordings", "Capture", "capture"]
123 | # These must be exact matches:
124 | INTERMEDIATE_LECTURE_CAPTURE_NAMES = [
125 | 'Lecture Capture', 'Lecture-Capture', 'Lecture Recordings',
126 | ]
127 | LECTURE_FOLDER_NAME = settings['lecture_subfolder_name']
128 | SUBJ_NAMES = settings['subject_names']
129 | FOLDER_ERROR = (" doesn\'t exist.\nWould you like to use the Downloads" +
130 | " folder instead? ")
131 | FOLDER_NAME_ERROR = ("No folder with the code subject_code in its name was",
132 | "found (e.g. 'My COMP10001 folder').\n",
133 | "Either create such a folder manually, or retry with",
134 | "'auto_create_subfolders' setting set to True in the",
135 | "settings file.")
136 |
137 | GET_ECHO = 'Getting past intermediate page / waiting for Echocenter to load...'
138 | NO_DL_FOLDER = 'The downloads folder doesn\'t exist either, shutting down.'
139 |
140 |
141 | class Subject(object):
142 | def __init__(self, code, name, link, num, path=None, downloaded=0):
143 | self.code = code
144 | self.name = name
145 | self.link = link
146 | self.num = num
147 | self.path = path
148 | self.downloaded = downloaded
149 |
150 | def __str__(self):
151 | return f"{self.code} - {self.name}"
152 |
153 |
154 | class Lecture(object):
155 | def __init__(self, link, subjCode, week, lecOfWeek, date, subjName,
156 | recNum, folder, fName=None, fPath=None, dl_status=None):
157 | self.link = link
158 | self.subjCode = subjCode
159 | self.week = week
160 | self.lecOfWeek = lecOfWeek
161 | self.date = date
162 | self.subjName = subjName
163 | self.recNum = recNum
164 | self.folder = folder
165 | self.fName = fName
166 | self.fPath = fPath
167 | self.dl_status = dl_status
168 |
169 | def __str__(self):
170 | strFormat = f"{self.subjCode} {self.subjName} - Week {self.week}"
171 | return strFormat + f" Lecture {self.lecOfWeek}"
172 |
173 |
174 | def check_uni_folder(uni_folder, home_dir):
175 | '''
176 | @param: uni_folder - pathname generated using os.path
177 | '''
178 | if not os.path.exists(uni_folder):
179 | conf = input(f"{uni_folder}{FOLDER_ERROR}")[0].lower()
180 | if conf != 'y':
181 | print('Ok, shutting down.')
182 | sys.exit(1)
183 | uni_folder = os.path.join(home_dir, "Downloads")
184 | if not os.path.exists(uni_folder):
185 | print(NO_DL_FOLDER, file=sys.stderr)
186 | sys.exit(1)
187 | return uni_folder
188 |
189 |
190 | def getSubjectFolder(subject_code, uni_folder):
191 | ''' Enables any subject_code in which the subject code is included to be
192 | identified as the appropriate folder for the subject.
193 | '''
194 | print(f"Retrieving folder with name that includes: {subject_code}")
195 |
196 | # Using the subject code to find the appropriate folder.
197 | for fold in os.listdir(uni_folder):
198 | if subject_code.lower() in fold.lower():
199 | subjectFolder = fold
200 | break
201 | try:
202 | return subjectFolder
203 |
204 | # If a folder with the subject code in the name wasn't found
205 | except NameError as e:
206 |
207 | # If the user wants to automatically create the folders, do so.
208 | if settings['auto_create_subfolders']:
209 | subjectFolder = settings['default_auto_create_format'].format(
210 | code=subject.code, name=subject.name)
211 | os.mkdir(os.path.join(uni_folder, subjectFolder))
212 | print('Made folder: ' + subjectFolder)
213 |
214 | # Print an error.
215 | else:
216 | print(FOLDER_NAME_ERROR, file=sys.stderr)
217 | sys.exit(1)
218 |
219 |
220 | # define function to find a link and return the one it finds
221 | # works by making a list of the elements and sorts by descending list length,
222 | # so it returns the one with length 1, avoiding the empty lists.
223 | # if it can't find anything, it will return none
224 | def search_link_text(browser, query_terms):
225 | link_elements = []
226 | for term in query_terms:
227 | link_elements.append(browser.find_elements_by_partial_link_text(term))
228 | sorted_links = sorted(link_elements, key=len, reverse=True)
229 | sorted_links_flat = []
230 | for i in sorted_links:
231 | for j in i:
232 | sorted_links_flat.append(j)
233 | return sorted_links_flat[0]
234 |
235 |
236 | # Determine download mode.
237 | def get_download_mode():
238 | valid_options = {'a': 'audio', 'v': 'video'}
239 | # Using the media_type specified in settings it was set.
240 | if settings['media_type']:
241 | return settings['media_type']
242 | valid = False
243 | while not valid:
244 | valid = True
245 | print("Enter 'v' to download videos or 'a' to download audio.")
246 | user_choice = input("> ")[0].lower()
247 | if user_choice in valid_options:
248 | return valid_options[user_choice]
249 | else:
250 | print('That wasn\'t an option.')
251 | valid = False
252 |
253 |
254 | # MUCH simpler selection of weeks.
255 | # def select_lectures()
256 |
257 |
258 | # if user enters comma-separated weeks, make a list for each and then
259 | # concatenate
260 | def get_weeks_to_download(current_year, week_day):
261 | # TODO break up this god awful huge function.
262 | # build week number dictionary
263 | current_date = datetime.datetime(current_year, 7, 24)
264 | today = datetime.datetime.today()
265 | today_midnight = datetime.datetime(today.year, today.month, today.day)
266 | # This is O-Week, so the start of week 1 should be 7 days after this.
267 | start_week0 = datetime.datetime(current_year, 7, 17)
268 | end_week0 = datetime.datetime(current_year, 7, 23)
269 | day_delta = datetime.timedelta(days=1)
270 | week_delta = datetime.timedelta(days=7)
271 | weeks_in_semester = 12
272 | week_counter = 1
273 | day_counter = 1
274 | midsemBreakWeek = 9 # Mid sem break occurs after this week.
275 |
276 | # assigns a week number to each date.
277 | while week_counter <= weeks_in_semester:
278 | while day_counter <= 7:
279 | week_day[current_date] = week_counter
280 | day_counter += 1
281 | current_date = current_date + day_delta
282 | week_counter += 1
283 | # If we enter the week of the midsem break, skip a week.
284 | if week_counter == midsemBreakWeek + 1:
285 | current_date = current_date + week_delta
286 | day_counter = 1
287 |
288 | current_week_no_offset = (datetime.datetime.today() - start_week0).days // 7
289 | midsem_offset = (current_week_no_offset+1) // midsemBreakWeek
290 | current_week = current_week_no_offset - midsem_offset
291 | if current_week > weeks_in_semester:
292 | current_week = weeks_in_semester
293 |
294 | # The user input stage.
295 | user_dates_input = "default"
296 | print("Would you like to download lectures from specific weeks or since a particular date?")
297 | while user_dates_input == "default":
298 |
299 | # Automatically set the week range if specified in the settings.
300 | if settings['update_lower_week']:
301 | settings['date_range'] = f"{current_week}-{weeks_in_semester}"
302 |
303 | # Read in the date range if none was given in the settings.
304 | if settings['date_range'] is None:
305 | print("Enter a range of weeks (eg. 1-5 or 1,3,4) or a date (DD/MM/2016) to download videos that have since been released.")
306 | user_dates_input = input("> ")
307 | else:
308 | if len(settings['date_range']) > 0:
309 | print("Using", settings['date_range'])
310 | else:
311 | print("Downloading lectures from every week.")
312 | settings['date_range'] = '1-{weeks_in_semester}' # TODO This is a hack.
313 | user_dates_input = settings['date_range']
314 | dates_list = []
315 |
316 | # if user enters comma-separated weeks, or just one, make a list for each and then concatenate
317 | if "," in user_dates_input or user_dates_input.isdigit():
318 | # TODO I think this might be a bit broken with the midsem thing.
319 | # This whole part needs to be reworked anyway.
320 | print("Lectures will be downloaded for: ")
321 | chosen_weeks = user_dates_input.replace(" ", "").split(",")
322 | for item in chosen_weeks:
323 | start_date = start_week0 + (int(item) * week_delta)
324 | end_date = end_week0 + (int(item) * week_delta)
325 | dates_in_week = [start_date + datetime.timedelta(n) for n in range(int((end_date - start_date).days))]
326 | dates_list += dates_in_week
327 | print("Week ", item)
328 | dates_list.append(today_midnight)
329 |
330 | # create a table of dates between start date and end date
331 | elif "-" in user_dates_input or "/" in user_dates_input:
332 |
333 | if "-" in user_dates_input:
334 | # splits the start and the end weeks
335 | chosen_weeks = user_dates_input.split("-")
336 | start_week = int(chosen_weeks[0])
337 | if start_week > midsemBreakWeek:
338 | start_week += 1
339 | start_date = start_week0 + (start_week * week_delta)
340 | end_week = int(chosen_weeks[1])
341 | if end_week > midsemBreakWeek:
342 | end_week += 1
343 | end_date = end_week0 + (end_week * week_delta)
344 |
345 | # create a range between start_date and today
346 | elif "/" in user_dates_input:
347 |
348 | start_date = datetime.datetime.strptime(user_dates_input, "%d/%m/%Y")
349 | end_date = datetime.datetime.today()
350 | # ???
351 | dates_list = [start_date + datetime.timedelta(n) for n in range((end_date - start_date).days)]
352 | dates_list.append(today_midnight)
353 | print("Lectures will be downloaded for the dates between " + datetime.datetime.strftime(start_date, "%d %B")
354 | + " and " + datetime.datetime.strftime(end_date, "%d %B") + ", inclusive.")
355 | # Go back to top of while loop.
356 | else:
357 | print("That wasn't a valid option")
358 | user_dates_input = "default"
359 | return dates_list
360 |
361 |
362 | def sign_in(driver):
363 | user_field = driver.find_element_by_css_selector("input[name=user_id]")
364 | if settings['username'] is None:
365 | settings['username'] = input("Enter your username: ")
366 | user_field.send_keys(settings['username'])
367 | pass_field = driver.find_element_by_css_selector("input[name=password]")
368 | if settings['password'] is None:
369 | settings['password'] = getpass.getpass("Enter your password: ")
370 | pass_field.send_keys(settings['password'])
371 | print()
372 | pass_field.send_keys(Keys.RETURN)
373 |
374 |
375 | # TODO think of a better way to select the lecture stuff and not the community stuff on the right.
376 | @retry_until_result('Waiting for course list to load...')
377 | def get_course_links(driver):
378 | # NOTE: Because of the decorator, use this function as if it were a regular
379 | # function that returns, not yields.
380 | course_links = None
381 | try:
382 | # list items in list class "courseListing"
383 | course_list_candidates = driver.find_elements_by_css_selector("ul.courseListing")
384 | course_list = None
385 | # Sometimes there is an invisible dummy subject list that of course
386 | # lists no subjects. If the style property 'display' is 'none', we
387 | # know it is the invisble one and we ignore it.
388 | for c in course_list_candidates:
389 | if c.value_of_css_property('display') == 'none':
390 | continue
391 | course_list = c
392 | if course_list is None:
393 | yield None
394 | continue
395 | # only get links with target="_top" to single out subject headings
396 | course_links = course_list.find_elements_by_css_selector('a[target=_top]')
397 | if course_links == []:
398 | yield None
399 | continue
400 | # list to be appended with [subj_code, subj_name, subj_link]
401 | yield course_links
402 | yield None
403 | except NoSuchElementException:
404 | # This section must not have loaded yet.
405 | yield None
406 |
407 |
408 | def getSubjectList(course_links):
409 | '''Takes the links found on the LMS page belonging to subjects,
410 | Returns the subject list (with all the information for each)
411 | '''
412 | subject_list = []
413 | for subj_num, link in enumerate(course_links):
414 | # Turn link text into usable information.
415 | # E.g. 'POLS20025_2017_SM2: International Relations: Key Questions'
416 | try:
417 | subj_code, _, _, subj_name = re.split(r"[_:]", link.text, 3)
418 | except ValueError:
419 | raise RuntimeError('Wrong box, communities probably')
420 | subj_name = subj_name.lstrip()
421 | subj_link = link.get_attribute("href")
422 |
423 | subject_list.append(Subject(subj_code, subj_name, subj_link,
424 | subj_num+1))
425 |
426 | # They loaded! Don't recurse, return the list instead :)
427 | return subject_list
428 |
429 |
430 | def getValidUserChoice(max_subject_number):
431 | ''' Returns a list of ints, corresponding to the subject numbers
432 | that the user wants to download.
433 | '''
434 | # This will be None if not specified in the settings.
435 | user_choice = settings['subject_choices']
436 | while True:
437 | # Either get the user's choice.
438 | if user_choice is None:
439 | print("Please enter subjects you would like to download",
440 | "(e.g. 1,2,3) or leave blank to download all.")
441 | user_choice = input("> ")
442 | # Or use pre-loaded subject choices.
443 | else:
444 | print(f"Using preloaded setting: {user_choice}")
445 | user_choice = settings['subject_choices']
446 | # If user_choice is empty, they just want all the subjects.
447 | if user_choice == '':
448 | print("User choice valid!")
449 | return list(range(1, max_subject_number+1))
450 | # The user has specified specific subjects, validate the input.
451 | # Despite the earlier message, we allow commas or spaces. If the input
452 | # is invalid we don't return and just go back around the loop.
453 | with suppress(ValueError):
454 | user_choice = user_choice.replace(',', ' ').split()
455 | out = [int(x) for x in user_choice]
456 | # Make sure that the selections are in the valid range.
457 | if not [x for x in out if x < 1 or x > max_subject_number]:
458 | return out
459 | # The user choice was invalid, go back around the loop.
460 | print('That was invalid, try again!')
461 | user_choice = None
462 |
463 |
464 | def getSubjects(subject_list):
465 | '''
466 | Takes a list of subjects, retrieves a valid selection of subjects from
467 | the user, and returns just those subjects selected.
468 | '''
469 | # Get the user's choices, as a list of ints.
470 | max_subject_number = max([subj.num for subj in subject_list])
471 | user_choice = getValidUserChoice(max_subject_number)
472 | return [subj for subj in subject_list if subj.num in user_choice]
473 |
474 |
475 |
476 | def determine_subjects_to_download(subject_list):
477 | '''
478 | Prints candidate subjects for download, before clarifying which subjects
479 | the user chooses to download.
480 | '''
481 | print("Subject list:")
482 | for subject in subject_list:
483 | print(f"{subject.num}. {subject.code}: {subject.name}")
484 | return getSubjects(subject_list)
485 |
486 |
487 | def download_lecture(dl_link, output_name, pretty_name, sizeLocal):
488 | partial = bool(sizeLocal)
489 | req = urllib.request.Request(dl_link)
490 | if not partial:
491 | # Full download.
492 | mode = 'wb'
493 | else:
494 | # Resuming a partially completed download.
495 | req.headers['Range'] = 'bytes=%s-' % sizeLocal
496 | mode = 'ab'
497 | f = urllib.request.urlopen(req)
498 | # We do + sizeLocal because if we are doing a partial download, the length
499 | # is only for what we requested to download, not the whole thing.
500 | sizeWeb = int(f.headers["Content-Length"]) + sizeLocal
501 |
502 | if not partial:
503 | print(f"Downloading {pretty_name} to {output_name}.")
504 | else:
505 | print(f"Resuming partial download of {pretty_name} ({sizeLocal/1000:0.1f}/{sizeWeb/1000:0.1f}).")
506 |
507 | # The ab is the append write mode.
508 | with open(output_name, mode) as output:
509 | for chunk in show_progress(f, pretty_name, sizeLocal, sizeWeb):
510 | # Process the chunk
511 | output.write(chunk)
512 | f.close()
513 |
514 |
515 | def getToRecordingsFirstPage(driver):
516 | recs_first_page = search_link_text(driver, LECTURE_TAB_STRINGS)
517 | if recs_first_page:
518 | with suppress(WebDriverException):
519 | recs_first_page.click()
520 | return
521 | # Try to move down the page (only once).
522 | actions = webdriver.ActionChains(driver)
523 | actions.send_keys(Keys.SPACE)
524 | actions.perform()
525 | recs_first_page = search_link_text(driver, LECTURE_TAB_STRINGS)
526 | recs_first_page.click()
527 |
528 |
529 | # @retry_until_result('Waiting for the echocenter to load... ')
530 | def getLectureList(driver):
531 | try:
532 | with suppress(Exception):
533 | iframe = driver.find_elements_by_tag_name('iframe')[1]
534 | driver.switch_to_frame(iframe)
535 | iframe = driver.find_elements_by_tag_name('iframe')[0]
536 | driver.switch_to_frame(iframe)
537 | iframe = driver.find_elements_by_tag_name('iframe')[0]
538 | driver.switch_to_frame(iframe)
539 | recs_ul = driver.find_element_by_css_selector("ul#echoes-list")
540 | recs_list = recs_ul.find_elements_by_css_selector("li.li-echoes")
541 | except NoSuchElementException:
542 | return None
543 | return (recs_ul, recs_list)
544 |
545 |
546 | def getPastIntermediateRecordingsPage(driver):
547 | # Try to get past an intermediate page if there is one.
548 | for i in INTERMEDIATE_LECTURE_CAPTURE_NAMES:
549 | with suppress(IndexError, StaleElementReferenceException):
550 | # You'd be surprised at how effective this is, it can break some
551 | # pretty nasty loops that happen because of same-name links.
552 | # The only potentialy problem is the chance of timing out after
553 | # a string of bad / unlucky choices.
554 | # TODO: There is probably a better way to do this with generators
555 | # or static vars or something.
556 | w = random.choice(driver.find_elements_by_link_text(i))
557 | w.click()
558 |
559 |
560 | # TODO This max_retries should be specifiable by the settings.
561 | @retry_until_result(GET_ECHO, max_retries=40)
562 | def getToEchoCenter(driver):
563 | getPastIntermediateRecordingsPage(driver)
564 | return getLectureList(driver)
565 |
566 |
567 | def assign_filepaths(lectures, download_mode, uni_folder):
568 | '''Assign filepaths (and therefore also file names) to lectures.
569 |
570 | Args:
571 | lectures (list): List of lecture objects
572 | download_mode (str): A string specifying audio ('audio') or video
573 | ('video') downloads.
574 |
575 | Returns:
576 | lectures (list): The list of lecture objects, with filepaths added.
577 | '''
578 | # Get the filepaths and file names
579 | for lec in lectures:
580 | filename = getLectureName(lec)
581 |
582 | # Adjust name for audio files
583 | if download_mode == 'audio':
584 | filename_with_ext = filename + '.mp3'
585 | else:
586 | filename_with_ext = filename + '.m4v'
587 | file_path = os.path.join(uni_folder, lec.folder, LECTURE_FOLDER_NAME,
588 | filename_with_ext)
589 |
590 | # Create the directory if it doesn't already exist.
591 | if not os.path.isdir(os.path.join(uni_folder, lec.folder,
592 | LECTURE_FOLDER_NAME)):
593 | print(f'Making {LECTURE_FOLDER_NAME} folder for {lec.folder}')
594 | os.makedirs(os.path.join(folder, lec.folder,
595 | LECTURE_FOLDER_NAME))
596 | lec.fName = filename
597 | lec.fPath = file_path
598 |
599 | return lectures
600 |
601 |
602 | def download_lectures_for_subject(driver, subject, current_year, week_day,
603 | dates_list, download_mode, uni_folder, q):
604 | downloaded = []
605 | skipped = []
606 | print(f"\nNow working on {subject.code}: {subject.name}")
607 |
608 | # Go to subject page and find Lecture Recordings page.
609 | driver.get(subject.link)
610 | main_window = driver.current_window_handle
611 |
612 | # Get to the list of lectures.
613 | getToRecordingsFirstPage(driver)
614 | try:
615 | recs_ul, recs_list = getToEchoCenter(driver)
616 | except RuntimeError:
617 | # TODO Make this error catching more specific.
618 | print(f'NOTE! The echocenter could not be found for {subject.name}! Moving on...')
619 | return None
620 |
621 | # setup for recordings
622 | multiple_lectures = False
623 | lectures_list = []
624 | to_download = []
625 |
626 | # Getting the subject folder in which to put the lecture.
627 | subjectFolder = getSubjectFolder(subject.code, uni_folder)
628 |
629 | # print status
630 | print("Building list of lectures...")
631 | # for each li element, build up filename info and add to download list
632 | for rec_num, recording in enumerate(recs_list):
633 | # click on each recording to get different download links
634 | date_div = recording.find_element_by_css_selector("div.echo-date")
635 |
636 | # Deals with error where the next element can't be selected if it isn't
637 | # literally visible. Limitation of selenium. Scrolls down to adjust.
638 | while True:
639 | try:
640 | # Prevent header from hiding list
641 | driver.execute_script(f"arguments[0].focus();", recs_ul)
642 | driver.execute_script(f"window.scrollTo(0, 15);")
643 | recording.click()
644 | break
645 | # Scroll down to element
646 | except ElementNotVisibleException:
647 | actions = webdriver.ActionChains(driver)
648 | actions.move_to_element(recording)
649 | actions.click()
650 | actions.perform()
651 |
652 | # convert string into datetime.datetime object
653 | # date is formatted like "August 02 3:20 PM" but I want "August 02 2016"
654 | # so I need to get rid of time and add year
655 | date_string = " ".join(date_div.text.split(" ")[:-2]) + f" {current_year}"
656 | try:
657 | date = datetime.datetime.strptime(date_string, "%d %B %Y")
658 | except ValueError:
659 | # Sometimes the date is presented in different format.
660 | date = datetime.datetime.strptime(date_string, "%B %d %Y")
661 |
662 | # Checking if we can terminate early.
663 | if date < dates_list[0]:
664 | print("The lectures further down are outside the date range, no need to check them.")
665 | break
666 |
667 | # lookup week number and set default lecture number
668 | try:
669 | week_num = week_day[date]
670 | except KeyError:
671 | print('NOTE! Ignoring lecture with date ' + str(date) + ' because\n'
672 | ' it is outside of the standard semester week range,\n'
673 | ' you\'ll have to download it manually :/')
674 | continue
675 | lec_num = 1
676 |
677 | # get link to initial download page for either audio or video
678 | while True:
679 | try:
680 | if download_mode == "audio":
681 | first_link = driver.find_element_by_partial_link_text("Audio File").get_attribute("href")
682 | else:
683 | first_link = driver.find_element_by_partial_link_text("Video File").get_attribute("href")
684 | break
685 | except NoSuchElementException:
686 | time.sleep(0.5)
687 |
688 | # check if week_num is already in to_download
689 | for lecture in lectures_list:
690 | if lecture.week == week_num:
691 | # set multiple_lectures to true so filenames include lec nums
692 | multiple_lectures = True
693 | # add 1 to lec_num of earlier video
694 | lecture.lecOfWeek += 1
695 |
696 | # Create Lecture
697 | lectures_list.append(Lecture(first_link, subject.code, week_num,
698 | lec_num, date, subject.name,
699 | len(recs_list) - rec_num, subjectFolder))
700 |
701 | # assign filepaths, filenames
702 | lectures_list = assign_filepaths(lectures_list, download_mode, uni_folder)
703 |
704 | # DOWNLOADING STARTS HERE
705 |
706 | # TODO - This is going into each link even if we don't need the lecture.
707 | # This slows the program down massively.
708 | # Perhaps filter out those with invalid dates & non-existent files?
709 | # A part of this is caused by having to check file sizes every
710 | # single time. Get the file sizes once, save into a document, so we
711 | # don't have to do this every time.
712 | # only add lectures to be downloaded if they are inside date range. else,
713 | # skip them
714 | for lec in lectures_list:
715 |
716 | # Append to download list if the file in date range and doesn't exist yet.
717 | if lec.date in dates_list and not os.path.isfile(lec.fPath):
718 | print(f"Will download {lec.fName}")
719 | to_download.append((lec, False)) # False means not downloaded at all.
720 |
721 | # If the file is in the range but does exist, check that the file is completely
722 | # downloaded. If not, we will add it to the download list and overwrite the
723 | # local incomplete version.
724 |
725 | # DAVETODO: SAVE FILE SIZES AND COMPLETED DOWNLOADS IN PICKLE FILE
726 | # DAVETODO: CREATE SETTING 're-download' WHICH MAKES THE PROGRAM CHECK
727 | # WHETHER OR NOT OLD FILES STILL EXIST, AND REDOWNLOAD IF
728 | # NECESSARY.
729 |
730 | elif lec.date in dates_list and os.path.isfile(lec.fPath):
731 | while True:
732 | try:
733 | driver.get(lec.link)
734 | dl_link = driver.find_element_by_partial_link_text("Download media file.").get_attribute("href")
735 | # send javascript to stop download redirect
736 | driver.execute_script('stopCounting=true')
737 | break
738 | except:
739 | time.sleep(0.5)
740 | # Check size of file on server. If the server version is larger than the local version,
741 | # we notify the user of an incomplete file (perhaps the connection dropped or the user
742 | # cancelled the download). We tell them we're going to download it again.
743 | # Using wget we could resume the download, but python urllib doesn't have such functionality.
744 | try:
745 | # TODO: This whole thing is weird, we shouldn't have to open the
746 | # web link twice. This should all probably be handled in the
747 | # download function, or at least more elegantly than this.
748 | f = urllib.request.urlopen(dl_link)
749 | # This is the size of the file on the server in bytes.
750 | sizeWeb = int(f.headers["Content-Length"])
751 | except:
752 | # Catching the situation where the server doesn't advertise the file length.
753 | sizeWeb = 0
754 |
755 | # Get size of file on disk.
756 | statinfo = os.stat(lec.fPath)
757 | sizeLocal = statinfo.st_size
758 |
759 | # Add to download list with note that it was incomplete.
760 | # TODO Unify the two bits of code to do with downloading / progress.
761 | # BUG: Fully downloaded lectures are re-downloading?
762 | if sizeWeb > sizeLocal:
763 | lec.dl_status = "Incomplete file (%0.1f/%0.1f MiB)." % (
764 | sizeLocal / 1024 / 1024,
765 | sizeWeb / 1024 / 1024,
766 | )
767 | # Include (sizeLocal, sizeWeb) if partially downloaded.
768 | to_download.append((lec, (sizeLocal, sizeWeb)))
769 | print("Resuming " + lec.fName + ": " + lec.dl_status)
770 | # Otherwise the file must be fully downloaded.
771 | else:
772 | lec.dl_status = "File already exists on disk (fully downloaded)."
773 | skipped.append(lec)
774 | print("Skipping " + lec.fName + ": " + lec.dl_status)
775 |
776 | # Dealing with other cases.
777 | else:
778 | # if both outside date range and already exists
779 | if not lec.date in dates_list and os.path.isfile(lec.fPath):
780 | lec.dl_status = "Outside date range and file already exists"
781 | # if just outside date range
782 | elif not lec.date in dates_list:
783 | lec.dl_status = "Outside date range"
784 | # If file already exists and is fully completed.
785 | # Shouldn't really get to this case (caught above).
786 | elif os.path.isfile(lec.fPath):
787 | lec.dl_status = "File already exists"
788 | skipped.append(lec)
789 | print(f"Skipping {lec.fName}: {lec.dl_status}")
790 |
791 | # print list of lectures to be downloaded
792 | if len(to_download) > 0:
793 | print("Lectures to be downloaded:")
794 | for lec, partial in to_download:
795 | # Print with additional note if it's there.
796 | # DAVE_HERE
797 | if lec.dl_status is not None:
798 | print(lec.fName, "-", lec.dl_status)
799 | else:
800 | print(lec.fName)
801 | else:
802 | print("No lectures to be downloaded for " + subject.name)
803 |
804 | # for each lecture, set filename and download
805 | for lec, partial in to_download:
806 |
807 | # build up filename
808 | print("Now working on", lec.fName)
809 | # go to initial download page and find actual download link
810 | while True:
811 | try:
812 | driver.get(lec.link)
813 | dl_link = driver.find_element_by_partial_link_text("Download media file.").get_attribute("href")
814 | # send javascript to stop download redirect
815 | driver.execute_script('stopCounting=true')
816 | break
817 | except:
818 | time.sleep(0.5)
819 |
820 | # This handles a full download. Report the local size as 0.
821 | if not partial:
822 | dl_func = functools.partial(download_lecture, dl_link, lec.fPath, lec.fName, 0)
823 | # This handles a partially downloaded file.
824 | else:
825 | sizeLocal, sizeWeb = partial
826 | dl_func = functools.partial(download_lecture, dl_link, lec.fPath, lec.fName, sizeLocal)
827 |
828 | q.put(dl_func)
829 | downloaded.append(lec)
830 |
831 | # when finished with subject
832 | print(f"Queued downloads for {subject.code}! Going to next file!")
833 | return downloaded, skipped
834 |
835 | # Check dates_list
836 | # The lectures further down are outside the date range, no need to check them.
837 |
838 | def consume_dl_queue(q):
839 | # This will just keep consuming an item from the queue and downloading it
840 | # until the program ends. get() blocks if there isn't an item in the queue.
841 | while True:
842 | dl_func = q.get()
843 | res = dl_func()
844 | if res is False:
845 | break
846 |
847 |
848 | def main():
849 | # Setup download folders
850 | home_dir = os.path.expanduser("~")
851 | uni_folder = check_uni_folder(settings['uni_location'], home_dir)
852 |
853 | print("Welcome to", sys.argv[0])
854 |
855 | # Date Junk
856 | current_year = datetime.datetime.now().year
857 | week_day = {}
858 | dates_list = get_weeks_to_download(current_year, week_day)
859 | # DATE ERROR
860 | # print(dates_list)
861 |
862 | download_mode = get_download_mode()
863 |
864 | # Start Chrome instance
865 | print("Starting up Chrome instance")
866 | chrome_options = Options()
867 | window_size = settings.get('window_size', '1600,900')
868 | chrome_options.add_argument('--window-size=' + window_size)
869 | if settings['hide_window']:
870 | print('Running in headless (hidden window) mode.')
871 | chrome_options.add_argument('--headless')
872 | chrome_options.add_argument('--disable-gpu') # TODO: Remove this
873 | try:
874 | # We build an absolute path to avoid the "Message: 'chromedriver'
875 | # executable needs to be in PATH" error.
876 | path = os.path.abspath(settings['driver_relative_path'])
877 | driver = webdriver.Chrome(path, chrome_options=chrome_options)
878 | except Exception as e1:
879 | try:
880 | path = path + '.exe' # We're on Windows.
881 | driver = webdriver.Chrome(path, chrome_options=chrome_options)
882 | except Exception as e2:
883 | print('Couldn\'t start Chrome!', file=sys.stderr)
884 | print(str(e1), file=sys.stderr)
885 | print(str(e2), file=sys.stderr)
886 | sys.exit(1)
887 |
888 | # Login
889 | print("Starting login process")
890 | driver.get("https://app.lms.unimelb.edu.au")
891 | sign_in(driver)
892 | driver.refresh()
893 | print("Building list of subjects")
894 |
895 | # This yucky looking control structure makes sure we get the right
896 | # box (subjects and not communities).
897 | subjectsFoundSuccess = False
898 | while not subjectsFoundSuccess:
899 | try:
900 | course_listing = get_course_links(driver)
901 | except StopIteration:
902 | # I know this is messy, that this is needed even with the decorator.
903 | time.sleep(0.5)
904 | continue
905 | try:
906 | subject_list = getSubjectList(course_listing)
907 | except RuntimeError:
908 | continue
909 | subjectsFoundSuccess = True
910 |
911 | numSubjects = len(subject_list)
912 |
913 | subjects_to_download = determine_subjects_to_download(subject_list)
914 | print("Subjects to be downloaded:")
915 | for subject in subjects_to_download:
916 | print(f"{subject.code}: {subject.name}")
917 |
918 | # Track which lectures we downloaded and which we skipped.
919 | all_downloaded = []
920 | all_skipped = []
921 |
922 | q = Queue()
923 | t = Thread(target=consume_dl_queue, args=(q,), daemon=True)
924 | t.start()
925 | for subject in subjects_to_download:
926 | res = download_lectures_for_subject(driver, subject, current_year,
927 | week_day, dates_list,
928 | download_mode, uni_folder, q)
929 | if res:
930 | downloaded, skipped = res
931 | all_downloaded += downloaded
932 | all_skipped += skipped
933 | # Done , close the browser.
934 | print("All links have been collected, waiting for downloads to complete...")
935 | driver.quit()
936 | # Let the thread know that we're done collecting download links.
937 | q.put(lambda: False)
938 | # Wait for all the downloads to complete.
939 | t.join()
940 |
941 | # List the lectures that we downloaded and those we skipped.
942 | if len(all_downloaded) > 0:
943 | print(f"Downloaded {len(all_downloaded)} lecture(s):")
944 | for lecture in all_downloaded:
945 | print(lecture.fName)
946 |
947 | if len(all_skipped) > 0:
948 | print(f"Skipped {len(all_skipped)} lecture(s):")
949 | for lecture in all_skipped:
950 | print(lecture.fName + ": " + lecture.dl_status)
951 |
952 | print("\nDone!\n")
953 |
954 |
955 | if __name__ == '__main__':
956 | main()
957 |
--------------------------------------------------------------------------------
/other/heads_up_2017-07-29.md:
--------------------------------------------------------------------------------
1 | # Update as of 2017-07-29, copied from lectureDL.py
2 |
3 | If you're modifying this in the future, know first off that the code was not designed with easy future use, nor abstraction in general, in mind. I've made it a bit better but it's still messy. Assuming you've got the required directory structure in place (check out the video_folder variable), you'll have to:
4 |
5 | 1. Change the current year and semester if necessary.
6 | 2. Change the variables representing the start of the semester (such as start_week0 and current_date) for this semester.
7 | 3. Manually download the latest ChromeDriver and change the driver variable accordingly.
8 | 4. Perhaps change / comment out the default variables (e.g. input_user).
9 |
10 | While it might be worth it, I feel like it'd be a fair bit of work to refactor this project to be "Good TM", after which you could start adding extra features. Like imagine trying to catch a selenium error and closing chrome if one is encountered, it'd be like a million try/excepts. So yeah, maybe one day. Still it wasn't too hard to get it working again.
11 |
--------------------------------------------------------------------------------
/other/initial_differences.md:
--------------------------------------------------------------------------------
1 | # Differences in this fork from original
2 |
3 | First, huge praise to @larryhudson for a super handy script. Many of my changes here are preference based, this fork mainly serves as a place for me to fiddle with the script :) Anyway, here's a list of most of the changes:
4 |
5 | - A progress indicator for each download.
6 | - Hides the password while the user enters it.
7 | - Detects when a download isn't fully completed, and if so download it again.
8 | - Makes sure echocenter and the list of subjects are fully loaded (on my slow slow slow connection the script would jump the gun on this). This is done by catching the exception for when a css element isn't found. Makes the already great script even more robust.
9 | - Makes the weeks print 01 instead of 1.
10 | - Facilitates automated running of the script with variables modifiable at the top of the file.
11 | - Changes download location to be subject specific. Meaning for a COMP30020 lecture, the script will download it to COMP30020/lectures/lecture name.m4v. This is of course purely a taste based thing.
12 | - Fixes a few bugs by introducing more duck typing. This led to improvements like automatic scrolling when the list of lectures was too long as well as gathering download links significantly faster.
13 | - Added support for partial downloads. Should hopefully be cross platform since I didn't end up using any external libraries.
14 |
15 | The whole thing was pretty perfect from the start, so my list of possible improvements here will be short:
16 |
17 | - Restructure the code into functions for each abstract task and then have a main which calls these. Would be nice for readability and maintainability's sake.
18 | - Way down the line it would be nice to have a way for it to handle future semesters that don't involve hardcoding date values. Problem for another time!
19 |
20 | Again, enormous thanks to @larryhudson for making that something that everybody's always wanted, and for it being so easy to use!
21 |
--------------------------------------------------------------------------------
/other/subj_list_screenshot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/banool/lectureDL/1916121d2f830a7cff98ff48f910cd9b07bfb7af/other/subj_list_screenshot.png
--------------------------------------------------------------------------------
/other/todo.md:
--------------------------------------------------------------------------------
1 | # To do list
2 |
3 | **Note:** This todo list has been migrated to the Issues tab.
4 |
5 | - ~Command-line arguments: adding a main function, as well as a way to pass in settings before running the script so that the user does not have to wait for the script to run.~ Mostly dealt with via the settings files.
6 | - Move some of the repeated code into defined functions for more flexibility, reusability of code. This has started with the Lecture class
7 | - ~Let the user save the username and password to a separate file.~
8 | - ~Download progress bar.~
9 | - Combine comma-separated weeks and week ranges so that input such as '1, 3-5' can be handled.
10 | - ~Detect if files did not finish downloading, resume or restart them if needed.~
11 | - ~Allow user to choose download folder.~
12 | - GUI, perhaps Tkinter.
13 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | py==1.4.34
2 | pytest==3.2.2
3 | selenium==3.7.0
4 |
--------------------------------------------------------------------------------
/settings.py:
--------------------------------------------------------------------------------
1 | from settings_example import *
2 |
--------------------------------------------------------------------------------
/settings_base.py:
--------------------------------------------------------------------------------
1 | # Don't import this directly.
2 |
3 | def getLectureName(lecture):
4 | ''' Sets the naming convention for lecture files.
5 | Current preference: COMP30022 Week 09 Lecture 1
6 | f'{lecture.subjCode} Week {lecture.week:02} Lecture {lecture.lecOfWeek}'
7 | Another preference: Models of Computation - L09
8 | f'{lec.subjName} - L{lec.recNum:02}'
9 | '''
10 | return f'{lecture.subjCode} Week {lecture.week:02} Lecture {lecture.lecOfWeek}'
11 |
12 | _settings_base = {
13 | # Whether to download video or audio.
14 | 'media_type': 'video',
15 | # Which subjects to download. An empty string '' means all.
16 | # Use numbers otherwise, 1 being the first subject in the list e.g. 1,3,4
17 | 'subject_choices': '',
18 | # If True, set lower week to current week (i.e. If in week 5 = 5-12).
19 | # Generally set this option to True unless you forgot to run the script
20 | # for a whole week or you're running this for the first time.
21 | 'update_lower_week': True,
22 | # Whether to hide the Chrome window or not.
23 | 'hide_window': False, # This is headless Chrome mode.
24 | # This is relative to where lectureDL.py is in the file system.
25 | 'driver_relative_path': 'chromedriver',
26 | }
27 |
--------------------------------------------------------------------------------
/settings_example.py:
--------------------------------------------------------------------------------
1 |
2 | import os
3 |
4 | from collections import defaultdict
5 | from settings_base import _settings_base, getLectureName
6 |
7 | settings = {
8 | # Your LMS username and password.
9 | 'username': 'porteousd',
10 | 'password': 'mysecurepassword1234',
11 | # The weeks of lectures you want to download.
12 | 'date_range': '1-12',
13 | # Where your uni folder exists.
14 | 'uni_location': os.path.join(os.path.expanduser('~'), 'Downloads/Uni'),
15 | # If you've selected a uni_location that doesn't have subfolders for each
16 | # subject in it, set this option to True and it'll make them automatically.
17 | 'auto_create_subfolders': True,
18 | # The name of the folder inside each subject's folder for holding the lecs.
19 | # Note the example folder structure at the bottom of the file.
20 | 'lecture_subfolder_name': 'Lectures',
21 | # The format string for the subject folder names.
22 | # Currently: CODE - Name e.g. COMP10001 - Foundations of Algorithms
23 | # Ignored if 'auto_create_folders' is False.
24 | # If false, the subject folder only needs to include the subject code.
25 | 'default_auto_create_format': '{code} - {name}',
26 | }
27 |
28 | # Merge settings_base and settings.
29 | # If there is a key clash, we prefer the value in settings over _settings_base.
30 | settings = defaultdict(lambda: None, {**_settings_base, **settings})
31 |
32 |
33 | # Example directory structure:
34 | # Uni/
35 | # COMP300026 - Models of Computation/
36 | # Assignment 1/
37 | # Lectures/
38 | # HIST10001 - Intro to Learning About Old Stuff/
39 | # Lectures/
40 | # Slides/
41 | # Other Junk/
42 | # blahblahblah.txt
43 | # SPAN30016 - Spanish 7/
44 | # Lectures/
45 | # Readings/
46 | # Note that if you have auto_create_subfolders on, you don't need to make
47 | # any of these subfolders yourself, just make sure uni_location exists.
48 | # With auto_create_subfolders off, directory structure may look like this:
49 | # Uni/
50 | # COMP300026 - MOC/
51 | # Assignment 1/
52 | # Lectures/
53 | # COMP300020 - DP/
54 | # Declarative Programming Assignment 1/
55 | # Lectures/
56 | # Other Junk/
57 | # blahblahblah.txt
--------------------------------------------------------------------------------
/util.py:
--------------------------------------------------------------------------------
1 | import inspect
2 | import io
3 | import shutil
4 | import sys
5 | import time
6 |
7 | def retry_until_result(wait_message, delay=0.25, max_retries=20):
8 | ''' Decorator to retry a function until it doesn't return None.
9 | As such it obviously relies on the function returning None on failure.
10 | Any function that waits on something to load should use this decorator.
11 | Note that in its current form, this reduces generators to be used as
12 | if they were just regular functions (so don't call next() or anything).
13 | '''
14 | def actual_decorator(function):
15 | def wrapper(*args, **kwargs):
16 | retries = 0
17 | print(wait_message)
18 | is_generator = inspect.isgeneratorfunction(function)
19 | if is_generator:
20 | iterator = iter(function(*args, **kwargs))
21 | # print(str(function) + ' is a generator')
22 | while True:
23 | if retries >= max_retries:
24 | raise RuntimeError('Max retries exceeded!')
25 | if not is_generator:
26 | result = function(*args, **kwargs)
27 | else:
28 | # Roughly handle if the function is a generator.
29 | result = next(iterator)
30 | retries += 1
31 | if result is None:
32 | time.sleep(delay)
33 | continue
34 | return result
35 | return wrapper
36 | return actual_decorator
37 |
38 |
39 | def show_progress(filehook, pretty_name, localSize, webSize, chunk_size=1024):
40 | ''' Downloads a file, optionally partially, while showing the progress of
41 | the download. This download progress is printed on the same line using a
42 | carriage return. This can mean other lines can sometimes display leftovers
43 | from this function if the line is shorter than the progress message.
44 | '''
45 | fh = filehook
46 | total_size = webSize
47 | total_read = localSize
48 | while True:
49 | chunk = fh.read(chunk_size)
50 | if not chunk:
51 | fh.close()
52 | break
53 | total_read += len(chunk)
54 | print("== Progress (%s):% 5.1f%% ==" % (pretty_name, total_read*100.0/total_size), end="\r", flush=True, file=sys.__stdout__)
55 | yield chunk
56 |
57 |
58 | class StdoutSpace(io.TextIOWrapper):
59 | '''
60 | Use like:
61 | sys.stdout = StdoutSpace(sys.stdout)
62 | '''
63 |
64 | def __init__(self, original_stdout):
65 | super()
66 | self.original_stdout = original_stdout
67 | self.current_line = []
68 |
69 | def write(self, text):
70 | if not text.endswith('\n'):
71 | self.current_line.append(text)
72 | else:
73 | terminal_width = get_terminal_width()
74 | string = ''.join(self.current_line)
75 | spaces = (terminal_width - len(string)) * ' '
76 | out = string + spaces + '\n'
77 | self.original_stdout.write(out)
78 | self.current_line = []
79 |
80 | def flush(self):
81 | # self.original_stdout.flush()
82 | pass
83 |
84 | def get_terminal_width():
85 | return shutil.get_terminal_size((80, 20)).columns
86 |
--------------------------------------------------------------------------------