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 @@
# 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
```
+ Следовать инструкциям установщика

View File

Before

Width:  |  Height:  |  Size: 8.4 KiB

After

Width:  |  Height:  |  Size: 8.4 KiB

View File

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

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

View File

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