Skip to content
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ Todos los cambios relevantes del proyecto se registran aquí. Formato basado en
## [Sin publicar]

### Agregado
- Playing a channel of a source without adding it (#105): each Explorar row has a play button that opens it in VLC, the same way and with the same messages as the catalog (Content ID or infohash, #100).
- Removing channels from a source (#104): "Quitar de la lista" in Explorar hides the chosen channels of their sources, and they stay hidden when the source is refreshed or its file uploaded again (kept by Content ID in the new `source_dismissed` table, migration 0007). Fuentes shows how many were removed from each source and "Restaurar quitados" brings them back. The catalog is not touched.
- Pages in Explorar (#103): 100 channels per page with first, previous, next and last links and "página X de Y", instead of only the first 200. The page goes in the address (`page=`) with the search, and adding channels comes back to the same page; changing a filter starts again at the first one.
- Choosing several channels in the list (#102): a check box per row and one to choose them all, and a bar with how many are chosen and three actions for them: Verificar, Regenerar capturas and Borrar (the last two ask first). Checks run in the background and every action comes back to the list with its filters.
Expand Down
31 changes: 29 additions & 2 deletions app/web/explore_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,23 @@
from fastapi.responses import HTMLResponse, RedirectResponse
from sqlalchemy.orm import Session

from app.db.models import Category
from app.services import categories, sources
from app.db.models import Category, SourceEntry
from app.services import categories, channels, sources
from app.services.catalog import Screenshots
from app.services.errors import DuplicateError, NotFoundError, ServiceError, ValidationError
from app.services.sources import ExploreQuery, SourceFetchError
from app.web.check_routes import start_checks
from app.web.deps import (
CheckRunnerDep,
EngineDep,
EngineFactoryDep,
EngineProbeDep,
SessionDep,
SessionFactoryDep,
SettingsDep,
)
from app.web.forms import resolve_category
from app.web.routes import play
from app.web.templating import templates

router = APIRouter(prefix="/explore")
Expand Down Expand Up @@ -147,6 +149,31 @@ def explore_add(
return _render_explore(request, session, query, result=result)


@router.post("/entries/{entry_id}/play", response_class=HTMLResponse, name="explore_play")
def explore_play(
request: Request, session: SessionDep, client: EngineDep, settings: SettingsDep, entry_id: int
):
"""Opens a channel of a source in VLC without adding it to the catalog, to try it."""
entry = _entry_or_404(session, entry_id)
known = channels.find_channel_by_content_id(session, entry.content_id)
response, _ = play(
request,
client,
settings,
entry.content_id,
title=entry.title,
kind=known.id_kind if known else None,
)
return response


def _entry_or_404(session: Session, entry_id: int) -> SourceEntry:
entry = session.get(SourceEntry, entry_id)
if entry is None:
raise HTTPException(status_code=404, detail="Canal no encontrado en las fuentes")
return entry


@router.post("/remove", response_class=HTMLResponse, name="explore_remove")
def explore_remove(
request: Request,
Expand Down
42 changes: 32 additions & 10 deletions app/web/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
from fastapi.responses import HTMLResponse, RedirectResponse, Response
from sqlalchemy.orm import Session

from app.acestream.client import EngineClient, StreamSession
from app.acestream.content_id import IdKind
from app.acestream.errors import ContentNotFoundError, EngineError
from app.db.base import utcnow
from app.db.models import Channel, Check
Expand All @@ -16,6 +18,7 @@
from app.services.iso import country_name, language_name
from app.services.listing import DEFAULT_DESCENDING, ChannelQuery, SortKey
from app.services.screenshots import SCREENSHOTS_SUBDIR
from app.services.settings import AppSettings
from app.web.check_routes import start_checks
from app.web.deps import (
CheckRunnerDep,
Expand Down Expand Up @@ -357,13 +360,34 @@ def channel_play(
request: Request, session: SessionDep, client: EngineDep, settings: SettingsDep, channel_id: int
):
channel = _get_channel_or_404(session, channel_id)
response, stream = play(
request,
client,
settings,
channel.content_id,
title=channel.title,
kind=channel.id_kind,
)
if stream is not None and channel.id_kind != stream.kind:
channel.id_kind = stream.kind # next time, straight the right way
session.commit()
return response


def play(
request: Request,
client: EngineClient,
settings: AppSettings,
content_id: str,
*,
title: str | None,
kind: IdKind | None = None,
) -> tuple[HTMLResponse, StreamSession | None]:
"""Opens `content_id` in VLC; the notice for #notices and the session, if it started."""
stream = None
try:
stream = player.open_in_player(
client,
channel.content_id,
kind=channel.id_kind,
title=channel.title,
vlc_path=settings.vlc_path,
client, content_id, kind=kind, title=title, vlc_path=settings.vlc_path
)
except player.VlcNotFoundError:
error = "No se encontró VLC. Instálalo o indica la ruta de vlc.exe en Ajustes."
Expand All @@ -378,16 +402,14 @@ def channel_play(
error = f"No se pudo abrir VLC: {exc}"
else:
error = None
if channel.id_kind != stream.kind:
channel.id_kind = stream.kind # next time, straight the right way
session.commit()
return templates.TemplateResponse(
response = templates.TemplateResponse(
request,
"channels/_play_result.html",
{"channel": channel, "error": error},
{"title": title or content_id, "error": error},
# 503: the player or the engine is not available; htmx shows it (see base.html).
status_code=503 if error else 200,
)
return response, stream


@router.get("/channels/{channel_id}/edit", response_class=HTMLResponse, name="channel_edit")
Expand Down
2 changes: 1 addition & 1 deletion app/web/templates/channels/_play_result.html
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{% if error %}
<p class="notice notice-error" role="alert">{{ error }}</p>
{% else %}
<p class="notice notice-ok" role="status">Abriendo «{{ channel.title }}» en VLC…</p>
<p class="notice notice-ok" role="status">Abriendo «{{ title }}» en VLC…</p>
{% endif %}
9 changes: 8 additions & 1 deletion app/web/templates/explore/index.html
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{% extends "base.html" %}
{% from "_icons.html" import copy_button %}
{% from "_icons.html" import copy_button, icon %}

{# Reloading would lose the summary of what was added. #}
{% set reload_on_checks = false %}
Expand Down Expand Up @@ -105,6 +105,7 @@ <h2 id="summary-title">Resultado</h2>
<th scope="col">Grupo</th>
<th scope="col">Hash</th>
<th scope="col">Fuente</th>
<th scope="col"><span class="visually-hidden">Acciones</span></th>
</tr>
</thead>
<tbody>
Expand All @@ -125,6 +126,12 @@ <h2 id="summary-title">Resultado</h2>
<td>{{ entry.group or "—" }}</td>
<td class="hash"><code title="{{ entry.content_id }}">{{ entry.content_id | short_hash }}</code>{{ copy_button(entry.content_id, "Copiar el hash de " ~ (entry.title or entry.content_id)) }}</td>
<td>{{ row.source_name }}</td>
<td class="row-actions">
{# Not a form: these rows are inside the add form. No parameters are sent. #}
<button type="button" class="icon-button" hx-post="{{ url_for('explore_play', entry_id=entry.id) }}"
hx-params="none" hx-target="#notices" hx-swap="innerHTML" hx-disabled-elt="this"
aria-label="Reproducir {{ entry.title or entry.content_id }}" title="Reproducir sin agregarlo">{{ icon("play") }}</button>
</td>
</tr>
{% endfor %}
</tbody>
Expand Down
60 changes: 60 additions & 0 deletions tests/test_web_explore.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,3 +303,63 @@ def test_restoring_from_the_sources_page(web, db, listed):
assert "Restaurar quitados" not in page
assert "Uno HD" in web.get("/explore").text
assert web.post("/explore/sources/99/restore").status_code == 404


@pytest.fixture
def opened(monkeypatch):
"""Replaces the player: records what would be opened, or raises `error`."""
from types import SimpleNamespace

from app.acestream.content_id import IdKind
from app.web import routes

class Opened:
calls = []
error = None

def __call__(self, client, content_id, *, kind=None, title=None, vlc_path=None):
self.calls.append((content_id, kind, title))
if self.error:
raise self.error
return SimpleNamespace(kind=IdKind.CONTENT_ID)

fake = Opened()
monkeypatch.setattr(routes.player, "open_in_player", fake)
return fake


def test_playing_a_channel_of_a_source_without_adding_it(web, db, listed, opened):
response = web.post(f"/explore/entries/{entry_id(db, 'Uno HD')}/play")

assert response.status_code == 200
assert "Abriendo «Uno HD» en VLC…" in response.text and "<html" not in response.text
assert opened.calls == [(HASH_A, None, "Uno HD")]
assert db.query(Channel).count() == 1 # still only "Mío"


def test_playing_uses_how_the_catalog_loads_the_same_channel(web, db, listed, opened):
listed.id_kind = "infohash"
db.commit()

web.post(f"/explore/entries/{entry_id(db, 'Dos')}/play")

assert opened.calls[-1][:2] == (HASH_B, "infohash")


def test_playing_failures_are_explained(web, db, listed, opened):
from app.acestream.errors import ContentNotFoundError

opened.error = ContentNotFoundError(HASH_A)

response = web.post(f"/explore/entries/{entry_id(db, 'Uno HD')}/play")

assert response.status_code == 503
assert "puede que el enlace haya muerto" in response.text
assert web.post("/explore/entries/999/play").status_code == 404


def test_explore_rows_have_a_play_button(web, db, listed):
page = web.get("/explore").text

assert f'hx-post="http://127.0.0.1/explore/entries/{entry_id(db, "Uno HD")}/play"' in page
assert 'hx-params="none"' in page
Loading