9 |
10 | ## Python dependencies
11 |
12 | - [woob](https://woob.tech)
13 | - cloudscraper
14 | - dateutil
15 | - termcolor
16 | - colorama
17 | - playsound (optional)
18 |
19 | ## How to use it
20 |
21 | You need python3 for this script. If you don't have it, please [install it first](https://www.python.org/).
22 |
23 | Install dependencies:
24 |
25 | ```
26 | pip install -r requirements.txt
27 | ```
28 |
29 | Run:
30 |
31 | ```
32 | ./doctoshotgun.py []
33 | ```
34 |
35 | Further optional arguments:
36 |
37 | ```
38 | --debug, -d show debug information
39 | --pfizer, -z select only Pfizer vaccine
40 | --moderna, -m select only Moderna vaccine
41 | --janssen, -j select only Janssen vaccine
42 | --astrazeneca, -a select only AstraZeneca vaccine
43 | --only-second, -2 select only second dose
44 | --only-third, -3 select only third dose
45 | --patient PATIENT, -p PATIENT
46 | give patient ID
47 | --time-window TIME_WINDOW, -t TIME_WINDOW
48 | set how many next days the script look for slots (default = 7)
49 | --center CENTER, -c CENTER
50 | filter centers
51 | --zipcode CODE
52 | filter centers by zipcode
53 | --center-regex CENTER_REGEX
54 | filter centers by regex
55 | --center-exclude CENTER_EXCLUDE, -x CENTER_EXCLUDE
56 | exclude centers
57 | --center-exclude-regex CENTER_EXCLUDE_REGEX
58 | exclude centers by regex
59 | --include-neighbor-city, -n
60 | include neighboring cities
61 | --start-date START_DATE
62 | first date on which you want to book the first slot (format should be DD/MM/YYYY)
63 | --end-date END_DATE last date on which you want to book the first slot (format should be DD/MM/YYYY)
64 | --weekdays-exclude, -e
65 | exclude weekdays, e.g. "tuesday Wednesday FRIDAY"
66 | --dry-run do not really book the slot
67 | --code CODE 2FA code
68 | --confirm prompt to confirm before booking
69 | ```
70 |
71 | ### With Docker
72 |
73 | Build the image:
74 |
75 | ```
76 | docker build . -t doctoshotgun
77 | ```
78 |
79 | Run the container:
80 |
81 | ```
82 | docker run -it doctoshotgun []
83 | ```
84 |
85 | ### Multiple cities
86 |
87 | You can also look for slot in multiple cities at the same time. Cities must be separated by commas:
88 |
89 | ```
90 | $ ./doctoshotgun.py ,, []
91 | ```
92 |
93 | ### Filter on centers
94 |
95 | You can give name of centers in which you want specifically looking for:
96 |
97 | ```
98 | $ ./doctoshotgun.py fr paris roger.philibert@gmail.com \
99 | --center "Centre de Vaccination Covid 19 - Ville de Paris" \
100 | --center "Centre de Vaccination du 7eme arrondissement de Paris - Gymnase Camou"
101 | ```
102 |
103 | ### Select patient
104 |
105 | For doctolib accounts with more thant one patient, you can select patient just after launching the script:
106 |
107 | ```
108 | $ ./doctoshotgun.py fr paris roger.philibert@gmail.com PASSWORD
109 | Available patients are:
110 | * [0] Roger Philibert
111 | * [1] Luce Philibert
112 | For which patient do you want to book a slot?
113 | ```
114 |
115 | You can also give the patient id as argument:
116 |
117 | ```
118 | $ ./doctoshotgun.py fr paris roger.philibert@gmail.com PASSWORD -p 1
119 | Starting to look for vaccine slots for Luce Philibert in 1 next day(s) starting today...
120 | ```
121 |
122 | ### Set time window
123 |
124 | By default, the script looks for slots between now and next day at 23:59:59. If you belong to a category of patients that is allowed to book a slot in a more distant future, you can expand the time window. For exemple, if you want to search in the next 5 days :
125 |
126 | ```
127 | $ ./doctoshotgun.py fr paris roger.philibert@gmail.com -t 5
128 | Password:
129 | Starting to look for vaccine slots for Roger Philibert in 5 next day(s) starting today...
130 | This may take a few minutes/hours, be patient!
131 | ```
132 |
133 | ### Look on specific date
134 |
135 | By default, the script looks for slots between now and next day at 23:59:59. If you can't be vaccinated right now (e.g covid in the last 3 months or out of town) and you are looking for an appointment in a distant future, you can pass a starting date:
136 |
137 | ```
138 | $ ./doctoshotgun.py fr paris roger.philibert@gmail.com --start-date 17/06/2021
139 | Password:
140 | Starting to look for vaccine slots for Roger Philibert in 7 next day(s) starting 17/06/2021...
141 | This may take a few minutes/hours, be patient!
142 | ```
143 |
144 | ### Filter by vaccine
145 |
146 | The Pfizer vaccine is the only vaccine allowed in France for people between 16 and 18. For this case, you can use the -z option.
147 |
148 | ```
149 | $ ./doctoshotgun.py fr paris roger.philibert@gmail.com PASSWORD -z
150 | Starting to look for vaccine slots for Luce Philibert...
151 | Vaccines: Pfizer
152 | This may take a few minutes/hours, be patient!
153 | ```
154 |
155 | It is also possible to filter on Moderna vaccine with the -m option and Janssen with the -j option.
156 |
157 | ## Development
158 |
159 | ### Running tests
160 |
161 | ```
162 | $ pip install -r requirements-dev.txt
163 | $ pytest test_browser.py
164 | ```
165 |
--------------------------------------------------------------------------------
/test_browser.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | from requests.adapters import Response
3 | import responses
4 | from html import escape
5 | import lxml.html as html
6 | import json
7 | import datetime
8 | from woob.browser.browsers import Browser
9 | from woob.browser.exceptions import ServerError
10 | from doctoshotgun import CentersPage, DoctolibDE, DoctolibFR, CenterBookingPage
11 |
12 | # globals
13 | FIXTURES_FOLDER = "test_fixtures"
14 |
15 | # URL to be mocked using responses
16 | SEARCH_URL_FOR_KOLN = (
17 | 'https://127.0.0.1/search_results/1234567.json?limit=4'
18 | '&ref_visit_motive_ids%5B%5D=6768'
19 | '&ref_visit_motive_ids%5B%5D=6769'
20 | '&ref_visit_motive_ids%5B%5D=9039'
21 | '&ref_visit_motive_ids%5B%5D=6936'
22 | '&ref_visit_motive_ids%5B%5D=6937'
23 | '&ref_visit_motive_ids%5B%5D=9040'
24 | '&ref_visit_motive_ids%5B%5D=7978'
25 | '&ref_visit_motive_ids%5B%5D=7109'
26 | '&ref_visit_motive_ids%5B%5D=7110'
27 | '&speciality_id=5494'
28 | '&search_result_format=json'
29 | )
30 |
31 | SEARCH_URL_FOR_MUNCHEN=(
32 | 'https://127.0.0.1/impfung-covid-19-corona/M%C3%BCnchen'
33 | '?ref_visit_motive_ids%5B%5D=6768'
34 | '&ref_visit_motive_ids%5B%5D=6769'
35 | '&ref_visit_motive_ids%5B%5D=9039'
36 | '&ref_visit_motive_ids%5B%5D=6936'
37 | '&ref_visit_motive_ids%5B%5D=6937'
38 | '&ref_visit_motive_ids%5B%5D=9040'
39 | '&ref_visit_motive_ids%5B%5D=7978'
40 | '&ref_visit_motive_ids%5B%5D=7109'
41 | '&ref_visit_motive_ids%5B%5D=7110'
42 | '&page=1'
43 | )
44 |
45 |
46 | @responses.activate
47 | def test_find_centers_fr_returns_503_should_continue(tmp_path):
48 | """
49 | Check that find_centers doesn't raise a ServerError in case of 503 HTTP response
50 | """
51 | docto = DoctolibFR("roger.phillibert@gmail.com",
52 | "1234", responses_dirname=tmp_path)
53 | docto.BASEURL = "https://127.0.0.1"
54 |
55 | responses.add(
56 | responses.GET,
57 | "https://127.0.0.1/vaccination-covid-19/Paris?ref_visit_motive_ids%5B%5D=6970&ref_visit_motive_ids%5B%5D=6971&ref_visit_motive_ids%5B%5D=8192&ref_visit_motive_ids%5B%5D=7005&ref_visit_motive_ids%5B%5D=7004&ref_visit_motive_ids%5B%5D=8193&ref_visit_motive_ids%5B%5D=7945&ref_visit_motive_ids%5B%5D=7107&ref_visit_motive_ids%5B%5D=7108&page=1",
58 | status=503
59 | )
60 |
61 | # this should not raise an exception
62 | for _ in docto.find_centers(["Paris"]):
63 | pass
64 |
65 |
66 | @responses.activate
67 | def test_find_centers_de_returns_503_should_continue(tmp_path):
68 | """
69 | Check that find_centers doesn't raise a ServerError in case of 503 HTTP response
70 | """
71 | docto = DoctolibDE("roger.phillibert@gmail.com",
72 | "1234", responses_dirname=tmp_path)
73 | docto.BASEURL = "https://127.0.0.1"
74 |
75 | responses.add(
76 | responses.GET,
77 | SEARCH_URL_FOR_MUNCHEN,
78 | status=503
79 | )
80 |
81 | # this should not raise an exception
82 | for _ in docto.find_centers(["München"]):
83 | pass
84 |
85 |
86 | @responses.activate
87 | def test_find_centers_de_returns_520_should_continue(tmp_path):
88 | """
89 | Check that find_centers doesn't raise a ServerError in case of 503 HTTP response
90 | """
91 | docto = DoctolibDE("roger.phillibert@gmail.com",
92 | "1234", responses_dirname=tmp_path)
93 | docto.BASEURL = "https://127.0.0.1"
94 |
95 | responses.add(
96 | responses.GET,
97 | SEARCH_URL_FOR_MUNCHEN,
98 | status=520
99 | )
100 |
101 | # this should not raise an exception
102 | for _ in docto.find_centers(["München"]):
103 | pass
104 |
105 |
106 | @responses.activate
107 | def test_find_centers_fr_returns_502_should_fail(tmp_path):
108 | """
109 | Check that find_centers raises an error in case of non-whitelisted status code
110 | """
111 | docto = DoctolibFR("roger.phillibert@gmail.com",
112 | "1234", responses_dirname=tmp_path)
113 | docto.BASEURL = "https://127.0.0.1"
114 |
115 | responses.add(
116 | responses.GET,
117 | "https://127.0.0.1/vaccination-covid-19/Paris?ref_visit_motive_ids%5B%5D=6970&ref_visit_motive_ids%5B%5D=6971&ref_visit_motive_ids%5B%5D=8192&ref_visit_motive_ids%5B%5D=7005&ref_visit_motive_ids%5B%5D=7004&ref_visit_motive_ids%5B%5D=8193&ref_visit_motive_ids%5B%5D=7945&ref_visit_motive_ids%5B%5D=7107&ref_visit_motive_ids%5B%5D=7108&page=1",
118 | status=502
119 | )
120 |
121 | # this should raise an exception
122 | with pytest.raises(ServerError):
123 | for _ in docto.find_centers(["Paris"]):
124 | pass
125 |
126 |
127 | @responses.activate
128 | def test_find_centers_de_returns_502_should_fail(tmp_path):
129 | """
130 | Check that find_centers raises an error in case of non-whitelisted status code
131 | """
132 | docto = DoctolibDE("roger.phillibert@gmail.com",
133 | "1234", responses_dirname=tmp_path)
134 | docto.BASEURL = "https://127.0.0.1"
135 |
136 | responses.add(
137 | responses.GET,
138 | SEARCH_URL_FOR_MUNCHEN,
139 | status=502
140 | )
141 |
142 | # this should raise an exception
143 | with pytest.raises(ServerError):
144 | for _ in docto.find_centers(["München"]):
145 | pass
146 |
147 |
148 | @responses.activate
149 | def test_get_next_page_fr_should_return_2_on_page_1(tmp_path):
150 | """
151 | Check that get_next_page returns 2 when we are on page 1 and there is a next page available
152 | """
153 |
154 | """
155 | Next (data-u decoded): /vaccination-covid-19-autres-professions-prioritaires/france?page=2&ref_visit_motive_ids%5B%5D=6970&ref_visit_motive_ids%5B%5D=7005
156 | """
157 |
158 | htmlString = """
159 |
427 | """
428 | doc = html.document_fromstring(htmlString)
429 |
430 | response = Response()
431 | response._content = b'{}'
432 |
433 | centers_page = CentersPage(browser=Browser(), response=response)
434 | centers_page.doc = doc
435 | next_page = centers_page.get_next_page()
436 | assert next_page == None
437 |
438 |
439 | @responses.activate
440 | def test_book_slots_should_succeed(tmp_path):
441 | """
442 | Check that try_to_book calls all services successfully
443 | """
444 | docto = DoctolibDE("roger.phillibert@gmail.com",
445 | "1234", responses_dirname=tmp_path)
446 | docto.BASEURL = "https://127.0.0.1"
447 | docto.patient = {
448 | "id": "patient-id",
449 | "first_name": "Roger",
450 | "last_name": "Phillibert"
451 | }
452 |
453 | mock_search_result_id = {
454 | "searchResultId": 1234567
455 | }
456 |
457 | mock_search_result_id_escaped_json = escape(
458 | json.dumps(mock_search_result_id, separators=(',', ':')))
459 |
460 | responses.add(
461 | responses.GET,
462 | ("https://127.0.0.1/impfung-covid-19-corona/K%C3%B6ln"
463 | "?ref_visit_motive_ids%5B%5D=6768"
464 | "&ref_visit_motive_ids%5B%5D=6769"
465 | "&ref_visit_motive_ids%5B%5D=9039"
466 | "&ref_visit_motive_ids%5B%5D=6936"
467 | "&ref_visit_motive_ids%5B%5D=6937"
468 | "&ref_visit_motive_ids%5B%5D=9040"
469 | "&ref_visit_motive_ids%5B%5D=7978"
470 | "&ref_visit_motive_ids%5B%5D=7109"
471 | "&ref_visit_motive_ids%5B%5D=7110"
472 | "&page=1"),
473 | status=200,
474 | body="".format(
475 | dataProps=mock_search_result_id_escaped_json)
476 | )
477 |
478 | with open(FIXTURES_FOLDER + '/search_result.json') as json_file:
479 | mock_search_result = json.load(json_file)
480 |
481 | responses.add(
482 | responses.GET,
483 | SEARCH_URL_FOR_KOLN,
484 | status=200,
485 | body=json.dumps(mock_search_result)
486 | )
487 |
488 | with open(FIXTURES_FOLDER + '/doctor_response.json') as json_file:
489 | mock_doctor_response = json.load(json_file)
490 |
491 | responses.add(
492 | responses.GET,
493 | "https://127.0.0.1/allgemeinmedizin/koeln/dr-dre?insurance_sector=public",
494 | status=200,
495 | body=json.dumps(mock_doctor_response)
496 | )
497 |
498 | responses.add(
499 | responses.GET,
500 | "https://127.0.0.1/booking/dr-dre.json",
501 | status=200,
502 | body=json.dumps(mock_doctor_response)
503 | )
504 |
505 | with open(FIXTURES_FOLDER + '/availabilities.json') as json_file:
506 | mock_availabilities = json.load(json_file)
507 |
508 | responses.add(
509 | responses.GET,
510 | "https://127.0.0.1/availabilities.json?start_date=2021-06-01&visit_motive_ids=2920448&agenda_ids=&insurance_sector=public&practice_ids=234567&destroy_temporary=true&limit=3",
511 | status=200,
512 | body=json.dumps(mock_availabilities)
513 | )
514 | responses.add(
515 | responses.GET,
516 | "https://127.0.0.1/availabilities.json?start_date=2021-06-01&visit_motive_ids=2746983&agenda_ids=&insurance_sector=public&practice_ids=234567&destroy_temporary=true&limit=3",
517 | status=200,
518 | body=json.dumps(mock_availabilities)
519 | )
520 |
521 | mock_appointments = {
522 | "id": "appointment-id"
523 | }
524 |
525 | responses.add(
526 | responses.POST,
527 | "https://127.0.0.1/appointments.json",
528 | status=200,
529 | body=json.dumps(mock_appointments)
530 | )
531 |
532 | mock_appointments_edit = {
533 | "id": "appointment-edit-id",
534 | "appointment": {
535 | "custom_fields": {}
536 | }
537 | }
538 |
539 | responses.add(
540 | responses.GET,
541 | "https://127.0.0.1/appointments/appointment-id/edit.json",
542 | status=200,
543 | body=json.dumps(mock_appointments_edit)
544 | )
545 |
546 | responses.add(
547 | responses.GET,
548 | "https://127.0.0.1/second_shot_availabilities.json?start_date=2021-07-20&visit_motive_ids=2746983&agenda_ids=&first_slot=2021-06-10T08%3A40%3A00.000%2B02%3A00&insurance_sector=public&practice_ids=234567&limit=3",
549 | status=200,
550 | body=json.dumps(mock_availabilities)
551 | )
552 |
553 | mock_appointment_id_put = {
554 | }
555 |
556 | responses.add(
557 | responses.PUT,
558 | "https://127.0.0.1/appointments/appointment-id.json",
559 | status=200,
560 | body=json.dumps(mock_appointment_id_put)
561 | )
562 |
563 | mock_appointment_id = {
564 | "confirmed": True
565 | }
566 |
567 | responses.add(
568 | responses.GET,
569 | "https://127.0.0.1/appointments/appointment-id.json",
570 | status=200,
571 | body=json.dumps(mock_appointment_id)
572 | )
573 |
574 | result_handled = False
575 | for result in docto.find_centers(["Köln"]):
576 | result_handled = True
577 |
578 | center = result['search_result']
579 |
580 | # single shot vaccination
581 | assert docto.try_to_book(center=center,
582 | vaccine_list=["Janssen"],
583 | start_date=datetime.date(
584 | year=2021, month=6, day=1),
585 | end_date=datetime.date(
586 | year=2021, month=6, day=14),
587 | excluded_weekdays=[],
588 | only_second=False,
589 | only_third=False,
590 | dry_run=False)
591 | assert len(responses.calls) == 10
592 |
593 | # two shot vaccination
594 | assert docto.try_to_book(center=center,
595 | vaccine_list=["Pfizer"],
596 | start_date=datetime.date(
597 | year=2021, month=6, day=1),
598 | end_date=datetime.date(
599 | year=2021, month=6, day=14),
600 | excluded_weekdays=[],
601 | only_second=False,
602 | only_third=False,
603 | dry_run=False)
604 | assert len(responses.calls) == 20
605 | pass
606 |
607 | assert result_handled
608 |
609 |
610 | @responses.activate
611 | def test_find_motive_should_ignore_second_shot(tmp_path):
612 | """
613 | Check that find_motive ignores second shot motives
614 | """
615 |
616 | with open(FIXTURES_FOLDER + '/doctor_response.json') as json_file:
617 | mock_doctor_response = json.load(json_file)
618 |
619 | response = Response()
620 | response._content = b'{}'
621 |
622 | booking_page = CenterBookingPage(browser=Browser(), response=response)
623 | booking_page.doc = mock_doctor_response
624 | visit_motive_id = CenterBookingPage.find_motive(
625 | booking_page, '.*(Pfizer)', False)
626 | assert visit_motive_id == mock_doctor_response['data']['visit_motives'][1]['id']
627 |
628 | visit_motive_id = CenterBookingPage.find_motive(
629 | booking_page, '.*(Janssen)', True)
630 | assert visit_motive_id == mock_doctor_response['data']['visit_motives'][3]['id']
631 |
--------------------------------------------------------------------------------
/COPYING:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/example.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/doctoshotgun.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | import sys
3 | import os
4 | import re
5 | import logging
6 | import tempfile
7 | from time import sleep
8 | import json
9 | from urllib.parse import urlparse
10 | import datetime
11 | import argparse
12 | from pathlib import Path
13 | import getpass
14 | import unicodedata
15 |
16 | from dateutil.parser import parse as parse_date
17 | from dateutil.relativedelta import relativedelta
18 |
19 | import calendar
20 | import cloudscraper
21 | import colorama
22 | from requests.adapters import ReadTimeout, ConnectionError
23 | from termcolor import colored
24 | from urllib import parse
25 | from urllib3.exceptions import NewConnectionError
26 |
27 | from woob.browser.exceptions import ClientError, ServerError, HTTPNotFound
28 | from woob.browser.browsers import LoginBrowser, StatesMixin
29 | from woob.browser.url import URL
30 | from woob.browser.pages import JsonPage, HTMLPage
31 | from woob.tools.log import createColoredFormatter
32 | from woob.tools.misc import get_backtrace
33 |
34 | SLEEP_INTERVAL_AFTER_CONNECTION_ERROR = 5
35 | SLEEP_INTERVAL_AFTER_LOGIN_ERROR = 10
36 | SLEEP_INTERVAL_AFTER_CENTER = 1
37 | SLEEP_INTERVAL_AFTER_RUN = 5
38 |
39 | try:
40 | from playsound import playsound as _playsound, PlaysoundException
41 |
42 | def playsound(*args):
43 | try:
44 | return _playsound(*args)
45 | except (PlaysoundException, ModuleNotFoundError):
46 | pass # do not crash if, for one reason or another, something wrong happens
47 | except ImportError:
48 | def playsound(*args):
49 | pass
50 |
51 |
52 | def log(text, *args, **kwargs):
53 | args = (colored(arg, 'yellow') for arg in args)
54 | if 'color' in kwargs:
55 | text = colored(text, kwargs.pop('color'))
56 | text = text % tuple(args)
57 | print(text, **kwargs)
58 |
59 |
60 | def log_ts(text=None, *args, **kwargs):
61 | ''' Log with timestamp'''
62 | now = datetime.datetime.now()
63 | print("[%s]" % now.isoformat(" ", "seconds"))
64 | if text:
65 | log(text, *args, **kwargs)
66 |
67 |
68 | class Session(cloudscraper.CloudScraper):
69 | def send(self, *args, **kwargs):
70 | callback = kwargs.pop('callback', lambda future, response: response)
71 | is_async = kwargs.pop('is_async', False)
72 |
73 | if is_async:
74 | raise ValueError('Async requests are not supported')
75 |
76 | resp = super().send(*args, **kwargs)
77 |
78 | return callback(self, resp)
79 |
80 |
81 | class LoginPage(JsonPage):
82 | def redirect(self):
83 | return self.doc['redirection']
84 |
85 |
86 | class SendAuthCodePage(JsonPage):
87 | def build_doc(self, content):
88 | return "" # Do not choke on empty response from server
89 |
90 |
91 | class ChallengePage(JsonPage):
92 | def build_doc(self, content):
93 | return "" # Do not choke on empty response from server
94 |
95 |
96 | class CentersPage(HTMLPage):
97 | def on_load(self):
98 | try:
99 | v = self.doc.xpath('//input[@id="wait-time-value"]')[0]
100 | except IndexError:
101 | return
102 | raise WaitingInQueue(int(v.attrib['value']))
103 |
104 | def iter_centers_ids(self):
105 | for div in self.doc.xpath('//div[@class="js-dl-search-results-calendar"]'):
106 | data = json.loads(div.attrib['data-props'])
107 | yield data['searchResultId']
108 |
109 | def get_next_page(self):
110 | # French doctolib uses data-u attribute of span-element to create the link when user hovers span
111 | for span in self.doc.xpath('//div[contains(@class, "next")]/span'):
112 | if not span.attrib.has_key('data-u'):
113 | continue
114 |
115 | # How to find the corresponding javascript-code:
116 | # Press F12 to open dev-tools, select elements-tab, find div.next, right click on element and enable break on substructure change
117 | # Hover "Next" element and follow callstack upwards
118 | # JavaScript:
119 | # var t = (e = r()(e)).data("u")
120 | # , n = atob(t.replace(/\s/g, '').split('').reverse().join(''));
121 |
122 | import base64
123 | href = base64.urlsafe_b64decode(''.join(span.attrib['data-u'].split())[::-1]).decode()
124 | query = dict(parse.parse_qsl(parse.urlsplit(href).query))
125 |
126 | if 'page' in query:
127 | return int(query['page'])
128 |
129 | for a in self.doc.xpath('//div[contains(@class, "next")]/a'):
130 | href = a.attrib['href']
131 | query = dict(parse.parse_qsl(parse.urlsplit(href).query))
132 |
133 | if 'page' in query:
134 | return int(query['page'])
135 |
136 | return None
137 |
138 |
139 | class CenterResultPage(JsonPage):
140 | pass
141 |
142 |
143 | class CenterPage(HTMLPage):
144 | pass
145 |
146 |
147 | class CenterBookingPage(JsonPage):
148 | def find_motive(self, regex, singleShot=False):
149 | for s in self.doc['data']['visit_motives']:
150 | # ignore case as some doctors use their own spelling
151 | if re.search(regex, s['name'], re.IGNORECASE):
152 | if s['allow_new_patients'] == False:
153 | log('Motive %s not allowed for new patients at this center. Skipping vaccine...',
154 | s['name'], flush=True)
155 | continue
156 | if not singleShot and not s['first_shot_motive']:
157 | log('Skipping second shot motive %s...',
158 | s['name'], flush=True)
159 | continue
160 | return s['id']
161 |
162 | return None
163 |
164 | def get_motives(self):
165 | return [s['name'] for s in self.doc['data']['visit_motives']]
166 |
167 | def get_places(self):
168 | return self.doc['data']['places']
169 |
170 | def get_practice(self):
171 | return self.doc['data']['places'][0]['practice_ids'][0]
172 |
173 | def get_agenda_ids(self, motive_id, practice_id=None):
174 | agenda_ids = []
175 | for a in self.doc['data']['agendas']:
176 | if motive_id in a['visit_motive_ids'] and \
177 | not a['booking_disabled'] and \
178 | (not practice_id or a['practice_id'] == practice_id):
179 | agenda_ids.append(str(a['id']))
180 |
181 | return agenda_ids
182 |
183 | def get_profile_id(self):
184 | return self.doc['data']['profile']['id']
185 |
186 |
187 | class AvailabilitiesPage(JsonPage):
188 | def find_best_slot(self, start_date=None, end_date=None, excluded_weekdays=[]):
189 | for a in self.doc['availabilities']:
190 | date = parse_date(a['date']).date()
191 | if start_date and date < start_date or end_date and date > end_date:
192 | continue
193 | if date.weekday() in excluded_weekdays:
194 | continue
195 | if len(a['slots']) == 0:
196 | continue
197 | return a['slots'][-1]
198 |
199 |
200 | class AppointmentPage(JsonPage):
201 | def get_error(self):
202 | return self.doc['error']
203 |
204 | def is_error(self):
205 | return 'error' in self.doc
206 |
207 |
208 | class AppointmentEditPage(JsonPage):
209 | def get_custom_fields(self):
210 | for field in self.doc['appointment']['custom_fields']:
211 | if field['required']:
212 | yield field
213 |
214 |
215 | class AppointmentPostPage(JsonPage):
216 | pass
217 |
218 |
219 | class MasterPatientPage(JsonPage):
220 | def get_patients(self):
221 | return self.doc
222 |
223 | def get_name(self):
224 | return '%s %s' % (self.doc[0]['first_name'], self.doc[0]['last_name'])
225 |
226 |
227 | class WaitingInQueue(Exception):
228 | pass
229 |
230 |
231 | class CityNotFound(Exception):
232 | pass
233 |
234 |
235 | class Doctolib(LoginBrowser, StatesMixin):
236 | # individual properties for each country. To be defined in subclasses
237 | BASEURL = ""
238 | vaccine_motives = {}
239 | centers = URL('')
240 | center = URL('')
241 | # common properties
242 | login = URL('/login.json', LoginPage)
243 | send_auth_code = URL('/api/accounts/send_auth_code', SendAuthCodePage)
244 | challenge = URL('/login/challenge', ChallengePage)
245 | center_result = URL(r'/search_results/(?P\d+).json', CenterResultPage)
246 | center_booking = URL(r'/booking/(?P.+).json', CenterBookingPage)
247 | availabilities = URL(r'/availabilities.json', AvailabilitiesPage)
248 | second_shot_availabilities = URL(
249 | r'/second_shot_availabilities.json', AvailabilitiesPage)
250 | appointment = URL(r'/appointments.json', AppointmentPage)
251 | appointment_edit = URL(
252 | r'/appointments/(?P.+)/edit.json', AppointmentEditPage)
253 | appointment_post = URL(
254 | r'/appointments/(?P.+).json', AppointmentPostPage)
255 | master_patient = URL(r'/account/master_patients.json', MasterPatientPage)
256 |
257 | def _setup_session(self, profile):
258 | session = Session()
259 |
260 | session.hooks['response'].append(self.set_normalized_url)
261 | if self.responses_dirname is not None:
262 | session.hooks['response'].append(self.save_response)
263 |
264 | self.session = session
265 |
266 | def __init__(self, *args, **kwargs):
267 | super().__init__(*args, **kwargs)
268 | self.session.headers['sec-fetch-dest'] = 'document'
269 | self.session.headers['sec-fetch-mode'] = 'navigate'
270 | self.session.headers['sec-fetch-site'] = 'same-origin'
271 | self.session.headers['User-Agent'] = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36'
272 |
273 | self.patient = None
274 |
275 | def locate_browser(self, state):
276 | # When loading state, do not locate browser on the last url.
277 | pass
278 |
279 | def do_login(self, code):
280 | try:
281 | self.open(self.BASEURL + '/sessions/new')
282 | except ServerError as e:
283 | if e.response.status_code in [503] \
284 | and 'text/html' in e.response.headers['Content-Type'] \
285 | and ('cloudflare' in e.response.text or 'Checking your browser before accessing' in e .response.text):
286 | log('Request blocked by CloudFlare', color='red')
287 | if e.response.status_code in [520]:
288 | log('Cloudflare is unable to connect to Doctolib server. Please retry later.', color='red')
289 | raise
290 | try:
291 | self.login.go(json={'kind': 'patient',
292 | 'username': self.username,
293 | 'password': self.password,
294 | 'remember': True,
295 | 'remember_username': True})
296 | except ClientError:
297 | print('Wrong login/password')
298 | return False
299 |
300 | if self.page.redirect() == "/sessions/two-factor":
301 | print("Requesting 2fa code...")
302 | if not code:
303 | if not sys.__stdin__.isatty():
304 | log("Auth Code input required, but no interactive terminal available. Please provide it via command line argument '--code'.", color='red')
305 | return False
306 | self.send_auth_code.go(
307 | json={'two_factor_auth_method': 'email'}, method="POST")
308 | code = input("Enter auth code: ")
309 | try:
310 | self.challenge.go(
311 | json={'auth_code': code, 'two_factor_auth_method': 'email'}, method="POST")
312 | except HTTPNotFound:
313 | print("Invalid auth code")
314 | return False
315 |
316 | return True
317 |
318 | def find_centers(self, where, motives=None, page=1):
319 | if motives is None:
320 | motives = self.vaccine_motives.keys()
321 | for city in where:
322 | try:
323 | self.centers.go(where=city, params={
324 | 'ref_visit_motive_ids[]': motives, 'page': page})
325 | except ServerError as e:
326 | if e.response.status_code in [503]:
327 | if 'text/html' in e.response.headers['Content-Type'] \
328 | and ('cloudflare' in e.response.text or
329 | 'Checking your browser before accessing' in e .response.text):
330 | log('Request blocked by CloudFlare', color='red')
331 | return
332 | if e.response.status_code in [520]:
333 | log('Cloudflare is unable to connect to Doctolib server. Please retry later.', color='red')
334 | return
335 | raise
336 | except HTTPNotFound as e:
337 | raise CityNotFound(city) from e
338 |
339 | next_page = self.page.get_next_page()
340 |
341 | for i in self.page.iter_centers_ids():
342 | page = self.center_result.open(
343 | id=i,
344 | params={
345 | 'limit': '4',
346 | 'ref_visit_motive_ids[]': motives,
347 | 'speciality_id': '5494',
348 | 'search_result_format': 'json'
349 | }
350 | )
351 | try:
352 | yield page.doc['search_result']
353 | except KeyError:
354 | pass
355 |
356 | if next_page:
357 | for center in self.find_centers(where, motives, next_page):
358 | yield center
359 |
360 | def get_patients(self):
361 | self.master_patient.go()
362 |
363 | return self.page.get_patients()
364 |
365 | @classmethod
366 | def normalize(cls, string):
367 | nfkd = unicodedata.normalize('NFKD', string)
368 | normalized = u"".join(
369 | [c for c in nfkd if not unicodedata.combining(c)])
370 | normalized = re.sub(r'\W', '-', normalized)
371 | return normalized.lower()
372 |
373 | def try_to_book(self, center, vaccine_list, start_date, end_date, excluded_weekdays, only_second, only_third, dry_run=False, confirm=False):
374 | try:
375 | self.open(center['url'])
376 | except ClientError as e:
377 | # Sometimes there are referenced centers which are not available anymore (410 Gone)
378 | log('Error: %s', e, color='red')
379 | return False
380 |
381 | p = urlparse(center['url'])
382 | center_id = p.path.split('/')[-1]
383 |
384 | center_page = self.center_booking.go(center_id=center_id)
385 | profile_id = self.page.get_profile_id()
386 | # extract motive ids based on the vaccine names
387 | motives_id = dict()
388 | for vaccine in vaccine_list:
389 | motives_id[vaccine] = self.page.find_motive(
390 | r'.*({})'.format(vaccine), singleShot=(vaccine == self.vaccine_motives[self.KEY_JANSSEN] or only_second or only_third))
391 |
392 | motives_id = dict((k, v)
393 | for k, v in motives_id.items() if v is not None)
394 | if len(motives_id.values()) == 0:
395 | log('Unable to find requested vaccines in motives', color='red')
396 | log('Motives: %s', ', '.join(self.page.get_motives()), color='red')
397 | return False
398 |
399 | for place in self.page.get_places():
400 | if place['name']:
401 | log('– %s...', place['name'])
402 | practice_id = place['practice_ids'][0]
403 | for vac_name, motive_id in motives_id.items():
404 | log(' Vaccine %s...', vac_name, end=' ', flush=True)
405 | agenda_ids = center_page.get_agenda_ids(motive_id, practice_id)
406 | if len(agenda_ids) == 0:
407 | # do not filter to give a chance
408 | agenda_ids = center_page.get_agenda_ids(motive_id)
409 |
410 | if self.try_to_book_place(profile_id, motive_id, practice_id, agenda_ids, vac_name.lower(), start_date, end_date, excluded_weekdays, only_second, only_third, dry_run, confirm):
411 | return True
412 |
413 | return False
414 |
415 | def try_to_book_place(self, profile_id, motive_id, practice_id, agenda_ids, vac_name, start_date, end_date, excluded_weekdays, only_second, only_third, dry_run=False, confirm=False):
416 | date = start_date.strftime('%Y-%m-%d')
417 | while date is not None:
418 | self.availabilities.go(
419 | params={'start_date': date,
420 | 'visit_motive_ids': motive_id,
421 | 'agenda_ids': '-'.join(agenda_ids),
422 | 'insurance_sector': 'public',
423 | 'practice_ids': practice_id,
424 | 'destroy_temporary': 'true',
425 | 'limit': 3})
426 | if 'next_slot' in self.page.doc:
427 | date = self.page.doc['next_slot']
428 | else:
429 | date = None
430 |
431 | if len(self.page.doc['availabilities']) == 0:
432 | log('no availabilities', color='red')
433 | return False
434 |
435 | slot = self.page.find_best_slot(start_date, end_date)
436 | if not slot:
437 | if only_second == False and only_third == False:
438 | log('First slot not found :(', color='red')
439 | else:
440 | log('Slot not found :(', color='red')
441 | return False
442 |
443 | # depending on the country, the slot is returned in a different format. Go figure...
444 | if isinstance(slot, dict) and 'start_date' in slot:
445 | slot_date_first = slot['start_date']
446 | if vac_name != "janssen":
447 | slot_date_second = slot['steps'][1]['start_date']
448 | elif isinstance(slot, str):
449 | if vac_name != "janssen" and not only_second and not only_third:
450 | log('Only one slot for multi-shot vaccination found')
451 | # should be for Janssen, second or third shots only, otherwise it is a list
452 | slot_date_first = slot
453 | elif isinstance(slot, list):
454 | slot_date_first = slot[0]
455 | if vac_name != "janssen": # maybe redundant?
456 | slot_date_second = slot[1]
457 | else:
458 | log('Error while fetching first slot.', color='red')
459 | return False
460 | if vac_name != "janssen" and not only_second and not only_third:
461 | assert slot_date_second
462 | log('found!', color='green')
463 | log(' ├╴ Best slot found: %s', parse_date(
464 | slot_date_first).strftime('%c'))
465 |
466 | appointment = {'profile_id': profile_id,
467 | 'source_action': 'profile',
468 | 'start_date': slot_date_first,
469 | 'visit_motive_ids': str(motive_id),
470 | }
471 |
472 | data = {'agenda_ids': '-'.join(agenda_ids),
473 | 'appointment': appointment,
474 | 'practice_ids': [practice_id]}
475 |
476 | headers = {
477 | 'content-type': 'application/json',
478 | }
479 | self.appointment.go(data=json.dumps(data), headers=headers)
480 |
481 | if self.page.is_error():
482 | log(' └╴ Appointment not available anymore :( %s', self.page.get_error())
483 | return False
484 |
485 | playsound('ding.mp3')
486 |
487 | if vac_name != "janssen" and not only_second and not only_third: # janssen has only one shot
488 | self.second_shot_availabilities.go(
489 | params={'start_date': slot_date_second.split('T')[0],
490 | 'visit_motive_ids': motive_id,
491 | 'agenda_ids': '-'.join(agenda_ids),
492 | 'first_slot': slot_date_first,
493 | 'insurance_sector': 'public',
494 | 'practice_ids': practice_id,
495 | 'limit': 3})
496 |
497 | second_slot = self.page.find_best_slot()
498 | if not second_slot:
499 | log(' └╴ No second shot found')
500 | return False
501 |
502 | # in theory we could use the stored slot_date_second result from above,
503 | # but we refresh with the new results to play safe
504 | if isinstance(second_slot, dict) and 'start_date' in second_slot:
505 | slot_date_second = second_slot['start_date']
506 | elif isinstance(slot, str):
507 | slot_date_second = second_slot
508 | # TODO: is this else needed?
509 | # elif isinstance(slot, list):
510 | # slot_date_second = second_slot[1]
511 | else:
512 | log('Error while fetching second slot.', color='red')
513 | return False
514 |
515 | log(' ├╴ Second shot: %s', parse_date(
516 | slot_date_second).strftime('%c'))
517 |
518 | data['second_slot'] = slot_date_second
519 | self.appointment.go(data=json.dumps(data), headers=headers)
520 |
521 | if self.page.is_error():
522 | log(' └╴ Appointment not available anymore :( %s',
523 | self.page.get_error())
524 | return False
525 |
526 | a_id = self.page.doc['id']
527 |
528 | self.appointment_edit.go(id=a_id)
529 |
530 | log(' ├╴ Booking for %(first_name)s %(last_name)s...' % self.patient)
531 |
532 | self.appointment_edit.go(
533 | id=a_id, params={'master_patient_id': self.patient['id']})
534 |
535 | custom_fields = {}
536 | for field in self.page.get_custom_fields():
537 | if field['id'] == 'cov19':
538 | value = 'Non'
539 | elif field['placeholder']:
540 | value = field['placeholder']
541 | else:
542 | for key, value in field.get('options', []):
543 | print(' │ %s %s' % (colored(key, 'green'), colored(value, 'yellow')))
544 | print(' ├╴ %s%s:' % (field['label'], (' (%s)' % field['placeholder']) if field['placeholder'] else ''),
545 | end=' ', flush=True)
546 | value = sys.stdin.readline().strip()
547 |
548 | custom_fields[field['id']] = value
549 |
550 | if dry_run:
551 | log(' └╴ Booking status: %s', 'fake')
552 | return True
553 |
554 | if confirm:
555 | print(' ├╴ Do you want to book it? (y/N)', end=' ', flush=True)
556 | if sys.stdin.readline().strip().lower() != 'y':
557 | log(' └╴ Skipped')
558 | return False
559 |
560 | data = {'appointment': {'custom_fields_values': custom_fields,
561 | 'new_patient': True,
562 | 'qualification_answers': {},
563 | 'referrer_id': None,
564 | },
565 | 'bypass_mandatory_relative_contact_info': False,
566 | 'email': None,
567 | 'master_patient': self.patient,
568 | 'new_patient': True,
569 | 'patient': None,
570 | 'phone_number': None,
571 | }
572 |
573 | self.appointment_post.go(id=a_id, data=json.dumps(
574 | data), headers=headers, method='PUT')
575 |
576 | if 'redirection' in self.page.doc and not 'confirmed-appointment' in self.page.doc['redirection']:
577 | log(' ├╴ Open %s to complete', self.BASEURL +
578 | self.page.doc['redirection'])
579 |
580 | self.appointment_post.go(id=a_id)
581 |
582 | log(' └╴ Booking status: %s', self.page.doc['confirmed'])
583 |
584 | return self.page.doc['confirmed']
585 |
586 |
587 | class DoctolibDE(Doctolib):
588 | BASEURL = 'https://www.doctolib.de'
589 | KEY_PFIZER = '6768'
590 | KEY_PFIZER_SECOND = '6769'
591 | KEY_PFIZER_THIRD = '9039'
592 | KEY_MODERNA = '6936'
593 | KEY_MODERNA_SECOND = '6937'
594 | KEY_MODERNA_THIRD = '9040'
595 | KEY_JANSSEN = '7978'
596 | KEY_ASTRAZENECA = '7109'
597 | KEY_ASTRAZENECA_SECOND = '7110'
598 | vaccine_motives = {
599 | KEY_PFIZER: 'Pfizer',
600 | KEY_PFIZER_SECOND: 'Zweit.*Pfizer|Pfizer.*Zweit',
601 | KEY_PFIZER_THIRD: 'Auffrischung.*Pfizer|Pfizer.*Auffrischung|Dritt.*Pfizer|Booster.*Pfizer',
602 | KEY_MODERNA: 'Moderna',
603 | KEY_MODERNA_SECOND: 'Zweit.*Moderna|Moderna.*Zweit',
604 | KEY_MODERNA_THIRD: 'Auffrischung.*Moderna|Moderna.*Auffrischung|Dritt.*Moderna|Booster.*Moderna',
605 | KEY_JANSSEN: 'Janssen',
606 | KEY_ASTRAZENECA: 'AstraZeneca',
607 | KEY_ASTRAZENECA_SECOND: 'Zweit.*AstraZeneca|AstraZeneca.*Zweit',
608 | }
609 | centers = URL(r'/impfung-covid-19-corona/(?P\w+)', CentersPage)
610 | center = URL(r'/praxis/.*', CenterPage)
611 |
612 |
613 | class DoctolibFR(Doctolib):
614 | BASEURL = 'https://www.doctolib.fr'
615 | KEY_PFIZER = '6970'
616 | KEY_PFIZER_SECOND = '6971'
617 | KEY_PFIZER_THIRD = '8192'
618 | KEY_MODERNA = '7005'
619 | KEY_MODERNA_SECOND = '7004'
620 | KEY_MODERNA_THIRD = '8193'
621 | KEY_JANSSEN = '7945'
622 | KEY_ASTRAZENECA = '7107'
623 | KEY_ASTRAZENECA_SECOND = '7108'
624 | vaccine_motives = {
625 | KEY_PFIZER: 'Pfizer',
626 | KEY_PFIZER_SECOND: '2de.*Pfizer',
627 | KEY_PFIZER_THIRD: '3e.*Pfizer',
628 | KEY_MODERNA: 'Moderna',
629 | KEY_MODERNA_SECOND: '2de.*Moderna',
630 | KEY_MODERNA_THIRD: '3e.*Moderna',
631 | KEY_JANSSEN: 'Janssen',
632 | KEY_ASTRAZENECA: 'AstraZeneca',
633 | KEY_ASTRAZENECA_SECOND: '2de.*AstraZeneca',
634 | }
635 |
636 | centers = URL(r'/vaccination-covid-19/(?P\w+)', CentersPage)
637 | center = URL(r'/centre-de-sante/.*', CenterPage)
638 |
639 |
640 | class Application:
641 | DATA_DIRNAME = (Path(os.environ.get("XDG_DATA_HOME") or Path.home() / ".local" / "share")) / 'doctoshotgun'
642 | STATE_FILENAME = DATA_DIRNAME / 'state.json'
643 |
644 | @classmethod
645 | def create_default_logger(cls):
646 | # stderr logger
647 | format = '%(asctime)s:%(levelname)s:%(name)s:' \
648 | ':%(filename)s:%(lineno)d:%(funcName)s %(message)s'
649 | handler = logging.StreamHandler(sys.stderr)
650 | handler.setFormatter(createColoredFormatter(sys.stderr, format))
651 | return handler
652 |
653 | def setup_loggers(self, level):
654 | logging.root.handlers = []
655 |
656 | logging.root.setLevel(level)
657 | logging.root.addHandler(self.create_default_logger())
658 |
659 | def load_state(self):
660 | try:
661 | with open(self.STATE_FILENAME, 'r') as fp:
662 | state = json.load(fp)
663 | except IOError:
664 | return {}
665 | else:
666 | return state
667 |
668 | def save_state(self, state):
669 | if not os.path.exists(self.DATA_DIRNAME):
670 | os.makedirs(self.DATA_DIRNAME)
671 | with open(self.STATE_FILENAME, 'w') as fp:
672 | json.dump(state, fp)
673 |
674 | def main(self, cli_args=None):
675 | colorama.init() # needed for windows
676 |
677 | doctolib_map = {
678 | "fr": DoctolibFR,
679 | "de": DoctolibDE
680 | }
681 |
682 | parser = argparse.ArgumentParser(
683 | description="Book a vaccine slot on Doctolib")
684 | parser.add_argument('--debug', '-d', action='store_true',
685 | help='show debug information')
686 | parser.add_argument('--pfizer', '-z', action='store_true',
687 | help='select only Pfizer vaccine')
688 | parser.add_argument('--moderna', '-m', action='store_true',
689 | help='select only Moderna vaccine')
690 | parser.add_argument('--janssen', '-j', action='store_true',
691 | help='select only Janssen vaccine')
692 | parser.add_argument('--astrazeneca', '-a', action='store_true',
693 | help='select only AstraZeneca vaccine')
694 | parser.add_argument('--only-second', '-2',
695 | action='store_true', help='select only second dose')
696 | parser.add_argument('--only-third', '-3',
697 | action='store_true', help='select only third dose')
698 | parser.add_argument('--patient', '-p', type=int,
699 | default=-1, help='give patient ID')
700 | parser.add_argument('--time-window', '-t', type=int, default=7,
701 | help='set how many next days the script look for slots (default = 7)')
702 | parser.add_argument(
703 | '--center', '-c', action='append', help='filter centers')
704 | parser.add_argument(
705 | '--zipcode', action='append', help='filter centers by zipcode (e.g. 76012)', type=str)
706 | parser.add_argument('--center-regex',
707 | action='append', help='filter centers by regex')
708 | parser.add_argument('--center-exclude', '-x',
709 | action='append', help='exclude centers')
710 | parser.add_argument('--center-exclude-regex',
711 | action='append', help='exclude centers by regex')
712 | parser.add_argument(
713 | '--include-neighbor-city', '-n', action='store_true', help='include neighboring cities')
714 | parser.add_argument('--start-date', type=str, default=None,
715 | help='first date on which you want to book the first slot (format should be DD/MM/YYYY)')
716 | parser.add_argument('--end-date', type=str, default=None,
717 | help='last date on which you want to book the first slot (format should be DD/MM/YYYY)')
718 | parser.add_argument('--weekday-exclude', '-w', nargs='*', type=str, default=[], action='append',
719 | help='Exclude specific weekdays, e.g. "tuesday Wednesday FRIDAY"')
720 | parser.add_argument('--dry-run', action='store_true',
721 | help='do not really book the slot')
722 | parser.add_argument('--confirm', action='store_true',
723 | help='prompt to confirm before booking')
724 | parser.add_argument(
725 | 'country', help='country where to book', choices=list(doctolib_map.keys()))
726 | parser.add_argument('city', help='city where to book')
727 | parser.add_argument('username', help='Doctolib username')
728 | parser.add_argument('password', nargs='?', help='Doctolib password')
729 | parser.add_argument('--code', type=str, default=None, help='2FA code')
730 | args = parser.parse_args(cli_args if cli_args else sys.argv[1:])
731 |
732 | if args.debug:
733 | responses_dirname = tempfile.mkdtemp(prefix='woob_session_')
734 | self.setup_loggers(logging.DEBUG)
735 | else:
736 | responses_dirname = None
737 | self.setup_loggers(logging.WARNING)
738 |
739 | if not args.password:
740 | args.password = getpass.getpass()
741 |
742 | docto = doctolib_map[args.country](
743 | args.username, args.password, responses_dirname=responses_dirname)
744 | docto.load_state(self.load_state())
745 |
746 | try:
747 | if not docto.do_login(args.code):
748 | return 1
749 |
750 | patients = docto.get_patients()
751 | if len(patients) == 0:
752 | print("It seems that you don't have any Patient registered in your Doctolib account. Please fill your Patient data on Doctolib Website.")
753 | return 1
754 | if args.patient >= 0 and args.patient < len(patients):
755 | docto.patient = patients[args.patient]
756 | elif len(patients) > 1:
757 | print('Available patients are:')
758 | for i, patient in enumerate(patients):
759 | print('* [%s] %s %s' %
760 | (i, patient['first_name'], patient['last_name']))
761 | while True:
762 | print('For which patient do you want to book a slot?',
763 | end=' ', flush=True)
764 | try:
765 | docto.patient = patients[int(sys.stdin.readline().strip())]
766 | except (ValueError, IndexError):
767 | continue
768 | else:
769 | break
770 | else:
771 | docto.patient = patients[0]
772 |
773 | motives = []
774 | if not args.pfizer and not args.moderna and not args.janssen and not args.astrazeneca:
775 | if args.only_second:
776 | motives.append(docto.KEY_PFIZER_SECOND)
777 | motives.append(docto.KEY_MODERNA_SECOND)
778 | # motives.append(docto.KEY_ASTRAZENECA_SECOND) #do not add AstraZeneca by default
779 | elif args.only_third:
780 | if not docto.KEY_PFIZER_THIRD and not docto.KEY_MODERNA_THIRD:
781 | print('Invalid args: No third shot vaccinations in this country')
782 | return 1
783 | motives.append(docto.KEY_PFIZER_THIRD)
784 | motives.append(docto.KEY_MODERNA_THIRD)
785 | else:
786 | motives.append(docto.KEY_PFIZER)
787 | motives.append(docto.KEY_MODERNA)
788 | motives.append(docto.KEY_JANSSEN)
789 | # motives.append(docto.KEY_ASTRAZENECA) #do not add AstraZeneca by default
790 | if args.pfizer:
791 | if args.only_second:
792 | motives.append(docto.KEY_PFIZER_SECOND)
793 | elif args.only_third:
794 | if not docto.KEY_PFIZER_THIRD: # not available in all countries
795 | print('Invalid args: Pfizer has no third shot in this country')
796 | return 1
797 | motives.append(docto.KEY_PFIZER_THIRD)
798 | else:
799 | motives.append(docto.KEY_PFIZER)
800 | if args.moderna:
801 | if args.only_second:
802 | motives.append(docto.KEY_MODERNA_SECOND)
803 | elif args.only_third:
804 | if not docto.KEY_MODERNA_THIRD: # not available in all countries
805 | print('Invalid args: Moderna has no third shot in this country')
806 | return 1
807 | motives.append(docto.KEY_MODERNA_THIRD)
808 | else:
809 | motives.append(docto.KEY_MODERNA)
810 | if args.janssen:
811 | if args.only_second or args.only_third:
812 | print('Invalid args: Janssen has no second or third shot')
813 | return 1
814 | else:
815 | motives.append(docto.KEY_JANSSEN)
816 | if args.astrazeneca:
817 | if args.only_second:
818 | motives.append(docto.KEY_ASTRAZENECA_SECOND)
819 | elif args.only_third:
820 | print('Invalid args: AstraZeneca has no third shot')
821 | return 1
822 | else:
823 | motives.append(docto.KEY_ASTRAZENECA)
824 |
825 | vaccine_list = [docto.vaccine_motives[motive] for motive in motives]
826 |
827 | if args.start_date:
828 | try:
829 | start_date = datetime.datetime.strptime(
830 | args.start_date, '%d/%m/%Y').date()
831 | except ValueError as e:
832 | print('Invalid value for --start-date: %s' % e)
833 | return 1
834 | else:
835 | start_date = datetime.date.today()
836 | if args.end_date:
837 | try:
838 | end_date = datetime.datetime.strptime(
839 | args.end_date, '%d/%m/%Y').date()
840 | except ValueError as e:
841 | print('Invalid value for --end-date: %s' % e)
842 | return 1
843 | else:
844 | end_date = start_date + relativedelta(days=args.time_window)
845 |
846 | _day_names = dict((name.lower(), k) for k, name in enumerate(calendar.day_name))
847 | try:
848 | excluded_weekdays = [d for days in args.weekday_exclude for d in days]
849 | excluded_weekdays = set(sorted([_day_names[d.lower()] for d in excluded_weekdays]))
850 | except KeyError as e:
851 | print('Invalid element value for --excluded-weekday: %s' % e)
852 | return 1
853 |
854 | log('Starting to look for vaccine slots for %s %s between %s and %s...',
855 | docto.patient['first_name'], docto.patient['last_name'], start_date, end_date)
856 | if len(excluded_weekdays) != 0:
857 | log('Excluded weekdays: %s', ', '.join([calendar.day_name[d] for d in excluded_weekdays]))
858 | log('Vaccines: %s', ', '.join(vaccine_list))
859 | log('Country: %s ', args.country)
860 | log('This may take a few minutes/hours, be patient!')
861 | cities = [docto.normalize(city) for city in args.city.split(',')]
862 |
863 | while True:
864 | log_ts()
865 | try:
866 | for center in docto.find_centers(cities, motives):
867 | if not args.include_neighbor_city and not docto.normalize(center['city']).startswith(tuple(cities)):
868 | logging.debug("Skipping city '%(city)s' %(name_with_title)s" % center)
869 | continue
870 | if args.center:
871 | if center['name_with_title'] not in args.center:
872 | logging.debug("Skipping center '%s'" %
873 | center['name_with_title'])
874 | continue
875 | if args.zipcode:
876 | center_matched = False
877 | for zipcode in args.zipcode:
878 | if center['zipcode'] == zipcode:
879 | center_matched = True
880 | if not center_matched:
881 | logging.debug("Skipping center '%(name_with_title)s' ['%(zipcode)s']" % center)
882 | continue
883 | if args.center_regex:
884 | center_matched = False
885 | for center_regex in args.center_regex:
886 | if re.match(center_regex, center['name_with_title']):
887 | center_matched = True
888 | else:
889 | logging.debug(
890 | "Skipping center '%(name_with_title)s'" % center)
891 | if not center_matched:
892 | continue
893 | if args.center_exclude:
894 | if center['name_with_title'] in args.center_exclude:
895 | logging.debug(
896 | "Skipping center '%(name_with_title)s' because it's excluded" % center)
897 | continue
898 | if args.center_exclude_regex:
899 | center_excluded = False
900 | for center_exclude_regex in args.center_exclude_regex:
901 | if re.match(center_exclude_regex, center['name_with_title']):
902 | logging.debug(
903 | "Skipping center '%(name_with_title)s' because it's excluded" % center)
904 | center_excluded = True
905 | if center_excluded:
906 | continue
907 |
908 | log('')
909 |
910 | log('Center %(name_with_title)s (%(city)s):' % center)
911 |
912 | if docto.try_to_book(center, vaccine_list, start_date, end_date, excluded_weekdays, args.only_second, args.only_third, args.dry_run, args.confirm):
913 | log('')
914 | log('💉 %s Congratulations.' %
915 | colored('Booked!', 'green', attrs=('bold',)))
916 | return 0
917 |
918 | sleep(SLEEP_INTERVAL_AFTER_CENTER)
919 |
920 | log('')
921 | log('No free slots found at selected centers. Trying another round in %s sec...', SLEEP_INTERVAL_AFTER_RUN)
922 | sleep(SLEEP_INTERVAL_AFTER_RUN)
923 | except CityNotFound as e:
924 | print('\n%s: City %s not found. Make sure you selected a city from the available countries.' % (
925 | colored('Error', 'red'), colored(e, 'yellow')))
926 | return 1
927 | except WaitingInQueue as waiting_time:
928 | log('Within the queue, estimated waiting time %s minutes', waiting_time)
929 | sleep(30)
930 | except (ReadTimeout, ConnectionError, NewConnectionError) as e:
931 | print('\n%s' % (colored(
932 | 'Connection error. Check your internet connection. Retrying ...', 'red')))
933 | print(str(e))
934 | sleep(SLEEP_INTERVAL_AFTER_CONNECTION_ERROR)
935 | except Exception as e:
936 | template = "An unexpected exception of type {0} occurred. Arguments:\n{1!r}"
937 | message = template.format(type(e).__name__, e.args)
938 | print(message)
939 | if args.debug:
940 | print(get_backtrace())
941 | return 1
942 | return 0
943 | finally:
944 | self.save_state(docto.dump_state())
945 |
946 |
947 | if __name__ == '__main__':
948 | try:
949 | sys.exit(Application().main())
950 | except KeyboardInterrupt:
951 | print('Abort.')
952 | sys.exit(1)
953 |
--------------------------------------------------------------------------------