Compare commits

...

16 Commits

Author SHA1 Message Date
Alexander Popov d31f591f52
added mkconfig 2022-05-16 22:58:59 +03:00
Alexander Popov 5511a355d4
add help 2022-05-16 22:43:32 +03:00
Alexander Popov 99331d966b
add color output 2022-05-16 21:18:04 +03:00
Alexander Popov 2f9c1ad76c
update 3party libs 2022-05-16 20:55:40 +03:00
Alexander Popov d2517bb3f2 edit install guide 2021-11-12 14:56:00 +03:00
Alexander Popov 31aeff8191 change output filename 2021-11-12 07:44:58 +03:00
Alexander Popov 011f888601 add travis 2021-08-29 14:17:36 +03:00
Alexander Popov dddaf080a7 add systemd guide 2021-08-29 14:01:50 +03:00
Alexander Popov 34a3395853 fix binary link 2021-08-29 13:50:55 +03:00
Alexander Popov 7e77d85988 remove unused fields 2021-08-29 13:35:28 +03:00
Alexander Popov ff9f7730c8 fix path and guide 2021-08-29 13:34:11 +03:00
Alexander Popov 9c774e0460 fix compile script 2021-07-16 23:50:06 +03:00
Alexander Popov becda71b3a build script 2021-07-16 06:58:22 +03:00
Alexander Popov 1c3f743d5c
Merge pull request #2 from iiiypuk/crystal
Crystal 💎
2021-07-16 06:37:08 +03:00
Alexander Popov 99a065b81b 2.0.0 2021-07-16 06:31:18 +03:00
Alexander Popov 09ca61e016 init Crystal 2021-07-16 05:38:16 +03:00
14 changed files with 232 additions and 149 deletions

9
.editorconfig Normal file
View File

@ -0,0 +1,9 @@
root = true
[*.cr]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 2
trim_trailing_whitespace = true

6
.gitignore vendored
View File

@ -1 +1,7 @@
/docs/
/lib/
/bin/
/.shards/
*.dwarf
config.json

12
HISTORY.md Normal file
View File

@ -0,0 +1,12 @@
## Legend
- 🐛 - Bug
- ✔️ - Fixed
- ❌ - Removed
- - Added
- - Information
- ♻️ - Edited
## 2.0.1 - [16/05/2022]
- - Added colors to output
- - Added help
- - Added `--mkconfig` param to make new config file

37
LICENSE
View File

@ -1,24 +1,21 @@
This is free and unencumbered software released into the public domain.
The MIT License (MIT)
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
Copyright (c) 2021 Alexander Popov <iiiypuk@iiiypuk.me>
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
For more information, please refer to <http://unlicense.org>
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -1,23 +1,47 @@
# service for set status online on vk.com
Скрипт для поддержания статуса __Онлайн__ в социальной сети Vk.com
включает в себя `Python` скрипт `systemd` юнит.
![preview](https://raw.githubusercontent.com/iiiypuk/vk0nline/master/asset/.preview.png)
# Будь **ОНЛАЙН** ВКонтакте
## Установка:
+ Активировать автоматический запуск сессии пользователя
```console
## Установка
Подготовка рабочей директории:
```bash
mkdir -p /home/$USER/.local/share/emilecok/vk0nline
cd /home/$USER/.local/share/emilecok/vk0nline
wget https://github.com/iiiypuk/vk0nline/releases/download/2.0.0/vk0nline-2.0.0.linux-x86_64
# Заполняем конфигурационный файл, поля appID и userIds
cp config.json.example config.json
vi config.json
# Запускаем, получаем accessToken и запускаем ещё раз
./vk0nline*
```
## Systemd
Активируем автоматический запуск сессии пользователя:
```bash
# Изменить параметр ReadWritePaths=/etc /run /var/lib/systemd/linger
nano /usr/lib/systemd/system/systemd-logind.service
# Перезапустить сервисы
systemctl daemon-reload
# Активировать пользователя
mkdir /var/lib/systemd/linger
loginctl enable-linger $USER
```
+ Скачать и запустить установщик
```console
curl -Lsk https://raw.githubusercontent.com/iiiypuk/vk0nline/master/install.sh | sh
```bash
# Правим имя пользователя в сервисе
sed -i "s/USERNAME/$USER/" ./systemd/user/vk0nline.service &> /dev/null
mkdir -p /home/$USER/.config/systemd/user &> /dev/null
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
# Запуск и активация сервисов
systemctl start vk0nline.\{service,timer\} --user
systemctl enable vk0nline.\{service,timer\} --user
```
+ Следовать инструкциям установщика

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.4 KiB

18
build.sh Executable file
View File

@ -0,0 +1,18 @@
#!/bin/sh
if ! [[ -d ./bin/ ]]
then
mkdir bin
fi
ARCH=`uname -m`
OS=`uname | tr '[:upper:]' '[:lower:]'`
VERSION=`cat shard.yml | grep -m 1 'version: ' | sed -e 's/version: //g'`
if [ "$1" = "all" ]
then
echo "..in progress.."
else
echo "Build $VERSION for `uname` `uname -m`"
crystal build --progress --no-debug --release src/vk0nline.cr -o bin/vk0nline-$VERSION.$OS-$ARCH
fi

View File

@ -1,6 +1,5 @@
{
"clientId": 1,
"secureKey": "",
"serviceKey": "",
"accessToken": ""
"appID": 6954184,
"userIds": 69040735,
"accessToken": null
}

View File

@ -1,44 +0,0 @@
#!/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 -i "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/.local/share/emilecok/vk0nline/vk0nline.py
echo
echo Edit configuration file
echo :: by /home/$USER/.config/emilecok/vk0nline/config.json
echo
echo And start \& activate systemd services
echo :: systemctl start vk0nline.\{service,timer\} --user
echo :: systemctl enable vk0nline.\{service,timer\} --user

18
shard.lock Normal file
View File

@ -0,0 +1,18 @@
version: 2.0
shards:
ameba:
git: https://github.com/crystal-ameba/ameba.git
version: 1.0.0
crest:
git: https://github.com/mamantoha/crest.git
version: 1.2.1
http-client-digest_auth:
git: https://github.com/mamantoha/http-client-digest_auth.git
version: 0.6.0
http_proxy:
git: https://github.com/mamantoha/http_proxy.git
version: 0.9.0

21
shard.yml Normal file
View File

@ -0,0 +1,21 @@
name: vk0nline
version: 2.0.1
authors:
- Alexander Popov <iiiypuk@fastmail.fm>
targets:
vk0nline:
main: src/vk0nline.cr
dependencies:
crest:
github: mamantoha/crest
development_dependencies:
ameba:
github: crystal-ameba/ameba
crystal: 1.4.1
license: MIT

92
src/vk0nline.cr Normal file
View File

@ -0,0 +1,92 @@
require "option_parser"
require "json"
require "colorize"
require "crest"
# program options
begin
OptionParser.parse do |parser|
parser.banner = "Make ONLINE on vk.com\n"
parser.on "--version", "Show version" do
print "vk0nline ".colorize(:green).mode(:bold)
puts "2.0.1".colorize(:yellow)
exit(0)
end
parser.on "--mkconfig", "Make new empty config" do
new_config = {appID: nil, userIds: nil, accessToken: nil}
File.open("config.json.new", "w") do |f|
f.puts new_config.to_json.to_s
end
print "Config saved to "
print "config.json.new".colorize(:yellow).mode(:bold)
puts " file."
exit(0)
end
parser.on "-h", "--help", "Show help" do
puts parser
exit(0)
end
end
rescue ex
puts ex.message, ""
end
begin # JSON::ParseException
json = File.open("config.json") do |file|
JSON.parse(file)
end
rescue
puts "Parse config.json error".colorize(:red)
exit
end
def get_access_token(app_id : Int32)
puts "Open this page, and save token to config.json:".colorize(:yellow)
token_url = "https://oauth.vk.com/authorize?client_id=" \
"#{app_id}&redirect_uri=vk.com&response_type=token" \
"&display=mobile&v=5.131&revoke=1&state=01010&scope=offline"
puts token_url.colorize(:green).mode(:bold)
end
if json["accessToken"] == nil
get_access_token(json["appID"].as_i)
else
response = Crest.get(
"https://api.vk.com/method/account.setOnline",
params: {:voip => "0", :v => "5.131",
:access_token => json["accessToken"].as_s,
:user_ids => json["userIds"].as_i}
)
status = JSON.parse(response.body)
begin # Missing hash key
if status["error"]
puts status["error"]["error_msg"].colorize(:yellow).mode(:bold)
puts "Error code #{status["error"]["error_code"]}".colorize(:red)
puts "---".colorize(:dark_gray)
get_access_token(json["appID"].as_i)
end
rescue
# execute if an exception is raised
end
begin # Status set
if status["response"] == 1
puts "Complete!".colorize(:green).mode(:bold)
end
rescue
# execute if an exception is raised
end
end

View File

@ -4,7 +4,7 @@ After=network.target network-online.target nss-lookup.target
[Service]
Type=simple
ExecStart=/home/USERNAME/.local/share/emilecok/vk0nline/vk0nline.py
ExecStart=/home/USERNAME/.local/share/emilecok/vk0nline/vk0nline.x86_64-lnx
[Install]
WantedBy=default.target

View File

@ -1,69 +0,0 @@
#!/usr/bin/env python3
import json
import requests
from datetime import datetime
import getpass
import sys
__author__ = 'Alexander Popov'
__copyright__ = '2019 by iiiypuk'
__credits__ = ['Alexander Popov']
__license__ = 'Unlicense'
__version__ = '1.0.3'
__maintainer__ = 'Alexander Popov'
__email__ = 'iiiypuk@fastmail.fm'
__status__ = 'Production'
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['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}&user_ids={user}'
.format(user=_C['clientId'],
key=_C['accessToken']))
content = json.loads(response.content.decode('utf-8'))
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']:
onlineStatus, lastSeen = getStatus()
lastSeen = datetime.fromtimestamp(lastSeen) \
.strftime('%Y-%m-%d %H:%M:%S')
if 0 == onlineStatus:
print('Not successful.')
sys.exit(1)
print('Last online', lastSeen)
if __name__ == "__main__":
setOnline()