Creating indexes on video columns to speedup video search.

This commit is contained in:
Roland 2021-12-24 14:53:47 -07:00
parent 2b5f48d8d7
commit 81fb9b06c5
No known key found for this signature in database
GPG key ID: 9D6DBD3ACF11AB93
7 changed files with 111 additions and 46 deletions

View file

@ -1,4 +1,4 @@
"""video censored
"""Video censored
Revision ID: 32d96eb9122d
Revises: 184329ed5137
@ -22,12 +22,12 @@ DOCKERIZED = True if os.environ.get('DOCKER', '').lower().startswith('t') else F
def upgrade():
bind = op.get_bind()
session = Session(bind=bind)
session.execute('ALTER TABLE video ADD COLUMN censored BOOL DEFAULT false')
session.execute('CREATE INDEX video_censored ON video (censored)')
def downgrade():
bind = op.get_bind()
session = Session(bind=bind)
session.execute('ALTER TABLE video DROP COLUMN IF EXISTS censored')
session.execute('DROP INDEX IF EXISTS video_censored')

View file

@ -0,0 +1,37 @@
"""Video indexes
Revision ID: 8df411232c17
Revises: 32d96eb9122d
Create Date: 2021-12-24 14:42:02.365100
"""
import os
from alembic import op
from sqlalchemy.orm import Session
# revision identifiers, used by Alembic.
revision = '8df411232c17'
down_revision = '32d96eb9122d'
branch_labels = None
depends_on = None
DOCKERIZED = True if os.environ.get('DOCKER', '').lower().startswith('t') else False
def upgrade():
bind = op.get_bind()
session = Session(bind=bind)
session.execute('CREATE INDEX video_favorite ON video (favorite)')
session.execute('CREATE INDEX video_view_count ON video (view_count)')
session.execute('CREATE INDEX video_validated_poster ON video (validated_poster)')
session.execute('CREATE INDEX video_upload_date ON video (upload_date)')
def downgrade():
bind = op.get_bind()
session = Session(bind=bind)
session.execute('DROP INDEX IF EXISTS video_favorite')
session.execute('DROP INDEX IF EXISTS video_view_count')
session.execute('DROP INDEX IF EXISTS video_validated_poster')
session.execute('DROP INDEX IF EXISTS video_upload_date')

View file

@ -464,7 +464,7 @@ export function scrollToTop() {
});
}
export function changePageHistory(history, location, activePage, searchStr, searchOrder) {
export function changePageHistory(history, location, activePage, searchStr, searchOrder, filters) {
let search = `?page=${activePage}`;
if (searchStr) {
search = `${search}&q=${searchStr}`;
@ -472,6 +472,10 @@ export function changePageHistory(history, location, activePage, searchStr, sear
if (searchOrder) {
search = `${search}&o=${searchOrder}`;
}
if (filters.length > 0) {
filters = filters.join(',');
search = `${search}&f=${filters}`;
}
history.push({
pathname: location.pathname,
search: search,

View file

@ -207,13 +207,14 @@ function FilterModal(props) {
<Radio toggle
checked={i.value}
label={i.label}
onClick={() => props.toggleFilter(i.name)}
onClick={!i.disabled ? () => props.toggleFilter(i.name) : null}
disabled={i.disabled}
/>
</Form.Input>
)
return (
<Modal closeIcon open={props.open} onClose={props.close} onOpen={props.open} size='mini'>
<Modal closeIcon open={props.open} onClose={props.onClose} onOpen={props.onOpen} size='mini'>
<Modal.Header>{props.header}</Modal.Header>
<Modal.Content>
<Modal.Description>
@ -224,7 +225,7 @@ function FilterModal(props) {
</Modal.Content>
<Modal.Actions>
{props.applyButton && <Button color='blue'>Apply</Button>}
<Button color='black' onClick={props.close}>Close</Button>
<Button color='black' onClick={props.onClose}>Close</Button>
</Modal.Actions>
</Modal>
)
@ -239,28 +240,38 @@ class Videos extends React.Component {
let activePage = query.page ? parseInt(query.page) : 1; // First page is 1 by default, of course.
let searchStr = query.q || '';
let searchOrder = query.o || defaultVideoOrder;
let filtersEnabled = query.f && query.f.length > 0 ? query.f.split(',') : [];
let filters = [
{label: 'Favorites', name: 'favorite', value: this.props.filter === 'favorite'},
{label: 'Censored', name: 'censored', value: this.props.filter === 'censored'},
{
label: 'Favorites',
name: 'favorite',
value: filtersEnabled.indexOf('favorite') >= 0 || props.filter === 'favorite',
disabled: props.filter === 'favorite',
},
{
label: 'Censored',
name: 'censored',
value: filtersEnabled.indexOf('censored') >= 0
},
];
this.state = {
activePage,
channel: null,
videos: null,
queryStr: searchStr,
searchStr: '',
limit: DEFAULT_LIMIT,
activePage: activePage,
totalPages: null,
prev: null,
next: null,
videoOrders: searchStr === '' ? videoOrders : searchOrders,
searchOrder: searchOrder,
header: '',
filtersOpen: false,
filters,
filterEnabled: false,
filtersEnabled,
filtersOpen: false,
header: '',
limit: DEFAULT_LIMIT,
next: null,
prev: null,
queryStr: searchStr,
searchOrder,
searchStr: '',
totalPages: null,
videoOrders: searchStr === '' ? videoOrders : searchOrders,
videos: null,
};
}
@ -289,11 +300,6 @@ class Videos extends React.Component {
this.applyStateToHistory();
await this.fetchVideos();
}
let filterEnabled = this.enabledFilters().length > 0;
if (this.state.filterEnabled !== filterEnabled) {
this.state.filterEnabled = filterEnabled;
}
}
setHeader() {
@ -369,7 +375,8 @@ class Videos extends React.Component {
applyStateToHistory = () => {
let {history, location} = this.props;
let {activePage, queryStr, searchOrder} = this.state;
changePageHistory(history, location, activePage, queryStr, searchOrder);
let filters = this.enabledFilters();
changePageHistory(history, location, activePage, queryStr, searchOrder, filters);
}
handleSearch = async (e) => {
@ -388,16 +395,26 @@ class Videos extends React.Component {
toggleFilter = (name) => {
let filters = this.state.filters;
let filtersEnabled = [];
for (let i = 0; i < filters.length; i++) {
if (filters[i].name === name) {
filters[i].value = !filters[i].value;
let filter = filters[i];
if (filter.name === name) {
filter.value = !filter.value;
}
if (filter.value) {
filtersEnabled = filtersEnabled.concat([filter.name]);
}
}
this.setState({filters}, this.fetchVideos);
this.setState({filters, filtersEnabled});
}
applyFilters = async () => {
this.applyStateToHistory();
await this.fetchVideos();
}
closeFilters = () => {
this.setState({filtersOpen: false});
this.setState({filtersOpen: false}, this.applyFilters);
}
openFilters = () => {
@ -415,7 +432,7 @@ class Videos extends React.Component {
totalPages,
videoOrders,
videos,
filterEnabled,
filtersEnabled,
} = this.state;
let body = <VideoPlaceholder/>;
@ -472,13 +489,13 @@ class Videos extends React.Component {
{queryStr && clearSearchButton}
</Grid.Column>
<Grid.Column width={1}>
<Button icon onClick={this.openFilters} color={filterEnabled ? 'black' : null}>
<Button icon onClick={this.openFilters} color={filtersEnabled.length > 0 ? 'black' : null}>
<Icon name='filter'/>
</Button>
<FilterModal
applyFilters={this.applyFilters}
open={this.state.filtersOpen}
close={this.closeFilters}
onClose={this.closeFilters}
header='Filter Videos'
filters={this.state.filters}
toggleFilter={this.toggleFilter}

View file

@ -12,8 +12,8 @@ logger = logger.getChild(__name__)
class ArchiveDownloader(Downloader, ABC):
@staticmethod
def valid_url(url: str) -> bool:
@classmethod
def valid_url(cls, url: str) -> bool:
"""
Archiver will attempt to archive anything, so it should be last!
"""

View file

@ -48,11 +48,12 @@ class ChannelDownloader(Downloader, ABC):
Handling downloading of all Videos in a Channel.
"""
@staticmethod
def valid_url(url) -> bool:
@classmethod
def valid_url(cls, url) -> bool:
for ie in ChannelIEs:
if ie.suitable(url):
return True
logger.debug(f'{cls.__name__} not suitable for {url}')
return False
def do_download(self, download: Download):
@ -60,7 +61,12 @@ class ChannelDownloader(Downloader, ABC):
Update a Channel's catalog, then schedule downloads of every missing video.
"""
with get_db_session() as session:
channel = session.query(Channel).filter_by(url=download.url).one()
channel = session.query(Channel).filter_by(url=download.url).one_or_none()
if not channel:
# Couldn't get channel by URL, this is probably a playlist. Find the channel for the playlist.
channel_source_id = get_channel_source_id(download.url)
channel = get_channel(channel_source_id, return_dict=False)
update_channel(channel)
@ -70,7 +76,7 @@ class ChannelDownloader(Downloader, ABC):
for video_id, source_id, missing_video in missing_videos:
url = video_url_resolver(domain, missing_video)
# Schedule any missing videos for download.
self.manager.create_download(url, session, skip_download=True)
self.manager.get_or_create_download(url, session)
if PYTEST:
self.manager.do_downloads_sync()
@ -85,8 +91,8 @@ class VideoDownloader(Downloader, ABC):
Download a single video. Store the video in it's channel's directory, otherwise store it in `videos/NO CHANNEL`.
"""
@staticmethod
def valid_url(url) -> bool:
@classmethod
def valid_url(cls, url) -> bool:
"""
Match against all Youtube-DL Info Extractors, except those that match a Channel.
"""
@ -101,6 +107,7 @@ class VideoDownloader(Downloader, ABC):
except DownloadError:
logger.debug(f'Video downloader extract_info failed for {url}')
return False
logger.debug(f'{cls.__name__} not suitable for {url}')
return False
def do_download(self, download: Download):
@ -440,4 +447,4 @@ def _skip_download(error):
def get_channel_source_id(url: str) -> str:
channel_info = YDL.extract_info(url, download=False, process=False)
return channel_info['id']
return channel_info.get('uploader_id') or channel_info['id']

View file

@ -119,8 +119,8 @@ class Downloader:
download_manager.register_downloader(self)
@staticmethod
def valid_url(url) -> bool:
@classmethod
def valid_url(cls, url) -> bool:
raise NotImplementedError()
def do_download(self, download: Download):