├── doc ├── iphone-guide.jpg ├── google_calendar_step_1.png └── google_calendar_step_2.png ├── requirements.txt ├── LICENSE ├── README.md ├── .github └── workflows │ └── refresh.yml ├── .gitignore └── prodcal_ics.py /doc/iphone-guide.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nikitastupin/prodcal_ics/HEAD/doc/iphone-guide.jpg -------------------------------------------------------------------------------- /doc/google_calendar_step_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nikitastupin/prodcal_ics/HEAD/doc/google_calendar_step_1.png -------------------------------------------------------------------------------- /doc/google_calendar_step_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nikitastupin/prodcal_ics/HEAD/doc/google_calendar_step_2.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | certifi==2019.6.16 2 | chardet==3.0.4 3 | icalendar==4.0.3 4 | idna==2.8 5 | lxml==4.6.5 6 | more-itertools==7.2.0 7 | python-dateutil==2.8.0 8 | pytz==2019.2 9 | requests==2.22.0 10 | six==1.12.0 11 | urllib3==1.25.8 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 nikitastupin 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Как использовать? 2 | 3 | Ссылка на подписной календарь: https://prodcal.nikitastupin.com/prodcal.ics 4 | 5 | ### Настройка подписного календаря на iOS 6 | ![Шаг 1](doc/iphone-guide.jpg) 7 | 8 | ### Настройка подписного календаря на MacOS 9 | 10 | В приложении Календарь: Файл -> Новая подписка на календарь... -> Ввести ссылку выше 11 | 12 | ### Настройка подписного календаря в Android 13 | 14 | Похоже через Google Calendar на телефоне не получится подписаться, поэтому смотри пункт `Настройка подписного календаря в Google Calendar`. 15 | 16 | ### Настройка подписного календаря в Google Calendar 17 | 18 | Переходим на `calendar.google.com`, выбираем `Добавить по URL`: 19 | ![Шаг 1](doc/google_calendar_step_1.png) 20 | 21 | В поле `URL календаря` вводим `https://prodcal.nikitastupin.com/prodcal.ics`, нажимаем `Добавить календарь`: 22 | 23 | ![Шаг 2](doc/google_calendar_step_2.png) 24 | 25 | Все! :) 26 | 27 | ## Как поднять у себя на сервере 28 | 29 | 1. Установить необходимые модули для Python: 30 | ``` 31 | $ pip3 install -r requirements.txt 32 | ``` 33 | 1. Настроить автообновление календаря: 34 | ``` 35 | $ crontab -l 36 | 0 1 * * * python3 /home/ubuntu/prodcal_ics.py --start-year=2018 -o /home/ubuntu/www/prodcal.ics 37 | ``` 38 | 1. Отдавать файл любым сервером prodcal.ics (например, nginx) 39 | 40 | ## Разработка 41 | 42 | https://icalendar.org/validator.html 43 | -------------------------------------------------------------------------------- /.github/workflows/refresh.yml: -------------------------------------------------------------------------------- 1 | name: Refresh ICS file 2 | 3 | on: 4 | schedule: 5 | - cron: '37 13 * * *' 6 | workflow_dispatch: 7 | 8 | jobs: 9 | fetch: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v4 13 | - name: Install dependencies 14 | run: sudo apt-get install libxml2-dev libxslt-dev 15 | - uses: actions/setup-python@v5 16 | with: 17 | python-version: 3.8 18 | cache: 'pip' 19 | - run: pip install -r requirements.txt 20 | - name: Fetch data and produce prodcal.ics 21 | run: python prodcal_ics.py --start-year=2018 -o /tmp/prodcal.ics 22 | - uses: actions/upload-artifact@v4 23 | with: 24 | name: prodcal.ics 25 | path: /tmp/prodcal.ics 26 | 27 | upload: 28 | runs-on: ubuntu-latest 29 | needs: fetch 30 | steps: 31 | - uses: actions/checkout@v4 32 | with: 33 | ref: gh-pages 34 | 35 | - uses: actions/download-artifact@v4 36 | with: 37 | name: prodcal.ics 38 | 39 | - name: Push changes if any 40 | run: | 41 | if [[ $(git status -s prodcal.ics) ]]; then 42 | git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com" 43 | git config --local user.name "github-actions[bot]" 44 | 45 | git add prodcal.ics && \ 46 | git commit -m "Update prodcal.ics" && \ 47 | git push 48 | fi 49 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | -------------------------------------------------------------------------------- /prodcal_ics.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | from icalendar import Calendar, Event 5 | from lxml import html 6 | import requests 7 | 8 | from datetime import datetime, timedelta 9 | import argparse 10 | import logging 11 | import hashlib 12 | 13 | 14 | def get_holidays_grouped_by_months(year): 15 | url = f"https://hh.ru/article/calendar{year}" 16 | 17 | logging.info(url) 18 | 19 | headers = {"User-Agent": "curl/7.68.0"} 20 | 21 | page = requests.get(url, headers=headers, allow_redirects=True) 22 | 23 | if page.status_code == 404: 24 | return None 25 | 26 | tree = html.fromstring(page.content) 27 | months = tree.xpath( 28 | "//div[@class='calendar-list__item__title' or @class='calendar-list__item-title']/.." 29 | ) 30 | 31 | if len(months) != 12: 32 | raise Exception( 33 | f"len(months) ({year} year) must be equal to 12, actual: {len(months)}" 34 | ) 35 | 36 | holidays = [] 37 | 38 | for m in months: 39 | holidays_in_month = m.xpath( 40 | ".//li[contains(@class, 'calendar-list__numbers__item_day-off')]/text()" 41 | ) 42 | holidays_in_month = [day.strip() for day in holidays_in_month if day.strip()] 43 | holidays.append([int(day) for day in holidays_in_month]) 44 | 45 | return holidays 46 | 47 | 48 | def create_dayoff_event(year, month, day_start, day_end): 49 | event = Event() 50 | event.add("summary", "Выходной") 51 | event.add("dtstart", datetime(year, month, day_start, 0, 0, 0).date()) 52 | event.add( 53 | "dtend", datetime(year, month, day_end, 0, 0, 0).date() + timedelta(days=1) 54 | ) 55 | 56 | # UID is REQUIRED https://tools.ietf.org/html/rfc5545#section-3.6.1 57 | uid = hashlib.sha512( 58 | f"{year}{month}{day_start}{day_end}".encode("ascii") 59 | ).hexdigest() 60 | event.add("uid", uid) 61 | 62 | return event 63 | 64 | 65 | def generate_events(year, holidays_by_months): 66 | import more_itertools as mit 67 | 68 | events = [] 69 | 70 | for month, holidays in enumerate(holidays_by_months, start=1): 71 | holidays_groups = [list(group) for group in mit.consecutive_groups(holidays)] 72 | 73 | for g in holidays_groups: 74 | e = create_dayoff_event(year, month, g[0], g[-1]) 75 | events.append(e) 76 | 77 | return events 78 | 79 | 80 | def parse_args(): 81 | parser = argparse.ArgumentParser( 82 | description="This script fetches data about production calendar and generates .ics file with it." 83 | ) 84 | 85 | default_output_file = "test.ics" 86 | parser.add_argument( 87 | "-o", 88 | dest="output_file", 89 | metavar="out", 90 | default=default_output_file, 91 | help="output file (default: {0})".format(default_output_file), 92 | ) 93 | 94 | parser.add_argument( 95 | "--start-year", 96 | metavar="yyyy", 97 | type=int, 98 | default=datetime.today().year, 99 | help="year calendar starts (default: current year)", 100 | ) 101 | 102 | parser.add_argument( 103 | "--end-year", 104 | metavar="yyyy", 105 | type=int, 106 | default=(datetime.today().year + 1), 107 | help="year calendar ends (default: next year)", 108 | ) 109 | 110 | parser.add_argument("--log-level", metavar="level", default="INFO") 111 | 112 | return parser.parse_args() 113 | 114 | 115 | def generate_calendar(events): 116 | cal = Calendar() 117 | cal.add("prodid", "-//My calendar product//mxm.dk//") 118 | cal.add("version", "2.0") 119 | cal.add("NAME", "Производственный календарь") 120 | cal.add("X-WR-CALNAME", "Производственный календарь") 121 | 122 | for e in events: 123 | cal.add_component(e) 124 | 125 | return cal 126 | 127 | 128 | def setup_logging(log_level): 129 | logging_level = getattr(logging, log_level.upper(), None) 130 | 131 | if not isinstance(logging_level, int): 132 | raise ValueError("Invalid log level: {0}".format(log_level)) 133 | 134 | logging.basicConfig( 135 | level=logging_level, 136 | format="%(asctime)s [%(levelname)s] %(message)s", 137 | datefmt="[%d/%m/%Y:%H:%M:%S %z]", 138 | ) 139 | 140 | 141 | if __name__ == "__main__": 142 | args = parse_args() 143 | setup_logging(args.log_level) 144 | 145 | events = [] 146 | 147 | # (args.end_year + 1) because range() function doesn't include right margin 148 | for year in range(args.start_year, args.end_year + 1, 1): 149 | holidays_by_months = get_holidays_grouped_by_months(year) 150 | 151 | if not holidays_by_months: 152 | break 153 | 154 | events += generate_events(year, holidays_by_months) 155 | 156 | cal = generate_calendar(events) 157 | 158 | with open(args.output_file, "w") as f: 159 | f.write(cal.to_ical().decode("utf-8")) 160 | --------------------------------------------------------------------------------