fix scripts

auto installation
pep8 code refactoring
This commit is contained in:
Alexander Popov 2020-03-31 01:55:11 +03:00
parent 7b7e7e49c7
commit 95a8889cbf
6 changed files with 101 additions and 65 deletions

View File

@ -1,35 +1,11 @@
# service for set status online on vk.com
# vk.com set online status service Скрипт для поддержания статуса __Онлайн__ в социальной сети Vk.com
Набор скриптов для поддержания статуса __Онлайн__ в социальной сети Vk.com включает в себя `Python` скрипт `systemd` юнит.
![preview](https://raw.githubusercontent.com/iiiypuk/vk0nline/master/.preview.png) ![preview](https://raw.githubusercontent.com/iiiypuk/vk0nline/master/asset/.preview.png)
Набор включает в себя скрипт на `Python` и юнит для `systemd`.
## Установка: ## Установка:
+ Скачать и распаковать набор скриптов, например в `/home/$USER/.vk0nline` + Активировать автоматический запуск сессии пользователя
+ Создать директорию для юнитов systemd: `mkdir -p ~/.config/systemd/user` ```console
и перейти в неё: `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`
+ Активируем автоматический запуск сессии пользователя
```
# Изменить параметр ReadWritePaths=/etc /run /var/lib/systemd/linger # Изменить параметр ReadWritePaths=/etc /run /var/lib/systemd/linger
nano /usr/lib/systemd/system/systemd-logind.service nano /usr/lib/systemd/system/systemd-logind.service
# Перезапустить сервисы # Перезапустить сервисы
@ -38,8 +14,10 @@ systemctl daemon-reload
mkdir /var/lib/systemd/linger mkdir /var/lib/systemd/linger
loginctl enable-linger $USER loginctl enable-linger $USER
``` ```
+ Активируем и запускаем скрипт:
``` + Скачать и запустить установщик
systemctl start vk0nline.{service,timer} --user ```console
systemctl enable vk0nline.{service,timer} --user curl -Lsk https://raw.githubusercontent.com/iiiypuk/vk0nline/master/install.sh | sh
``` ```
+ Следовать инструкциям установщика

View File

Before

Width:  |  Height:  |  Size: 8.4 KiB

After

Width:  |  Height:  |  Size: 8.4 KiB

View File

@ -2,6 +2,5 @@
"clientId": 1, "clientId": 1,
"secureKey": "", "secureKey": "",
"serviceKey": "", "serviceKey": "",
"accessToken": "", "accessToken": ""
"userIds": ""
} }

44
install.sh Normal file
View File

@ -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

View File

@ -1,9 +1,10 @@
[Unit] [Unit]
Description=vk.com set online status service Description=vk.com set online status service
After=network.target network-online.target nss-lookup.target
[Service] [Service]
Type=simple Type=simple
ExecStart=/full/path/to/vk0nline.py ExecStart=/home/USERNAME/.local/share/emilecok/vk0nline/vk0nline.py
[Install] [Install]
WantedBy=default.target WantedBy=default.target

View File

@ -3,49 +3,63 @@
import json import json
import requests import requests
from datetime import datetime from datetime import datetime
import getpass
__author__ = 'Alexander Popov' __author__ = 'Alexander Popov'
__copyright__ = '2019 by iiiypuk' __copyright__ = '2019 by iiiypuk'
__credits__ = ['Alexander Popov'] __credits__ = ['Alexander Popov']
__license__ = 'Unlicense' __license__ = 'Unlicense'
__version__ = '1.0.0' __version__ = '1.0.1'
__maintainer__ = 'Alexander Popov' __maintainer__ = 'Alexander Popov'
__email__ = 'iiiypuk@fastmail.fm' __email__ = 'iiiypuk@fastmail.fm'
__status__ = 'Production' __status__ = 'Production'
# EDIT IT username = getpass.getuser()
with open('./config.json', 'r', encoding='utf-8') as f: with open('/home/{user}/.config/emilecok/vk0nline/config.json'
.format(user=getpass.getuser()), 'r', encoding='utf-8') as f:
_C = json.load(f) _C = json.load(f)
def getStatus(): def getStatus():
response = requests.get('https://api.vk.com/method/users.get?' + \ response = requests.get('https://api.vk.com/method/users.get?'
'fields=online,last_seen&v=5.95' + \ 'fields=online,last_seen&v=5.95'
'&access_token={key}&user_ids={user}'.format( '&access_token={key}&user_ids={user}'
key=_C['serviceKey'], user=_C['userIds'])) .format(key=_C['serviceKey'], user=_C['clientId']))
userLoginTime = json.loads(response.content.decode('utf-8'))
userLoginTime = json.loads(response.content.decode('utf-8'))['response'][0]['last_seen']['time'] userLoginTime = userLoginTime['response'][0]['last_seen']['time']
userOnline = json.loads(response.content.decode('utf-8'))['response'][0]['online'] userOnline = json.loads(response.content.decode('utf-8'))
userOnline = userOnline['response'][0]['online']
return([userOnline, userLoginTime]) return([userOnline, userLoginTime])
def setOnline(): def setOnline():
response = requests.get('https://api.vk.com/method/account.setOnline' + \ response = requests.get('https://api.vk.com/method/account.setOnline?'
'?voip=0&v=5.95&access_token={key}'.format(key=_C['accessToken']) + \ 'voip=0&v=5.95&access_token={key}&user_ids={user}'
'&user_ids={user}'.format(user=_C['userIds'])) .format(user=_C['clientId'],
content = json.loads(response.content.decode('utf-8')) key=_C['accessToken']))
content = json.loads(response.content.decode('utf-8'))
if 'error' in content: if 'error' in content:
if 5 == content['error']['error_code']: # User authorization failed # User authorization failed
print('User authorization failed.\nOpen this link in browser, and copy access token.') if 5 == content['error']['error_code']:
print('https://oauth.vk.com/authorize?client_id={appid}'.format(appid=_C['clientId']) + \ print('User authorization failed.\n',
'&redirect_uri=vk.com&display=mobile&response_type=' + \ 'Open this link in browser, and copy access token.')
'token&v=5.95&revoke=1&state=01010&scope=offline') print('https://oauth.vk.com/authorize?client_id={appid}'
else: '&redirect_uri=vk.com&display=mobile&response_type=token'
print('Error: {}.'.format(content['error']['error_code'])) '&v=5.95&revoke=1&state=01010&scope=offline'
elif 'response' in content: .format(appid=_C['clientId']))
if 1 == content['response']: else:
print('Ok!') print('Error: {}.'.format(content['error']['error_code']))
onlineStatus, lastSeen = getStatus() elif 'response' in content:
print(onlineStatus, datetime.fromtimestamp(lastSeen).strftime('%Y-%m-%d %H:%M:%S')) 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()