Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: code quality #7

Merged
merged 2 commits into from
Aug 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
name: lint
on:
push:
branches:
- main
pull_request:

jobs:
lint:
uses: lnbits/lnbits/.github/workflows/lint.yml@dev
15 changes: 7 additions & 8 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
on:
push:
tags:
- "v[0-9]+.[0-9]+.[0-9]+"
- 'v[0-9]+.[0-9]+.[0-9]+'

jobs:

release:
runs-on: ubuntu-latest
steps:
Expand Down Expand Up @@ -34,12 +33,12 @@ jobs:
- name: Create pull request in extensions repo
env:
GH_TOKEN: ${{ secrets.EXT_GITHUB }}
repo_name: "${{ github.event.repository.name }}"
tag: "${{ github.ref_name }}"
branch: "update-${{ github.event.repository.name }}-${{ github.ref_name }}"
title: "[UPDATE] ${{ github.event.repository.name }} to ${{ github.ref_name }}"
body: "https://github.com/lnbits/${{ github.event.repository.name }}/releases/${{ github.ref_name }}"
archive: "https://github.com/lnbits/${{ github.event.repository.name }}/archive/refs/tags/${{ github.ref_name }}.zip"
repo_name: '${{ github.event.repository.name }}'
tag: '${{ github.ref_name }}'
branch: 'update-${{ github.event.repository.name }}-${{ github.ref_name }}'
title: '[UPDATE] ${{ github.event.repository.name }} to ${{ github.ref_name }}'
body: 'https://github.com/lnbits/${{ github.event.repository.name }}/releases/${{ github.ref_name }}'
archive: 'https://github.com/lnbits/${{ github.event.repository.name }}/archive/refs/tags/${{ github.ref_name }}.zip'
run: |
cd lnbits-extensions
git checkout -b $branch
Expand Down
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
__pycache__
node_modules
.mypy_cache
.venv
12 changes: 12 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"semi": false,
"arrowParens": "avoid",
"insertPragma": false,
"printWidth": 80,
"proseWrap": "preserve",
"singleQuote": true,
"trailingComma": "none",
"useTabs": false,
"bracketSameLine": false,
"bracketSpacing": false
}
47 changes: 47 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
all: format check

format: prettier black ruff

check: mypy pyright checkblack checkruff checkprettier

prettier:
poetry run ./node_modules/.bin/prettier --write .
pyright:
poetry run ./node_modules/.bin/pyright

mypy:
poetry run mypy .

black:
poetry run black .

ruff:
poetry run ruff check . --fix

checkruff:
poetry run ruff check .

checkprettier:
poetry run ./node_modules/.bin/prettier --check .

checkblack:
poetry run black --check .

checkeditorconfig:
editorconfig-checker

test:
PYTHONUNBUFFERED=1 \
DEBUG=true \
poetry run pytest
install-pre-commit-hook:
@echo "Installing pre-commit hook to git"
@echo "Uninstall the hook with poetry run pre-commit uninstall"
poetry run pre-commit install

pre-commit:
poetry run pre-commit run --all-files


checkbundle:
@echo "skipping checkbundle"
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# DJ Livestream - <small>[LNbits](https://github.com/lnbits/lnbits) extension</small>

<small>For more about LNBits extension check [this tutorial](https://github.com/lnbits/lnbits/wiki/LNbits-Extensions)</small>

## Help DJ's and music producers conduct music livestreams
Expand Down
37 changes: 21 additions & 16 deletions __init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
from fastapi import APIRouter
from loguru import logger

from lnbits.db import Database
from lnbits.helpers import template_renderer
from lnbits.tasks import create_permanent_unique_task

db = Database("ext_livestream")
from .crud import db
from .tasks import wait_for_paid_invoices
from .views import livestream_generic_router
from .views_api import livestream_api_router
from .views_lnurl import livestream_lnurl_router

livestream_static_files = [
{
Expand All @@ -17,27 +17,32 @@
]

livestream_ext: APIRouter = APIRouter(prefix="/livestream", tags=["livestream"])


def livestream_renderer():
return template_renderer(["livestream/templates"])


from .lnurl import * # noqa: F401,F403
from .tasks import wait_for_paid_invoices
from .views import * # noqa: F401,F403
from .views_api import * # noqa: F401,F403

livestream_ext.include_router(livestream_generic_router)
livestream_ext.include_router(livestream_api_router)
livestream_ext.include_router(livestream_lnurl_router)

scheduled_tasks: list[asyncio.Task] = []


def livestream_stop():
for task in scheduled_tasks:
try:
task.cancel()
except Exception as ex:
logger.warning(ex)


def livestream_start():
from lnbits.tasks import create_permanent_unique_task

task = create_permanent_unique_task("ext_livestream", wait_for_paid_invoices)
scheduled_tasks.append(task)


__all__ = [
"livestream_ext",
"livestream_static_files",
"livestream_start",
"livestream_stop",
"db",
]
5 changes: 1 addition & 4 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@
"name": "DJ Livestream",
"short_description": "Sell tracks and split revenue (lnurl-pay)",
"tile": "/livestream/static/image/livestream.png",
"contributors": [
"fiatjaf",
"cryptograffiti"
],
"contributors": ["fiatjaf", "cryptograffiti"],
"min_lnbits_version": "0.12.5",
"hidden": false
}
16 changes: 9 additions & 7 deletions crud.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
from typing import List, Optional
from typing import Optional

from lnbits.core.crud import create_account, create_wallet
from lnbits.db import SQLITE
from lnbits.db import SQLITE, Database

from . import db
from .models import Livestream, Producer, Track

db = Database("ext_livestream")


async def create_livestream(*, wallet_id: str) -> int:
returning = "" if db.type == SQLITE else "RETURNING ID"
method = db.execute if db.type == SQLITE else db.fetchone

result = await (method)(
result = await method(
f"""
INSERT INTO livestream.livestreams (wallet)
VALUES (?)
Expand Down Expand Up @@ -85,7 +86,8 @@ async def add_track(
) -> int:
result = await db.execute(
"""
INSERT INTO livestream.tracks (livestream, name, download_url, price_msat, producer)
INSERT INTO livestream.tracks \
(livestream, name, download_url, price_msat, producer)
VALUES (?, ?, ?, ?, ?)
""",
(livestream, name, download_url, price_msat, producer),
Expand Down Expand Up @@ -129,7 +131,7 @@ async def get_track(track_id: Optional[int]) -> Optional[Track]:
return Track(**row) if row else None


async def get_tracks(livestream: int) -> List[Track]:
async def get_tracks(livestream: int) -> list[Track]:
rows = await db.fetchall(
"""
SELECT id, download_url, price_msat, name, producer
Expand Down Expand Up @@ -193,7 +195,7 @@ async def get_producer(producer_id: int) -> Optional[Producer]:
return Producer(**row) if row else None


async def get_producers(livestream: int) -> List[Producer]:
async def get_producers(livestream: int) -> list[Producer]:
rows = await db.fetchall(
"""
SELECT id, "user", wallet, name
Expand Down
14 changes: 7 additions & 7 deletions manifest.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
{
"repos": [
{
"id": "livestream",
"organisation": "lnbits",
"repository": "livestream"
}
]
"repos": [
{
"id": "livestream",
"organisation": "lnbits",
"repository": "livestream"
}
]
}
7 changes: 4 additions & 3 deletions migrations.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ async def m001_initial(db):
"""
Initial livestream tables.
"""
ref = db.references_schema
await db.execute(
f"""
CREATE TABLE livestream.livestreams (
Expand All @@ -16,7 +17,7 @@ async def m001_initial(db):
await db.execute(
f"""
CREATE TABLE livestream.producers (
livestream INTEGER NOT NULL REFERENCES {db.references_schema}livestreams (id),
livestream INTEGER NOT NULL REFERENCES {ref}livestreams (id),
id {db.serial_primary_key},
"user" TEXT NOT NULL,
wallet TEXT NOT NULL,
Expand All @@ -28,12 +29,12 @@ async def m001_initial(db):
await db.execute(
f"""
CREATE TABLE livestream.tracks (
livestream INTEGER NOT NULL REFERENCES {db.references_schema}livestreams (id),
livestream INTEGER NOT NULL REFERENCES {ref}livestreams (id),
id {db.serial_primary_key},
download_url TEXT,
price_msat INTEGER NOT NULL DEFAULT 0,
name TEXT,
producer INTEGER REFERENCES {db.references_schema}producers (id) NOT NULL
producer INTEGER REFERENCES {ref}producers (id) NOT NULL
);
"""
)
20 changes: 4 additions & 16 deletions models.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from fastapi import Query, Request
from lnurl import Lnurl
from lnurl import encode as lnurl_encode
from lnurl.models import ClearnetUrl, Max144Str, UrlAction
from lnurl.types import LnurlPayMetadata
from pydantic import BaseModel

Expand Down Expand Up @@ -73,24 +72,13 @@ async def lnurlpay_metadata(self) -> LnurlPayMetadata:
) + " Like this track? Send some sats in appreciation."

if self.download_url:
description += f" Send {round(self.price_msat/1000)} sats or more and you can download it."
description += (
f"Send {round(self.price_msat/1000)} "
"sats or more and you can download it."
)

return LnurlPayMetadata(json.dumps([["text/plain", description]]))

def success_action(
self, payment_hash: str, request: Request
) -> Optional[UrlAction]:
if not self.download_url:
return None

url = str(request.url_for("livestream.track_redirect_download", track_id=self.id))
url_with_query = f"{url}?p={payment_hash}"

return UrlAction(
url=ClearnetUrl(url_with_query, scheme="https"),
description=Max144Str(f"Download the track {self.name}!"),
)


class Producer(BaseModel):
id: int
Expand Down
59 changes: 59 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "livestream",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"prettier": "^3.2.5",
"pyright": "^1.1.358"
}
}
Loading