From 09ca61e0168b7f6147b7b2f41c43b68c54447607 Mon Sep 17 00:00:00 2001 From: Alexander Popov Date: Fri, 16 Jul 2021 05:38:16 +0300 Subject: [PATCH 1/2] init Crystal --- .editorconfig | 9 +++++++++ .gitignore | 6 ++++++ .travis.yml | 6 ++++++ LICENSE | 37 +++++++++++++++++-------------------- README.md | 39 +++++++++++++++++++++++++++++++-------- config.json.example | 9 +++++---- shard.lock | 14 ++++++++++++++ shard.yml | 17 +++++++++++++++++ spec/spec_helper.cr | 2 ++ spec/src_spec.cr | 9 +++++++++ src/vk0nline.cr | 36 ++++++++++++++++++++++++++++++++++++ 11 files changed, 152 insertions(+), 32 deletions(-) create mode 100644 .editorconfig create mode 100644 .travis.yml create mode 100644 shard.lock create mode 100644 shard.yml create mode 100644 spec/spec_helper.cr create mode 100644 spec/src_spec.cr create mode 100644 src/vk0nline.cr diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..163eb75 --- /dev/null +++ b/.editorconfig @@ -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 diff --git a/.gitignore b/.gitignore index d344ba6..2aa0834 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,7 @@ +/docs/ +/lib/ +/bin/ +/.shards/ +*.dwarf + config.json diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..765f0e9 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,6 @@ +language: crystal + +# Uncomment the following if you'd like Travis to run specs and check code formatting +# script: +# - crystal spec +# - crystal tool format --check diff --git a/LICENSE b/LICENSE index cf1ab25..e3d881c 100644 --- a/LICENSE +++ b/LICENSE @@ -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 -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 +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. diff --git a/README.md b/README.md index fce5a03..4e556b7 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,12 @@ -# service for set status online on vk.com -Скрипт для поддержания статуса __Онлайн__ в социальной сети Vk.com -включает в себя `Python` скрипт `systemd` юнит. -![preview](https://raw.githubusercontent.com/iiiypuk/vk0nline/master/asset/.preview.png) +# vk0nline +Утилита для поддержания статуса __Онлайн__ в социальной сети Vk.com. -## Установка: -+ Активировать автоматический запуск сессии пользователя +Включает в себя `systemd` юнит. + +![preview](https://raw.githubusercontent.com/iiiypuk/vk0nline/master/asset/.preview.png) + +## Установка +Активировать автоматический запуск сессии пользователя ```console # Изменить параметр ReadWritePaths=/etc /run /var/lib/systemd/linger nano /usr/lib/systemd/system/systemd-logind.service @@ -15,9 +17,30 @@ mkdir /var/lib/systemd/linger loginctl enable-linger $USER ``` -+ Скачать и запустить установщик +Скачать и запустить установщик: ```console curl -Lsk https://raw.githubusercontent.com/iiiypuk/vk0nline/master/install.sh | sh ``` -+ Следовать инструкциям установщика +Следовать инструкциям установщика. + +## Использование +* Скачать исполняемый файл программы +* Заполнить `appID` и `userIds` в `config.json` +* Запустить программу `vk0nline` и получить `accessToken` + +## Development + +TODO: Write development instructions here + +## Contributing + +1. Fork it () +2. Create your feature branch (`git checkout -b my-new-feature`) +3. Commit your changes (`git commit -am 'Add some feature'`) +4. Push to the branch (`git push origin my-new-feature`) +5. Create a new Pull Request + +## Contributors + +- [Alexander Popov](https://github.com/iiiypuk) - creator and maintainer diff --git a/config.json.example b/config.json.example index da90d7f..b0c7a67 100644 --- a/config.json.example +++ b/config.json.example @@ -1,6 +1,7 @@ { - "clientId": 1, - "secureKey": "", - "serviceKey": "", - "accessToken": "" + "appID": 6954184, + "userIds": 69040735, + "secureKey": null, + "serviceKey": null, + "accessToken": null } diff --git a/shard.lock b/shard.lock new file mode 100644 index 0000000..b932c94 --- /dev/null +++ b/shard.lock @@ -0,0 +1,14 @@ +version: 2.0 +shards: + crest: + git: https://github.com/mamantoha/crest.git + version: 0.27.0 + + 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.8.0 + diff --git a/shard.yml b/shard.yml new file mode 100644 index 0000000..9956ec3 --- /dev/null +++ b/shard.yml @@ -0,0 +1,17 @@ +name: vk0nline +version: 0.1.0 + +authors: + - Alexander Popov + +targets: + src: + main: src/src.cr + +dependencies: + crest: + github: mamantoha/crest + +crystal: 1.0.0 + +license: MIT diff --git a/spec/spec_helper.cr b/spec/spec_helper.cr new file mode 100644 index 0000000..25986a6 --- /dev/null +++ b/spec/spec_helper.cr @@ -0,0 +1,2 @@ +require "spec" +require "../src/src" diff --git a/spec/src_spec.cr b/spec/src_spec.cr new file mode 100644 index 0000000..a3b770b --- /dev/null +++ b/spec/src_spec.cr @@ -0,0 +1,9 @@ +require "./spec_helper" + +describe Src do + # TODO: Write tests + + it "works" do + false.should eq(true) + end +end diff --git a/src/vk0nline.cr b/src/vk0nline.cr new file mode 100644 index 0000000..1e38f65 --- /dev/null +++ b/src/vk0nline.cr @@ -0,0 +1,36 @@ +require "json" +require "crest" + +# TODO: Write documentation for `Src` +module Src + VERSION = "0.1.0" + + json = File.open("config.json") do |file| + JSON.parse(file) + end + + # TODO: Get accessToken + if json["accessToken"] == nil + puts "Get accessToken" + + token_url = "https://oauth.vk.com/authorize?client_id=#{json["appID"].as_i}&redirect_uri=vk.com&response_type=token&display=mobile&v=5.131&revoke=1&state=01010&scope=offline" + + puts token_url + + puts "Open this page, and save token to config.json" + else + # TODO: If return 1 == COMPLETE + 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) + + if status["response"] == 1 + puts "Complete!" + end + end +end From 99a065b81b6b07884aab7e6c1dff7f90893bcf76 Mon Sep 17 00:00:00 2001 From: Alexander Popov Date: Fri, 16 Jul 2021 06:31:18 +0300 Subject: [PATCH 2/2] 2.0.0 --- asset/.preview.png => .preview.png | Bin README.md | 2 +- shard.yml | 2 +- src/vk0nline.cr | 62 +++++++++++++++++--------- vk0nline.py | 69 ----------------------------- 5 files changed, 43 insertions(+), 92 deletions(-) rename asset/.preview.png => .preview.png (100%) delete mode 100644 vk0nline.py diff --git a/asset/.preview.png b/.preview.png similarity index 100% rename from asset/.preview.png rename to .preview.png diff --git a/README.md b/README.md index 4e556b7..dfc5a7a 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ Включает в себя `systemd` юнит. -![preview](https://raw.githubusercontent.com/iiiypuk/vk0nline/master/asset/.preview.png) +![preview](https://raw.githubusercontent.com/iiiypuk/vk0nline/master/.preview.png) ## Установка Активировать автоматический запуск сессии пользователя diff --git a/shard.yml b/shard.yml index 9956ec3..53494bc 100644 --- a/shard.yml +++ b/shard.yml @@ -1,5 +1,5 @@ name: vk0nline -version: 0.1.0 +version: 2.0.0 authors: - Alexander Popov diff --git a/src/vk0nline.cr b/src/vk0nline.cr index 1e38f65..6e6b1e7 100644 --- a/src/vk0nline.cr +++ b/src/vk0nline.cr @@ -1,36 +1,56 @@ require "json" require "crest" -# TODO: Write documentation for `Src` -module Src - VERSION = "0.1.0" - +begin # JSON::ParseException json = File.open("config.json") do |file| JSON.parse(file) end +rescue + puts "Parse config.json error" - # TODO: Get accessToken - if json["accessToken"] == nil - puts "Get accessToken" + exit +end - token_url = "https://oauth.vk.com/authorize?client_id=#{json["appID"].as_i}&redirect_uri=vk.com&response_type=token&display=mobile&v=5.131&revoke=1&state=01010&scope=offline" +def get_access_token(appId : Int32) + puts "Open this page, and save token to config.json\n\n" - puts token_url + token_url = "https://oauth.vk.com/authorize?client_id="\ + "#{appId}&redirect_uri=vk.com&response_type=token"\ + "&display=mobile&v=5.131&revoke=1&state=01010&scope=offline" - puts "Open this page, and save token to config.json" - else - # TODO: If return 1 == COMPLETE - 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 } - ) + puts token_url +end - status = JSON.parse(response.body) +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 } + ) - if status["response"] == 1 + status = JSON.parse(response.body) + + begin # Missing hash key + if status["error"] + puts status["error"]["error_msg"] + puts "Error code #{status["error"]["error_code"]}" + + puts "---" + + get_access_token(json["appID"].as_i) + end + rescue + # execute if an exception is raised + end + + begin # Missing hash key + if status["response"] == 1 puts "Complete!" - end + end + rescue + # execute if an exception is raised end end diff --git a/vk0nline.py b/vk0nline.py deleted file mode 100644 index c0a872c..0000000 --- a/vk0nline.py +++ /dev/null @@ -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()