Skip to content

Commit

Permalink
maybe tests are green now?
Browse files Browse the repository at this point in the history
  • Loading branch information
halcy authored and halcy committed Jun 23, 2023
1 parent d891589 commit b917978
Show file tree
Hide file tree
Showing 159 changed files with 76,914 additions and 77,876 deletions.
15 changes: 6 additions & 9 deletions mastodon/accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from mastodon.internals import Mastodon as Internals

from typing import Union, Optional, Tuple, List
from mastodon.types import AccountCreationError, Account, IdType, Status, PaginatableList, NonPaginatableList, UserList, Relationship, FamiliarFollowers, Tag, IdType, PathOrFile
from mastodon.types import AccountCreationError, Account, IdType, Status, PaginatableList, NonPaginatableList, UserList, Relationship, FamiliarFollowers, Tag, IdType, PathOrFile, AttribAccessDict, try_cast
from datetime import datetime

class Mastodon(Internals):
Expand Down Expand Up @@ -69,17 +69,18 @@ def create_account(self, username: str, password: str, email: str, agreement: bo
oauth_params['client_secret'] = self.client_secret
oauth_params['grant_type'] = 'client_credentials'

response = self.__api_request('POST', '/oauth/token', oauth_params, do_ratelimiting=False)
response = self.__api_request('POST', '/oauth/token', oauth_params, do_ratelimiting=False, override_type=AttribAccessDict)
temp_access_token = response['access_token']
except Exception as e:
raise MastodonIllegalArgumentError(f'Invalid request during oauth phase: {e}')

# Step 2: Use that to create a user
try:
response = self.__api_request('POST', '/api/v1/accounts', params, do_ratelimiting=False, access_token_override=temp_access_token, skip_error_check=True)
response = self.__api_request('POST', '/api/v1/accounts', params, do_ratelimiting=False, access_token_override=temp_access_token, skip_error_check=True, override_type=dict)
print(response)
if "error" in response:
if return_detailed_error:
return None, response
return None, try_cast(AccountCreationError, response)
raise MastodonIllegalArgumentError(f'Invalid request: {response["error"]}')
self.access_token = response['access_token']
self.__set_refresh_token(response.get('refresh_token'))
Expand Down Expand Up @@ -107,7 +108,7 @@ def create_account(self, username: str, password: str, email: str, agreement: bo
self.__logged_in_id = None

if return_detailed_error:
return response['access_token'], {}
return response['access_token'], AccountCreationError()
else:
return response['access_token']

Expand Down Expand Up @@ -420,10 +421,6 @@ def account_update_credentials(self, display_name: Optional[str] = None, note: O

# Convert fields
if fields is not None:
if len(fields) > 4:
raise MastodonIllegalArgumentError(
'A maximum of four fields are allowed.')

fields_attributes = []
for idx, (field_name, field_value) in enumerate(fields):
params_initial[f'fields_attributes[{idx}][name]'] = field_name
Expand Down
4 changes: 2 additions & 2 deletions mastodon/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ def admin_account_moderate(self, id: Union[Account, AdminAccount, IdType], actio
self.__api_request('POST', f'/api/v1/admin/accounts/{id}/action', params)

@api_version("2.9.1", "2.9.1", _DICT_VERSION_REPORT)
def admin_reports(self, resolved: Optional[bool] = False, account_id = Optional[Union[Account, AdminAccount, IdType]],
def admin_reports(self, resolved: Optional[bool] = False, account_id: Optional[Union[Account, AdminAccount, IdType]] = None,
target_account_id: Optional[Union[Account, AdminAccount, IdType]] = None, max_id: Optional[IdType] = None,
min_id: Optional[IdType] = None, since_id: Optional[IdType] = None, limit: Optional[int] = None) -> PaginatableList[AdminReport]:
"""
Expand Down Expand Up @@ -531,7 +531,7 @@ def admin_measures(self, start_at, end_at, active_users: bool = False, new_users

@api_version("3.5.0", "3.5.0", _DICT_VERSION_ADMIN_DIMENSION)
def admin_dimensions(self, start_at: datetime, end_at: datetime, limit: Optional[int] = None, languages: bool = False, sources: bool = False,
servers: bool = False, space_usag: bool = False, software_versions: bool = False, tag_servers: Optional[Union[Tag, IdType]] = None,
servers: bool = False, space_usage: bool = False, software_versions: bool = False, tag_servers: Optional[Union[Tag, IdType]] = None,
tag_languages: Optional[Union[Tag, IdType]] = None, instance_accounts: Optional[str] = None, instance_languages: Optional[str] = None) -> NonPaginatableList[AdminDimension]:
"""
Retrieves primarily categorical instance information for the time period (at day granularity) between `start_at` and `end_at`.
Expand Down
4 changes: 2 additions & 2 deletions mastodon/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,7 +336,7 @@ def log_in(self, username: Optional[str] = None, password: Optional[str] = None,
params['scope'] = " ".join(scopes)

try:
response = self.__api_request('POST', '/oauth/token', params, do_ratelimiting=False)
response = self.__api_request('POST', '/oauth/token', params, do_ratelimiting = False, override_type = dict)
self.access_token = response['access_token']
self.__set_refresh_token(response.get('refresh_token'))
self.__set_token_expired(int(response.get('expires_in', 0)))
Expand All @@ -360,7 +360,7 @@ def log_in(self, username: Optional[str] = None, password: Optional[str] = None,
assert self.api_base_url is not None
assert self.client_id is not None and isinstance(self.client_id, str)
assert self.client_secret is not None
with open(to_file, 'w') as token_file:
with open(str(to_file), 'w') as token_file:
token_file.write(response['access_token'] + "\n")
token_file.write(self.api_base_url + "\n")
token_file.write(self.client_id + "\n")
Expand Down
11 changes: 5 additions & 6 deletions mastodon/instance.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@ def instance_v1(self) -> Instance:
"""
return self.__instance()

def __instance(self):
def __instance(self) -> Instance:
"""
Internal, non-version-checking helper that does the same as instance_v1()
"""
instance = self.__api_request('GET', '/api/v1/instance/')
instance = self.__api_request('GET', '/api/v1/instance/', override_type=Instance)
return instance

@api_version("4.0.0", "4.0.0", _DICT_VERSION_INSTANCE)
Expand All @@ -55,7 +55,7 @@ def instance(self) -> Union[Instance, InstanceV2]:
Returns an :ref:`instance dict <instance dict>`.
"""
return self.__api_request('GET', '/api/v2/instance/')
return self.__api_request('GET', '/api/v2/instance/') # TODO FIXME VERSIONING

@api_version("2.1.2", "2.1.2", _DICT_VERSION_ACTIVITY)
def instance_activity(self) -> NonPaginatableList[Activity]:
Expand Down Expand Up @@ -99,16 +99,15 @@ def instance_nodeinfo(self, schema: str = "http://nodeinfo.diaspora.software/ns/
To override the schema, specify the desired schema with the `schema`
parameter.
"""
links = self.__api_request('GET', '/.well-known/nodeinfo')["links"]
links = self.__api_request('GET', '/.well-known/nodeinfo', override_type = AttribAccessDict)["links"]

schema_url = None
for available_schema in links:
if available_schema.rel == schema:
schema_url = available_schema.href

if schema_url is None:
raise MastodonIllegalArgumentError(
"Requested nodeinfo schema is not available.")
raise MastodonIllegalArgumentError("Requested nodeinfo schema is not available.")

try:
return self.__api_request('GET', schema_url, base_url_override="")
Expand Down
9 changes: 4 additions & 5 deletions mastodon/internals.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
# internals.py - many internal helpers

from datetime import timezone, datetime
from datetime import timezone, datetime, timedelta
from contextlib import closing
import mimetypes
import threading
import six
import uuid
import dateutil.parser
import time
Expand Down Expand Up @@ -342,7 +341,7 @@ def __get_streaming_base(self) -> str:
Returns the correct URL for the streaming API.
"""
instance = self.instance()
instance = self.__instance()
if "streaming_api" in instance["urls"] and instance["urls"]["streaming_api"] != self.api_base_url:
# This is probably a websockets URL, which is really for the browser, but requests can't handle it
# So we do this below to turn it into an HTTPS or HTTP URL
Expand Down Expand Up @@ -548,11 +547,11 @@ def __decode_webpush_b64(self, data):

def __get_token_expired(self):
"""Internal helper for oauth code"""
return self._token_expired < datetime.datetime.now()
return self._token_expired < datetime.now()

def __set_token_expired(self, value):
"""Internal helper for oauth code"""
self._token_expired = datetime.datetime.now() + datetime.timedelta(seconds=value)
self._token_expired = datetime.now() + timedelta(seconds=value)
return

def __get_refresh_token(self):
Expand Down
10 changes: 3 additions & 7 deletions mastodon/preferences.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,28 +19,25 @@ def preferences(self) -> Preferences:
"""
Fetch the user's preferences, which can be used to set some default options.
As of 2.8.0, apps can only fetch, not update preferences.
Returns a :ref:`preference dict <preference dict>`.
"""
return self.__api_request('GET', '/api/v1/preferences')

##
# Reading data: Read markers
##
@api_version("3.0.0", "3.0.0", _DICT_VERSION_MARKER)
def markers_get(self, timeline: Union[str, List[str]] = ["home"]) -> List[Marker]:
def markers_get(self, timeline: Union[str, List[str]] = ["home"]) -> Dict[str, Marker]:
"""
Get the last-read-location markers for the specified timelines. Valid timelines
are the same as in :ref:`timeline() <timeline()>`
Note that despite the singular name, `timeline` can be a list.
Returns a dict of :ref:`read marker dicts <read marker dicts>`, keyed by timeline name.
Returns a dict with the markers, keyed by timeline name.
"""
if not isinstance(timeline, (list, tuple)):
timeline = [timeline]
params = self.__generate_params(locals())

return self.__api_request('GET', '/api/v1/markers', params)

##
Expand Down Expand Up @@ -68,5 +65,4 @@ def markers_set(self, timelines: Union[str, List[str]], last_read_ids: Union[Sta
for timeline, last_read_id in zip(timelines, last_read_ids):
params[timeline] = collections.OrderedDict()
params[timeline]["last_read_id"] = self.__unpack_id(last_read_id)

return self.__api_request('POST', '/api/v1/markers', params, use_json=True)
return self.__api_request('POST', '/api/v1/markers', params, use_json=True)
4 changes: 2 additions & 2 deletions mastodon/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,10 @@ def search(self, q: str, resolve: bool = True, result_type: Optional[str] = None
number will be used for this to avoid uneccesary requests.
"""
if self.verify_minimum_version("2.4.1", cached=True):
return self.search_v2(q, resolve=resolve, result_type=result_type, account_id=account_id, offset=offset, min_id=min_id, max_id=max_id, exclude_unreviewed=exclude_unreviewed, override_type=SearchV2)
return self.search_v2(q, resolve=resolve, result_type=result_type, account_id=account_id, offset=offset, min_id=min_id, max_id=max_id, exclude_unreviewed=exclude_unreviewed)
else:
self.__ensure_search_params_acceptable(account_id, offset, min_id, max_id)
return self.search_v1(q, resolve=resolve, override_type=Search)
return self.search_v1(q, resolve=resolve)

@api_version("1.1.0", "2.1.0", "2.1.0")
def search_v1(self, q: str, resolve: bool = False) -> Search:
Expand Down

0 comments on commit b917978

Please sign in to comment.