├── calbot
├── __init__.py
├── commands
│ ├── __init__.py
│ ├── add.py
│ ├── format.py
│ ├── advance.py
│ ├── lang.py
│ └── cal.py
├── classes.puml
├── processing.py
├── stats.py
├── bot.py
├── formatting.py
├── ical.py
└── conf.py
├── ansible
├── roles
│ ├── letsencrypt
│ │ ├── tests
│ │ │ ├── inventory
│ │ │ └── test.yml
│ │ ├── vars
│ │ │ ├── default.yml
│ │ │ ├── Debian-7.yml
│ │ │ └── Ubuntu-14.yml
│ │ ├── meta
│ │ │ └── main.yml
│ │ ├── defaults
│ │ │ └── main.yml
│ │ ├── README.md
│ │ ├── tasks
│ │ │ └── main.yml
│ │ └── LICENSE
│ ├── python
│ │ ├── defaults
│ │ │ └── main.yml
│ │ └── tasks
│ │ │ ├── main.yml
│ │ │ ├── python-install.yml
│ │ │ └── pyenv-install.yml
│ ├── common
│ │ ├── tasks
│ │ │ ├── apt-update.yml
│ │ │ ├── ntp-install.yml
│ │ │ ├── cron-install.yml
│ │ │ ├── locales-config.yml
│ │ │ ├── timezone-config.yml
│ │ │ ├── unattended-upgrades-install.yml
│ │ │ ├── iptables-config.yml
│ │ │ └── main.yml
│ │ ├── files
│ │ │ ├── 20auto-upgrades
│ │ │ ├── iptables.rules.v4
│ │ │ └── iptables.rules.v6
│ │ └── handlers
│ │ │ └── main.yml
│ ├── locales
│ │ ├── tasks
│ │ │ ├── main.yml
│ │ │ └── locales-config.yml
│ │ └── defaults
│ │ │ └── main.yml
│ ├── bot-deploy
│ │ ├── tasks
│ │ │ ├── main.yml
│ │ │ └── bot-deploy.yml
│ │ ├── handlers
│ │ │ └── main.yml
│ │ ├── defaults
│ │ │ └── main.yml
│ │ └── templates
│ │ │ └── bot.cfg
│ ├── nginx-bot
│ │ ├── tasks
│ │ │ ├── nginx-install.yml
│ │ │ ├── main.yml
│ │ │ └── nginx-config.yml
│ │ ├── handlers
│ │ │ └── main.yml
│ │ ├── defaults
│ │ │ └── main.yml
│ │ └── templates
│ │ │ └── config
│ ├── nginx
│ │ ├── tasks
│ │ │ ├── main.yml
│ │ │ └── nginx-install.yml
│ │ └── handlers
│ │ │ └── main.yml
│ └── bot-provision
│ │ ├── tasks
│ │ ├── main.yml
│ │ └── bot-provision.yml
│ │ ├── handlers
│ │ └── main.yml
│ │ ├── defaults
│ │ └── main.yml
│ │ └── templates
│ │ └── bot.service
├── hosts
├── ansible.cfg
├── Makefile
├── deploy.yml
├── provision.yml
└── group_vars
│ └── bothosts.yml.sample
├── icon.png
├── .hgignore
├── requirements.txt
├── .gitignore
├── calbot.cfg.sample
├── .editorconfig
├── Makefile
├── calbot.py
├── test
├── test.ics
└── repeat.ics
├── README.md
└── calbot_test.py
/calbot/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/calbot/commands/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/ansible/roles/letsencrypt/tests/inventory:
--------------------------------------------------------------------------------
1 | localhost
2 |
--------------------------------------------------------------------------------
/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/gelin/calendar-bot/HEAD/icon.png
--------------------------------------------------------------------------------
/ansible/roles/letsencrypt/vars/default.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | virtualenv_package_name: virtualenv
4 |
--------------------------------------------------------------------------------
/ansible/roles/python/defaults/main.yml:
--------------------------------------------------------------------------------
1 | pyenv_root: '/opt/pyenv'
2 | python_version: '3.9.18'
3 |
--------------------------------------------------------------------------------
/ansible/roles/common/tasks/apt-update.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | - name: apt-get update
4 | apt:
5 | update_cache: yes
6 |
--------------------------------------------------------------------------------
/ansible/roles/letsencrypt/vars/Debian-7.yml:
--------------------------------------------------------------------------------
1 | --- # Debian wheezy
2 |
3 | virtualenv_package_name: python-virtualenv
4 |
--------------------------------------------------------------------------------
/ansible/roles/letsencrypt/vars/Ubuntu-14.yml:
--------------------------------------------------------------------------------
1 | --- # Ubuntu Trusty
2 |
3 | virtualenv_package_name: python-virtualenv
4 |
--------------------------------------------------------------------------------
/ansible/roles/locales/tasks/main.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | - import_tasks: 'locales-config.yml'
4 | tags:
5 | - locales
6 |
--------------------------------------------------------------------------------
/ansible/roles/common/files/20auto-upgrades:
--------------------------------------------------------------------------------
1 | APT::Periodic::Update-Package-Lists "1";
2 | APT::Periodic::Unattended-Upgrade "1";
3 |
--------------------------------------------------------------------------------
/ansible/roles/common/tasks/ntp-install.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | - name: install ntp
4 | apt:
5 | name: 'ntp'
6 | state: present
7 |
--------------------------------------------------------------------------------
/ansible/hosts:
--------------------------------------------------------------------------------
1 | [all:vars]
2 | ansible_user=root
3 |
4 | [bothosts]
5 | #rbx1-fr.quadhost.net
6 | #sandbox1.gelin.ru
7 | au1.gelin.ru
8 |
--------------------------------------------------------------------------------
/ansible/roles/bot-deploy/tasks/main.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | - import_tasks: 'bot-deploy.yml'
4 | tags:
5 | - bot
6 | - bot:deploy
7 |
--------------------------------------------------------------------------------
/ansible/roles/common/tasks/cron-install.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | - name: install cron
4 | apt:
5 | name: 'cron'
6 | state: present
7 |
--------------------------------------------------------------------------------
/ansible/roles/nginx-bot/tasks/nginx-install.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | - name: install nginx
4 | apt:
5 | name: 'nginx'
6 | state: present
7 |
--------------------------------------------------------------------------------
/ansible/roles/nginx/tasks/main.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | - import_tasks: 'nginx-install.yml'
4 | tags:
5 | - nginx
6 | - nginx:install
7 |
--------------------------------------------------------------------------------
/.hgignore:
--------------------------------------------------------------------------------
1 | syntax: glob
2 |
3 | *.iml
4 | .idea/*
5 |
6 | *.retry
7 |
8 | var/*
9 |
10 | ansible/group_vars/*.yml
11 | calbot.cfg
12 |
--------------------------------------------------------------------------------
/ansible/ansible.cfg:
--------------------------------------------------------------------------------
1 | [defaults]
2 | inventory = hosts
3 | # host_key_checking = False
4 | roles_path = roles
5 | pipelining = True
6 | nocows = 1
7 |
--------------------------------------------------------------------------------
/ansible/roles/bot-provision/tasks/main.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | - import_tasks: 'bot-provision.yml'
4 | tags:
5 | - bot
6 | - bot:provision
7 |
--------------------------------------------------------------------------------
/ansible/roles/bot-deploy/handlers/main.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | - name: restart bot
4 | service:
5 | name: '{{ bot_service_name }}'
6 | state: restarted
7 |
--------------------------------------------------------------------------------
/ansible/roles/common/tasks/locales-config.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | - name: configure locales
4 | locale_gen:
5 | name: 'en_US.UTF-8'
6 | state: present
7 |
--------------------------------------------------------------------------------
/ansible/roles/nginx-bot/handlers/main.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: restart nginx
3 | service:
4 | name: 'nginx'
5 | state: restarted
6 | enabled: yes
7 |
--------------------------------------------------------------------------------
/ansible/roles/nginx/handlers/main.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | - name: restart nginx
4 | service:
5 | name: 'nginx'
6 | state: started
7 | enabled: yes
8 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | python-telegram-bot == 9.0.0
2 | icalendar == 3.8
3 | python-dateutil == 2.8.1
4 | recurring-ical-events == 1.0.2b0
5 | raven == 6.0.0
6 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .idea/*
3 |
4 | *.retry
5 |
6 | var/*
7 |
8 | ansible/group_vars/*.yml
9 | calbot.cfg
10 |
11 | .python-version
12 | bak/*
13 |
--------------------------------------------------------------------------------
/ansible/roles/nginx/tasks/nginx-install.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | - name: install nginx
4 | apt:
5 | name: 'nginx'
6 | state: present
7 | notify: start nginx
8 |
--------------------------------------------------------------------------------
/ansible/Makefile:
--------------------------------------------------------------------------------
1 | .PHONY: deploy
2 | deploy:
3 | ansible-playbook -i hosts deploy.yml
4 |
5 | .PHONY: provision
6 | provision:
7 | ansible-playbook -i hosts provision.yml
8 |
--------------------------------------------------------------------------------
/ansible/roles/locales/tasks/locales-config.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | - name: generate locales
4 | locale_gen:
5 | name: '{{ item }}'
6 | state: present
7 | with_items: '{{ locales_install }}'
8 |
--------------------------------------------------------------------------------
/ansible/roles/nginx-bot/defaults/main.yml:
--------------------------------------------------------------------------------
1 | ---
2 | bot_domain: bot.telegram.example.com
3 | bot_token: '225478221:AAFvpu4aBjixXmDJKAWVO3wNMjWFpxlkcHY'
4 | bot_webhook_port: 5000
5 | bot_site_config: bot
6 |
--------------------------------------------------------------------------------
/ansible/deploy.yml:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env ansible-playbook
2 |
3 | ---
4 | - name: Copies bot files, restarts the bot
5 | hosts: bothosts
6 | remote_user: root
7 |
8 | roles:
9 | - bot-deploy
10 |
--------------------------------------------------------------------------------
/ansible/roles/common/handlers/main.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | - name: restart iptables
4 | service: name=netfilter-persistent state=restarted
5 |
6 | - name: update timezone
7 | command: dpkg-reconfigure --frontend noninteractive tzdata
8 |
--------------------------------------------------------------------------------
/ansible/roles/nginx-bot/tasks/main.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | - import_tasks: 'nginx-install.yml'
4 | tags:
5 | - nginx
6 | - nginx:install
7 |
8 | - import_tasks: 'nginx-config.yml'
9 | tags:
10 | - nginx
11 | - nginx:config
12 |
--------------------------------------------------------------------------------
/ansible/roles/python/tasks/main.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | - import_tasks: 'python-install.yml'
4 | tags:
5 | - python
6 | - python:install
7 |
8 | - import_tasks: 'pyenv-install.yml'
9 | tags:
10 | - python
11 | - python:install
12 |
--------------------------------------------------------------------------------
/ansible/provision.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - name: Install Python, Nginx, Letsencypt
3 | hosts: bothosts
4 |
5 | roles:
6 | # - common
7 | - locales
8 | - python
9 | # - nginx
10 | # - letsencrypt
11 | # - nginx-bot
12 | - bot-provision
13 |
--------------------------------------------------------------------------------
/ansible/roles/bot-deploy/defaults/main.yml:
--------------------------------------------------------------------------------
1 | ---
2 | bot_token: '225478221:AAFvpu4aBjixXmDJKAWVO3wNMjWFpxlkcHY'
3 | bot_webhook_listen: '127.0.0.1'
4 | bot_webhook_port: 5000
5 | bot_bootstrap_retries: -1
6 |
7 | bot_python: '/opt/pyenv/versions/3.9.18/bin/python'
8 |
--------------------------------------------------------------------------------
/ansible/roles/bot-provision/handlers/main.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | - name: reload systemd
4 | command: systemctl daemon-reload
5 | notify: restart bot
6 |
7 | - name: restart bot
8 | service:
9 | name: '{{ bot_service_name }}'
10 | state: restarted
11 |
--------------------------------------------------------------------------------
/ansible/roles/bot-provision/defaults/main.yml:
--------------------------------------------------------------------------------
1 | ---
2 | bot_user: bot
3 | bot_basedir: /opt/bot
4 | bot_service_name: bot
5 | bot_service_description: 'Telegram bot'
6 |
7 | bot_python: '/opt/pyenv/versions/3.9.18/bin/python'
8 |
9 | bot_restart_interval: '24h'
10 |
--------------------------------------------------------------------------------
/ansible/roles/common/tasks/timezone-config.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | - name: set timezone variables
4 | copy:
5 | content: "Asia/Omsk\n"
6 | dest: '/etc/timezone'
7 | owner: 'root'
8 | group: 'root'
9 | mode: '0644'
10 | backup: yes
11 | notify: update timezone
12 |
--------------------------------------------------------------------------------
/ansible/roles/common/tasks/unattended-upgrades-install.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | - name: install unattended-upgrades
4 | apt:
5 | name: 'unattended-upgrades'
6 | state: present
7 |
8 | - name: configure unattended-upgrades
9 | copy:
10 | src: '20auto-upgrades'
11 | dest: '/etc/apt/apt.conf.d'
12 |
--------------------------------------------------------------------------------
/ansible/roles/python/tasks/python-install.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | - name: install python3
4 | apt:
5 | name:
6 | - 'python3'
7 | - 'python3-pip'
8 | - 'python3-virtualenv'
9 | state: present
10 |
11 | #- name: install secondary dependencies
12 | # apt:
13 | # name:
14 | # - 'python3-urllib3'
15 | # state: present
16 |
--------------------------------------------------------------------------------
/ansible/roles/letsencrypt/tests/test.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | - hosts: localhost
4 | remote_user: root
5 |
6 | vars:
7 | letsencrypt_email: admin@example.com
8 | letsencrypt_cert_domains:
9 | - www.example.com
10 | letsencrypt_server: https://acme-staging.api.letsencrypt.org/directory
11 |
12 | roles:
13 | - ansible-letsencrypt
14 |
--------------------------------------------------------------------------------
/calbot.cfg.sample:
--------------------------------------------------------------------------------
1 | [bot]
2 | token = 225478221:AAFvpu4aBjixXmDJKAWVO3wNMjWFpxlkcHY
3 | vardir = var
4 | interval = 3600
5 | bootstrap_retries = -1
6 | errors_count_threshold = 3
7 |
8 | #[polling]
9 | #poll_interval = 15
10 | #timeout = 0
11 | #read_latency = 15
12 |
13 | [webhook]
14 | webhook = yes
15 | domain = bot.example.com
16 | listen = 127.0.0.1
17 | port = 5000
18 |
--------------------------------------------------------------------------------
/ansible/roles/common/files/iptables.rules.v4:
--------------------------------------------------------------------------------
1 | # {{ ansible_managed }}
2 | *filter
3 | -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
4 | -A INPUT -p icmp -j ACCEPT
5 | -A INPUT -i lo -j ACCEPT
6 | -A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
7 | -A INPUT -j REJECT --reject-with icmp-host-prohibited
8 | -A FORWARD -j REJECT --reject-with icmp-host-prohibited
9 | COMMIT
10 |
--------------------------------------------------------------------------------
/ansible/roles/bot-deploy/templates/bot.cfg:
--------------------------------------------------------------------------------
1 | [bot]
2 | token = {{ bot_token }}
3 | vardir = {{ bot_basedir }}/var
4 | interval = 3600
5 | bootstrap_retries = {{ bot_bootstrap_retries }}
6 |
7 | #[polling]
8 | #poll_interval = 10
9 | #timeout = 10
10 | #read_latency = 15
11 |
12 | [webhook]
13 | webhook = no
14 | domain = {{ bot_domain }}
15 | listen = {{ bot_webhook_listen }}
16 | port = {{ bot_webhook_port }}
17 |
--------------------------------------------------------------------------------
/ansible/roles/common/tasks/iptables-config.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | - name: install iptables-persistent
4 | apt:
5 | name: 'iptables-persistent'
6 | state: present
7 |
8 | - name: set up iptables rules
9 | copy:
10 | src: 'iptables.rules.v4'
11 | dest: '/etc/iptables/rules.v4'
12 | notify: restart iptables
13 |
14 | - name: set up ip6tables rules
15 | copy:
16 | src: 'iptables.rules.v6'
17 | dest: '/etc/iptables/rules.v6'
18 | notify: restart iptables
19 |
--------------------------------------------------------------------------------
/ansible/group_vars/bothosts.yml.sample:
--------------------------------------------------------------------------------
1 | ---
2 | bot_domain: bot.telegram.example.com
3 | bot_token: '225478221:AAFvpu4aBjixXmDJKAWVO3wNMjWFpxlkcHY'
4 | bot_webhook_port: 5000
5 | bot_site_config: bot
6 | bot_user: bot
7 | bot_basedir: /opt/bot
8 | bot_service_name: bot
9 | bot_service_description: 'Telegram bot'
10 |
11 | bot_bootstrap_retries: -1
12 |
13 | sentry_dsn: 'put your dns here'
14 |
15 | letsencrypt_cert_domains:
16 | - "{{ bot.domain }}"
17 | letsencrypt_email: "webmaster@example.com"
18 |
--------------------------------------------------------------------------------
/ansible/roles/common/files/iptables.rules.v6:
--------------------------------------------------------------------------------
1 | # {{ ansible_managed }}
2 | *filter
3 | -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
4 | -A INPUT -p icmp -j ACCEPT
5 | -A INPUT -i lo -j ACCEPT
6 | -A INPUT -p tcp -m state --state NEW -m tcp --dport 443 -j ACCEPT
7 | -A INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT
8 | -A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
9 | -A INPUT -j REJECT --reject-with adm-prohibited
10 | -A FORWARD -j REJECT --reject-with adm-prohibited
11 | COMMIT
12 |
--------------------------------------------------------------------------------
/ansible/roles/locales/defaults/main.yml:
--------------------------------------------------------------------------------
1 | ---
2 | # https://en.wikipedia.org/wiki/List_of_languages_by_total_number_of_speakers
3 | # https://docs.moodle.org/dev/Table_of_locales
4 | locales_install:
5 | - zh_CN.UTF-8
6 | - zh_TW.UTF-8
7 | - en_US.UTF-8
8 | - es_ES.UTF-8
9 | - ar_SA.UTF-8
10 | - ru_RU.UTF-8
11 | - pt_PT.UTF-8
12 | - ms_MY.UTF-8
13 | - fr_FR.UTF-8
14 | - de_DE.UTF-8
15 | - ja_JP.UTF-8
16 | - it_IT.UTF-8
17 | - ko_KR.UTF-8
18 | - tr_TR.UTF-8
19 | - ca_ES.UTF-8
20 | - cs_CZ.UTF-8
21 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | # EditorConfig is awesome: http://EditorConfig.org
2 |
3 | # top-most EditorConfig file
4 | root = true
5 |
6 | # Unix-style newlines with a newline ending every file
7 | [*]
8 | end_of_line = lf
9 | insert_final_newline = true
10 | charset = utf-8
11 |
12 | # Tab indentation (no size specified)
13 | [Makefile]
14 | indent_style = tab
15 | trim_trailing_whitespace = false
16 |
17 | # Indentation override for all JS under lib directory
18 | [*.{js,json,pug,jade}]
19 | indent_style = space
20 | indent_size = 2
21 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | .PHONY: help
2 | help:
3 | @echo "make run | deploy"
4 |
5 | .PHONY: install
6 | install:
7 | python -m pip install --upgrade pip
8 | python -m pip install setuptools
9 | python -m pip install -r requirements.txt
10 |
11 | .PHONY: run
12 | run:
13 | python calbot.py
14 |
15 | .PHONY: test
16 | test:
17 | python -m unittest calbot_test.py
18 |
19 | .PHONY: deploy
20 | deploy:
21 | cd ansible && ansible-playbook deploy.yml
22 |
23 | .PHONY: docker
24 | docker:
25 | docker run -it -v "$$PWD:/calbot" python:3.4.2 /bin/bash
26 |
--------------------------------------------------------------------------------
/ansible/roles/bot-provision/templates/bot.service:
--------------------------------------------------------------------------------
1 | [Unit]
2 | Description={{ bot_service_description }}
3 |
4 | [Service]
5 | Type=simple
6 | ExecStart={{ bot_basedir }}/venv/bin/python {{ bot_basedir }}/calbot.py {{ bot_basedir }}/{{ bot_service_name }}.cfg
7 | WorkingDirectory={{ bot_basedir }}
8 | User={{ bot_user }}
9 | Environment=SENTRY_DSN={{ sentry_dsn }}
10 |
11 | {% if bot_restart_interval is defined %}
12 | Restart=always
13 | RuntimeMaxSec={{ bot_restart_interval }}
14 | {% endif %}
15 |
16 | [Install]
17 | WantedBy=multi-user.target
18 |
--------------------------------------------------------------------------------
/ansible/roles/letsencrypt/meta/main.yml:
--------------------------------------------------------------------------------
1 | ---
2 | galaxy_info:
3 | author: Finn Herzfeld
4 | description: Generate TLS certificates and get them signed by Let's Encrypt.
5 | issue_tracker_url: https://github.com/thefinn93/ansible-letsencrypt/issues
6 | license: GPL
7 | min_ansible_version: 2.0
8 |
9 | platforms:
10 | - name: Ubuntu
11 | versions:
12 | - trusty
13 | - xenial
14 | - name: Debian
15 | versions:
16 | - jessie
17 |
18 | galaxy_tags:
19 | - networking
20 | - web
21 |
22 | dependencies: []
23 |
--------------------------------------------------------------------------------
/ansible/roles/nginx-bot/tasks/nginx-config.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | - name: generate DH params
4 | command: 'openssl dhparam -out /etc/nginx/dhparams.pem 2048'
5 | args:
6 | creates: '/etc/nginx/dhparams.pem'
7 |
8 | - name: copy nginx configuration
9 | template:
10 | src: 'config'
11 | dest: '/etc/nginx/sites-available/{{ bot_site_config }}'
12 | notify: restart nginx
13 |
14 | - name: enable nginx configuration
15 | file:
16 | src: '/etc/nginx/sites-available/{{ bot_site_config }}'
17 | dest: '/etc/nginx/sites-enabled/{{ bot_site_config }}'
18 | state: link
19 | notify: restart nginx
20 |
--------------------------------------------------------------------------------
/ansible/roles/common/tasks/main.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | - import_tasks: 'apt-update.yml'
4 | tags:
5 | - common
6 | - common:apt
7 |
8 | - import_tasks: 'iptables-config.yml'
9 | tags:
10 | - common
11 | - common:iptables
12 |
13 | - import_tasks: 'locales-config.yml'
14 | tags:
15 | - common
16 | - common:locales
17 |
18 | - import_tasks: 'timezone-config.yml'
19 | tags:
20 | - common
21 | - common:timezone
22 |
23 | - import_tasks: 'ntp-install.yml'
24 | tags:
25 | - common
26 | - common:ntp
27 |
28 | - import_tasks: 'cron-install.yml'
29 | tags:
30 | - common
31 | - common:cron
32 |
33 | - import_tasks: 'unattended-upgrades-install.yml'
34 | tags:
35 | - common
36 | - common:upgrades
37 |
--------------------------------------------------------------------------------
/ansible/roles/bot-provision/tasks/bot-provision.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | - name: create bot user
4 | user:
5 | name: '{{ bot_user }}'
6 | system: yes
7 |
8 | - name: create bot dir
9 | file:
10 | path: '{{ bot_basedir }}'
11 | state: directory
12 | owner: '{{ bot_user }}'
13 |
14 | - name: create and update venv
15 | pip:
16 | virtualenv: '{{ bot_basedir }}/venv'
17 | virtualenv_python: '{{ bot_python }}'
18 | name:
19 | - 'pip'
20 | - 'setuptools'
21 | state: latest
22 |
23 | - name: install systemd service
24 | template:
25 | src: bot.service
26 | dest: '/etc/systemd/system/{{ bot_service_name }}.service'
27 | notify: reload systemd
28 |
29 | - name: enable service
30 | service:
31 | name: '{{ bot_service_name }}'
32 | enabled: yes
33 |
34 | - name: start service
35 | service:
36 | name: '{{ bot_service_name }}'
37 | state: started
38 |
--------------------------------------------------------------------------------
/ansible/roles/letsencrypt/defaults/main.yml:
--------------------------------------------------------------------------------
1 | ---
2 | letsencrypt_src_directory: /usr/local/share/letsencrypt
3 | letsencrypt_venv: "{{ letsencrypt_src_directory }}/env"
4 | letsencrypt_cert_domains:
5 | - "example.com"
6 | letsencrypt_webroot_path: /var/www/html
7 | letsencrypt_authenticator: webroot
8 | letsencrypt_email: "webmaster@example.com"
9 | letsencrypt_command: "{{ letsencrypt_venv }}/bin/letsencrypt --agree-tos {% if letsencrypt_rsa_key_size is defined %}--rsa-key-size {{ letsencrypt_rsa_key_size }}{% endif %} --text {% for domain in letsencrypt_cert_domains %}-d {{ domain }} {% endfor %}--email {{ letsencrypt_email }} {% if letsencrypt_server is defined %}--server {{ letsencrypt_server }}{% endif %} --expand"
10 | letsencrypt_renewal_frequency:
11 | day: "*"
12 | hour: 0
13 | minute: 0
14 | letsencrypt_renewal_command_args: '--renew-hook "/usr/sbin/service nginx restart"'
15 |
--------------------------------------------------------------------------------
/ansible/roles/python/tasks/pyenv-install.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | - name: install necessary packages
4 | apt:
5 | name:
6 | - 'git'
7 | # see https://github.com/pyenv/pyenv/wiki#suggested-build-environment
8 | - 'build-essential'
9 | - 'libssl-dev'
10 | - 'zlib1g-dev'
11 | - 'libbz2-dev'
12 | - 'libreadline-dev'
13 | - 'libsqlite3-dev'
14 | - 'curl'
15 | - 'libncursesw5-dev'
16 | - 'xz-utils'
17 | - 'tk-dev'
18 | - 'libxml2-dev'
19 | - 'libxmlsec1-dev'
20 | - 'libffi-dev'
21 | - 'liblzma-dev'
22 |
23 | - name: clone pyenv
24 | git:
25 | repo: 'https://github.com/pyenv/pyenv.git'
26 | dest: '{{ pyenv_root }}'
27 |
28 | - name: install pyenv python
29 | command:
30 | cmd: '{{ pyenv_root }}/bin/pyenv install {{ python_version }}'
31 | creates: '{{ pyenv_root }}/versions/{{ python_version }}'
32 | environment:
33 | PYENV_ROOT: '{{ pyenv_root }}'
34 |
--------------------------------------------------------------------------------
/ansible/roles/bot-deploy/tasks/bot-deploy.yml:
--------------------------------------------------------------------------------
1 | ---
2 |
3 | - name: copy bot files
4 | copy:
5 | src: '../{{ item }}'
6 | dest: '{{ bot_basedir }}/{{ item }}'
7 | owner: '{{ bot_user }}'
8 | group: '{{ bot_user }}'
9 | notify: restart bot
10 | with_items:
11 | - 'calbot.py'
12 | - 'requirements.txt'
13 | - 'COPYING'
14 |
15 | - name: copy bot files
16 | synchronize:
17 | src: '../calbot/'
18 | dest: '{{ bot_basedir }}/calbot/'
19 | rsync_opts:
20 | - '--chown={{ bot_user }}:{{ bot_user }}'
21 | notify: restart bot
22 |
23 | - name: install dependencies
24 | pip:
25 | virtualenv: '{{ bot_basedir }}/venv'
26 | virtualenv_python: '{{ bot_python }}'
27 | requirements: '{{ bot_basedir }}/requirements.txt'
28 | notify: restart bot
29 |
30 | - name: create config
31 | template:
32 | src: bot.cfg
33 | dest: '{{ bot_basedir }}/{{ bot_service_name }}.cfg'
34 | notify: restart bot
35 |
36 | - name: start service
37 | service:
38 | name: '{{ bot_service_name }}'
39 | state: started
40 |
--------------------------------------------------------------------------------
/ansible/roles/nginx-bot/templates/config:
--------------------------------------------------------------------------------
1 | server {
2 |
3 | listen [::]:443 ssl default_server;
4 |
5 | ssl_certificate /etc/letsencrypt/live/{{ bot_domain }}/fullchain.pem;
6 | ssl_certificate_key /etc/letsencrypt/live/{{ bot_domain }}/privkey.pem;
7 | ssl_trusted_certificate /etc/letsencrypt/live/{{ bot_domain }}/chain.pem;
8 |
9 | # https://weakdh.org/sysadmin.html
10 | ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA';
11 | ssl_prefer_server_ciphers on;
12 | ssl_dhparam /etc/nginx/dhparams.pem;
13 |
14 | server_name {{ bot_domain }};
15 |
16 | location /.well-known {
17 | root /var/www/html;
18 | }
19 |
20 | location /{{ bot_token }} {
21 | proxy_pass http://127.0.0.1:{{ bot_webhook_port }};
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/calbot/classes.puml:
--------------------------------------------------------------------------------
1 | @startuml
2 |
3 | class Config <> {
4 | vardir
5 | token
6 | interval
7 | bootstrap_retries
8 | errors_count_threshold
9 | poll_interval
10 | timeout
11 | read_latency
12 | webhook
13 | domain
14 | listen
15 | port
16 | }
17 |
18 | class UserConfig <> {
19 | user_id
20 | format
21 | language
22 | advance
23 | errors_count_threshold
24 | }
25 |
26 | Config *-- UserConfig
27 |
28 | class CalendarConfig <> {
29 | id
30 | user_id^
31 | url
32 | name
33 | channel_id
34 | verified
35 | enabled
36 | format^
37 | language^
38 | advance^
39 | day_start
40 | last_process_at
41 | last_process_error
42 | last_errors_count
43 | errors_count_threshold^
44 | }
45 |
46 | UserConfig *-- CalendarConfig
47 |
48 | class Calendar <> {
49 | url
50 | advance
51 | day_start
52 | name
53 | timezone
54 | description
55 | }
56 |
57 | CalendarConfig -* Calendar
58 |
59 | class EventConfig <> {
60 | id
61 | cal_id
62 | user_id
63 | last_notified
64 | }
65 |
66 | class Event <> {
67 | id
68 | uid
69 | instance_id
70 | title
71 | date
72 | location
73 | description
74 | date
75 | time
76 | notify_datetime
77 | repeat_rule
78 | exception_dates
79 | recurrence_id
80 | notified_for_advance
81 | day_start
82 | }
83 |
84 | EventConfig -* Event
85 |
86 | Calendar *-- "*" Event
87 |
88 | @enduml
89 |
--------------------------------------------------------------------------------
/calbot.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 |
4 | # Copyright 2016 Denis Nelubin.
5 | #
6 | # This file is part of Calendar Bot.
7 | #
8 | # Calendar Bot is free software: you can redistribute it and/or modify
9 | # it under the terms of the GNU General Public License as published by
10 | # the Free Software Foundation, either version 3 of the License, or
11 | # (at your option) any later version.
12 | #
13 | # Calendar Bot is distributed in the hope that it will be useful,
14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | # GNU General Public License for more details.
17 | #
18 | # You should have received a copy of the GNU General Public License
19 | # along with Calendar Bot. If not, see http://www.gnu.org/licenses/.
20 |
21 |
22 | import logging
23 | import os
24 | import sys
25 |
26 | from raven.handlers.logging import SentryHandler
27 | from raven.conf import setup_logging
28 |
29 | from calbot.bot import run_bot
30 | from calbot.conf import Config
31 |
32 |
33 | def main():
34 | if len(sys.argv) > 1:
35 | configfile = sys.argv[1]
36 | else:
37 | configfile = os.path.join(os.path.dirname(__file__), 'calbot.cfg')
38 | config = Config(configfile)
39 | run_bot(config)
40 |
41 |
42 | if __name__ == '__main__':
43 | logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
44 | setup_logging(SentryHandler(level=logging.WARNING))
45 | main()
46 |
--------------------------------------------------------------------------------
/test/test.ics:
--------------------------------------------------------------------------------
1 | BEGIN:VCALENDAR
2 | PRODID:-//Google Inc//Google Calendar 70.9054//EN
3 | VERSION:2.0
4 | CALSCALE:GREGORIAN
5 | METHOD:PUBLISH
6 | X-WR-CALNAME:Тест
7 | X-WR-CALDESC:Just a test calendar
8 |
9 | BEGIN:VTIMEZONE
10 | TZID:Asia/Omsk
11 | X-LIC-LOCATION:Asia/Omsk
12 | BEGIN:STANDARD
13 | TZOFFSETFROM:+0600
14 | TZOFFSETTO:+0600
15 | TZNAME:+06
16 | DTSTART:19700101T000000
17 | END:STANDARD
18 | END:VTIMEZONE
19 |
20 | BEGIN:VEVENT
21 | DTSTART:20160624T000000Z
22 | DTEND:20160624T010000Z
23 | DTSTAMP:20160623T144230Z
24 | UID:lhglai7eabsf1knm3lk7pcnnng@google.com
25 | CREATED:20160623T144059Z
26 | DESCRIPTION:Какое-то описание\nВ две строки
27 | LAST-MODIFIED:20160623T144059Z
28 | LOCATION:Где-то в Омске
29 | SEQUENCE:0
30 | STATUS:CONFIRMED
31 | SUMMARY:Событие по-русски
32 | TRANSP:OPAQUE
33 | END:VEVENT
34 |
35 | BEGIN:VEVENT
36 | DTSTART:20160623T000000Z
37 | DTEND:20160623T010000Z
38 | DTSTAMP:20160623T144230Z
39 | UID:avh1vjkc3bick23mf42oo2lke0@google.com
40 | CREATED:20160622T052053Z
41 | DESCRIPTION:Event description
42 | LAST-MODIFIED:20160622T052053Z
43 | LOCATION:Event location
44 | SEQUENCE:0
45 | STATUS:CONFIRMED
46 | SUMMARY:Event title
47 | TRANSP:OPAQUE
48 | END:VEVENT
49 |
50 | BEGIN:VEVENT
51 | DTSTART;TZID=Asia/Omsk:20170104T100000
52 | DTEND;TZID=Asia/Omsk:20170104T110000
53 | RRULE:FREQ=DAILY
54 | DTSTAMP:20170105T074421Z
55 | UID:37o21h4an4bcqi3728i1oim5uo@google.com
56 | CREATED:20170105T074400Z
57 | DESCRIPTION:
58 | LAST-MODIFIED:20170105T074400Z
59 | LOCATION:
60 | SEQUENCE:0
61 | STATUS:CONFIRMED
62 | SUMMARY:Daily event
63 | TRANSP:OPAQUE
64 | END:VEVENT
65 | END:VCALENDAR
66 |
--------------------------------------------------------------------------------
/ansible/roles/letsencrypt/README.md:
--------------------------------------------------------------------------------
1 | # ansible-letsencrypt
2 | An ansible role to generate TLS certificates and get them signed by Let's Encrypt.
3 |
4 | Currently attempts first to use the `webroot` authenticator, then if that fails to create certificates,
5 | it will use the standalone authenticator. This is handy for generating certs on a fresh machine before
6 | the web server has been configured or even installed.
7 |
8 | I've tested this on a couple of Debian Jessie boxes with nginx, if you test it on other things please let me know
9 | the results (positive or otherwise) so I can document them here/fix the issue.
10 |
11 | Requires Ansible >= 2.0
12 |
13 | # Usage
14 | First, read Let's Encrypt's TOS and EULA. Only proceed if you agree to them.
15 |
16 | The following variables are available:
17 |
18 | `letsencrypt_webroot_path` is the root path that gets served by your web server. Defaults to `/var/www`.
19 |
20 | `letsencrypt_email` needs to be set to your email address. Let's Encrypt wants it. Defaults to `webmaster@{{ ansible_fqdn }}`.
21 |
22 | `letsencrypt_rsa_key_size` allows to specify a size for the generated key
23 |
24 | `letsencrypt_cert_domains` is a list of domains you wish to get a certificate for. It defaults to a single item with the value of `{{ ansible_fqdn }}`.
25 |
26 | `letsencrypt_install_directory` should probably be left alone, but if you set it, it will change where the letsencrypt program is installed.
27 |
28 | `letsencrypt_server` sets the auth server. Set to `https://acme-staging.api.letsencrypt.org/directory` to use the staging server (far higher rate limits, but certs are not trusted, intended for testing)
29 |
30 | `letsencrypt_renewal_command_args` add arguments to the `letsencrypt renewal` command that gets run using cron. For example, use the renewal hooks to restart a web server.
31 |
32 | The [Let's Encrypt client](https://github.com/letsencrypt/letsencrypt) will put the certificate and accessories in `/etc/letsencrypt/live//`. For more info, see the [Let's Encrypt documentation](https://letsencrypt.readthedocs.org/en/latest/using.html#where-are-my-certificates).
33 |
34 | # Example Playbook
35 | ```
36 | ---
37 | - hosts: tls_servers
38 | user: root
39 | roles:
40 | - role: letsencrypt
41 | letsencrypt_webroot_path: /var/www/html
42 | letsencrypt_email: user@example.net
43 | letsencrypt_cert_domains:
44 | - www.example.net
45 | - example.net
46 | letsencrypt_renewal_command_args: '--renew-hook "systemctl restart nginx"'
47 | ```
48 |
--------------------------------------------------------------------------------
/ansible/roles/letsencrypt/tasks/main.yml:
--------------------------------------------------------------------------------
1 | ---
2 | - apt: update_cache=yes cache_valid_time=3600
3 | become: yes
4 | tags: install
5 |
6 | - name: Install depends
7 | package: name={{ item }} state=present
8 | become: yes
9 | with_items:
10 | - python
11 | - python-dev
12 | - python-virtualenv
13 | - gcc
14 | - dialog
15 | - libaugeas0
16 | - libssl-dev
17 | - libffi-dev
18 | - ca-certificates
19 | - python-pip
20 | - git
21 | tags: install
22 |
23 | - include_vars: "{{ item }}"
24 | with_first_found:
25 | - "../vars/{{ ansible_distribution }}-{{ ansible_distribution_major_version | int }}.yml"
26 | - "../vars/{{ ansible_distribution }}.yml"
27 | - "../vars/{{ ansible_os_family }}.yml"
28 | - "../vars/default.yml"
29 | when: virtualenv_package_name is not defined
30 | tags: install
31 |
32 | - name: Install virtualenv
33 | package: name={{ item }} state=present
34 | become: yes
35 | with_items:
36 | - "{{ virtualenv_package_name }}"
37 | tags: install
38 |
39 | - name: Install python depends
40 | pip: virtualenv="{{ letsencrypt_venv }}" virtualenv_site_packages=no name={{ item }} state=latest virtualenv_python=python2
41 | become: yes
42 | with_items:
43 | - setuptools
44 | - pip
45 | tags: install
46 |
47 | - name: More python depends
48 | pip: virtualenv="{{ letsencrypt_venv }}" virtualenv_site_packages=no name=letsencrypt state=latest
49 | become: yes
50 | tags: install
51 |
52 | - name: Ensure webroot exists
53 | file: path="{{ letsencrypt_webroot_path }}" state=directory
54 | become: yes
55 |
56 | - name: Attempt to get the certificate using the webroot authenticator
57 | command: "{{ letsencrypt_command }} -a webroot --webroot-path {{ letsencrypt_webroot_path }} certonly"
58 | become: yes
59 | args:
60 | creates: "/etc/letsencrypt/live/{{ letsencrypt_cert_domains[0] }}"
61 | when: letsencrypt_authenticator == "webroot"
62 | ignore_errors: True
63 |
64 | - name: Attempt to get the certificate using the standalone authenticator (in case eg the webserver isn't running yet)
65 | command: "{{ letsencrypt_command }} -a standalone auth"
66 | become: yes
67 | args:
68 | creates: "/etc/letsencrypt/live/{{ letsencrypt_cert_domains[0] }}"
69 |
70 | - name: Fix the renewal file
71 | ini_file: section=renewalparams option={{ item.key }} value={{ item.value }} dest="/etc/letsencrypt/renewal/{{ letsencrypt_cert_domains[0] }}.conf"
72 | become: yes
73 | with_dict:
74 | os_packages_only: False
75 | verb: certonly
76 | noninteractive_mode: False
77 | uir: False
78 | hsts: False
79 | authenticator: '{{ letsencrypt_authenticator }}'
80 |
81 | - name: Fix the webroot map in the renewal file
82 | ini_file: section="[webroot_map]" option={{ item }} value={{ letsencrypt_webroot_path }} dest="/etc/letsencrypt/renewal/{{ letsencrypt_cert_domains[0] }}.conf"
83 | become: yes
84 | with_items: "{{ letsencrypt_cert_domains }}"
85 |
86 | - name: Install renewal cron
87 | become: yes
88 | cron: name="Let's Encrypt Renewal" day="{{ letsencrypt_renewal_frequency.day }}" hour="{{ letsencrypt_renewal_frequency.hour }}" minute="{{ letsencrypt_renewal_frequency.minute }}" job="{{ letsencrypt_venv }}/bin/letsencrypt renew {{ letsencrypt_renewal_command_args }} > /dev/null"
89 |
--------------------------------------------------------------------------------
/calbot/commands/add.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | # Copyright 2017 Denis Nelubin.
4 | #
5 | # This file is part of Calendar Bot.
6 | #
7 | # Calendar Bot is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation, either version 3 of the License, or
10 | # (at your option) any later version.
11 | #
12 | # Calendar Bot is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU General Public License
18 | # along with Calendar Bot. If not, see http://www.gnu.org/licenses/.
19 |
20 | import logging
21 |
22 | from telegram.ext import ConversationHandler
23 | from telegram.ext import CommandHandler
24 | from telegram.ext import MessageHandler
25 | from telegram.ext import Filters
26 |
27 | from calbot.processing import update_calendar
28 |
29 | __all__ = ['create_handler']
30 |
31 | logger = logging.getLogger('commands.add')
32 |
33 | ENTERING_URL = 0
34 | ENTERING_CHANNEL = 1
35 | END = ConversationHandler.END
36 |
37 |
38 | def create_handler(config):
39 | """
40 | Creates handler for /add command.
41 | :return: ConversationHandler
42 | """
43 |
44 | def add_calendar_with_config(bot, update, chat_data):
45 | return add_calendar(bot, update, chat_data, config)
46 |
47 | return ConversationHandler(
48 | entry_points=[CommandHandler('add', start)],
49 | states={
50 | ENTERING_URL: [MessageHandler(Filters.text, enter_url, pass_chat_data=True)],
51 | ENTERING_CHANNEL: [MessageHandler(
52 | Filters.text, add_calendar_with_config, pass_chat_data=True)]
53 | },
54 | fallbacks=[CommandHandler('cancel', cancel)],
55 | allow_reentry=True
56 | )
57 |
58 |
59 | def start(bot, update):
60 | message = update.message
61 | user_id = str(message.chat_id)
62 | try:
63 | message.reply_text("You're going to add a new calendar.\nEnter an URL of iCal file or /cancel")
64 | return ENTERING_URL
65 | except Exception:
66 | logger.error('Failed to send reply to user %s', user_id, exc_info=True)
67 | return END
68 |
69 |
70 | def enter_url(bot, update, chat_data):
71 | message = update.message
72 | user_id = str(message.chat_id)
73 | try:
74 | chat_data['calendar_url'] = message.text.strip()
75 | message.reply_text('Enter a channel name or /cancel.\nChannel name should start with @.')
76 | return ENTERING_CHANNEL
77 | except Exception:
78 | logger.error('Failed to send reply to user %s', user_id, exc_info=True)
79 | return END
80 |
81 |
82 | def add_calendar(bot, update, chat_data, config):
83 | message = update.message
84 | user_id = str(message.chat_id)
85 | url = chat_data['calendar_url']
86 | try:
87 | channel_id = message.text.strip()
88 | calendar = config.add_calendar(user_id, url, channel_id)
89 | message.reply_text(
90 | 'The new calendar is queued for verification.\nWait for messages here and in the %s.' % channel_id)
91 | update_calendar(bot, calendar)
92 | except Exception as e:
93 | logger.warning('Failed to add calendar for user %s', user_id, exc_info=True)
94 | try:
95 | message.reply_text('Failed to add calendar:\n%s' % e)
96 | except Exception:
97 | logger.error('Failed to send reply to user %s', user_id, exc_info=True)
98 | return END
99 |
100 |
101 | def cancel(bot, update):
102 | message = update.message
103 | user_id = str(message.chat_id)
104 | try:
105 | message.reply_text('Cancelled.')
106 | except Exception:
107 | logger.error('Failed to send reply to user %s', user_id, exc_info=True)
108 | return END
109 |
--------------------------------------------------------------------------------
/calbot/commands/format.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | # Copyright 2017 Denis Nelubin.
4 | #
5 | # This file is part of Calendar Bot.
6 | #
7 | # Calendar Bot is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation, either version 3 of the License, or
10 | # (at your option) any later version.
11 | #
12 | # Calendar Bot is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU General Public License
18 | # along with Calendar Bot. If not, see http://www.gnu.org/licenses/.
19 |
20 | import logging
21 |
22 | from telegram.ext import ConversationHandler
23 | from telegram.ext import CommandHandler
24 | from telegram.ext import MessageHandler
25 | from telegram.ext import Filters
26 |
27 | from calbot.formatting import format_event
28 | from calbot.ical import sample_event
29 |
30 |
31 | __all__ = ['create_handler']
32 |
33 | logger = logging.getLogger('commands.format')
34 |
35 | SETTING = 0
36 | END = ConversationHandler.END
37 |
38 |
39 | def create_handler(config):
40 | """
41 | Creates handler for /format command.
42 | :return: ConversationHandler
43 | """
44 |
45 | def get_format_with_config(bot, update):
46 | return get_format(bot, update, config)
47 |
48 | def set_format_with_config(bot, update):
49 | return set_format(bot, update, config)
50 |
51 | def cancel_with_config(bot, update):
52 | return cancel(bot, update, config)
53 |
54 | return ConversationHandler(
55 | entry_points=[CommandHandler('format', get_format_with_config)],
56 | states={
57 | SETTING: [MessageHandler(Filters.text, set_format_with_config)],
58 | },
59 | fallbacks=[CommandHandler('cancel', cancel_with_config)],
60 | allow_reentry=True
61 | )
62 |
63 |
64 | def get_format(bot, update, config):
65 | message = update.message
66 | user_id = str(message.chat_id)
67 | try:
68 | user_config = config.load_user(user_id)
69 | message.reply_text('Current format:')
70 | message.reply_text(user_config.format)
71 | message.reply_text('Sample event:')
72 | message.reply_text(format_event(user_config, sample_event))
73 | message.reply_text('Type a new format string to set or /cancel')
74 | return SETTING
75 | except Exception:
76 | logger.error('Failed to send reply to user %s', user_id, exc_info=True)
77 | return END
78 |
79 |
80 | def set_format(bot, update, config):
81 | message = update.message or update.edited_message
82 | user_id = str(message.chat_id)
83 | try:
84 | user_config = config.load_user(user_id)
85 | new_format = message.text.strip()
86 | user_config.set_format(new_format)
87 | message.reply_text('Format is updated.\nSample event:')
88 | message.reply_text(format_event(user_config, sample_event))
89 | return END
90 | except Exception as e:
91 | logger.warning('Failed to update format for user %s', user_id, exc_info=True)
92 | try:
93 | message.reply_text('Failed to update format:\n%s' % e)
94 | message.reply_text('Try again or /cancel')
95 | except Exception:
96 | logger.error('Failed to send reply to user %s', user_id, exc_info=True)
97 | return SETTING
98 |
99 |
100 | def cancel(bot, update, config):
101 | message = update.message
102 | user_id = str(message.chat_id)
103 | try:
104 | user_config = config.load_user(user_id)
105 | message.reply_text('Cancelled.\nCurrent format:')
106 | message.reply_text(user_config.format)
107 | except Exception:
108 | logger.error('Failed to send reply to user %s', user_id, exc_info=True)
109 | return END
110 |
--------------------------------------------------------------------------------
/calbot/commands/advance.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | # Copyright 2017 Denis Nelubin.
4 | #
5 | # This file is part of Calendar Bot.
6 | #
7 | # Calendar Bot is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation, either version 3 of the License, or
10 | # (at your option) any later version.
11 | #
12 | # Calendar Bot is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU General Public License
18 | # along with Calendar Bot. If not, see http://www.gnu.org/licenses/.
19 |
20 | import logging
21 |
22 | from telegram.ext import ConversationHandler
23 | from telegram.ext import CommandHandler
24 | from telegram.ext import MessageHandler
25 | from telegram.ext import Filters
26 |
27 | __all__ = ['create_handler']
28 |
29 | logger = logging.getLogger('commands.advance')
30 |
31 | SETTING = 0
32 | END = ConversationHandler.END
33 |
34 |
35 | def create_handler(config):
36 | """
37 | Creates handler for /advance command.
38 | :return: ConversationHandler
39 | """
40 |
41 | def get_advance_with_config(bot, update):
42 | return get_advance(bot, update, config)
43 |
44 | def set_advance_with_config(bot, update):
45 | return set_advance(bot, update, config)
46 |
47 | def cancel_with_config(bot, update):
48 | return cancel(bot, update, config)
49 |
50 | return ConversationHandler(
51 | entry_points=[CommandHandler('advance', get_advance_with_config)],
52 | states={
53 | SETTING: [MessageHandler(Filters.text, set_advance_with_config)],
54 | },
55 | fallbacks=[CommandHandler('cancel', cancel_with_config)],
56 | allow_reentry=True
57 | )
58 |
59 |
60 | def get_advance(bot, update, config):
61 | message = update.message
62 | user_id = str(message.chat_id)
63 | try:
64 | user_config = config.load_user(user_id)
65 | text = 'Events are notified %s hours in advance.\n\n' \
66 | 'Type how many hours in advance events should be notified. ' \
67 | 'Several intervals can be entered separated by space.\n\n' \
68 | 'Example:\n48 24 12 6\n\n' \
69 | 'Type /cancel to cancel update.' % (
70 | ', '.join(map(str, user_config.advance)),
71 | )
72 | message.reply_text(text)
73 | return SETTING
74 | except Exception:
75 | logger.error('Failed to send reply to user %s', user_id, exc_info=True)
76 | return END
77 |
78 |
79 | def set_advance(bot, update, config):
80 | message = update.message
81 | user_id = str(message.chat_id)
82 | try:
83 | user_config = config.load_user(user_id)
84 | hours = message.text.split()
85 | user_config.set_advance(hours)
86 | text = 'Advance hours are updated.\nEvents will be notified %s hours in advance.' % (
87 | ', '.join(map(str, user_config.advance)),
88 | )
89 | message.reply_text(text)
90 | return END
91 | except Exception as e:
92 | logger.warning('Failed to update advance to for user %s', user_id, exc_info=True)
93 | text = 'Failed to update advance hours:\n%s' % e
94 | try:
95 | message.reply_text(text)
96 | message.reply_text('Try again or /cancel')
97 | except Exception:
98 | logger.error('Failed to send reply to user %s', user_id, exc_info=True)
99 | return SETTING
100 |
101 |
102 | def cancel(bot, update, config):
103 | message = update.message
104 | user_id = str(message.chat_id)
105 | try:
106 | user_config = config.load_user(user_id)
107 | text = 'Cancelled.\nEvents will be notified %s hours in advance.' % (
108 | ', '.join(map(str, user_config.advance)),
109 | )
110 | message.reply_text(text)
111 | except Exception:
112 | logger.error('Failed to send reply to user %s', user_id, exc_info=True)
113 | return END
114 |
--------------------------------------------------------------------------------
/calbot/commands/lang.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | # Copyright 2017 Denis Nelubin.
4 | #
5 | # This file is part of Calendar Bot.
6 | #
7 | # Calendar Bot is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation, either version 3 of the License, or
10 | # (at your option) any later version.
11 | #
12 | # Calendar Bot is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU General Public License
18 | # along with Calendar Bot. If not, see http://www.gnu.org/licenses/.
19 |
20 | import locale
21 | import logging
22 |
23 | from telegram.ext import ConversationHandler
24 | from telegram.ext import CommandHandler
25 | from telegram.ext import MessageHandler
26 | from telegram.ext import Filters
27 |
28 | from calbot.formatting import normalize_locale, format_event
29 | from calbot.ical import sample_event
30 |
31 |
32 | __all__ = ['create_handler']
33 |
34 | logger = logging.getLogger('commands.lang')
35 |
36 | SETTING = 0
37 | END = ConversationHandler.END
38 |
39 |
40 | def create_handler(config):
41 | """
42 | Creates handler for /lang command.
43 | :return: ConversationHandler
44 | """
45 |
46 | def get_lang_with_config(bot, update):
47 | return get_lang(bot, update, config)
48 |
49 | def set_lang_with_config(bot, update):
50 | return set_lang(bot, update, config)
51 |
52 | def cancel_with_config(bot, update):
53 | return cancel(bot, update, config)
54 |
55 | return ConversationHandler(
56 | entry_points=[CommandHandler('lang', get_lang_with_config)],
57 | states={
58 | SETTING: [MessageHandler(Filters.text, set_lang_with_config)],
59 | },
60 | fallbacks=[CommandHandler('cancel', cancel_with_config)],
61 | allow_reentry=True
62 | )
63 |
64 |
65 | def get_lang(bot, update, config):
66 | message = update.message
67 | user_id = str(message.chat_id)
68 | try:
69 | user_config = config.load_user(user_id)
70 | message.reply_text('Current language is %s\nSample event:' % user_config.language)
71 | message.reply_text(format_event(user_config, sample_event))
72 | message.reply_text('Type another language name to set or /cancel')
73 | return SETTING
74 | except Exception:
75 | logger.error('Failed to send reply to user %s', user_id, exc_info=True)
76 | return END
77 |
78 |
79 | def set_lang(bot, update, config):
80 | message = update.message
81 | user_id = str(message.chat_id)
82 | try:
83 | user_config = config.load_user(user_id)
84 | new_lang = message.text.strip()
85 | old_lang = user_config.language
86 | normalized_locale = normalize_locale(new_lang)
87 | user_config.set_language(normalized_locale)
88 | try:
89 | sample = format_event(user_config, sample_event)
90 | message.reply_text('Language is updated to %s\nSample event:' % normalized_locale)
91 | message.reply_text(sample)
92 | return END
93 | except locale.Error as e:
94 | if old_lang:
95 | user_config.set_language(old_lang)
96 | logger.warning('Unsupported language "%s" for user %s', new_lang, user_id, exc_info=True)
97 | message.reply_text('Unsupported language:\n%s' % e)
98 | message.reply_text('Try again or /cancel')
99 | return SETTING
100 | except Exception as e:
101 | logger.warning('Failed to update language for user %s', user_id, exc_info=True)
102 | try:
103 | message.reply_text('Failed to update language:\n%s' % e)
104 | message.reply_text('Try again or /cancel')
105 | except Exception:
106 | logger.error('Failed to send reply to user %s', user_id, exc_info=True)
107 | return SETTING
108 |
109 |
110 | def cancel(bot, update, config):
111 | message = update.message
112 | user_id = str(message.chat_id)
113 | try:
114 | user_config = config.load_user(user_id)
115 | text = 'Cancelled.\nCurrent language is %s' % user_config.language
116 | message.reply_text(text)
117 | except Exception:
118 | logger.error('Failed to send reply to user %s', user_id, exc_info=True)
119 | return END
120 |
--------------------------------------------------------------------------------
/calbot/processing.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | # Copyright 2017 Denis Nelubin.
4 | #
5 | # This file is part of Calendar Bot.
6 | #
7 | # Calendar Bot is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation, either version 3 of the License, or
10 | # (at your option) any later version.
11 | #
12 | # Calendar Bot is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU General Public License
18 | # along with Calendar Bot. If not, see http://www.gnu.org/licenses/.
19 |
20 | import logging
21 |
22 | from calbot.formatting import format_event
23 | from calbot.ical import Calendar
24 | from calbot.stats import update_stats
25 |
26 | __all__ = ['update_calendars_job', 'update_calendars', 'update_calendar']
27 |
28 | logger = logging.getLogger('processing')
29 |
30 |
31 | def update_calendars_job(bot, job):
32 | """
33 | Job queue callback.
34 | Runs the update of all calendars one by one.
35 | Finally, updates statistics.
36 | :param bot: Bot instance
37 | :param job: it's context contains main config
38 | :return: None
39 | """
40 | config = job.context
41 | update_calendars(bot, config)
42 |
43 |
44 | def update_calendars(bot, config):
45 | """
46 | Runs the update of all calendars one by one.
47 | Finally, updates statistics.
48 | :param bot: Bot instance
49 | :param config: main config
50 | :return: None
51 | """
52 | for calendar in config.all_calendars():
53 | update_calendar(bot, calendar)
54 | update_stats(config)
55 |
56 |
57 | def update_calendar(bot, config):
58 | """
59 | Update data from the calendar.
60 | Reads ical file and notifies events if necessary.
61 | After the first successful read the calendar is marked as validated.
62 | :param bot: Bot instance
63 | :param config: CalendarConfig instance to persist and update events notification status
64 | :return: None
65 | """
66 | if not config.enabled:
67 | logger.info('Skipping processing of disabled calendar %s of user %s', config.id, config.user_id)
68 | return
69 |
70 | try:
71 | calendar = Calendar(config)
72 |
73 | if not config.verified:
74 | bot.sendMessage(chat_id=config.channel_id,
75 | text='Events from %s will be notified here' % calendar.name)
76 | config.save_calendar(calendar)
77 | bot.sendMessage(chat_id=config.user_id,
78 | text='''Verified calendar %s
79 | Name: %s
80 | URL: %s
81 | Channel: %s''' % (config.id, config.name, config.url, config.channel_id))
82 |
83 | for event in calendar.events:
84 | send_event(bot, config, event)
85 | config.event_notified(event)
86 | config.save_events()
87 |
88 | config.save_error(None) # successful processing completion
89 | except Exception as e:
90 | logger.warning('Failed to process calendar %s of user %s', config.id, config.user_id, exc_info=True)
91 | was_enabled = config.enabled
92 | config.save_error(e) # unsuccessful completion
93 |
94 | if was_enabled and not config.verified: # still enabled
95 | try:
96 | bot.sendMessage(chat_id=config.user_id,
97 | text='Failed to process calendar /cal%s:\n%s' % (config.id, e))
98 | except Exception:
99 | logger.error('Failed to send message to user %s', config.user_id, exc_info=True)
100 |
101 | if was_enabled and not config.enabled: # just disabled
102 | try:
103 | bot.sendMessage(chat_id=config.user_id,
104 | text='Calendar /cal%s is disabled due too many processing errors\n' % config.id)
105 | except Exception:
106 | logger.error('Failed to send message to user %s', config.user_id, exc_info=True)
107 |
108 |
109 | def send_event(bot, config, event):
110 | """
111 | Sends the event notification to the channel
112 | :param bot: Bot instance
113 | :param config: CalendarConfig instance
114 | :param event: Event instance, read from ical
115 | :return: None
116 | """
117 | logger.info('Sending event %s "%s" to %s', event.id, event.title, config.channel_id)
118 | bot.sendMessage(chat_id=config.channel_id, text=format_event(config, event))
119 |
--------------------------------------------------------------------------------
/calbot/stats.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | # Copyright 2016 Denis Nelubin.
4 | #
5 | # This file is part of Calendar Bot.
6 | #
7 | # Calendar Bot is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation, either version 3 of the License, or
10 | # (at your option) any later version.
11 | #
12 | # Calendar Bot is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU General Public License
18 | # along with Calendar Bot. If not, see http://www.gnu.org/licenses/.
19 |
20 | import os
21 | import datetime
22 | import logging
23 | from configparser import ConfigParser
24 |
25 | from calbot.conf import ConfigFile
26 |
27 |
28 | __all__ = ['update_stats', 'get_stats']
29 |
30 | logger = logging.getLogger('stats')
31 |
32 | STATS_MESSAGE_FORMAT="""Active users: {}
33 | Active calendars: {}
34 | Disabled calendars: {}
35 | Notified events: {}
36 | Last calendars processed:
37 | {} - {}"""
38 |
39 |
40 | def update_stats(config):
41 | """
42 | Updates statistics.
43 | :param config: Main config object
44 | :return: None
45 | """
46 | try:
47 | config_file = StatsConfigFile(config.vardir)
48 | parser = ConfigParser(interpolation=None)
49 | parser.add_section('stats')
50 |
51 | users = 0
52 | calendars = 0
53 | disabled_calendars = 0
54 | events = 0
55 | last_process_min = datetime.datetime.utcnow().isoformat()
56 | last_process_max = datetime.datetime.utcfromtimestamp(0).isoformat()
57 |
58 | for name in os.listdir(config.vardir):
59 | if os.path.isdir(os.path.join(config.vardir, name)):
60 | users += 1
61 | user_id = name
62 | for calendar in config.load_calendars(user_id):
63 | if calendar.enabled:
64 | calendars += 1
65 | last_process_min = min(calendar.last_process_at or last_process_min, last_process_min)
66 | last_process_max = max(calendar.last_process_at or last_process_max, last_process_max)
67 | calendar.load_events()
68 | events += len(calendar.events)
69 | else:
70 | disabled_calendars += 1
71 |
72 | parser.set('stats', 'users', str(users))
73 | parser.set('stats', 'calendars', str(calendars))
74 | parser.set('stats', 'disabled_calendars', str(disabled_calendars))
75 | parser.set('stats', 'events', str(events))
76 | parser.set('stats', 'last_process_min', last_process_min)
77 | parser.set('stats', 'last_process_max', last_process_max)
78 |
79 | config_file.write(parser)
80 | except Exception as e:
81 | logger.warning('Failed to update stats', exc_info=True)
82 |
83 |
84 | def get_stats(config):
85 | """
86 | Reads stats object from the stats.cfg file
87 | :param config: Main Config object
88 | :return: Stats object
89 | """
90 | config_file = StatsConfigFile(config.vardir)
91 | return Stats.load(config_file)
92 |
93 |
94 | class Stats:
95 | """
96 | Holds statistics data.
97 | """
98 |
99 | def __init__(self, **kwargs):
100 | self.users = kwargs['users']
101 | """Number of active users"""
102 | self.calendars = kwargs['calendars']
103 | """Number of active calendars"""
104 | self.disabled_calendars = kwargs['disabled_calendars']
105 | """Number of disabled calendars"""
106 | self.events = kwargs['events']
107 | """Number of notified events"""
108 | self.last_process_min = kwargs['last_process_min']
109 | """Timestamp of the calendar processed, min value"""
110 | self.last_process_max = kwargs['last_process_max']
111 | """Timestamp of the calendar processed, max value"""
112 |
113 | @classmethod
114 | def load(cls, stats_config):
115 | """
116 | Loads stats from the stats.cfg file
117 | """
118 | parser = stats_config.read_parser()
119 | return cls(
120 | users=parser.getint('stats', 'users', fallback=0),
121 | calendars=parser.getint('stats', 'calendars', fallback=0),
122 | disabled_calendars=parser.getint('stats', 'disabled_calendars', fallback=0),
123 | events=parser.getint('stats', 'events', fallback=0),
124 | last_process_min=parser.get('stats', 'last_process_min', fallback=None),
125 | last_process_max=parser.get('stats', 'last_process_max', fallback=None)
126 | )
127 |
128 | def __str__(self):
129 | return STATS_MESSAGE_FORMAT.format(self.users,
130 | self.calendars,
131 | self.disabled_calendars,
132 | self.events,
133 | self.last_process_min,
134 | self.last_process_max)
135 |
136 |
137 | class StatsConfigFile(ConfigFile):
138 | """
139 | Reads and writes stats config file.
140 | """
141 |
142 | def __init__(self, vardir):
143 | """
144 | Creates the config
145 | :param vardir: basic var dir
146 | """
147 | super().__init__(os.path.join(vardir, 'stats.cfg'))
148 |
--------------------------------------------------------------------------------
/test/repeat.ics:
--------------------------------------------------------------------------------
1 | BEGIN:VCALENDAR
2 | PRODID:-//Google Inc//Google Calendar 70.9054//EN
3 | VERSION:2.0
4 | CALSCALE:GREGORIAN
5 | METHOD:PUBLISH
6 | X-WR-CALNAME:Omsk IT Events
7 | X-WR-TIMEZONE:Asia/Omsk
8 |
9 | BEGIN:VTIMEZONE
10 | TZID:Asia/Omsk
11 | X-LIC-LOCATION:Asia/Omsk
12 | BEGIN:STANDARD
13 | TZOFFSETFROM:+0600
14 | TZOFFSETTO:+0600
15 | TZNAME:+06
16 | DTSTART:19700101T000000
17 | END:STANDARD
18 | END:VTIMEZONE
19 |
20 | BEGIN:VTIMEZONE
21 | TZID:Asia/Almaty
22 | X-LIC-LOCATION:Asia/Almaty
23 | BEGIN:STANDARD
24 | TZOFFSETFROM:+0600
25 | TZOFFSETTO:+0600
26 | TZNAME:+06
27 | DTSTART:19700101T000000
28 | END:STANDARD
29 | END:VTIMEZONE
30 |
31 | BEGIN:VEVENT
32 | DTSTART;TZID=Asia/Omsk:20200408T190000
33 | DTEND;TZID=Asia/Omsk:20200408T203000
34 | DTSTAMP:20200407T044006Z
35 | UID:6pqb3bhvtu0k2aq285m13ppnr7@google.com
36 | ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=ACCEPTED;CN=Omsk I
37 | T Events;X-NUM-GUESTS=0:mailto:aqclsibjm591jbbk875uio9k40@group.calendar.go
38 | ogle.com
39 | RECURRENCE-ID;TZID=Asia/Omsk:20200408T190000
40 | CREATED:20180108T111016Z
41 | DESCRIPTION:Дата Ужин - это свободный формат\, где можно пообщаться на тем
42 | у анализа данных\, маш.обуча.\, обсудить соревнования по ML\, ближе познако
43 | миться. Определенной темы беседы нет\, но я думаю она сразу же найдется.\n\
44 | n\nВстречаемся в дискорде на нашем сервере: https://discord.gg/WhKnyWr.\nТе
45 | кстовый чат в телеграмме: https://t.me/mlomsk
46 | LAST-MODIFIED:20200329T065050Z
47 | LOCATION:
48 | SEQUENCE:2
49 | STATUS:CONFIRMED
50 | SUMMARY:Дата Ужин (OML)
51 | TRANSP:OPAQUE
52 | END:VEVENT
53 |
54 | BEGIN:VEVENT
55 | DTSTART;TZID=Asia/Omsk:20190925T190000
56 | DTEND;TZID=Asia/Omsk:20190925T203000
57 | RRULE:FREQ=WEEKLY;INTERVAL=2;BYDAY=WE
58 | EXDATE;TZID=Asia/Omsk:20200101T190000
59 | DTSTAMP:20200407T044006Z
60 | UID:6pqb3bhvtu0k2aq285m13ppnr7@google.com
61 | ATTENDEE;CUTYPE=INDIVIDUAL;ROLE=REQ-PARTICIPANT;PARTSTAT=ACCEPTED;CN=Omsk I
62 | T Events;X-NUM-GUESTS=0:mailto:aqclsibjm591jbbk875uio9k40@group.calendar.go
63 | ogle.com
64 | CREATED:20180108T111016Z
65 | DESCRIPTION:Дата Ужин - это свободный формат\, где можно пообщаться на тем
66 | у анализа данных\, маш.обуча.\, обсудить соревнования по ML\, ближе познако
67 | миться. Определенной темы беседы нет\, но я думаю она сразу же найдется.\n\
68 | n\nМесто встречи: Пиццот\, Лермонтова 8
69 | LAST-MODIFIED:20190916T124150Z
70 | LOCATION:Пиццот\, ул. Лермонтова\, 8\, Омск\, Омская обл.\, Россия\, 644024
71 | SEQUENCE:2
72 | STATUS:CONFIRMED
73 | SUMMARY:Дата Ужин (OML)
74 | TRANSP:OPAQUE
75 | END:VEVENT
76 |
77 | BEGIN:VEVENT
78 | DTSTART;TZID=Asia/Omsk:20190320T190000
79 | DTEND;TZID=Asia/Omsk:20190320T203000
80 | RRULE:FREQ=WEEKLY;UNTIL=20190917T175959Z;INTERVAL=2;BYDAY=WE
81 | DTSTAMP:20200407T044006Z
82 | UID:2cfl3hu8lmsnenr2clvn7o9j5l_R20190320T130000@google.com
83 | CREATED:20181001T030034Z
84 | DESCRIPTION:Дата Ужин - это свободный формат\, где можно пообщаться на тем
85 | у анализа данных\, маш.обуча.\, обсудить соревнования по ML\, ближе познако
86 | миться. Определенной темы беседы нет\, но я думаю она сразу же найдется.\n\
87 | n\nМесто встречи: Пиццот\, Лермонтова 8
88 | LAST-MODIFIED:20190916T124112Z
89 | LOCATION:Пиццот\, ул. Лермонтова\, 8\, Омск\, Омская обл.\, Россия\, 644024
90 | SEQUENCE:0
91 | STATUS:CONFIRMED
92 | SUMMARY:Дата ужин (OML)
93 | TRANSP:OPAQUE
94 | END:VEVENT
95 |
96 | BEGIN:VEVENT
97 | DTSTART;TZID=Asia/Omsk:20190206T190000
98 | DTEND;TZID=Asia/Omsk:20190206T203000
99 | RRULE:FREQ=WEEKLY;UNTIL=20190319T175959Z;INTERVAL=2;BYDAY=WE
100 | DTSTAMP:20200407T044006Z
101 | UID:2cfl3hu8lmsnenr2clvn7o9j5l_R20190206T130000@google.com
102 | CREATED:20181001T030034Z
103 | DESCRIPTION:Дата \; Ужин - это свободный формат\, где можно пообщаться
104 | на тему анализа данных\, маш.обуча.\, обсудить соревнования по ML\, ближе п
105 | ознакомиться. Определенной темы беседы нет\, но я думаю она сразу же найдет
106 | ся.
Место встречи: "Розы Морозы"\, Ленина 14
110 | LAST-MODIFIED:20190916T124112Z
111 | LOCATION:ул. Ленина\, 14\, Омск\, Омская обл.\, Россия\, 644043
112 | SEQUENCE:0
113 | STATUS:CONFIRMED
114 | SUMMARY:Дата ужин (OML)
115 | TRANSP:OPAQUE
116 | END:VEVENT
117 |
118 | BEGIN:VEVENT
119 | DTSTART;TZID=Asia/Omsk:20181212T190000
120 | DTEND;TZID=Asia/Omsk:20181212T203000
121 | RRULE:FREQ=WEEKLY;UNTIL=20190205T175959Z;INTERVAL=2;BYDAY=WE
122 | DTSTAMP:20200407T044006Z
123 | UID:2cfl3hu8lmsnenr2clvn7o9j5l_R20181212T130000@google.com
124 | CREATED:20181001T030034Z
125 | DESCRIPTION:Дата \; Ужин - это свободный формат\, где можно пообщаться
126 | на тему анализа данных\, маш.обуча.\, обсудить соревнования по ML\, ближе п
127 | ознакомиться. Определенной темы беседы нет\, но я думаю она сразу же найдет
128 | ся.
Встречаемся в "Бутерbrot" в на Ленина 50.
131 | LAST-MODIFIED:20190916T124112Z
132 | LOCATION:ул. Ленина\, 50\, Омск\, Омская обл.\, Россия\, 644042
133 | SEQUENCE:0
134 | STATUS:CONFIRMED
135 | SUMMARY:Дата ужин (OML)
136 | TRANSP:OPAQUE
137 | END:VEVENT
138 |
139 | BEGIN:VEVENT
140 | DTSTART;TZID=Asia/Omsk:20181215T160000
141 | DTEND;TZID=Asia/Omsk:20181215T190000
142 | RRULE:FREQ=WEEKLY;UNTIL=20190614T175959Z
143 | EXDATE;TZID=Asia/Omsk:20190608T160000
144 | EXDATE;TZID=Asia/Omsk:20190601T160000
145 | EXDATE;TZID=Asia/Omsk:20190518T160000
146 | EXDATE;TZID=Asia/Omsk:20190511T160000
147 | EXDATE;TZID=Asia/Omsk:20190504T160000
148 | EXDATE;TZID=Asia/Omsk:20190330T160000
149 | EXDATE;TZID=Asia/Omsk:20190223T160000
150 | EXDATE;TZID=Asia/Omsk:20190209T160000
151 | EXDATE;TZID=Asia/Omsk:20190105T160000
152 | EXDATE;TZID=Asia/Omsk:20181229T160000
153 | DTSTAMP:20200407T044006Z
154 | UID:1jhr86fgcjqqa1tt18541shd64@google.com
155 | CREATED:20181215T033454Z
156 | DESCRIPTION:Место проведения: Таубе 5\, 1 этаж\, кабинет 112.
Регист
157 | рация в кружке обязательна: \; http://mlomsk.1der.link/practice/register !!
Контакт
159 | ы организатора:
Илья Сиганов\, ilya.blan4@gmail.com\, vk.com/senior_sigan
162 | LAST-MODIFIED:20190612T190739Z
163 | LOCATION:ул. Таубе\, 5\, Омск\, Омская\, Россия\, 644037
164 | SEQUENCE:0
165 | STATUS:CONFIRMED
166 | SUMMARY:ML кружок IT-lift | 7bits
167 | TRANSP:OPAQUE
168 | END:VEVENT
169 |
170 | END:VCALENDAR
171 |
--------------------------------------------------------------------------------
/calbot/bot.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | # Copyright 2016 Denis Nelubin.
4 | #
5 | # This file is part of Calendar Bot.
6 | #
7 | # Calendar Bot is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation, either version 3 of the License, or
10 | # (at your option) any later version.
11 | #
12 | # Calendar Bot is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU General Public License
18 | # along with Calendar Bot. If not, see http://www.gnu.org/licenses/.
19 |
20 | import logging
21 |
22 | from telegram.ext import CommandHandler
23 | from telegram.ext import Filters
24 | from telegram.ext import MessageHandler
25 | from telegram.ext import Updater
26 |
27 | from calbot import stats
28 | from calbot.commands import add as add_command
29 | from calbot.commands import cal as cal_command
30 | from calbot.commands import format as format_command
31 | from calbot.commands import lang as lang_command
32 | from calbot.commands import advance as advance_command
33 | from calbot.processing import update_calendars_job
34 |
35 | __all__ = ['run_bot']
36 |
37 | GREETING = '''Hello, I'm calendar bot, please give me some commands.
38 | /add — add new iCal to be sent to a channel
39 | /list — see all configured calendars
40 | /format — get and set a calendar event formatting, use {title}, {date}, {time}, {location} and {description} variables
41 | /lang — get and set language to print the event, may affect the week day name
42 | /advance — get and set calendar events advance, i.e. how many hours before the event to publish it
43 | '''
44 |
45 | # logging.basicConfig(level=logging.DEBUG,
46 | # format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
47 |
48 | logger = logging.getLogger('bot')
49 |
50 |
51 | def run_bot(config):
52 | """
53 | Starts the bot
54 | :param config: main bot configuration
55 | :return: None
56 | """
57 | updater = Updater(config.token)
58 |
59 | dispatcher = updater.dispatcher
60 |
61 | dispatcher.add_handler(CommandHandler('start', start))
62 | dispatcher.add_handler(CommandHandler('help', start))
63 |
64 | dispatcher.add_handler(add_command.create_handler(config))
65 |
66 | def list_calendars_from_config(bot, update):
67 | list_calendars(bot, update, config)
68 | dispatcher.add_handler(CommandHandler('list', list_calendars_from_config))
69 |
70 | dispatcher.add_handler(cal_command.create_handler(config))
71 | dispatcher.add_handler(format_command.create_handler(config))
72 | dispatcher.add_handler(lang_command.create_handler(config))
73 | dispatcher.add_handler(advance_command.create_handler(config))
74 |
75 | def get_stats_with_config(bot, update):
76 | get_stats(bot, update, config)
77 | dispatcher.add_handler(CommandHandler('stats', get_stats_with_config))
78 |
79 | dispatcher.add_handler(CommandHandler('cancel', cancel))
80 | dispatcher.add_handler(MessageHandler(Filters.command, unknown))
81 |
82 | dispatcher.add_error_handler(error)
83 |
84 | if config.webhook:
85 | webhook_url = 'https://%s/%s' % (config.domain, config.token)
86 | updater.start_webhook(listen=config.listen,
87 | port=config.port,
88 | url_path=config.token,
89 | webhook_url=webhook_url,
90 | bootstrap_retries=config.bootstrap_retries)
91 | logger.info('Started webhook on %s:%s' % (config.listen, config.port))
92 | updater.bot.set_webhook(webhook_url)
93 | logger.info('Set webhook to %s' % webhook_url)
94 | else:
95 | updater.start_polling(clean=False,
96 | poll_interval=config.poll_interval,
97 | timeout=config.timeout,
98 | read_latency=config.read_latency,
99 | bootstrap_retries=config.bootstrap_retries,
100 | )
101 | logger.info('Started polling')
102 |
103 | updater.job_queue.run_repeating(update_calendars_job, config.interval, first=0, context=config)
104 |
105 | updater.idle()
106 |
107 |
108 | def start(bot, update):
109 | """
110 | /start or /help command handler. Prints greeting message.
111 | :param bot: Bot instance
112 | :param update: Update instance
113 | :return: None
114 | """
115 | logger.info('Started from %s', update.message.chat_id)
116 | bot.sendMessage(chat_id=update.message.chat_id, text=GREETING)
117 |
118 |
119 | def list_calendars(bot, update, config):
120 | """
121 | /list command handler. Prints the list of all calendars configured for the user.
122 | :param bot: Bot instance
123 | :param update: Update instance
124 | :param config: Config instance to read list of user's calendars
125 | :return: None
126 | """
127 | message = update.message
128 | user_id = str(message.chat_id)
129 | text = 'ID\tNAME\tCHANNEL\n'
130 | for calendar in config.user_calendars(user_id):
131 | text += '/cal%s\t%s\t%s%s\n' % (calendar.id, calendar.name, calendar.channel_id,
132 | ('' if calendar.enabled else '\tDISABLED'))
133 | bot.sendMessage(chat_id=user_id, text=text)
134 |
135 |
136 | def get_stats(bot, update, config):
137 | """
138 | /stats command handler.
139 | Prints the current known statistics.
140 | :param bot: Bot instance
141 | :param update: Update instance
142 | :param config: Config instance
143 | :return: None
144 | """
145 | message = update.message
146 | text = str(stats.get_stats(config))
147 | bot.sendMessage(chat_id=message.chat_id, text=text)
148 |
149 |
150 | def cancel(bot, update):
151 | """
152 | Handler for /cancel command. Prints error message.
153 | :param bot: Bot instance
154 | :param update: Update instance
155 | :return: None
156 | """
157 | bot.sendMessage(chat_id=update.message.chat_id, text="Sorry, there's nothing to cancel.")
158 |
159 |
160 | def unknown(bot, update):
161 | """
162 | Handler for unknown command. Prints error message.
163 | :param bot: Bot instance
164 | :param update: Update instance
165 | :return: None
166 | """
167 | bot.sendMessage(chat_id=update.message.chat_id, text="Sorry, I don't understand this command.")
168 |
169 |
170 | def error(bot, update, error):
171 | """
172 | Error handler. Prints error message.
173 | :param bot: Bot instance
174 | :param update: Update instance
175 | :param error: the error
176 | :return: None
177 | """
178 | logger.warning('Update "%s" caused error "%s"' % (update, error))
179 |
--------------------------------------------------------------------------------
/calbot/formatting.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | # Copyright 2016 Denis Nelubin.
4 | #
5 | # This file is part of Calendar Bot.
6 | #
7 | # Calendar Bot is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation, either version 3 of the License, or
10 | # (at your option) any later version.
11 | #
12 | # Calendar Bot is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU General Public License
18 | # along with Calendar Bot. If not, see http://www.gnu.org/licenses/.
19 |
20 |
21 | import locale
22 | import re
23 | from html.parser import HTMLParser
24 |
25 | # https://gist.github.com/gruber/8891611
26 | url_regex = re.compile(r'''(?i)\b((?:https?:(?:/{1,3}|[a-z0-9%])|[a-z0-9.\-]+[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|link|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)/)(?:[^\s()<>{}\[\]]+|\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\))+(?:\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’])|(?:(?') # is required for Python 3.4.2, otherwise parser does nothing
146 | s.feed(str(html))
147 | s.feed('
')
148 | return s.get_data()
149 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Calendar Bot
2 |
3 | It's the bot for [Telegram](https://telegram.org/).
4 |
5 | It reads [iCalendar](https://en.wikipedia.org/wiki/ICalendar) files of Google Calendar (or any other public iCal URLs).
6 | And sends notifications to a [telegram channel](https://telegram.org/faq_channels) some hours in advance to the events start in the calendar.
7 | Use it to mirror calendar events to the channel and notify the subscribers.
8 |
9 | ## Quick Start
10 |
11 | 1. Start talk with [@icalbot](https://telegram.me/icalbot).
12 | 2. Invite @icalbot to your channel and make it the [channel administrator](https://telegram.org/faq_channels#q-what-can-administrators-do) (to allow it to post messages to the channel).
13 | 3. Find the URL of your iCalendar file ([ICAL link](https://support.google.com/calendar/answer/37083?hl=en#link)).
14 | 4. Type `/add`, then, after prompts, enter `https://your_calendar.ics` and `@your_channel` (setting your actual data) in the chat with the bot.
15 | 5. Wait for bot notifications in the chat and in the channel.
16 |
17 | ## Bot Commands
18 |
19 | ### /add
20 |
21 | `/add` — add a new iCal to be sent to a channel
22 |
23 | Adds the new calendar to be processed by the bot and be broadcasted to the channel.
24 |
25 | You should enter two parameters after prompts, one by one:
26 |
27 | * URL of the iCalendar file. Can look like `https://calendar.google.com/calendar/ical/many_many_characters/public/basic.ics`
28 | * Name of the channel where to broadcast calendar events, starting from `@`
29 |
30 | For example:
31 |
32 | ```
33 | You're going to add a new calendar.
34 | Enter an URL of iCal file or /cancel
35 | ```
36 |
37 | And then:
38 |
39 | ```
40 | Enter a channel name or /cancel
41 | Channel name should start with @.
42 | ```
43 |
44 | ### /list
45 |
46 | `/list` — see all configured calendars
47 |
48 | Prints a table with calendar ID, calendar name and the broadcast channel with all calendars you configured with the bot.
49 | For example:
50 |
51 | ```
52 | ID NAME CHANNEL
53 | /cal1 My Google Calendar @mychannel
54 | /cal2 Another Calendar @anotherchannel
55 | ```
56 |
57 | ### /calN
58 |
59 | `/cal` — see calendar details, edit, disable, or delete it if necessary
60 |
61 | Show details of the specified calendar from the list.
62 | Allows to modify, disable, or delete it.
63 | For example:
64 |
65 | ```
66 | Calendar 1 details
67 | Name: My Google Calendar
68 | URL: https://calendar.google.com/calendar/ical/XXXXXXXXXXXXXX/public/basic.ics
69 | Channel: @mychannel
70 | Verified: True
71 | Enabled: True
72 | Last processed: 2022-01-07T11:55:09.762176
73 | Last error: None
74 | Errors count: 0
75 |
76 | Edit the calendar /url or /channel, or /disable it, or /delete, or /cancel
77 | ```
78 |
79 | You can type `/url` and enter a new URL to the iCal file after the prompt.
80 | For example:
81 |
82 | ```
83 | The current calendar URL is:
84 |
85 | https://calendar.google.com/calendar/ical/XXXXXXXXXXXXXX/public/basic.ics
86 |
87 | Enter a new URL of iCal file or /cancel
88 | ```
89 |
90 | You can type `/channel` and, after the prompt, enter a new channel name where to send the calendar event.
91 | For example:
92 |
93 | ```
94 | The current calendar channel is:
95 |
96 | @mychannel
97 |
98 | Enter a new channel name or /cancel
99 | ```
100 |
101 | After changing of the URL or channel name the calendar is verified again, as it happens when adding a new calendar.
102 |
103 | You can `/enable` or `/disable` the calendar or `/delete` it permanently by typing the specific command.
104 |
105 | ### /format
106 |
107 | `/format` — get and set a calendar event formatting, use `{title}`, `{date}`, `{time}`, `{location}` and `{description}` variables
108 |
109 | The command prints the current format of the calendar event and asks the new format to set.
110 | For example:
111 |
112 | ```
113 | Current format:
114 |
115 | {title}
116 | {date:%A, %d %B %Y}{time:, %H:%M %Z}
117 | {location}
118 | {description}
119 |
120 | Sample event:
121 |
122 | This is sample event
123 | Friday, 09 September 2016, 14:43 UTC
124 | It happens in Milky Way
125 | The sample event is to demonstrate how the event can be formatted
126 |
127 | Type a new format string to set or /cancel
128 | ```
129 |
130 | Type the new format template and send it.
131 | See below the details of the formatting.
132 |
133 | ### /lang
134 |
135 | `/lang` — get and set language to print the event, may affect the weekday / month name
136 |
137 | The command prints the current language and asks the new language to set.
138 | For example:
139 |
140 | ```
141 | Current language: ru_RU.UTF-8
142 | Sample event:
143 |
144 | This is sample event
145 | Пятница, 23 Сентябрь 2016, 18:03 UTC
146 | It happens in Milky Way
147 | The sample event is to demonstrate how the event can be formatted
148 |
149 | Type another language name to set or /cancel
150 | ```
151 |
152 | Enter the language name to set the new language.
153 | The language can be two letter code ('ru') or the full name ('russian').
154 | Not all languages are supported by the bot.
155 |
156 | ### /advance
157 |
158 | `/advance` — get and set calendar events advance, i.e. how many hours before the event to publish it
159 |
160 | The bot broadcasts the event from the calendar to the channel some hours in advance before the event starts.
161 | How many hours in advance to notify can be configured by this command.
162 | It's possible to define multiple advance hours, in this case the same event will be notified multiple times.
163 |
164 | The command prints the current advance hours and asks new values to update.
165 | For example:
166 |
167 | ```
168 | Events are notified 24, 12 hours in advance.
169 |
170 | Type how many hours in advance events should be notified. Several intervals can be entered separated by space.
171 |
172 | Example:
173 | 48 24 12 6
174 |
175 | Enter /cancel to cancel update.
176 | ```
177 |
178 | Enter one or more space separated integer numbers to set the new notification advance.
179 | Each number means hours to advance.
180 |
181 | ## Event Formatting
182 |
183 | Event has some properties.
184 | To print the property during the event broadcasting you should include the property name to the format string in curly braces.
185 | The format string can be modified using `/format` command (see above).
186 | It uses the syntax of Python's [str.format()](https://docs.python.org/3/library/string.html#formatstrings) method.
187 | Date and time are formatted according to [strftime()](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior) rules.
188 |
189 | Event properties:
190 |
191 | * `title` — event one-line title, use `{title}` in format string.
192 | * `date` — day, month and year of the event start, you may define additional format parameters in braces, for example: `{date:%A, %d %B %Y}`.
193 | Possible 'percent' parameters:
194 |
195 | * `%a` — weekday abbreviated name (depends on language)
196 | * `%A` — weekday full name (depends on language)
197 | * `%w` — weekday as decimal number
198 | * `%d` — day of the month as a zero-padded decimal number
199 | * `%b` — month abbreviated name (depends on language)
200 | * `%B` — month full name (depends on language)
201 | * `%m` — month as a zero-padded decimal number
202 | * `%y` — year without century as a zero-padded decimal number
203 | * `%Y` — year with century as a decimal number
204 | * `%j` — day of the year as a zero-padded decimal number
205 | * `%U` — week number of the year (Sunday as the first day of the week)
206 | * `%W` — week number of the year (Monday as the first day of the week)
207 | * `%x` — whole date representation (depends on language)
208 |
209 | * `time` — hour, minute of the event start, you may define additional format parameters in braces, for example: `{time:%H:%M %Z}`.
210 | Possible 'percent' parameters:
211 |
212 | * `%H` — hour (24-hour clock) as a zero-padded decimal number
213 | * `%I` — hour (12-hour clock) as a zero-padded decimal number
214 | * `%p` — AM or PM (depends on language)
215 | * `%M` — minute as a zero-padded decimal number
216 | * `%S` — second as a zero-padded decimal number
217 | * `%z` — UTC offset in the form +HHMM or -HHMM
218 | * `%Z` — time zone name
219 | * `%X` — whole time representation (depends on language)
220 |
221 | * `location` — event location, as string, use `{location}` in format string.
222 | * `description` — event description, can be multi-line, use `{description}` in format string.
223 |
--------------------------------------------------------------------------------
/calbot/ical.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | # Copyright 2016 Denis Nelubin.
4 | #
5 | # This file is part of Calendar Bot.
6 | #
7 | # Calendar Bot is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation, either version 3 of the License, or
10 | # (at your option) any later version.
11 | #
12 | # Calendar Bot is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU General Public License
18 | # along with Calendar Bot. If not, see http://www.gnu.org/licenses/.
19 |
20 |
21 | import logging
22 | from datetime import datetime, date, timedelta
23 | from urllib.request import urlopen
24 | import pytz
25 | import icalendar
26 | import recurring_ical_events
27 |
28 | from calbot.formatting import BlankFormat
29 |
30 | __all__ = ['Calendar', 'sample_event']
31 |
32 |
33 | logger = logging.getLogger('ical')
34 |
35 |
36 | class Calendar:
37 | """
38 | Calendar, as it was read from ical file.
39 | """
40 |
41 | def __init__(self, config):
42 | self.url = config.url
43 | """url of the ical file, from persisted config"""
44 | self.advance = config.advance
45 | """array of the numbers: how many hours in advance notify about the event, from persisted config"""
46 | self.day_start = config.day_start
47 | """when the day starts if the event has no specified time, from persisted config"""
48 | self.name = None
49 | """name of the calendar, from ical file"""
50 | self.timezone = pytz.UTC
51 | """timezone of the calendar, from ical file"""
52 | self.description = None
53 | """description of the calendar, from ical file"""
54 |
55 | after = datetime.now(tz=pytz.UTC)
56 | before = after + timedelta(hours=max(self.advance))
57 |
58 | self.all_events = list(self.read_ical(self.url, after, before))
59 | """list of all calendar events, from ical file"""
60 |
61 | unnotified_events = filter_notified_events(self.all_events, config)
62 | sorted_events = sort_events(unnotified_events)
63 |
64 | self.events = list(sorted_events)
65 | """list of calendar events which should be notified, filtered from ical file"""
66 |
67 | def read_ical(self, url, after, before):
68 | """
69 | Reads ical file from url.
70 | :param url: url to read
71 | :param after: also generate repeating events after this datetime
72 | :param before: also generate repeating events before this datetime
73 | :return: it's generator, yields each event read from ical
74 | """
75 | # TODO also filter past events to avoid reading of the whole calendar
76 | logger.info('Getting %s', url)
77 | with urlopen(url) as f:
78 | timezone_set = 'none'
79 | vcalendar = icalendar.Calendar.from_ical(f.read())
80 | self.name = str(vcalendar.get('X-WR-CALNAME'))
81 | self.description = str(vcalendar.get('X-WR-CALDESC'))
82 |
83 | if vcalendar.get('X-WR-TIMEZONE') is not None:
84 | self.timezone = pytz.timezone(str(vcalendar.get('X-WR-TIMEZONE')))
85 | timezone_set = 'x-wr-timezone'
86 |
87 | for component in vcalendar.walk():
88 | if component.name == 'VTIMEZONE' and timezone_set in ('none', 'x-wr-timezone'):
89 | try:
90 | self.timezone = pytz.timezone(str(component.get('TZID')))
91 | timezone_set = 'vtimezone.tzid'
92 | except Exception as e:
93 | logger.warning(e)
94 |
95 | for event in recurring_ical_events.of(vcalendar).between(after, before):
96 | yield Event.from_vevent(event, self.timezone, self.day_start)
97 |
98 |
99 | class Event:
100 | """
101 | Calendar event as it was read from ical file.
102 | """
103 |
104 | def __init__(self, **kwargs):
105 | self.id = kwargs['id']
106 | """unique id of the event"""
107 | self.uid = kwargs.get('uid', kwargs['id'])
108 | """uid from vevent from """
109 | self.instance_id = kwargs.get('instance_id', (kwargs['id'], None))
110 | """event instance id, to identify each event in the sequence of recurring events"""
111 | self.title = kwargs['title']
112 | """title of the event"""
113 | self.location = kwargs.get('location')
114 | """the event location as string"""
115 | self.description = kwargs.get('description')
116 | """the event description"""
117 | self.date = kwargs.get('date')
118 | """event (start) date"""
119 | self.time = kwargs.get('time')
120 | """event (start) time, can be None"""
121 | self.notify_datetime = kwargs.get('notify_datetime')
122 | """calendar event datetime, relative to which to calculate notification moment,
123 | uses day_start if time for current event is None"""
124 | self.notified_for_advance = kwargs.get('notified_for_advance')
125 | """hours in advance for which this event should be notified"""
126 | self.day_start = kwargs.get('day_start')
127 | """notification time for full-day events"""
128 |
129 | def __repr__(self):
130 | return f'Event(id={self.id}, uid={self.uid}, instance_id={self.instance_id}, ' \
131 | f'title={self.title}, location={self.location}, description={self.description}, ' \
132 | f'date={self.date}, time={self.time}, notify_datetime={self.notify_datetime}, ' \
133 | f'notified_for_advance={self.notified_for_advance}, ' \
134 | f'day_start={self.day_start})'
135 |
136 | @classmethod
137 | def from_vevent(cls, vevent, timezone, day_start=None):
138 | """
139 | Creates calendar event from vEvent component read from ical file.
140 | :param vevent: vEvent component
141 | :param timezone: default timezone for the calendar
142 | :param day_start: notification moment for full-day events
143 | :return: calendar event instance
144 | """
145 |
146 | event_uid = str(vevent.get('UID'))
147 | event_title = str(vevent.get('SUMMARY'))
148 | event_location = str(vevent.get('LOCATION'))
149 | event_description = str(vevent.get('DESCRIPTION'))
150 |
151 | event_date = None
152 | event_time = None
153 | notify_datetime = None
154 |
155 | dtstart = vevent.get('DTSTART').dt
156 | if isinstance(dtstart, datetime):
157 | dtstarttz = timezoned(dtstart, timezone)
158 | event_date = dtstarttz.date()
159 | event_time = dtstarttz.timetz()
160 | notify_datetime = datetime.combine(event_date, event_time)
161 | elif isinstance(dtstart, date):
162 | event_date = dtstart
163 | notify_datetime = datetime.combine(event_date, day_start.replace(tzinfo=timezone))
164 |
165 | if notify_datetime is None:
166 | event_id = event_uid
167 | else:
168 | event_id = "%s_%s" % (event_uid, notify_datetime.isoformat())
169 |
170 | event_instance_id = (event_uid, notify_datetime)
171 |
172 | event_day_start = day_start.replace(tzinfo=timezone) if day_start is not None else None
173 |
174 | return cls(
175 | id=event_id,
176 | uid=event_uid,
177 | instance_id=event_instance_id,
178 | title=event_title,
179 | location=event_location,
180 | description=event_description,
181 | date=event_date,
182 | time=event_time,
183 | notify_datetime=notify_datetime,
184 | day_start=event_day_start
185 | )
186 |
187 | def to_dict(self):
188 | """
189 | Converts the event to dict to be easy passed to format function.
190 | :return: dict of the event properties
191 | """
192 | return dict(title=self.title or BlankFormat(),
193 | date=self.date or BlankFormat(),
194 | time=self.time or BlankFormat(),
195 | location=self.location or BlankFormat(),
196 | description=self.description or BlankFormat())
197 |
198 |
199 | def filter_notified_events(events, config):
200 | """
201 | Filters events which were already notified.
202 | Uses the array expected notification advances from the config.
203 | For each filtered event sets the advance it should be notified for (notified_for_advance).
204 | :param events: iterable of events
205 | :param config: CalendarConfig
206 | :return: it's generator, yields each filtered event
207 | """
208 | now = datetime.now(tz=pytz.UTC)
209 | for event in events:
210 | for advance in sorted(config.advance, reverse=True):
211 | notified = config.event(event.id)
212 | last_notified = notified is not None and notified.last_notified
213 | if last_notified is not None and last_notified <= advance:
214 | continue
215 | if event.notify_datetime <= now + timedelta(hours=advance):
216 | event.notified_for_advance = advance
217 | yield event
218 | break
219 |
220 |
221 | def sort_events(events):
222 | def sort_key(event):
223 | return event.notify_datetime
224 | return sorted(events, key=sort_key)
225 |
226 |
227 | def timezoned(dt, timezone):
228 | if isinstance(dt, datetime):
229 | if dt.tzinfo is None:
230 | return timezone.localize(dt)
231 | elif dt.tzinfo == pytz.UTC:
232 | return dt.astimezone(timezone)
233 | else:
234 | return dt
235 | else:
236 | return dt
237 |
238 |
239 | def _get_sample_event():
240 | now = datetime.now(tz=pytz.timezone('Asia/Omsk'))
241 | return Event(
242 | id='SAMPLE EVENT',
243 | uid='SAMPLE EVENT',
244 | instance_id=('SAMPLE EVENT', now),
245 | title='This is sample event',
246 | location='It happens in Milky Way',
247 | description='The sample event is to demonstrate how the event can be formatted',
248 | date=now.date(),
249 | time=now.timetz())
250 |
251 |
252 | sample_event = _get_sample_event()
253 |
--------------------------------------------------------------------------------
/calbot/commands/cal.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | # Copyright 2017 Denis Nelubin.
4 | #
5 | # This file is part of Calendar Bot.
6 | #
7 | # Calendar Bot is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation, either version 3 of the License, or
10 | # (at your option) any later version.
11 | #
12 | # Calendar Bot is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU General Public License
18 | # along with Calendar Bot. If not, see http://www.gnu.org/licenses/.
19 |
20 | import logging
21 |
22 | from telegram.ext import ConversationHandler, MessageHandler, Filters
23 | from telegram.ext import CommandHandler
24 | from telegram.ext import RegexHandler
25 |
26 | from calbot.conf import CalendarConfig
27 |
28 |
29 | __all__ = ['create_handler']
30 |
31 | from calbot.processing import update_calendar
32 |
33 | logger = logging.getLogger('commands.cal')
34 |
35 | EDITING = 0
36 | EDITING_URL = 1
37 | EDITING_CHANNEL = 2
38 | END = ConversationHandler.END
39 |
40 |
41 | def create_handler(config):
42 | """
43 | Creates handler for /calX command.
44 | :return: ConversationHandler
45 | """
46 |
47 | def get_cal_with_config(bot, update, groups, chat_data):
48 | return get_cal(bot, update, groups, chat_data, config)
49 |
50 | def del_cal_with_config(bot, update, chat_data, job_queue):
51 | return del_cal(bot, update, chat_data, job_queue, config)
52 |
53 | def enable_cal_with_config(bot, update, chat_data):
54 | return enable_cal(bot, update, chat_data, config)
55 |
56 | def disable_cal_with_config(bot, update, chat_data):
57 | return disable_cal(bot, update, chat_data, config)
58 |
59 | def start_edit_cal_url_with_config(bot, update, chat_data):
60 | return start_edit_cal_url(bot, update, chat_data, config)
61 |
62 | def edit_cal_url_with_config(bot, update, chat_data):
63 | return edit_cal_url(bot, update, chat_data, config)
64 |
65 | def start_edit_cal_channel_with_config(bot, update, chat_data):
66 | return start_edit_cal_channel(bot, update, chat_data, config)
67 |
68 | def edit_cal_channel_with_config(bot, update, chat_data):
69 | return edit_cal_channel(bot, update, chat_data, config)
70 |
71 | return ConversationHandler(
72 | entry_points=[RegexHandler(r'^/cal(\d+)', get_cal_with_config, pass_groups=True, pass_chat_data=True)],
73 | states={
74 | EDITING: [
75 | CommandHandler('url', start_edit_cal_url_with_config, pass_chat_data=True),
76 | CommandHandler('channel', start_edit_cal_channel_with_config, pass_chat_data=True),
77 | CommandHandler('enable', enable_cal_with_config, pass_chat_data=True),
78 | CommandHandler('disable', disable_cal_with_config, pass_chat_data=True),
79 | CommandHandler('delete', del_cal_with_config, pass_chat_data=True, pass_job_queue=True),
80 | ],
81 | EDITING_URL: [MessageHandler(Filters.text, edit_cal_url_with_config, pass_chat_data=True)],
82 | EDITING_CHANNEL: [MessageHandler(Filters.text, edit_cal_channel_with_config, pass_chat_data=True)],
83 | },
84 | fallbacks=[CommandHandler('cancel', cancel)],
85 | allow_reentry=True
86 | )
87 |
88 |
89 | def get_cal(bot, update, groups, chat_data, config):
90 | message = update.message
91 | user_id = str(message.chat_id)
92 | calendar_id = groups[0]
93 | chat_data['calendar_id'] = calendar_id
94 |
95 | try:
96 | calendar = config.load_calendar(user_id, calendar_id)
97 | message.reply_text(
98 | '''Calendar %s details
99 | Name: %s
100 | URL: %s
101 | Channel: %s
102 | Verified: %s
103 | Enabled: %s
104 | Last processed: %s
105 | Last error: %s
106 | Errors count: %s''' % (calendar.id, calendar.name, calendar.url, calendar.channel_id,
107 | calendar.verified, calendar.enabled,
108 | calendar.last_process_at, calendar.last_process_error, calendar.last_errors_count))
109 | message.reply_text('Edit the calendar /url or /channel, or %s it, or /delete, or /cancel' %
110 | ('/disable' if calendar.enabled else '/enable'))
111 | return EDITING
112 | except Exception as e:
113 | logger.warning('Failed to load calendar %s for user %s', calendar_id, user_id, exc_info=True)
114 | try:
115 | message.reply_text('Failed to find calendar %s:\n%s' % (calendar_id, e))
116 | except Exception:
117 | logger.error('Failed to send reply to user %s', user_id, exc_info=True)
118 | return END
119 |
120 |
121 | def del_cal(bot, update, chat_data, job_queue, config):
122 | message = update.message
123 | user_id = str(message.chat_id)
124 | calendar_id = chat_data['calendar_id']
125 |
126 | try:
127 | config.delete_calendar(user_id, calendar_id)
128 | for job in job_queue.jobs():
129 | if (hasattr(job, 'context')
130 | and isinstance(job.context, CalendarConfig)
131 | and job.context.id == calendar_id):
132 | job.schedule_removal()
133 | message.reply_text('Calendar %s is deleted' % calendar_id)
134 | except Exception as e:
135 | logger.warning('Failed to delete calendar %s for user %s', calendar_id, user_id, exc_info=True)
136 | try:
137 | message.reply_text('Failed to delete calendar %s:\n%s' % (calendar_id, e))
138 | except Exception:
139 | logger.error('Failed to send reply to user %s', user_id, exc_info=True)
140 |
141 | return END
142 |
143 |
144 | def start_edit_cal_url(bot, update, chat_data, config):
145 | message = update.message
146 | user_id = str(message.chat_id)
147 | calendar_id = chat_data['calendar_id']
148 |
149 | try:
150 | calendar = config.load_calendar(user_id, calendar_id)
151 | message.reply_text("The current calendar URL is:")
152 | message.reply_text(calendar.url)
153 | message.reply_text("Enter a new URL of iCal file or /cancel")
154 | return EDITING_URL
155 | except Exception:
156 | logger.error('Failed to send reply to user %s', user_id, exc_info=True)
157 | return END
158 |
159 |
160 | def edit_cal_url(bot, update, chat_data, config):
161 | message = update.message
162 | user_id = str(message.chat_id)
163 | calendar_id = chat_data['calendar_id']
164 |
165 | try:
166 | url = message.text.strip()
167 | calendar = config.change_calendar_url(user_id, calendar_id, url)
168 | message.reply_text('The updated calendar is queued for verification.\nWait for messages here.')
169 | update_calendar(bot, calendar)
170 | except Exception as e:
171 | logger.warning('Failed to change url of calendar %s for user %s', calendar_id, user_id, exc_info=True)
172 | try:
173 | message.reply_text('Failed to change url of calendar %s:\n%s' % (calendar_id, e))
174 | except Exception:
175 | logger.error('Failed to send reply to user %s', user_id, exc_info=True)
176 |
177 | return END
178 |
179 |
180 | def start_edit_cal_channel(bot, update, chat_data, config):
181 | message = update.message
182 | user_id = str(message.chat_id)
183 | calendar_id = chat_data['calendar_id']
184 |
185 | try:
186 | calendar = config.load_calendar(user_id, calendar_id)
187 | message.reply_text("The current calendar channel is:")
188 | message.reply_text(calendar.channel_id)
189 | message.reply_text("Enter a new channel name or /cancel")
190 | return EDITING_CHANNEL
191 | except Exception:
192 | logger.error('Failed to send reply to user %s', user_id, exc_info=True)
193 | return END
194 |
195 |
196 | def edit_cal_channel(bot, update, chat_data, config):
197 | message = update.message
198 | user_id = str(message.chat_id)
199 | calendar_id = chat_data['calendar_id']
200 |
201 | try:
202 | channel_id = message.text.strip()
203 | calendar = config.change_calendar_channel(user_id, calendar_id, channel_id)
204 | message.reply_text('The updated calendar is queued for verification.\nWait for messages here.')
205 | update_calendar(bot, calendar)
206 | except Exception as e:
207 | logger.warning('Failed to change channel of calendar %s for user %s', calendar_id, user_id, exc_info=True)
208 | try:
209 | message.reply_text('Failed to change channel of calendar %s:\n%s' % (calendar_id, e))
210 | except Exception:
211 | logger.error('Failed to send reply to user %s', user_id, exc_info=True)
212 |
213 | return END
214 |
215 |
216 | def enable_cal(bot, update, chat_data, config):
217 | message = update.message
218 | user_id = str(message.chat_id)
219 | calendar_id = chat_data['calendar_id']
220 |
221 | try:
222 | config.enable_calendar(user_id, calendar_id, True)
223 | message.reply_text('Calendar /cal%s is enabled' % calendar_id)
224 | except Exception as e:
225 | logger.warning('Failed to enable calendar %s for user %s', calendar_id, user_id, exc_info=True)
226 | try:
227 | message.reply_text('Failed to enable calendar /cal%s:\n%s' % (calendar_id, e))
228 | except Exception:
229 | logger.error('Failed to send reply to user %s', user_id, exc_info=True)
230 |
231 | return END
232 |
233 |
234 | def disable_cal(bot, update, chat_data, config):
235 | message = update.message
236 | user_id = str(message.chat_id)
237 | calendar_id = chat_data['calendar_id']
238 |
239 | try:
240 | config.enable_calendar(user_id, calendar_id, False)
241 | message.reply_text('Calendar /cal%s is disabled' % calendar_id)
242 | except Exception as e:
243 | logger.warning('Failed to disable calendar %s for user %s', calendar_id, user_id, exc_info=True)
244 | try:
245 | message.reply_text('Failed to disable calendar /cal%s:\n%s' % (calendar_id, e))
246 | except Exception:
247 | logger.error('Failed to send reply to user %s', user_id, exc_info=True)
248 |
249 | return END
250 |
251 |
252 | def cancel(bot, update):
253 | message = update.message
254 | user_id = str(message.chat_id)
255 | try:
256 | message.reply_text('Cancelled.')
257 | except Exception:
258 | logger.error('Failed to send reply to user %s', user_id, exc_info=True)
259 | return END
260 |
--------------------------------------------------------------------------------
/calbot/conf.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | # Copyright 2016 Denis Nelubin.
4 | #
5 | # This file is part of Calendar Bot.
6 | #
7 | # Calendar Bot is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation, either version 3 of the License, or
10 | # (at your option) any later version.
11 | #
12 | # Calendar Bot is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU General Public License
18 | # along with Calendar Bot. If not, see http://www.gnu.org/licenses/.
19 |
20 | """
21 | We have a hierarchy of data to be persisted.
22 | So, under `var` directory we have the following files and folders.
23 |
24 | ```
25 | var/
26 | user1_chat_id/
27 | settings.cfg - general user config like notification format
28 | calendars.cfg - the list of user's calendars
29 | calendar1_id/
30 | events.cfg - the list of calendar events
31 | calendar2_id/
32 | ...
33 | user2_chat_id/
34 | ...
35 | ```
36 | """
37 |
38 | from configparser import ConfigParser
39 | import logging
40 | import os
41 | from datetime import time, datetime
42 |
43 |
44 | __all__ = ['Config', 'ConfigFile']
45 |
46 | logger = logging.getLogger('conf')
47 |
48 | DEFAULT_FORMAT = '''{title}
49 | {date:%A, %d %B %Y}{time:, %H:%M %Z}
50 | {location}
51 | {description}'''
52 |
53 | DEFAULT_ADVANCE = [48, 24]
54 |
55 | DEFAULT_ERRORS_COUNT_THRESHOLD = 12
56 |
57 |
58 | class Config:
59 | """
60 | Main config, read from the file.
61 | """
62 |
63 | def __init__(self, configfile):
64 | """
65 | Creates the config
66 | :param configfile: location of main config file
67 | """
68 | config = ConfigParser()
69 | config.read(configfile)
70 | self.vardir = config.get('bot', 'vardir')
71 | """path to var directory, where current state is stored"""
72 | self.token = config.get('bot', 'token')
73 | """the bot token"""
74 | self.interval = config.getint('bot', 'interval', fallback=3600)
75 | """the interval to reread calendars, in seconds"""
76 | self.bootstrap_retries = config.getint('bot', 'bootstrap_retries', fallback=0)
77 | """Whether the bootstrapping phase of the Updater will retry on failures on the Telegram server."""
78 | self.errors_count_threshold = config.getint('bot', 'errors_count_threshold',
79 | fallback=DEFAULT_ERRORS_COUNT_THRESHOLD)
80 | """Disable a calendar if it processing attempts failed with so many errors"""
81 |
82 | self.poll_interval = config.getfloat('polling', 'poll_interval', fallback=0.0)
83 | """Time to wait between polling updates from Telegram"""
84 | self.timeout = config.getfloat('polling', 'timeout', fallback=10.0)
85 | """Timeout in seconds for long polling"""
86 | self.read_latency = config.getfloat('polling', 'read_latency', fallback=2.0)
87 | """Additional timeout in seconds to allow the response from Telegram servers."""
88 |
89 | self.webhook = config.getboolean('webhook', 'webhook', fallback=False)
90 | """use webhook or not"""
91 | self.domain = config.get('webhook', 'domain', fallback=None)
92 | """public domain where the webhook of the bot is listening"""
93 | self.listen = config.get('webhook', 'listen', fallback='[::1]')
94 | """IP address to listen by webhook"""
95 | self.port = config.getint('webhook', 'port', fallback=5000)
96 | """webhook port"""
97 |
98 | def user_calendars(self, user_id):
99 | """
100 | Returns list of calendars configured for the user
101 | :param user_id: id of the user to list calendars
102 | :return: list of CalendarConfig
103 | """
104 | for calendar in self.load_calendars(user_id):
105 | yield calendar
106 |
107 | def all_calendars(self):
108 | """
109 | Returns list of all known and monitoring calendars with events
110 | :return: list of CalendarConfig
111 | """
112 | for name in os.listdir(self.vardir):
113 | if os.path.isdir(os.path.join(self.vardir, name)):
114 | user_id = name
115 | for calendar in self.load_calendars(user_id):
116 | calendar.load_events()
117 | yield calendar
118 |
119 | def load_user(self, user_id):
120 | """
121 | Loads UserConfig
122 | :param user_id: ID of the user
123 | :return: UserConfig instance
124 | """
125 | parser = UserConfigFile(self.vardir, user_id).read_parser()
126 | return UserConfig.load(self, user_id, parser)
127 |
128 | def load_calendars(self, user_id):
129 | """
130 | Loads all calendars of the specified user.
131 | :param user_id: ID of the user
132 | :return: yields the CalendarConfig instances
133 | """
134 | user_config = self.load_user(user_id)
135 | calendar_parser = CalendarsConfigFile(self.vardir, user_id).read_parser()
136 |
137 | for section in calendar_parser.sections():
138 | if section != 'settings':
139 | calendar = CalendarConfig.load(user_config, calendar_parser, section)
140 | yield calendar
141 |
142 | def load_calendar(self, user_id, calendar_id):
143 | """
144 | Loads one calendar of the specified user.
145 | :param user_id: ID of the user
146 | :param calendar_id: ID of the calendar
147 | :return: the CalendarConfig instance
148 | """
149 | user_config = self.load_user(user_id)
150 | calendar_parser = CalendarsConfigFile(self.vardir, user_id).read_parser()
151 |
152 | if not calendar_parser.has_section(calendar_id):
153 | raise KeyError('Calendar %s not found' % calendar_id)
154 |
155 | calendar = CalendarConfig.load(user_config, calendar_parser, calendar_id)
156 | return calendar
157 |
158 | def add_calendar(self, user_id, url, channel_id):
159 | """
160 | Adds the calendar to the persisted list
161 | :param user_id: id of the user for which the calendar is persisted
162 | :param url: URL of the ical file
163 | :param channel_id: ID of the channel where to send calendar events
164 | :return: CalendarConfig instance
165 | """
166 | calendar_config_file = CalendarsConfigFile(self.vardir, user_id)
167 | calendar_parser = calendar_config_file.read_parser()
168 | user_parser = UserConfigFile(self.vardir, user_id).read_parser()
169 | user = UserConfig.load(self, user_id, user_parser)
170 |
171 | next_id = str(calendar_parser.getint('settings', 'last_id', fallback=0) + 1)
172 | if not calendar_parser.has_section('settings'):
173 | calendar_parser.add_section('settings')
174 | calendar_parser.set('settings', 'last_id', next_id)
175 |
176 | calendar = CalendarConfig.new(user, next_id, url, channel_id)
177 | calendar_parser.add_section(next_id)
178 | calendar_parser.set(next_id, 'url', url)
179 | calendar_parser.set(next_id, 'channel_id', channel_id)
180 | calendar_parser.set(next_id, 'verified', 'false')
181 |
182 | calendar_config_file.write(calendar_parser)
183 |
184 | return calendar
185 |
186 | def change_calendar_url(self, user_id, calendar_id, url):
187 | """
188 | Updates the calendar url. Resets verified flag.
189 | :param user_id: id of the user
190 | :param calendar_id: id of the calendar
191 | :param url: new URL of the ical file
192 | :return: updated CalendarConfig instance
193 | """
194 | calendar = self.load_calendar(user_id, calendar_id)
195 | calendar.url = url
196 | calendar.verified = False
197 | calendar.enabled = True
198 | calendar.save() # save and clear last error
199 | return calendar
200 |
201 | def change_calendar_channel(self, user_id, calendar_id, channel_id):
202 | """
203 | Updates the calendar channel. Resets verified flag.
204 | :param user_id: id of the user
205 | :param calendar_id: id of the calendar
206 | :param channel_id: new channel ID
207 | :return: updated CalendarConfig instance
208 | """
209 | calendar = self.load_calendar(user_id, calendar_id)
210 | calendar.channel_id = channel_id
211 | calendar.verified = False
212 | calendar.enabled = True
213 | calendar.save() # save and clear last error
214 | return calendar
215 |
216 | def delete_calendar(self, user_id, calendar_id):
217 | """
218 | Deleted the calendar from the persisted list
219 | :param user_id: id of the user
220 | :param calendar_id: id of the calendar
221 | :return: None
222 | """
223 | config_file = CalendarsConfigFile(self.vardir, user_id)
224 | config_parser = config_file.read_parser()
225 |
226 | if not config_parser.has_section(calendar_id):
227 | raise KeyError('%s not found' % calendar_id)
228 | config_parser.remove_section(calendar_id)
229 |
230 | config_file.write(config_parser)
231 |
232 | def enable_calendar(self, user_id, calendar_id, enabled):
233 | """
234 | Sets enable flag for the calendar
235 | :param user_id: id of the user
236 | :param calendar_id: id of the calendar
237 | :param enabled: enabled flag
238 | :return: None
239 | """
240 | config_file = CalendarsConfigFile(self.vardir, user_id)
241 | config_parser = config_file.read_parser()
242 | if not config_parser.has_section(calendar_id):
243 | raise KeyError('%s not found' % calendar_id)
244 |
245 | config_parser.set(calendar_id, 'enabled', str(enabled))
246 |
247 | config_file.write(config_parser)
248 |
249 |
250 | class UserConfig:
251 | """
252 | Per-user configuration parameters.
253 | """
254 |
255 | def __init__(self, **kwargs):
256 | self.vardir = kwargs['vardir']
257 | """Base var directory"""
258 | self.id = kwargs['user_id']
259 | """ID of the user"""
260 | self.format = kwargs['format']
261 | """Event message format for the user"""
262 | self.language = kwargs['language']
263 | """Language to format the event"""
264 | self.advance = kwargs['advance']
265 | """Array of hours for advance the calendar event"""
266 | self.config_parser = kwargs.get('config_parser', None)
267 | """ConfigParser from which this object was loaded, None if this is new a config"""
268 | self.errors_count_threshold = kwargs.get('errors_count_threshold', DEFAULT_ERRORS_COUNT_THRESHOLD)
269 | """Disable a calendar if it processing attempts failed with so many errors"""
270 |
271 | @classmethod
272 | def new(cls, config, user_id):
273 | """
274 | Creates the new config, when there is nothing to read from settings.cfg file
275 | :param config: main config instance
276 | :param user_id: ID of the user
277 | :return: UserConfig instance
278 | """
279 | return cls(
280 | vardir=config.vardir,
281 | user_id=user_id,
282 | format=DEFAULT_FORMAT,
283 | language=None,
284 | advance=DEFAULT_ADVANCE,
285 | errors_count_threshold=config.errors_count_threshold
286 | )
287 |
288 | @classmethod
289 | def load(cls, config, user_id, config_parser):
290 | """
291 | Loads the config from the ConfigParser
292 | :param config: main config instance
293 | :param user_id: ID of the user
294 | :param config_parser: ConfigParser which read the user settings.cfg file
295 | :return: UserConfig instance
296 | """
297 | return cls(
298 | vardir=config.vardir,
299 | user_id=user_id,
300 | format=config_parser.get('settings', 'format', fallback=DEFAULT_FORMAT),
301 | language=config_parser.get('settings', 'language', fallback=None),
302 | advance=list(
303 | map(int,
304 | config_parser.get('settings', 'advance', fallback=' '.join(map(str, DEFAULT_ADVANCE))).split())
305 | ),
306 | config_parser=config_parser,
307 | errors_count_threshold=config.errors_count_threshold,
308 | )
309 |
310 | def set_format(self, format):
311 | """
312 | Sets the event format for the user, writes it to settings.cfg of the user.
313 | :param format: new format
314 | :return: None
315 | """
316 | config_file = UserConfigFile(self.vardir, self.id)
317 | parser = self.config_parser or config_file.read_parser()
318 | if not parser.has_section('settings'):
319 | parser.add_section('settings')
320 | parser.set('settings', 'format', format)
321 | config_file.write(parser)
322 | self.format = format
323 |
324 | def set_language(self, language):
325 | """
326 | Sets the event format for the user, writes it to settings.cfg of the user.
327 | :param language: new language
328 | :return: None
329 | """
330 | config_file = UserConfigFile(self.vardir, self.id)
331 | parser = self.config_parser or config_file.read_parser()
332 | if not parser.has_section('settings'):
333 | parser.add_section('settings')
334 | parser.set('settings', 'language', language)
335 | config_file.write(parser)
336 | self.language = language
337 |
338 | def set_advance(self, hours):
339 | """
340 | Sets the list of hours to notify events in advance.
341 | :param hours: advance hours
342 | :return: None
343 | """
344 | config_file = UserConfigFile(self.vardir, self.id)
345 | parser = self.config_parser or config_file.read_parser()
346 | if not parser.has_section('settings'):
347 | parser.add_section('settings')
348 | int_hours = sorted(set(map(int, hours)), reverse=True)
349 | parser.set('settings', 'advance', ' '.join(map(str, int_hours)))
350 | config_file.write(parser)
351 | self.advance = int_hours
352 |
353 |
354 | class CalendarConfig:
355 | """
356 | Current persisted calendar state.
357 | """
358 |
359 | def __init__(self, **kwargs):
360 | self.vardir = kwargs['vardir']
361 | """Base var directory"""
362 | self.id = kwargs['cal_id']
363 | """Current calendar ID"""
364 | self.user_id = kwargs['user_id']
365 | """Chat ID of the user to whom this calendar belongs to"""
366 | self.url = kwargs['url']
367 | """Url of the ical file to download"""
368 | self.name = kwargs['name']
369 | """Human readable name of the calendar"""
370 | self.channel_id = kwargs['channel_id']
371 | """Channel where to broadcast calendar events"""
372 | self.verified = kwargs['verified']
373 | """Flag indicating should the calendar fetching errors be sent to user"""
374 | self.enabled = kwargs['enabled']
375 | """Flag calendar is enabled and should be processed"""
376 | self.format = kwargs['format']
377 | """Format string for the event"""
378 | self.language = kwargs['language']
379 | """Language for the event"""
380 | self.advance = kwargs['advance']
381 | """Array of the numbers: how many hours in advance notify about the event"""
382 | self.day_start = time(10, 0)
383 | """When the day starts if the event has no specified time"""
384 | self.events = {}
385 | """Dictionary of known configured events"""
386 | self.last_process_at = kwargs.get('last_process_at')
387 | """Moment when the calendar was processed last time"""
388 | self.last_process_error = kwargs.get('last_process_error')
389 | """Error message if last processing failed with an error"""
390 | self.last_errors_count = kwargs.get('last_errors_count', 0)
391 | """How many errors were observed during last calendar processing attempts"""
392 | self.errors_count_threshold = kwargs.get('errors_count_threshold', DEFAULT_ERRORS_COUNT_THRESHOLD)
393 |
394 | @classmethod
395 | def new(cls, user_config, cal_id, url, channel_id):
396 | """
397 | Creates the new calendar config, for just added calendar by an /add command
398 | :param user_config: UserConfig instance
399 | :param cal_id: ID for this calendar
400 | :param url: URL of the calendar
401 | :param channel_id: ID of the channel where to post calendar events
402 | :return: CalendarConfig instance
403 | """
404 | return cls(
405 | vardir=user_config.vardir,
406 | user_id=user_config.id,
407 | format=user_config.format,
408 | language=user_config.language,
409 | advance=user_config.advance,
410 | cal_id=cal_id,
411 | url=url,
412 | name=None,
413 | channel_id=channel_id,
414 | verified=False,
415 | enabled=True,
416 | errors_count_threshold=user_config.errors_count_threshold,
417 | )
418 |
419 | @classmethod
420 | def load(cls, user_config, config_parser, cal_id):
421 | """
422 | Creates the calendar config from the calendar.cfg file already read to ConfigParser
423 | :param user_config: UserConfig instance
424 | :param config_parser: ConfigParser which read calendars.cfg file
425 | :param cal_id: ID of the calendar, used as name of the section in ConfigParser
426 | :return: CalendarConfig instance
427 | """
428 | section = cal_id
429 | verified = config_parser.getboolean(section, 'verified', fallback=False)
430 | enabled = config_parser.getboolean(section, 'enabled', fallback=True)
431 | return cls(
432 | vardir=user_config.vardir,
433 | user_id=user_config.id,
434 | format=user_config.format,
435 | language=user_config.language,
436 | advance=user_config.advance,
437 | cal_id=cal_id,
438 | url=config_parser.get(section, 'url'),
439 | name=config_parser.get(section, 'name', fallback=('Unknown' if verified else 'Unverified')),
440 | channel_id=config_parser.get(section, 'channel_id'),
441 | verified=verified,
442 | enabled=enabled,
443 | last_process_at=config_parser.get(section, 'last_process_at', fallback=None),
444 | last_process_error=config_parser.get(section, 'last_process_error', fallback=None),
445 | last_errors_count=config_parser.getint(section, 'last_errors_count', fallback=0),
446 | errors_count_threshold=user_config.errors_count_threshold
447 | )
448 |
449 | def save(self, exception=None):
450 | """
451 | Saves changes in url, name, channel_id, verified and enabled flags
452 | of the calendar, updates last error.
453 | :param exception: exception, can be None
454 | :return: None
455 | """
456 | config_file = CalendarsConfigFile(self.vardir, self.user_id)
457 | config_parser = config_file.read_parser()
458 | self._create_section(config_parser)
459 |
460 | config_parser.set(self.id, 'url', self.url)
461 | config_parser.set(self.id, 'name', self.name)
462 | config_parser.set(self.id, 'channel_id', self.channel_id)
463 | config_parser.set(self.id, 'verified', str(self.verified))
464 | config_parser.set(self.id, 'enabled', str(self.enabled))
465 |
466 | self._update_last_process(config_parser, exception)
467 | config_file.write(config_parser)
468 |
469 | def load_events(self):
470 | """
471 | Loads the calendar events from the events.cfg file.
472 | :return: None
473 | """
474 | config_parser = EventsConfigFile(self.vardir, self.user_id, self.id).read_parser()
475 |
476 | for event_id in config_parser.sections():
477 | event = EventConfig(self, event_id)
478 | event.last_notified = config_parser.getint(event_id, 'last_notified', fallback=None)
479 | self.events[event_id] = event
480 |
481 | def event(self, id):
482 | """
483 | Returns the persisted state of calendar event by it's id
484 | :param id: id of the event
485 | :return: the EventConfig instance, read from persisted storage or a new one
486 | """
487 | try:
488 | return self.events[id]
489 | except KeyError:
490 | event = EventConfig(self, id)
491 | self.events[id] = event
492 | return event
493 |
494 | def event_notified(self, event):
495 | """
496 | Marks the event in config as notified.
497 | Copies data from the ical event object
498 | :param event: runtime event processed by ical module
499 | :return: None
500 | """
501 | config_event = self.event(event.id)
502 | config_event.last_notified = event.notified_for_advance
503 |
504 | def save_calendar(self, calendar):
505 | """
506 | Saves the calendar as verified and persisted
507 | :param calendar: Calendar read from ical file
508 | :return: None
509 | """
510 | config_file = CalendarsConfigFile(self.vardir, self.user_id)
511 | config_parser = config_file.read_parser()
512 |
513 | self._create_section(config_parser)
514 |
515 | self.verified = True
516 | config_parser.set(self.id, 'verified', 'true')
517 | self.name = calendar.name
518 | config_parser.set(self.id, 'name', calendar.name)
519 |
520 | self._update_last_process(config_parser)
521 |
522 | config_file.write(config_parser)
523 |
524 | def save_events(self):
525 | """
526 | Saves all tracked events into persisted file
527 | :return: None
528 | """
529 | config_file = EventsConfigFile(self.vardir, self.user_id, self.id)
530 | config_parser = ConfigParser(interpolation=None)
531 |
532 | for event in self.events.values():
533 | config_parser.add_section(event.id)
534 | if type(event.last_notified) is int:
535 | config_parser.set(event.id, 'last_notified', str(event.last_notified))
536 |
537 | config_file.write(config_parser)
538 |
539 | self.save_error(None)
540 |
541 | def save_error(self, exception):
542 | """
543 | Saves the last error
544 | :param exception: exception, can be None
545 | :return: None
546 | """
547 | config_file = CalendarsConfigFile(self.vardir, self.user_id)
548 | config_parser = config_file.read_parser()
549 | self._create_section(config_parser)
550 | self._update_last_process(config_parser, exception)
551 | config_file.write(config_parser)
552 |
553 | def _create_section(self, config_parser):
554 | if not config_parser.has_section(self.id):
555 | config_parser.add_section(self.id)
556 | config_parser.set(self.id, 'url', self.url)
557 | config_parser.set(self.id, 'channel_id', self.channel_id)
558 |
559 | def _update_last_process(self, config_parser, error=None):
560 | self.last_process_at = datetime.utcnow().isoformat()
561 | config_parser.set(self.id, 'last_process_at', self.last_process_at)
562 | self.last_process_error = error
563 | config_parser.set(self.id, 'last_process_error', str(self.last_process_error))
564 | if error is None:
565 | self.last_errors_count = 0
566 | config_parser.set(self.id, 'last_errors_count', str(self.last_errors_count))
567 | else:
568 | self.last_errors_count += 1
569 | config_parser.set(self.id, 'last_errors_count', str(self.last_errors_count))
570 | if self.last_errors_count >= self.errors_count_threshold:
571 | logger.warning('Disabling calendar %s of user %s due %s errors count',
572 | self.id, self.user_id, self.last_errors_count)
573 | self.enabled = False
574 | config_parser.set(self.id, 'enabled', str(self.enabled))
575 |
576 |
577 | class EventConfig:
578 | """
579 | Current calendar event state.
580 | """
581 |
582 | def __init__(self, calendar, id):
583 | self.id = id
584 | """the event id, as it was read from the ical file"""
585 | self.cal_id = calendar.id
586 | """ID of the calendar to which this event belongs to"""
587 | self.user_id = calendar.user_id
588 | """Chat ID of the user to whom the calendar belongs to"""
589 | self.last_notified = None
590 | """the last notification made for this event, as hours in advance, the integer or None"""
591 |
592 |
593 | class ConfigFile:
594 | """
595 | Reads and writes a config file.
596 | """
597 |
598 | def __init__(self, file_path):
599 | """
600 | Creates the config
601 | :param file_path: path to the config file
602 | """
603 | self.path = file_path
604 |
605 | def read(self, parser):
606 | """
607 | Reads the configuration from the file
608 | :param parser: ConfigParser to be read from the file
609 | :return: None
610 | """
611 | parser.read(self.path, encoding='UTF-8')
612 |
613 | def read_parser(self):
614 | """
615 | Creates the new ConfigParser and read values from file to it
616 | :return: ConfigParser instance
617 | """
618 | parser = ConfigParser(interpolation=None)
619 | self.read(parser)
620 | return parser
621 |
622 | def write(self, parser):
623 | """
624 | Writes the configuration to the file. Creates dirs and files if necessary
625 | :param parser: ConfigParser to be written
626 | :return: None
627 | """
628 | os.makedirs(os.path.dirname(self.path), exist_ok=True)
629 | with open(self.path, 'wt', encoding='UTF-8') as file:
630 | parser.write(file)
631 |
632 |
633 | class UserConfigFile(ConfigFile):
634 | """
635 | Reads and writes user settings config file.
636 | """
637 |
638 | def __init__(self, vardir, user_id):
639 | """
640 | Creates the config
641 | :param vardir: basic var dir
642 | :param user_id: user ID as string
643 | """
644 | super().__init__(os.path.join(vardir, user_id, 'settings.cfg'))
645 |
646 |
647 | class CalendarsConfigFile(ConfigFile):
648 | """
649 | Reads and writes calendars config file.
650 | """
651 |
652 | def __init__(self, vardir, user_id):
653 | """
654 | Creates the config
655 | :param vardir: basic var dir
656 | :param user_id: user ID as string
657 | """
658 | super().__init__(os.path.join(vardir, user_id, 'calendars.cfg'))
659 |
660 |
661 | class EventsConfigFile(ConfigFile):
662 | """
663 | Reads and writes events config file.
664 | """
665 |
666 | def __init__(self, vardir, user_id, cal_id):
667 | """
668 | Creates the config
669 | :param vardir: basic var dir
670 | :param user_id: user ID as string
671 | :param cal_id: ID of the calendar
672 | """
673 | super().__init__(os.path.join(vardir, user_id, cal_id, 'events.cfg'))
674 |
--------------------------------------------------------------------------------
/calbot_test.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | # Copyright 2016 Denis Nelubin.
4 | #
5 | # This file is part of Calendar Bot.
6 | #
7 | # Calendar Bot is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation, either version 3 of the License, or
10 | # (at your option) any later version.
11 | #
12 | # Calendar Bot is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU General Public License
18 | # along with Calendar Bot. If not, see http://www.gnu.org/licenses/.
19 |
20 |
21 | import datetime
22 | import os
23 | import unittest
24 | import pytz
25 | import shutil
26 | from dateutil.parser import parse
27 |
28 | from icalendar.cal import Component
29 |
30 | from calbot.formatting import normalize_locale, format_event, strip_tags
31 | from calbot.conf import CalendarConfig, Config, UserConfig, UserConfigFile, DEFAULT_FORMAT, CalendarsConfigFile
32 | from calbot.ical import Event, Calendar, filter_notified_events, sort_events
33 | from calbot.stats import update_stats, get_stats
34 |
35 |
36 | def _get_component():
37 | component = Component()
38 | component.add('summary', 'summary')
39 | component.add('location', 'location')
40 | component.add('description', 'description')
41 | return component
42 |
43 |
44 | class CalbotTestCase(unittest.TestCase):
45 |
46 | def test_format_event(self):
47 | component = _get_component()
48 | component.add('dtstart', datetime.datetime(2016, 6, 23, 19, 50, 35, tzinfo=pytz.UTC))
49 | event = Event.from_vevent(component, pytz.UTC)
50 | user_config = UserConfig.new(Config('calbot.cfg.sample'), 'TEST')
51 | result = format_event(user_config, event)
52 | self.assertEqual(
53 | 'summary\n'
54 | 'Thursday, 23 June 2016, 19:50 UTC\n'
55 | 'location\n'
56 | 'description',
57 | result)
58 |
59 | # TODO: fix event time assertion
60 | def test_read_calendar(self):
61 | config = CalendarConfig.new(
62 | UserConfig.new(Config('calbot.cfg.sample'), 'TEST'),
63 | '1', 'file://{}/test/test.ics'.format(os.path.dirname(__file__)), 'TEST')
64 |
65 | calendar = Calendar(config)
66 | self.assertEqual(pytz.timezone('Asia/Omsk'), calendar.timezone)
67 | self.assertEqual('Тест', calendar.name)
68 | self.assertEqual('Just a test calendar', calendar.description)
69 |
70 | for e in calendar.all_events:
71 | print(e)
72 | self.assertEqual(2, len(calendar.all_events))
73 | # events in the past are skipped, daily event is repeated for 48 hours to future
74 |
75 | # event in the past, skipped
76 | # event = calendar.all_events[0]
77 | # self.assertEqual(datetime.date(2016, 6, 24), event.date)
78 | # self.assertEqual(datetime.time(6, 0, 0, tzinfo=pytz.timezone('Asia/Omsk')), event.time)
79 | # self.assertEqual('Событие по-русски', event.title)
80 |
81 | # event in the past, skipped
82 | # event = calendar.all_events[1]
83 | # self.assertEqual(datetime.date(2016, 6, 23), event.date)
84 | # self.assertEqual(datetime.time(6, 0, 0, tzinfo=pytz.timezone('Asia/Omsk')), event.time)
85 | # self.assertEqual('Event title', event.title)
86 |
87 | today = datetime.date.today()
88 | event = calendar.all_events[0]
89 | self.assertEqual(today + datetime.timedelta(days=1), event.date)
90 | self.assertEqual(datetime.time(10, 0, 0, tzinfo=pytz.timezone('Asia/Omsk')), event.time)
91 | self.assertEqual('Daily event', event.title)
92 | event = calendar.all_events[1]
93 | self.assertTrue(today + datetime.timedelta(days=2), event.date)
94 | self.assertEqual(datetime.time(10, 0, 0, tzinfo=pytz.timezone('Asia/Omsk')), event.time)
95 | self.assertEqual('Daily event', event.title)
96 |
97 | def test_filter_notified_events(self):
98 | timezone = pytz.UTC
99 | component_now = _get_component()
100 | component_now.add('dtstart', datetime.datetime.now(tz=timezone) + datetime.timedelta(minutes=5))
101 | component_future24 = _get_component()
102 | component_future24.add('dtstart', datetime.datetime.now(tz=timezone) + datetime.timedelta(hours=24, minutes=-5))
103 | component_future48 = _get_component()
104 | component_future48.add('dtstart', datetime.datetime.now(tz=timezone) + datetime.timedelta(hours=48, minutes=-5))
105 |
106 | class TestCalendarConfig:
107 |
108 | def __init__(self):
109 | self.advance = [24, 48]
110 |
111 | def event(self, id):
112 | return TestEventConfig()
113 |
114 | class TestEventConfig:
115 |
116 | def __init__(self):
117 | self.id = 1
118 | self.last_notified = 48
119 |
120 | events = [Event.from_vevent(component_now, timezone), Event.from_vevent(component_future24, timezone),
121 | Event.from_vevent(component_future48, timezone)]
122 | config = TestCalendarConfig()
123 | result = list(filter_notified_events(events, config))
124 | self.assertEqual(2, len(result))
125 | self.assertEqual(component_now.decoded('dtstart'), result[0].notify_datetime)
126 | self.assertEqual(component_future24.decoded('dtstart'), result[1].notify_datetime)
127 |
128 | def test_date_only_event(self):
129 | timezone = pytz.UTC
130 | component = _get_component()
131 | component.add('dtstart', datetime.date.today())
132 | event = Event.from_vevent(component, timezone, datetime.time(10, 0))
133 | self.assertTrue(isinstance(event.date, datetime.date))
134 | self.assertIsNone(event.time)
135 | self.assertEqual(10, event.notify_datetime.hour)
136 | self.assertEqual(0, event.notify_datetime.minute)
137 | self.assertEqual(pytz.UTC, event.notify_datetime.tzinfo)
138 |
139 | def test_default_user_config(self):
140 | user_config = UserConfig.new(Config('calbot.cfg.sample'), 'TEST')
141 | self.assertEqual('var', user_config.vardir)
142 | self.assertEqual('TEST', user_config.id)
143 | self.assertEqual(DEFAULT_FORMAT, user_config.format)
144 | self.assertIsNone(user_config.language)
145 | self.assertEqual([48, 24], user_config.advance)
146 | self.assertEqual(3, user_config.errors_count_threshold)
147 |
148 | def test_default_calendar_config(self):
149 | calendar_config = CalendarConfig.new(
150 | UserConfig.new(Config('calbot.cfg.sample'), 'TEST'),
151 | '1', 'file://{}/test/test.ics'.format(os.path.dirname(__file__)), 'TEST')
152 | self.assertEqual([48, 24], calendar_config.advance)
153 | self.assertEqual(3, calendar_config.errors_count_threshold)
154 | self.assertEqual(0, calendar_config.last_errors_count)
155 | self.assertTrue(calendar_config.enabled)
156 |
157 | def test_set_format(self):
158 | user_config = UserConfig.new(Config('calbot.cfg.sample'), 'TEST')
159 | user_config.set_format("TEST FORMAT")
160 | self.assertEqual('TEST FORMAT', user_config.format)
161 | config_file = UserConfigFile('var', 'TEST')
162 | user_config = UserConfig.load(Config('calbot.cfg.sample'), 'TEST', config_file.read_parser())
163 | self.assertEqual('TEST FORMAT', user_config.format)
164 | shutil.rmtree('var/TEST')
165 |
166 | def test_set_language(self):
167 | user_config = UserConfig.new(Config('calbot.cfg.sample'), 'TEST')
168 | user_config.set_language("TEST_LANGUAGE")
169 | self.assertEqual('TEST_LANGUAGE', user_config.language)
170 | config_file = UserConfigFile('var', 'TEST')
171 | user_config = UserConfig.load(Config('calbot.cfg.sample'), 'TEST', config_file.read_parser())
172 | self.assertEqual('TEST_LANGUAGE', user_config.language)
173 | shutil.rmtree('var/TEST')
174 |
175 | def test_format_event_ru(self):
176 | component = _get_component()
177 | component.add('dtstart', datetime.datetime(2016, 6, 23, 19, 50, 35, tzinfo=pytz.UTC))
178 | event = Event.from_vevent(component, pytz.UTC)
179 | user_config = UserConfig.new(Config('calbot.cfg.sample'), 'TEST')
180 | user_config.language = 'ru_RU.UTF-8'
181 | result = format_event(user_config, event)
182 | self.assertEqual(
183 | 'summary\n'
184 | 'Четверг, 23 июня 2016, 19:50 UTC\n'
185 | 'location\n'
186 | 'description',
187 | result)
188 |
189 | def test_normalize_locale(self):
190 | result = normalize_locale('it')
191 | self.assertEqual('it_IT.UTF-8', result)
192 |
193 | def test_set_advance(self):
194 | user_config = UserConfig.new(Config('calbot.cfg.sample'), 'TEST')
195 | user_config.set_advance(['1', '3', '2', '3'])
196 | self.assertEqual([3, 2, 1], user_config.advance)
197 | config_file = UserConfigFile('var', 'TEST')
198 | user_config = UserConfig.load(Config('calbot.cfg.sample'), 'TEST', config_file.read_parser())
199 | self.assertEqual([3, 2, 1], user_config.advance)
200 | shutil.rmtree('var/TEST')
201 |
202 | def test_sort_events(self):
203 | timezone = pytz.UTC
204 | component_past = _get_component()
205 | component_past.add('dtstart', datetime.datetime.now(tz=timezone) - datetime.timedelta(hours=1))
206 | component_now = _get_component()
207 | component_now.add('dtstart', datetime.datetime.now(tz=timezone) + datetime.timedelta(minutes=10))
208 | component_future = _get_component()
209 | component_future.add('dtstart', datetime.datetime.now(tz=timezone) + datetime.timedelta(hours=2))
210 | events = [Event.from_vevent(component_future, timezone), Event.from_vevent(component_now, timezone),
211 | Event.from_vevent(component_past, timezone)]
212 | result = list(sort_events(events))
213 | self.assertEqual(events[2], result[0])
214 | self.assertEqual(events[1], result[1])
215 | self.assertEqual(events[0], result[2])
216 |
217 | def test_format_date_only_event(self):
218 | timezone = pytz.UTC
219 | component = _get_component()
220 | component.add('dtstart', datetime.date(2016, 6, 23))
221 | event = Event.from_vevent(component, timezone, datetime.time(10, 0))
222 | user_config = UserConfig.new(Config('calbot.cfg.sample'), 'TEST')
223 | result = format_event(user_config, event)
224 | self.assertEqual(
225 | 'summary\n'
226 | 'Thursday, 23 June 2016\n'
227 | 'location\n'
228 | 'description',
229 | result)
230 |
231 | def test_save_calendar(self):
232 | calendar_config = CalendarConfig.new(
233 | UserConfig.new(Config('calbot.cfg.sample'), 'TEST'),
234 | '1', 'file://{}/test/test.ics'.format(os.path.dirname(__file__)), 'TEST')
235 | calendar = Calendar(calendar_config)
236 | calendar_config.save_calendar(calendar)
237 | config_file = CalendarsConfigFile('var', 'TEST')
238 | calendar_config = CalendarConfig.load(
239 | UserConfig.new(Config('calbot.cfg.sample'), 'TEST'),
240 | config_file.read_parser(),
241 | '1')
242 | self.assertEqual('Тест', calendar_config.name)
243 | self.assertEqual(3, calendar_config.errors_count_threshold)
244 | self.assertEqual(0, calendar_config.last_errors_count)
245 | self.assertTrue(calendar_config.enabled)
246 | shutil.rmtree('var/TEST')
247 |
248 | def test_update_stats(self):
249 | config = Config('calbot.cfg.sample')
250 | update_stats(config)
251 | stats1 = get_stats(config)
252 | calendar_config = CalendarConfig.new(
253 | UserConfig.new(config, 'TEST'),
254 | '1', 'file://{}/test/test.ics'.format(os.path.dirname(__file__)), 'TEST')
255 | calendar = Calendar(calendar_config)
256 | calendar_config.save_calendar(calendar)
257 | update_stats(config)
258 | stats2 = get_stats(config)
259 | self.assertEqual(1, (stats2.users - stats1.users))
260 | self.assertEqual(1, (stats2.calendars - stats1.calendars))
261 | self.assertEqual(stats2.events, stats1.events)
262 | shutil.rmtree('var/TEST')
263 |
264 | def test_calendar_save_error(self):
265 | calendar_config = CalendarConfig.new(
266 | UserConfig.new(Config('calbot.cfg.sample'), 'TEST'),
267 | '1', 'file://{}/test/test.ics'.format(os.path.dirname(__file__)), 'TEST')
268 | now = datetime.datetime.utcnow()
269 | calendar_config.save_error(Exception('TEST ERROR'))
270 | config_file = CalendarsConfigFile('var', 'TEST')
271 | calendar_config = CalendarConfig.load(
272 | UserConfig.new(Config('calbot.cfg.sample'), 'TEST'),
273 | config_file.read_parser(),
274 | '1')
275 | self.assertTrue(parse(calendar_config.last_process_at) > now)
276 | self.assertEqual('TEST ERROR', calendar_config.last_process_error)
277 | self.assertEqual(3, calendar_config.errors_count_threshold)
278 | self.assertEqual(1, calendar_config.last_errors_count)
279 | self.assertTrue(calendar_config.enabled)
280 |
281 | now = datetime.datetime.utcnow()
282 | calendar_config.save_error(Exception('TEST ERROR 2'))
283 | calendar_config = CalendarConfig.load(
284 | UserConfig.new(Config('calbot.cfg.sample'), 'TEST'),
285 | config_file.read_parser(),
286 | '1')
287 | calendar_config.save_error(Exception('TEST ERROR 3'))
288 | calendar_config = CalendarConfig.load(
289 | UserConfig.new(Config('calbot.cfg.sample'), 'TEST'),
290 | config_file.read_parser(),
291 | '1')
292 | self.assertTrue(parse(calendar_config.last_process_at) > now)
293 | self.assertEqual('TEST ERROR 3', calendar_config.last_process_error)
294 | self.assertEqual(3, calendar_config.last_errors_count)
295 | self.assertFalse(calendar_config.enabled)
296 |
297 | shutil.rmtree('var/TEST')
298 |
299 | def test_format_event_html(self):
300 | component = Component()
301 | component.add('summary', 'summary')
302 | component.add('location', 'location')
303 | component.add('description',
304 | 'description'
305 | '
'
306 | '
link')
307 | component.add('dtstart', datetime.datetime(2018, 2, 3, 13, 3, 4, tzinfo=pytz.UTC))
308 | event = Event.from_vevent(component, pytz.UTC)
309 | user_config = UserConfig.new(Config('calbot.cfg.sample'), 'TEST')
310 | user_config.language = 'ru_RU.UTF-8'
311 | result = format_event(user_config, event)
312 | self.assertEqual(
313 | 'summary\n'
314 | 'Суббота, 03 февраля 2018, 13:03 UTC\n'
315 | 'location\n'
316 | 'description'
317 | '\n'
318 | '\n link (link.html)',
319 | result)
320 |
321 | def test_format_event_blanks(self):
322 | component = Component()
323 | component.add('dtstart', datetime.datetime(2018, 2, 3, 13, 3, 4, tzinfo=pytz.UTC))
324 | event = Event.from_vevent(component, pytz.UTC)
325 | user_config = UserConfig.new(Config('calbot.cfg.sample'), 'TEST')
326 | user_config.language = 'ru_RU.UTF-8'
327 | result = format_event(user_config, event)
328 | self.assertEqual(
329 | 'None\n'
330 | 'Суббота, 03 февраля 2018, 13:03 UTC\n'
331 | 'None\n'
332 | 'None',
333 | result)
334 |
335 | def test_strip_tags_href(self):
336 | result = strip_tags('example\n'
337 | 'http://example.com\n'
338 | 'example.com\n'
339 | 'mlomsk.1der.link/telegram/chat\n')
340 | self.assertEqual('example (http://example.com)\n'
341 | 'http://example.com\n'
342 | 'example.com\n'
343 | 'mlomsk.1der.link/telegram/chat\n', result)
344 |
345 | def test_format_event_real_html_tags_br_and_a(self):
346 | component = Component()
347 | component.add('summary', 'Встреча ML-клуба')
348 | component.add('location', 'ул. Таубе, 5, Омск, Омская обл., Россия, 644037')
349 | component.add('description',
350 | '10 февраля в 11:00 пройдет 5-я встреча ML клуба'
351 | ' в офисе 7bits, Таубе 5. '
352 | 'Регистрация на встречу: mlomsk.1der.link/meetup/signup.'
353 | '
'
354 | '
'
355 | 'В этот раз у нас будет 2 доклада:')
356 | timezone = pytz.timezone('Asia/Omsk')
357 | component.add('dtstart', datetime.datetime(2018, 2, 10, 11, 0, 0, tzinfo=timezone))
358 | event = Event.from_vevent(component, timezone)
359 | user_config = UserConfig.new(Config('calbot.cfg.sample'), 'TEST')
360 | user_config.language = 'ru_RU.UTF-8'
361 | result = format_event(user_config, event)
362 | self.assertEqual(
363 | 'Встреча ML-клуба\n'
364 | 'Суббота, 10 февраля 2018, 11:00 Asia/Omsk\n'
365 | 'ул. Таубе, 5, Омск, Омская обл., Россия, 644037\n'
366 | '10 февраля в 11:00 пройдет 5-я встреча ML клуба (https://vk.com/mlomsk)'
367 | ' в офисе 7bits (https://vk.com/7bits), Таубе 5. '
368 | 'Регистрация на встречу: mlomsk.1der.link/meetup/signup.'
369 | '\n'
370 | '\n'
371 | 'В этот раз у нас будет 2 доклада:',
372 | result)
373 |
374 | def test_format_event_real_html_tag_p(self):
375 | component = Component()
376 | component.add('summary', 'Встреча ML-клуба')
377 | component.add('location', 'ул. Таубе, 5, Омск, Омская обл., Россия, 644037')
378 | component.add('description',
379 | '10 февраля в 11:00 пройдет 5-я встреча ML клуба'
380 | ' в офисе 7bits, Таубе 5.'
381 | 'Регистрация на встречу
')
382 | timezone = pytz.timezone('Asia/Omsk')
383 | component.add('dtstart', datetime.datetime(2018, 2, 10, 11, 0, 0, tzinfo=timezone))
384 | event = Event.from_vevent(component, timezone)
385 | user_config = UserConfig.new(Config('calbot.cfg.sample'), 'TEST')
386 | user_config.language = 'ru_RU.UTF-8'
387 | result = format_event(user_config, event)
388 | self.assertEqual(
389 | 'Встреча ML-клуба\n'
390 | 'Суббота, 10 февраля 2018, 11:00 Asia/Omsk\n'
391 | 'ул. Таубе, 5, Омск, Омская обл., Россия, 644037\n'
392 | '10 февраля в 11:00 пройдет 5-я встреча ML клуба (https://vk.com/mlomsk)'
393 | ' в офисе 7bits (https://vk.com/7bits), Таубе 5.'
394 | '\nРегистрация на встречу',
395 | result)
396 |
397 | def test_format_event_real_html_tag_p_with_style(self):
398 | component = Component()
399 | component.add('summary', 'Встреча ML-клуба')
400 | component.add('location', 'ул. Таубе, 5, Омск, Омская обл., Россия, 644037')
401 | component.add('description',
402 | '10 февраля в 11:00 пройдет 5-я встреча ML клуба'
403 | ' в офисе 7bits, Таубе 5.'
404 | 'Регистрация на встречу
')
405 | timezone = pytz.timezone('Asia/Omsk')
406 | component.add('dtstart', datetime.datetime(2018, 2, 10, 11, 0, 0, tzinfo=timezone))
407 | event = Event.from_vevent(component, timezone)
408 | user_config = UserConfig.new(Config('calbot.cfg.sample'), 'TEST')
409 | user_config.language = 'ru_RU.UTF-8'
410 | result = format_event(user_config, event)
411 | self.assertEqual(
412 | 'Встреча ML-клуба\n'
413 | 'Суббота, 10 февраля 2018, 11:00 Asia/Omsk\n'
414 | 'ул. Таубе, 5, Омск, Омская обл., Россия, 644037\n'
415 | '10 февраля в 11:00 пройдет 5-я встреча ML клуба (https://vk.com/mlomsk)'
416 | ' в офисе 7bits (https://vk.com/7bits), Таубе 5.'
417 | '\nРегистрация на встречу',
418 | result)
419 |
420 | def test_format_event_real_html_tags_p(self):
421 | component = Component()
422 | component.add('summary', 'Встреча ML-клуба')
423 | component.add('location', 'ул. Таубе, 5, Омск, Омская обл., Россия, 644037')
424 | component.add('description',
425 | '10 февраля в 11:00 пройдет 5-я встреча ML клуба'
426 | ' в офисе 7bits, Таубе 5.
'
427 | 'Регистрация на встречу: mlomsk.1der.link/meetup/signup.
'
428 | 'В этот раз у нас будет 2 доклада:
')
429 | timezone = pytz.timezone('Asia/Omsk')
430 | component.add('dtstart', datetime.datetime(2018, 2, 10, 11, 0, 0, tzinfo=timezone))
431 | event = Event.from_vevent(component, timezone)
432 | user_config = UserConfig.new(Config('calbot.cfg.sample'), 'TEST')
433 | user_config.language = 'ru_RU.UTF-8'
434 | result = format_event(user_config, event)
435 | self.assertEqual(
436 | 'Встреча ML-клуба\n'
437 | 'Суббота, 10 февраля 2018, 11:00 Asia/Omsk\n'
438 | 'ул. Таубе, 5, Омск, Омская обл., Россия, 644037\n'
439 | '\n10 февраля в 11:00 пройдет 5-я встреча ML клуба (https://vk.com/mlomsk)'
440 | ' в офисе 7bits (https://vk.com/7bits), Таубе 5.\n'
441 | '\nРегистрация на встречу: mlomsk.1der.link/meetup/signup.\n'
442 | '\nВ этот раз у нас будет 2 доклада:',
443 | result)
444 |
445 | def test_format_event_real_html_tags_ul_li(self):
446 | component = Component()
447 | component.add('summary', 'Встреча ML-клуба')
448 | component.add('location', 'ул. Таубе, 5, Омск, Омская обл., Россия, 644037')
449 | component.add('description',
450 | 'Всем привет!
'
451 | 'Список:
'
452 | ''
453 | '- что-то
'
454 | '- что-то еще
'
455 | '
'
456 | 'Конец!')
457 | timezone = pytz.timezone('Asia/Omsk')
458 | component.add('dtstart', datetime.datetime(2018, 2, 10, 11, 0, 0, tzinfo=timezone))
459 | event = Event.from_vevent(component, timezone)
460 | user_config = UserConfig.new(Config('calbot.cfg.sample'), 'TEST')
461 | user_config.language = 'ru_RU.UTF-8'
462 | result = format_event(user_config, event)
463 | self.assertEqual(
464 | 'Встреча ML-клуба\n'
465 | 'Суббота, 10 февраля 2018, 11:00 Asia/Omsk\n'
466 | 'ул. Таубе, 5, Омск, Омская обл., Россия, 644037\n'
467 | '\nВсем привет!\n'
468 | '\nСписок:\n'
469 | '\n'
470 | '* что-то\n'
471 | '* что-то еще\n'
472 | '\n'
473 | 'Конец!',
474 | result)
475 |
476 | def test_format_event_real_html_tags_ul_in_p(self):
477 | component = Component()
478 | component.add('summary', 'Встреча ML-клуба')
479 | component.add('location', 'ул. Таубе, 5, Омск, Омская обл., Россия, 644037')
480 | component.add('description',
481 | 'Всем привет!
'
482 | 'Список:'
483 | '
'
484 | '- что-то
'
485 | '- что-то еще
'
486 | '
'
487 | '
'
488 | 'Конец!')
489 | timezone = pytz.timezone('Asia/Omsk')
490 | component.add('dtstart', datetime.datetime(2018, 2, 10, 11, 0, 0, tzinfo=timezone))
491 | event = Event.from_vevent(component, timezone)
492 | user_config = UserConfig.new(Config('calbot.cfg.sample'), 'TEST')
493 | user_config.language = 'ru_RU.UTF-8'
494 | result = format_event(user_config, event)
495 | self.assertEqual(
496 | 'Встреча ML-клуба\n'
497 | 'Суббота, 10 февраля 2018, 11:00 Asia/Omsk\n'
498 | 'ул. Таубе, 5, Омск, Омская обл., Россия, 644037\n'
499 | '\nВсем привет!\n'
500 | '\nСписок:'
501 | '\n'
502 | '* что-то\n'
503 | '* что-то еще\n'
504 | '\n'
505 | 'Конец!',
506 | result)
507 |
508 | def test_format_event_real_html_tags_ul_nested(self):
509 | component = Component()
510 | component.add('summary', 'Встреча ML-клуба')
511 | component.add('location', 'ул. Таубе, 5, Омск, Омская обл., Россия, 644037')
512 | component.add('description',
513 | 'Всем привет!
'
514 | 'Список:
'
515 | ''
516 | '- что-то
'
517 | '- список внутри:'
518 | '
'
519 | '- внутри что-то
'
520 | '- внутри что-то еще
'
521 | '
'
522 | ' '
523 | '- что-то еще
'
524 | '
'
525 | 'Конец!')
526 | timezone = pytz.timezone('Asia/Omsk')
527 | component.add('dtstart', datetime.datetime(2018, 2, 10, 11, 0, 0, tzinfo=timezone))
528 | event = Event.from_vevent(component, timezone)
529 | user_config = UserConfig.new(Config('calbot.cfg.sample'), 'TEST')
530 | user_config.language = 'ru_RU.UTF-8'
531 | result = format_event(user_config, event)
532 | self.assertEqual(
533 | 'Встреча ML-клуба\n'
534 | 'Суббота, 10 февраля 2018, 11:00 Asia/Omsk\n'
535 | 'ул. Таубе, 5, Омск, Омская обл., Россия, 644037\n'
536 | '\nВсем привет!\n'
537 | '\nСписок:\n'
538 | '\n'
539 | '* что-то\n'
540 | '* список внутри:\n'
541 | ' * внутри что-то\n'
542 | ' * внутри что-то еще\n'
543 | '* что-то еще\n'
544 | '\n'
545 | 'Конец!',
546 | result)
547 |
548 | def test_format_event_real_html_tags_ol_li(self):
549 | component = Component()
550 | component.add('summary', 'Встреча ML-клуба')
551 | component.add('location', 'ул. Таубе, 5, Омск, Омская обл., Россия, 644037')
552 | component.add('description',
553 | 'Всем привет!
'
554 | 'Список:
'
555 | ''
556 | '- что-то
'
557 | '- что-то еще
'
558 | '
'
559 | 'Конец!')
560 | timezone = pytz.timezone('Asia/Omsk')
561 | component.add('dtstart', datetime.datetime(2018, 2, 10, 11, 0, 0, tzinfo=timezone))
562 | event = Event.from_vevent(component, timezone)
563 | user_config = UserConfig.new(Config('calbot.cfg.sample'), 'TEST')
564 | user_config.language = 'ru_RU.UTF-8'
565 | result = format_event(user_config, event)
566 | self.assertEqual(
567 | 'Встреча ML-клуба\n'
568 | 'Суббота, 10 февраля 2018, 11:00 Asia/Omsk\n'
569 | 'ул. Таубе, 5, Омск, Омская обл., Россия, 644037\n'
570 | '\nВсем привет!\n'
571 | '\nСписок:\n'
572 | '\n'
573 | '* что-то\n'
574 | '* что-то еще\n'
575 | '\n'
576 | 'Конец!',
577 | result)
578 |
579 | def test_format_event_real_html_tags_ul_li_p(self):
580 | component = Component()
581 | component.add('summary', 'Встреча ML-клуба')
582 | component.add('location', 'ул. Таубе, 5, Омск, Омская обл., Россия, 644037')
583 | component.add('description',
584 | 'Майский IT-субботник доверяем Gems Development!
'
585 | 'Ребята подготовят митап для разработчиков.
'
586 | 'Темы:
'
587 | ''
591 | 'До встречи!')
592 | timezone = pytz.timezone('Asia/Omsk')
593 | component.add('dtstart', datetime.datetime(2018, 2, 10, 11, 0, 0, tzinfo=timezone))
594 | event = Event.from_vevent(component, timezone)
595 | user_config = UserConfig.new(Config('calbot.cfg.sample'), 'TEST')
596 | user_config.language = 'ru_RU.UTF-8'
597 | result = format_event(user_config, event)
598 | self.assertEqual(
599 | 'Встреча ML-клуба\n'
600 | 'Суббота, 10 февраля 2018, 11:00 Asia/Omsk\n'
601 | 'ул. Таубе, 5, Омск, Омская обл., Россия, 644037\n'
602 | '\nМайский IT-субботник доверяем Gems Development!\n '
603 | '\nРебята подготовят митап для разработчиков.\n'
604 | '\nТемы: \n'
605 | '\n'
606 | '* Андрей: «Vue.js».\n'
607 | '* Виктор «Гибкие механизмы».\n'
608 | '\n'
609 | 'До встречи!',
610 | result)
611 |
612 | def test_read_repeated_event_override(self):
613 | timezone = pytz.timezone('Asia/Omsk')
614 |
615 | config = CalendarConfig.new(
616 | UserConfig.new(Config('calbot.cfg.sample'), 'TEST'),
617 | '1', 'file://{}/test/repeat.ics'.format(os.path.dirname(__file__)), 'TEST')
618 | calendar = Calendar(config)
619 | self.assertEqual(timezone, calendar.timezone)
620 |
621 | events = sort_events(list(
622 | calendar.read_ical(calendar.url,
623 | datetime.datetime(2020, 3, 23, 0, 0, 0, tzinfo=timezone),
624 | datetime.datetime(2020, 4, 26, 23, 59, 59, tzinfo=timezone))
625 | ))
626 |
627 | for e in events:
628 | print(e)
629 | self.assertEqual(3, len(events))
630 |
631 | event = events[0]
632 | self.assertEqual(datetime.date(2020, 3, 25), event.date)
633 | self.assertEqual(datetime.time(19, 0, 0, tzinfo=timezone), event.time)
634 | self.assertEqual('Дата Ужин (OML)', event.title)
635 | self.assertRegex(event.description, r'Пиццот')
636 | event = events[1]
637 | self.assertEqual(datetime.date(2020, 4, 8), event.date)
638 | self.assertEqual(datetime.time(19, 0, 0, tzinfo=timezone), event.time)
639 | self.assertEqual('Дата Ужин (OML)', event.title)
640 | self.assertRegex(event.description, r'discord')
641 | event = events[2]
642 | self.assertEqual(datetime.date(2020, 4, 22), event.date)
643 | self.assertEqual(datetime.time(19, 0, 0, tzinfo=timezone), event.time)
644 | self.assertEqual('Дата Ужин (OML)', event.title)
645 | self.assertRegex(event.description, r'Пиццот')
646 |
647 | ids = set(map(lambda e: e.id, events))
648 | self.assertEqual(len(events), len(ids)) # all ids must be unique
649 |
650 | def test_read_repeated_event_until(self):
651 | timezone = pytz.timezone('Asia/Omsk')
652 |
653 | config = CalendarConfig.new(
654 | UserConfig.new(Config('calbot.cfg.sample'), 'TEST'),
655 | '1', 'file://{}/test/repeat.ics'.format(os.path.dirname(__file__)), 'TEST')
656 | calendar = Calendar(config)
657 |
658 | events = sort_events(list(
659 | calendar.read_ical(calendar.url,
660 | datetime.datetime(2019, 1, 21, 0, 0, 0, tzinfo=timezone),
661 | datetime.datetime(2019, 2, 10, 23, 59, 59, tzinfo=timezone))
662 | ))
663 |
664 | for e in events:
665 | print(e)
666 | self.assertEqual(4, len(events))
667 |
668 | event = events[0]
669 | self.assertEqual(datetime.date(2019, 1, 23), event.date)
670 | self.assertEqual(datetime.time(19, 0, 0, tzinfo=timezone), event.time)
671 | self.assertEqual('Дата ужин (OML)', event.title)
672 | self.assertRegex(event.description, r'Бутерbrot')
673 | event = events[3]
674 | self.assertEqual(datetime.date(2019, 2, 6), event.date)
675 | self.assertEqual(datetime.time(19, 0, 0, tzinfo=timezone), event.time)
676 | self.assertEqual('Дата ужин (OML)', event.title)
677 | self.assertRegex(event.description, r'Розы Морозы')
678 |
679 | print('---')
680 |
681 | events = sort_events(list(
682 | calendar.read_ical(calendar.url,
683 | datetime.datetime(2019, 3, 4, 0, 0, 0, tzinfo=timezone),
684 | datetime.datetime(2019, 3, 24, 23, 59, 59, tzinfo=timezone))
685 | ))
686 |
687 | for e in events:
688 | print(e)
689 | self.assertEquals(5, len(events))
690 |
691 | event = events[0]
692 | self.assertEqual(datetime.date(2019, 3, 6), event.date)
693 | self.assertEqual(datetime.time(19, 0, 0, tzinfo=timezone), event.time)
694 | self.assertEqual('Дата ужин (OML)', event.title)
695 | self.assertRegex(event.description, r'Розы Морозы')
696 | event = events[3]
697 | self.assertEqual(datetime.date(2019, 3, 20), event.date)
698 | self.assertEqual(datetime.time(19, 0, 0, tzinfo=timezone), event.time)
699 | self.assertEqual('Дата ужин (OML)', event.title)
700 | self.assertRegex(event.description, r'Пиццот')
701 |
702 | def test_read_repeated_event_exdate(self):
703 | timezone = pytz.timezone('Asia/Omsk')
704 |
705 | config = CalendarConfig.new(
706 | UserConfig.new(Config('calbot.cfg.sample'), 'TEST'),
707 | '1', 'file://{}/test/repeat.ics'.format(os.path.dirname(__file__)), 'TEST')
708 | calendar = Calendar(config)
709 |
710 | events = sort_events(list(
711 | calendar.read_ical(calendar.url,
712 | datetime.datetime(2019, 12, 16, 0, 0, 0, tzinfo=timezone),
713 | datetime.datetime(2020, 1, 19, 23, 59, 59, tzinfo=timezone))
714 | ))
715 |
716 | for e in events:
717 | print(e)
718 | self.assertEqual(2, len(events))
719 |
720 | event = events[0]
721 | self.assertEqual(datetime.date(2019, 12, 18), event.date)
722 | self.assertEqual(datetime.time(19, 0, 0, tzinfo=timezone), event.time)
723 | self.assertEqual('Дата Ужин (OML)', event.title)
724 | self.assertRegex(event.description, r'Пиццот')
725 | event = events[1]
726 | self.assertEqual(datetime.date(2020, 1, 15), event.date)
727 | self.assertEqual(datetime.time(19, 0, 0, tzinfo=timezone), event.time)
728 | self.assertEqual('Дата Ужин (OML)', event.title)
729 | self.assertRegex(event.description, r'Пиццот')
730 |
--------------------------------------------------------------------------------
/ansible/roles/letsencrypt/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------