From 95a8889cbfde5c30146579d64d306f7bf0d1d818 Mon Sep 17 00:00:00 2001 From: Alexander Popov Date: Tue, 31 Mar 2020 01:55:11 +0300 Subject: [PATCH] fix scripts auto installation pep8 code refactoring --- README.md | 46 +++++-------------- .preview.png => asset/.preview.png | Bin config.json.example | 3 +- install.sh | 44 ++++++++++++++++++ systemd/user/vk0nline.service | 3 +- vk0nline.py | 70 +++++++++++++++++------------ 6 files changed, 101 insertions(+), 65 deletions(-) rename .preview.png => asset/.preview.png (100%) create mode 100644 install.sh diff --git a/README.md b/README.md index 1ca4eb6..97b68ef 100644 --- a/README.md +++ b/README.md @@ -1,35 +1,11 @@ - -# vk.com set online status service -Набор скриптов для поддержания статуса __Онлайн__ в социальной сети Vk.com -![preview](https://raw.githubusercontent.com/iiiypuk/vk0nline/master/.preview.png) -Набор включает в себя скрипт на `Python` и юнит для `systemd`. +# service for set status online on vk.com +Скрипт для поддержания статуса __Онлайн__ в социальной сети Vk.com +включает в себя `Python` скрипт `systemd` юнит. +![preview](https://raw.githubusercontent.com/iiiypuk/vk0nline/master/asset/.preview.png) ## Установка: -+ Скачать и распаковать набор скриптов, например в `/home/$USER/.vk0nline` -+ Создать директорию для юнитов systemd: `mkdir -p ~/.config/systemd/user` -и перейти в неё: `cd ~/.config/systemd/user` -+ Сделать символические ссылки на сервис и таймер: -``` -ln -s /home/user_name/.vk0nline/systemd/user/vk0nline.service . -ln -s /home/user_name/.vk0nline/systemd/user/vk0nline.timer . -``` -+ Изменить настройки скрипта и сделать его исполняемым: -``` -cd ~/.vk0nline/ -mv config.json.example config.json -chmod 755 ./vk0nline.py -edit config.json -``` -+ Прописать полный путь к файлу конфигурации в скрипте: -```python -# EDIT IT -with open('./config.json', 'r', encoding='utf-8') as f: -``` -+ Прописать полный путь к файлу скрипта в сервисе systemd: -`edit ~/.config/systemd/user/vk0nline.service` -`ExecStart=/full/path/to/vk0nline.py` -+ Активируем автоматический запуск сессии пользователя -``` ++ Активировать автоматический запуск сессии пользователя +```console # Изменить параметр ReadWritePaths=/etc /run /var/lib/systemd/linger nano /usr/lib/systemd/system/systemd-logind.service # Перезапустить сервисы @@ -38,8 +14,10 @@ systemctl daemon-reload mkdir /var/lib/systemd/linger loginctl enable-linger $USER ``` -+ Активируем и запускаем скрипт: -``` -systemctl start vk0nline.{service,timer} --user -systemctl enable vk0nline.{service,timer} --user + ++ Скачать и запустить установщик +```console +curl -Lsk https://raw.githubusercontent.com/iiiypuk/vk0nline/master/install.sh | sh ``` + ++ Следовать инструкциям установщика diff --git a/.preview.png b/asset/.preview.png similarity index 100% rename from .preview.png rename to asset/.preview.png diff --git a/config.json.example b/config.json.example index 2e544cd..da90d7f 100644 --- a/config.json.example +++ b/config.json.example @@ -2,6 +2,5 @@ "clientId": 1, "secureKey": "", "serviceKey": "", - "accessToken": "", - "userIds": "" + "accessToken": "" } diff --git a/install.sh b/install.sh new file mode 100644 index 0000000..ab8f75c --- /dev/null +++ b/install.sh @@ -0,0 +1,44 @@ +#!/bin/sh + +# Prepating installation +mkdir -p /home/$USER/.local/share/emilecok/vk0nline +mkdir -p /home/$USER/.config/emilecok/vk0nline + +if [ -x "$(command -v git)" ]; then + echo Installing distribution via Git... + + git clone https://github.com/iiiypuk/vk0nline.git --depth 1 /home/$USER/.local/share/emilecok/vk0nline &> /dev/null +elif [ -x "$(command -v unzip)" ]; then + echo Installing distribution via zip file... + + cd /home/$USER/.local/share/emilecok/vk0nline + curl -LsOk https://github.com/iiiypuk/vk0nline/archive/master.zip + unzip master.zip + mv vk0nline-master vk0nline +else + echo Git +fi + +cd /home/$USER/.local/share/emilecok/vk0nline +sed "s/USERNAME/$USER/" ./systemd/user/vk0nline.service &> /dev/null +chmod 755 ./vk0nline.py +cp -p ./config.json.example /home/$USER/.config/emilecok/vk0nline/config.json &> /dev/null + +echo Installing systemd services... +mkdir -p /home/$USER/.config/systemd/user + +cd /home/$USER/.config/systemd/user +ln -s /home/$USER/.local/share/emilecok/vk0nline/systemd/user/vk0nline.service . &> /dev/null +ln -s /home/$USER/.local/share/emilecok/vk0nline/systemd/user/vk0nline.timer . &> /dev/null + +echo Installation complete. +echo +echo Start script, authorize and save access token +echo :: python /home/$USER/.config/emilecok/vk0nline/ +echo +echo Edit configuration file +echo :: by ./home/$USER/.local/share/emilecok/vk0nline/vk0nline.py +echo +echo And start \& activate systemd services +echo :: systemctl start vk0nline.\{service,timer\} --user +echo :: systemctl enable vk0nline.\{service,timer\} --user diff --git a/systemd/user/vk0nline.service b/systemd/user/vk0nline.service index 15962ed..826c598 100644 --- a/systemd/user/vk0nline.service +++ b/systemd/user/vk0nline.service @@ -1,9 +1,10 @@ [Unit] Description=vk.com set online status service +After=network.target network-online.target nss-lookup.target [Service] Type=simple -ExecStart=/full/path/to/vk0nline.py +ExecStart=/home/USERNAME/.local/share/emilecok/vk0nline/vk0nline.py [Install] WantedBy=default.target diff --git a/vk0nline.py b/vk0nline.py index e8ce062..e5d503f 100644 --- a/vk0nline.py +++ b/vk0nline.py @@ -3,49 +3,63 @@ import json import requests from datetime import datetime +import getpass + __author__ = 'Alexander Popov' __copyright__ = '2019 by iiiypuk' __credits__ = ['Alexander Popov'] __license__ = 'Unlicense' -__version__ = '1.0.0' +__version__ = '1.0.1' __maintainer__ = 'Alexander Popov' __email__ = 'iiiypuk@fastmail.fm' __status__ = 'Production' -# EDIT IT -with open('./config.json', 'r', encoding='utf-8') as f: +username = getpass.getuser() +with open('/home/{user}/.config/emilecok/vk0nline/config.json' + .format(user=getpass.getuser()), 'r', encoding='utf-8') as f: _C = json.load(f) + def getStatus(): - response = requests.get('https://api.vk.com/method/users.get?' + \ - 'fields=online,last_seen&v=5.95' + \ - '&access_token={key}&user_ids={user}'.format( - key=_C['serviceKey'], user=_C['userIds'])) - - userLoginTime = json.loads(response.content.decode('utf-8'))['response'][0]['last_seen']['time'] - userOnline = json.loads(response.content.decode('utf-8'))['response'][0]['online'] + response = requests.get('https://api.vk.com/method/users.get?' + 'fields=online,last_seen&v=5.95' + '&access_token={key}&user_ids={user}' + .format(key=_C['serviceKey'], user=_C['clientId'])) + userLoginTime = json.loads(response.content.decode('utf-8')) + userLoginTime = userLoginTime['response'][0]['last_seen']['time'] + userOnline = json.loads(response.content.decode('utf-8')) + userOnline = userOnline['response'][0]['online'] return([userOnline, userLoginTime]) + def setOnline(): - response = requests.get('https://api.vk.com/method/account.setOnline' + \ - '?voip=0&v=5.95&access_token={key}'.format(key=_C['accessToken']) + \ - '&user_ids={user}'.format(user=_C['userIds'])) - content = json.loads(response.content.decode('utf-8')) + response = requests.get('https://api.vk.com/method/account.setOnline?' + 'voip=0&v=5.95&access_token={key}&user_ids={user}' + .format(user=_C['clientId'], + key=_C['accessToken'])) + content = json.loads(response.content.decode('utf-8')) - if 'error' in content: - if 5 == content['error']['error_code']: # User authorization failed - print('User authorization failed.\nOpen this link in browser, and copy access token.') - print('https://oauth.vk.com/authorize?client_id={appid}'.format(appid=_C['clientId']) + \ - '&redirect_uri=vk.com&display=mobile&response_type=' + \ - 'token&v=5.95&revoke=1&state=01010&scope=offline') - else: - print('Error: {}.'.format(content['error']['error_code'])) - elif 'response' in content: - if 1 == content['response']: - print('Ok!') - onlineStatus, lastSeen = getStatus() - print(onlineStatus, datetime.fromtimestamp(lastSeen).strftime('%Y-%m-%d %H:%M:%S')) + if 'error' in content: + # User authorization failed + if 5 == content['error']['error_code']: + print('User authorization failed.\n', + 'Open this link in browser, and copy access token.') + print('https://oauth.vk.com/authorize?client_id={appid}' + '&redirect_uri=vk.com&display=mobile&response_type=token' + '&v=5.95&revoke=1&state=01010&scope=offline' + .format(appid=_C['clientId'])) + else: + print('Error: {}.'.format(content['error']['error_code'])) + elif 'response' in content: + if 1 == content['response']: + print('Ok!') + onlineStatus, lastSeen = getStatus() + lastSeen = datetime.fromtimestamp(lastSeen) \ + .strftime('%Y-%m-%d %H:%M:%S') + print(onlineStatus, lastSeen) -if __name__ == "__main__": setOnline() + +if __name__ == "__main__": + setOnline()