squarecloud-api 3.3.2__py3-none-any.whl → 3.4.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
squarecloud/__init__.py CHANGED
@@ -1,5 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
+ from . import errors, utils
3
4
  from .client import Client, create_config_file
4
5
  from .data import (
5
6
  AppData,
@@ -7,13 +8,11 @@ from .data import (
7
8
  FileInfo,
8
9
  LogsData,
9
10
  PlanData,
10
- StatisticsData,
11
11
  StatusData,
12
12
  UploadData,
13
13
  UserData,
14
14
  )
15
15
  from .file import File
16
16
  from .http.endpoints import Endpoint
17
- from . import errors
18
17
 
19
- __version__ = '3.3.0'
18
+ __version__ = '3.4.1'
squarecloud/app.py CHANGED
@@ -1,11 +1,13 @@
1
1
  from __future__ import annotations
2
2
 
3
- from abc import ABC
3
+ from functools import wraps
4
4
  from io import BytesIO
5
- from typing import TYPE_CHECKING, Callable
5
+ from typing import TYPE_CHECKING, Any, Callable
6
6
 
7
7
  from pydantic import PositiveInt
8
8
 
9
+ from squarecloud import errors
10
+
9
11
  from .data import (
10
12
  AppData,
11
13
  BackupData,
@@ -15,10 +17,10 @@ from .data import (
15
17
  LogsData,
16
18
  StatusData,
17
19
  )
18
- from .errors import SquareException
19
20
  from .file import File
20
21
  from .http import Endpoint, HTTPClient, Response
21
- from .listeners import CaptureListenerManager
22
+ from .listeners import Listener, ListenerConfig
23
+ from .listeners.capture_listener import CaptureListenerManager
22
24
 
23
25
  # avoid circular imports
24
26
  if TYPE_CHECKING:
@@ -40,8 +42,7 @@ class AppCache:
40
42
  attributes.
41
43
 
42
44
 
43
- :return: The instance of the class
44
- :rtype: None
45
+ :return: None
45
46
  """
46
47
  self._status: StatusData | None = None
47
48
  self._logs: LogsData | None = None
@@ -51,9 +52,10 @@ class AppCache:
51
52
  @property
52
53
  def status(self) -> StatusData:
53
54
  """
54
- The status function returns the status of the application.
55
+ The status method is a property that returns the cached StatusData of
56
+ the application.
55
57
 
56
- :return: The status of the application.
58
+ :return: A StatusData object.
57
59
  :rtype: StatusData
58
60
  """
59
61
  return self._status
@@ -61,7 +63,8 @@ class AppCache:
61
63
  @property
62
64
  def logs(self) -> LogsData:
63
65
  """
64
- The logs function the logs of the application.
66
+ The logs method is a property that returns the cached LogsData of
67
+ the application.
65
68
 
66
69
  :return: The logs of your application
67
70
  :rtype: LogsData
@@ -71,7 +74,8 @@ class AppCache:
71
74
  @property
72
75
  def backup(self) -> BackupData:
73
76
  """
74
- The backup function is used to create a backup of the application.
77
+ The backup method is a property that returns the cached BackupData of
78
+ the application.
75
79
 
76
80
  :return: The value of the _backup attribute
77
81
  :rtype: BackupData
@@ -81,7 +85,8 @@ class AppCache:
81
85
  @property
82
86
  def app_data(self) -> AppData:
83
87
  """
84
- The app_data function is a property that returns the AppData object.
88
+ The app_data method is a property that returns the cached AppData
89
+ object
85
90
 
86
91
  :return: The data from the app_data
87
92
  :rtype: AppData
@@ -90,12 +95,11 @@ class AppCache:
90
95
 
91
96
  def clear(self):
92
97
  """
93
- The clear function is used to clear the status, logs, backup and data
98
+ The clear method is used to clear the status, logs, backup and data
94
99
  variables.
95
100
 
96
101
  :param self: Refer to the class instance
97
102
  :return: None
98
- :rtype: None
99
103
  """
100
104
  self._status = None
101
105
  self._logs = None
@@ -104,17 +108,15 @@ class AppCache:
104
108
 
105
109
  def update(self, *args):
106
110
  """
107
- The update function is used to update the data of a given instance.
111
+ The update method is used to update the data of a given instance.
108
112
  It takes in an arbitrary number of arguments, and updates the
109
113
  corresponding data if it is one of the following types:
110
114
  StatusData, LogsData, BackupData or AppData.
111
115
  If any other type is provided as an argument to this function,
112
116
  a SquareException will be raised.
113
117
 
114
- :param self: Refer to the class instance
115
118
  :param args: Pass a variable number of arguments to a function
116
119
  :return: None
117
- :rtype: None
118
120
  """
119
121
  for arg in args:
120
122
  if isinstance(arg, StatusData):
@@ -135,16 +137,12 @@ class AppCache:
135
137
  AppData,
136
138
  ]
137
139
  ]
138
- raise SquareException(
140
+ raise errors.SquareException(
139
141
  f'you must provide stats of the following types:\n{types}'
140
142
  )
141
143
 
142
144
 
143
- class AbstractApplication(ABC):
144
- """Abstract application class"""
145
-
146
-
147
- class Application:
145
+ class Application(CaptureListenerManager):
148
146
  """Represents an application"""
149
147
 
150
148
  __slots__ = [
@@ -176,26 +174,24 @@ class Application:
176
174
  desc: str | None = None,
177
175
  ) -> None:
178
176
  """
179
- The `__init__` function is called when the class is instantiated.
177
+ The `__init__` method is called when the class is instantiated.
180
178
  It sets up all the attributes that are passed in as arguments,
181
179
  and does any other initialization your class needs before It's ready
182
180
  for use.
183
181
 
184
182
 
185
- :param self: Refer to the class instance.
186
- :param client: 'Client': Store a reference to the client that created
183
+ :param client: Store a reference to the client that created
187
184
  this app.
188
- :param http: HTTPClient: Make http requests to the api.
189
- :param id: str: The id of the app.
190
- :param tag: str: The tag of the app.
191
- :param ram: PositiveInt: The amount of ram that is allocated.
192
- :param lang: str: The programming language of the app.
193
- :param cluster: str: The cluster that the app is hosted on
194
- :param isWebsite: bool: Whether if the app is a website
195
- :param desc: str | None: Define the description of the app
185
+ :param http: Store a reference to the HTTPClient
186
+ :param id: The application id
187
+ :param tag: The tag of the app
188
+ :param ram: The amount of ram that is allocated
189
+ :param lang: The programming language of the app
190
+ :param cluster: The cluster that the app is hosted on
191
+ :param isWebsite: Whether if the app is a website
192
+ :param desc: Define the description of the app
196
193
 
197
194
  :return: None
198
- :rtype: None
199
195
  """
200
196
  self._id: str = id
201
197
  self._tag: str = tag
@@ -209,26 +205,26 @@ class Application:
209
205
  self._listener: CaptureListenerManager = CaptureListenerManager()
210
206
  self.cache: AppCache = AppCache()
211
207
  self.always_avoid_listeners: bool = False
208
+ super().__init__()
212
209
 
213
210
  def __repr__(self) -> str:
214
211
  """
215
- The __repr__ function is used to create a string representation of an
212
+ The `__repr__` method is used to create a string representation of an
216
213
  object.
217
214
  This is useful for debugging, logging and other instances where you
218
215
  would want a string representation of the object.
219
216
  The __repr__ function should return a string that would make sense to
220
217
  someone looking at the results in the interactive interpreter.
221
218
 
222
-
223
- :param self: Refer to the class instance
224
219
  :return: The class name, tag and id of the element
220
+ :rtype: str
225
221
  """
226
222
  return f'<{self.__class__.__name__} tag={self.tag} id={self.id}>'
227
223
 
228
224
  @property
229
225
  def client(self) -> 'Client':
230
226
  """
231
- The client function is a property that returns the client object.
227
+ The client method is a property that returns the client object.
232
228
 
233
229
  :return: The client instance
234
230
  :rtype: Client
@@ -239,7 +235,7 @@ class Application:
239
235
  def id(self) -> str:
240
236
  """
241
237
  The id function is a property that returns
242
- the id of the application.
238
+ the id of the application.
243
239
 
244
240
  :return: The id of the application
245
241
  :rtype: str
@@ -317,9 +313,57 @@ class Application:
317
313
  """
318
314
  return self._isWebsite
319
315
 
320
- def capture(self, endpoint: Endpoint) -> Callable:
316
+ @staticmethod
317
+ def _notify_listener(endpoint: Endpoint):
318
+ """
319
+ The _notify_listener function is a decorator that call a listener after
320
+ the decorated coroutine is called
321
+
322
+ :param endpoint: the endpoint for witch the listener will fetch
323
+ :return: a callable
324
+ """
325
+
326
+ def wrapper(func: Callable):
327
+ @wraps(func)
328
+ async def decorator(self: Application, *args, **kwargs) -> Any:
329
+ result = await func(self, *args, **kwargs)
330
+ avoid_listener = kwargs.pop('avoid_listener', False)
331
+ if not (avoid_listener or self.always_avoid_listeners):
332
+ await self.notify(
333
+ endpoint=endpoint,
334
+ before=self.cache.app_data,
335
+ after=result,
336
+ extra=kwargs.get('extra'),
337
+ )
338
+ return result
339
+
340
+ return decorator
341
+
342
+ return wrapper
343
+
344
+ @staticmethod
345
+ def _update_cache(func: Callable):
346
+ """
347
+ This is a decorator checks whether the kwargs `update_cache` in the
348
+ decorated coroutine is not False, and updates the application cache
349
+
350
+ :param func:
351
+ :return: a callable
352
+ """
353
+
354
+ @wraps(func)
355
+ async def wrapper(self, *args, **kwargs):
356
+ update_cache = kwargs.pop('update_cache', True)
357
+ result = await func(self, *args, **kwargs)
358
+ if update_cache:
359
+ self.cache.update(result)
360
+ return result
361
+
362
+ return wrapper
363
+
364
+ def capture(self, endpoint: Endpoint, **kwargs) -> Callable:
321
365
  """
322
- The capture function is a decorator that can be used to add a function
366
+ The capture function is a decorator that can be used to add a callable
323
367
  to be called when a request is made to the specified endpoint.
324
368
 
325
369
  :param self: Refer to the class instance.
@@ -328,14 +372,10 @@ class Application:
328
372
  :return: A decorator
329
373
  :rtype: Callable
330
374
  """
331
- allowed_endpoints: tuple[Endpoint, Endpoint, Endpoint, Endpoint] = (
332
- Endpoint.logs(),
333
- Endpoint.app_status(),
334
- Endpoint.backup(),
335
- Endpoint.app_data(),
336
- )
337
375
 
338
- def wrapper(func) -> None:
376
+ def wrapper(
377
+ call: Callable[[Endpoint, Endpoint], Any]
378
+ ) -> Callable[[Endpoint, Endpoint], Any]:
339
379
  """
340
380
  The wrapper function is a decorator that takes in the endpoint as
341
381
  an argument.
@@ -345,116 +385,80 @@ class Application:
345
385
  with the function passed to wrapper().
346
386
  Otherwise, it raises another SquareException.
347
387
 
348
- :param func: Pass the function to be wrapped
388
+ :param call: Pass the function to be wrapped
349
389
  :return: The wrapper function itself
350
390
  :rtype: None
391
+ :raises InvalidListener: Raised if the endpoint is already
392
+ registered
351
393
  """
352
- if endpoint not in allowed_endpoints:
353
- raise SquareException(
354
- f'the endpoint to capture must be {allowed_endpoints}'
355
- )
356
-
357
- if self._listener.get_capture_listener(endpoint) is None:
358
- return self._listener.add_capture_listener(endpoint, func)
359
- raise SquareException(
360
- f'Already exists an capture_listener for {endpoint}'
361
- f'{self._listener.get_capture_listener(endpoint)}'
394
+ for key, value in kwargs.items():
395
+ if key not in ListenerConfig.__annotations__:
396
+ raise ValueError(
397
+ f'Invalid listener configuration: "{key}={value}"'
398
+ )
399
+ config = ListenerConfig(**kwargs)
400
+ listener = Listener(
401
+ app=self,
402
+ client=self.client,
403
+ endpoint=endpoint,
404
+ callback=call,
405
+ config=config,
362
406
  )
407
+ self.include_listener(listener)
408
+ return call
363
409
 
364
410
  return wrapper
365
411
 
366
- async def data(
367
- self, avoid_listener: bool = None, update_cache: bool = True
368
- ) -> AppData:
412
+ @_update_cache
413
+ @_notify_listener(Endpoint.app_data())
414
+ async def data(self, *_args, **__kwargs) -> AppData:
369
415
  """
370
- The data function is used to retrieve the data of an app.
416
+ The data method is used to retrieve the data of this app.
371
417
 
372
- :param update_cache: if True, update the application cache
373
- :param avoid_listener: whether the capture listener will be called
374
418
  :param self: Refer to the class instance
375
419
  :return: A AppData object
376
420
  :rtype: AppData
377
421
  """
378
422
  app_data: AppData = await self.client.app_data(self.id)
379
- avoid_listener = avoid_listener or self.always_avoid_listeners
380
- if not avoid_listener:
381
- endpoint: Endpoint = Endpoint.app_data()
382
- await self._listener.on_capture(
383
- endpoint=endpoint,
384
- before=self.cache.app_data,
385
- after=app_data,
386
- )
387
- if update_cache:
388
- self.cache.update(app_data)
389
423
  return app_data
390
424
 
391
- async def logs(
392
- self, avoid_listener: bool = None, update_cache: bool = True
393
- ) -> LogsData:
425
+ @_update_cache
426
+ @_notify_listener(Endpoint.logs())
427
+ async def logs(self, *_args, **__kwargs) -> LogsData:
394
428
  """
395
- The logs function is used to get the application's logs.
429
+ The logs method is used to get the application's logs.
396
430
 
397
431
  :param self: Refer to the class instance
398
- :param update_cache: if True, update the application cache
399
- :param avoid_listener: whether the capture listener will be called
400
432
  :return: A LogsData object
401
433
  :rtype: LogsData
402
434
  """
403
435
  logs: LogsData = await self.client.get_logs(self.id)
404
- avoid_listener = avoid_listener or self.always_avoid_listeners
405
- if not avoid_listener:
406
- endpoint: Endpoint = Endpoint.logs()
407
- await self._listener.on_capture(
408
- endpoint=endpoint, before=self.cache.logs, after=logs
409
- )
410
- if update_cache:
411
- self.cache.update(logs)
412
436
  return logs
413
437
 
414
- async def status(
415
- self, avoid_listener: bool = None, update_cache: bool = True
416
- ) -> StatusData:
438
+ @_update_cache
439
+ @_notify_listener(Endpoint.app_status())
440
+ async def status(self, *_args, **__kwargs) -> StatusData:
417
441
  """
418
442
  The status function returns the status of an application.
419
443
 
420
444
  :param self: Refer to the class instance
421
- :param update_cache: if True, update the application cache
422
- :param avoid_listener: whether the capture listener will be called
423
445
  :return: A StatusData object
424
446
  :rtype: StatusData
425
447
  """
426
448
  status: StatusData = await self.client.app_status(self.id)
427
- avoid_listener = avoid_listener or self.always_avoid_listeners
428
- if not avoid_listener:
429
- endpoint: Endpoint = Endpoint.app_status()
430
- await self._listener.on_capture(
431
- endpoint=endpoint, before=self.cache.status, after=status
432
- )
433
- if update_cache:
434
- self.cache.update(status)
435
449
  return status
436
450
 
437
- async def backup(
438
- self, avoid_listener: bool = None, update_cache: bool = True
439
- ) -> BackupData:
451
+ @_update_cache
452
+ @_notify_listener(Endpoint.backup())
453
+ async def backup(self, *_args, **__kwargs) -> BackupData:
440
454
  """
441
455
  The backup function is used to create a backup of the application.
442
456
 
443
457
  :param self: Refer to the class instance
444
- :param update_cache: if True, update the application cache
445
- :param avoid_listener: whether the capture listener will be called
446
458
  :return: A BackupData object
447
459
  :rtype: BackupData
448
460
  """
449
461
  backup: BackupData = await self.client.backup(self.id)
450
- avoid_listener = avoid_listener or self.always_avoid_listeners
451
- if not avoid_listener:
452
- endpoint: Endpoint = Endpoint.backup()
453
- await self._listener.on_capture(
454
- endpoint=endpoint, before=self.cache.backup, after=backup
455
- )
456
- if update_cache:
457
- self.cache.update(backup)
458
462
  return backup
459
463
 
460
464
  async def start(self) -> Response:
squarecloud/cli/app.py CHANGED
@@ -48,7 +48,7 @@ async def app_group(ctx: Context, app_id: str, token: str):
48
48
  if not app_id:
49
49
  click.echo(ctx.get_help())
50
50
  return
51
- client = Client(token, debug=False)
51
+ client = Client(token, log_level='CRITICAL')
52
52
  if not ctx.invoked_subcommand:
53
53
  with Console().status('loading'):
54
54
  app = await client.app(app_id)
@@ -114,7 +114,7 @@ async def get_app_status(ctx: Context):
114
114
  @click.pass_context
115
115
  @run_async
116
116
  async def app_list(ctx: Context, token: str):
117
- client = Client(token, debug=False)
117
+ client = Client(token, log_level='CRITICAL')
118
118
  with Console().status('loading'):
119
119
  apps: list[Application] = await client.all_apps()
120
120
  if not apps:
@@ -299,8 +299,8 @@ async def delete_app(ctx: Context):
299
299
  )
300
300
  @run_async
301
301
  async def upload_app(token: str, file: BufferedReader):
302
- client = Client(token, debug=False)
303
- with Console().status('loading'):
302
+ client = Client(token, log_level='CRITICAL')
303
+ with Console().status('uploading'):
304
304
  upload_data: UploadData = await client.upload_app(
305
305
  file=squarecloud.File(file)
306
306
  )
squarecloud/cli/main.py CHANGED
@@ -1,61 +1,21 @@
1
+ from pathlib import Path
1
2
  from typing import Literal
2
3
 
3
4
  import click
4
5
  from click import prompt
5
6
  from dotenv import load_dotenv
6
7
  from rich import print
7
- from rich.console import Console
8
8
  from rich.panel import Panel
9
- from rich.table import Table
10
-
11
- from squarecloud.client import Client, create_config_file
12
- from squarecloud.data import StatisticsData
13
9
 
14
10
  from ..errors import RequestError, SquareException
15
- from . import cli, run_async
11
+ from ..utils import ConfigFile
12
+ from . import cli
16
13
  from .app import app_list, upload_app
17
14
  from .files import app_group
18
15
 
19
16
  load_dotenv()
20
17
 
21
18
 
22
- @cli.command(
23
- name='statistics', help='Get statistics information about the host'
24
- )
25
- @click.option(
26
- '--token',
27
- '-t',
28
- help='your api token',
29
- envvar='SQUARECLOUD_KEY',
30
- required=True,
31
- type=click.STRING,
32
- prompt='API KEY',
33
- hide_input=True,
34
- )
35
- @run_async
36
- async def get_squarecloud_statistics(token: str):
37
- client = Client(api_key=token, debug=False)
38
-
39
- with Console().status('loading'):
40
- statistics_data: StatisticsData = await client.statistics()
41
- table = Table(title='Statistics', header_style='purple')
42
-
43
- table.add_column('Apps', justify='center')
44
- table.add_column('Websites', justify='center')
45
- table.add_column('Time', justify='center')
46
- table.add_column('Ping', justify='center')
47
- table.add_column('Users', justify='center')
48
-
49
- table.add_row(
50
- str(statistics_data.apps),
51
- str(statistics_data.websites),
52
- str(statistics_data.ping),
53
- str(statistics_data.users),
54
- style='green',
55
- )
56
- print(table)
57
-
58
-
59
19
  @click.command(
60
20
  name='create-config-file',
61
21
  help='Create a config file to upload an application',
@@ -131,8 +91,7 @@ def create_config(
131
91
  auto_restart: bool | None = None,
132
92
  ):
133
93
 
134
- content = create_config_file(
135
- path='/',
94
+ config_file = ConfigFile(
136
95
  display_name=display_name,
137
96
  main=main,
138
97
  memory=memory,
@@ -141,11 +100,10 @@ def create_config(
141
100
  subdomain=subdomain,
142
101
  start=start,
143
102
  auto_restart=auto_restart,
144
- save=False,
145
103
  )
146
104
  if output_file:
147
- with open(output_file, 'w') as f:
148
- f.write(content)
105
+ if not Path(output_file).exists():
106
+ raise Exception(f'File or directory {output_file} not exists')
149
107
  print(
150
108
  Panel(
151
109
  f'\u2728 file saved successfully at {output_file}',
@@ -157,7 +115,7 @@ def create_config(
157
115
  else:
158
116
  print(
159
117
  Panel(
160
- content,
118
+ config_file.content(),
161
119
  title='squarecloud.app',
162
120
  border_style='purple',
163
121
  style='green',
@@ -172,8 +130,7 @@ def create_config(
172
130
  path = prompt(
173
131
  'where do you want to save the file', default='squarecloud.app'
174
132
  )
175
- with open(path, 'w') as f:
176
- f.write(content)
133
+ config_file.save(path)
177
134
  print(
178
135
  Panel(
179
136
  f'\u2728 file saved successfully at {path}',
@@ -211,3 +168,7 @@ def safe_entry_point():
211
168
  style='red',
212
169
  ),
213
170
  )
171
+
172
+
173
+ if __name__ == '__main__':
174
+ safe_entry_point()