Skip to content

Commit

Permalink
Merge pull request #16 from stepanzubkov/dev
Browse files Browse the repository at this point in the history
Version v0.10.0: Pastes stats
  • Loading branch information
stepanzubkov authored Jul 9, 2023
2 parents fefe82f + 1fb12d5 commit ebc4bbc
Show file tree
Hide file tree
Showing 4 changed files with 141 additions and 3 deletions.
76 changes: 76 additions & 0 deletions florgon_cc_cli/commands/paste.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
get_paste_info_by_hash,
delete_paste_by_hash,
extract_hash_from_paste_short_url,
get_paste_stats_by_hash,
clear_paste_stats_by_hash,
)
from florgon_cc_cli.services.files import concat_files

Expand Down Expand Up @@ -175,3 +177,77 @@ def delete(short_url: str):
return
else:
click.secho("Paste was successfully deleted!", fg="green")


@paste.command()
@click.option("-s", "--short-url", type=str, help="Short url.")
@click.option(
"-r",
"--referers-as",
type=click.Choice(["percent", "number"]),
default="percent",
help="Paste views referers as.",
)
@click.option(
"-d",
"--dates-as",
type=click.Choice(["percent", "number"]),
default="percent",
help="Paste views dates as.",
)
def stats(short_url: str, referers_as: str, dates_as: str):
"""Prints paste views statistics."""
if short_url:
paste_hash = extract_hash_from_paste_short_url(short_url)
else:
click.echo("Short url is not specified, requesting for list of your pastes.")
paste_hash = request_hash_from_pastes_list(access_token=get_access_token())

success, response = get_paste_stats_by_hash(
paste_hash,
url_views_by_referers_as=referers_as,
url_views_by_dates_as=dates_as,
access_token=get_access_token(),
)
if not success:
click.secho(response["message"], err=True, fg="red")
return

click.echo("Total views: " + click.style(response["total"], fg="green"))
if response.get("by_referers"):
click.echo("Views by referers:")
for referer in response["by_referers"]:
click.echo(
f"\t{referer} - {response['by_referers'][referer]}"
+ "%" * int(referers_as == "percent")
)

if response.get("by_dates"):
click.echo("Views by dates:")
for date in response["by_dates"]:
click.echo(
f"\t{date} - {response['by_dates'][date]}" + "%" * int(dates_as == "percent")
)


@paste.command()
@click.option("-s", "--short-url", type=str, help="Short url.")
def clear_stats(short_url: str):
"""
Clears paste stats. Auth required.
If short url is not passed, you can choose it from your pastes interactively.
"""
if short_url:
short_url_hash = extract_hash_from_paste_short_url(short_url)
else:
click.echo("Short url is not specified, requesting for list of your pastes.")
short_url_hash = request_hash_from_pastes_list(access_token=get_access_token())

success, *response = clear_paste_stats_by_hash(
hash=short_url_hash, access_token=get_access_token()
)
if not success:
click.secho(response[0]["message"], err=True, fg="red")
return

click.secho("Paste stats was successfully cleared!", fg="green")
14 changes: 14 additions & 0 deletions florgon_cc_cli/models/stats.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
"""
Stats model for url and paste stats.
"""
from typing import TypedDict, Dict, NotRequired


class Views(TypedDict):
total: int
by_refferers: NotRequired[Dict[str, int]]
by_dates: NotRequired[Dict[str, int]]


class Stats(TypedDict):
views: Views
51 changes: 50 additions & 1 deletion florgon_cc_cli/services/paste.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from florgon_cc_cli import config
from florgon_cc_cli.models.paste import Paste
from florgon_cc_cli.models.error import Error
from florgon_cc_cli.models.stats import Stats


def build_paste_open_url(hash: str) -> str:
Expand Down Expand Up @@ -156,7 +157,7 @@ def delete_paste_by_hash(
) -> Union[Tuple[bool, Optional[Error]], NoReturn]:
"""
Deletes user's paste by access_token.
:param str hash: url hash
:param str hash: paste hash
:param Optional[str] access_token: access token
:return: Tuple with two or one elements.
First is a deletion status (True if successfully).
Expand All @@ -168,3 +169,51 @@ def delete_paste_by_hash(
if response.status_code == 204:
return (True,)
return try_decode_response_to_json(response)


def get_paste_stats_by_hash(
hash: str,
url_views_by_referers_as: str = "percent",
url_views_by_dates_as: str = "percent",
access_token: Optional[str] = None,
) -> Union[Tuple[Literal[True], Stats], Tuple[Literal[False], Error], NoReturn]:
"""
Returns statistics about paste by hash.
:param str hash: paste hash
:return: Tuple with two elements.
First is a response status (True if successfully).
Seconds is a response body.
:rtype: Tuple[True, Stats] if response requested successfully, Tuple[False, Error] if error occured,
or exit application if cannot decode response to json
"""
response = execute_json_api_method(
"GET",
f"pastes/{hash}/stats",
params={
"referer_views_value_as": url_views_by_referers_as,
"dates_views_value_as": url_views_by_dates_as,
},
access_token=access_token,
)
if "success" in response:
return True, response["success"]["views"]
return False, response["error"]


def clear_paste_stats_by_hash(
hash: str, access_token: Optional[str] = None
) -> Union[Tuple[Literal[True]], Tuple[Literal[False], Error], NoReturn]:
"""
Clears user's paste stats by access_token.
:param str hash: paste hash
:param Optional[str] access_token: access token
:return: Tuple with two or one elements.
First is a clearsing status (True if successfully).
Seconds is a response body (if error).
:rtype: Tuple[True] if successfully cleared, Tuple[False, Error] if error occured,
or exit application if cannot decode to json
"""
response = execute_api_method("DELETE", f"pastes/{hash}/stats", access_token=access_token)
if response.status_code == 204:
return (True,)
return try_decode_response_to_json(response)
3 changes: 1 addition & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "florgon-cc-cli"
version = "0.9.1"
version = "0.10.0"
license = "MIT"
homepage = "https://cc.florgon.com/"
keywords = ["cli", "url shortener", "paste manager"]
Expand Down Expand Up @@ -31,7 +31,6 @@ name = "test"
url = "https://test.pypi.org/legacy/"
priority = "primary"


[[tool.poetry.source]]
name = "PyPI"
priority = "primary"
Expand Down

0 comments on commit ebc4bbc

Please sign in to comment.