Skip to content

Commit 5332ba1

Browse files
committed
Merge branch 'master' into reports
2 parents 92a6074 + b6ecad8 commit 5332ba1

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

41 files changed

+1868
-783
lines changed

.travis.yml

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
language: python
2+
3+
python:
4+
- 3.6
5+
6+
dist: xenial
7+
sudo: false
8+
9+
cache: pip
10+
11+
install:
12+
- pip install --upgrade pycodestyle
13+
14+
script:
15+
- pycodestyle nyaa/ --show-source --max-line-length=100
16+
17+
notifications:
18+
email: false

README.md

+15-19
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,6 @@
11
# NyaaV2
22

3-
## Setup:
4-
5-
- Create your virtualenv, for example with `pyvenv venv`
6-
- Enter your virtualenv with `source venv/bin/activate`
7-
- Install dependencies with `pip install -r requirements.txt`
8-
- Run `python db_create.py` to create the database
9-
- Start the dev server with `python run.py`
10-
11-
## Updated Setup (python 3.6.1):
3+
## Setup
124

135
- Install dependencies https://github.com/pyenv/pyenv/wiki/Common-build-problems
146
- Install `pyenv` https://github.com/pyenv/pyenv/blob/master/README.md#installation
@@ -20,7 +12,7 @@
2012
- Copy `config.example.py` into `config.py`
2113
- Change TABLE_PREFIX to `nyaa_` or `sukebei_` depending on the site
2214

23-
## Setting up MySQL/MariaDB database for advanced functionality
15+
### Setting up MySQL/MariaDB database for advanced functionality
2416
- Enable `USE_MYSQL` flag in config.py
2517
- Install latest mariadb by following instructions here https://downloads.mariadb.org/mariadb/repositories/
2618
- Tested versions: `mysql Ver 15.1 Distrib 10.0.30-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2`
@@ -35,52 +27,56 @@
3527
- `CREATE DATABASE nyaav2 DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;`
3628
- `SOURCE ~/path/to/database/nyaa_maria_vx.sql`
3729

38-
## Finishing up
30+
### Finishing up
3931
- Run `python db_create.py` to create the database
4032
- Load the .sql file
4133
- `mysql -u user -p nyaav2`
4234
- `SOURCE cocks.sql`
4335
- Remember to change the default user password to an empty string to disable logging in
4436
- Start the dev server with `python run.py`
45-
- Deactivate `source deactivate`
37+
- When you are finished developing, deactivate your virtualenv with `source deactivate`
4638

47-
# Enabling ElasticSearch
39+
## Enabling ElasticSearch
4840

49-
## Basics
41+
### Basics
5042
- Install jdk `sudo apt-get install openjdk-8-jdk`
5143
- Install elasticsearch https://www.elastic.co/guide/en/elasticsearch/reference/current/deb.html
5244
- `sudo systemctl enable elasticsearch.service`
5345
- `sudo systemctl start elasticsearch.service`
5446
- Run `curl -XGET 'localhost:9200'` and make sure ES is running
5547
- Optional: install Kabana as a search frontend for ES
5648

57-
## Enable MySQL Binlogging
49+
### Enable MySQL Binlogging
5850
- Add the `[mariadb]` bin-log section to my.cnf and reload mysql server
5951
- Connect to mysql
6052
- `SHOW VARIABLES LIKE 'binlog_format';`
6153
- Make sure it shows ROW
6254
- Connect to root user
6355
- `GRANT REPLICATION SLAVE ON *.* TO 'test'@'localhost';` where test is the user you will be running `sync_es.py` with
6456

65-
## Setting up ES
57+
### Setting up ES
6658
- Run `./create_es.sh` and this creates two indicies: `nyaa` and `sukebei`
6759
- The output should show `acknowledged: true` twice
6860
- The safest bet is to disable the webapp here to ensure there's no database writes
6961
- Run `python import_to_es.py` with `SITE_FLAVOR` set to `nyaa`
7062
- Run `python import_to_es.py` with `SITE_FLAVOR` set to `sukebei`
7163
- These will take some time to run as it's indexing
7264

73-
## Setting up sync_es.py
65+
### Setting up sync_es.py
7466
- Sync_es.py keeps the ElasticSearch index updated by reading the BinLog
7567
- Configure the MySQL options with the user where you granted the REPLICATION permissions
7668
- Connect to MySQL, run `SHOW MASTER STATUS;`.
7769
- Copy the output to `/var/lib/sync_es_position.json` with the contents `{"log_file": "FILE", "log_pos": POSITION}` and replace FILENAME with File (something like master1-bin.000002) in the SQL output and POSITION (something like 892528513) with Position
7870
- Set up `sync_es.py` as a service and run it, preferably as the system/root
7971
- Make sure `sync_es.py` runs within venv with the right dependencies
8072

81-
## Good to go!
82-
- After that, enable the `USE_ELASTIC_SEARCH` flag and restart the webapp and you're good to go
73+
Enable the `USE_ELASTIC_SEARCH` flag in `config.py`, restart the application, and you're good to go.
8374

75+
## Database migrations
76+
- Uses [flask-Migrate](https://flask-migrate.readthedocs.io/)
77+
- Run `./db_migrate.py db migrate` to generate the migration script after database model changes.
78+
- Take a look at the result in `migrations/versions/...` to make sure nothing went wrong.
79+
- Run `./db_migrate.py db upgrade` to upgrade your database.
8480

8581
## Code Quality:
8682
- Remember to follow PEP8 style guidelines and run `./lint.sh` before committing.

config.example.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
1313
if USE_MYSQL:
14-
SQLALCHEMY_DATABASE_URI = ('mysql://test:test123@localhost/nyaav2')
14+
SQLALCHEMY_DATABASE_URI = ('mysql://test:test123@localhost/nyaav2?charset=utf8mb4')
1515
else:
1616
SQLALCHEMY_DATABASE_URI = (
1717
'sqlite:///' + os.path.join(BASE_DIR, 'test.db') + '?check_same_thread=False')

db_create.py

-6
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,3 @@
3333
db.session.add(main_cat)
3434

3535
db.session.commit()
36-
37-
# Create fulltext index
38-
39-
if app.config['USE_MYSQL']:
40-
db.engine.execute('ALTER TABLE ' + app.config['TABLE_PREFIX'] + 'torrents ADD FULLTEXT KEY (display_name)')
41-

db_migrate.py

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
#!/usr/bin/python3
2+
# -*- coding: utf-8 -*-
3+
from nyaa import app, db
4+
from flask_script import Manager
5+
from flask_migrate import Migrate, MigrateCommand
6+
7+
migrate = Migrate(app, db)
8+
9+
manager = Manager(app)
10+
manager.add_command("db", MigrateCommand)
11+
12+
if __name__ == "__main__":
13+
manager.run()

es_mapping.yml

+6-1
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,19 @@ settings:
2121
- resolution
2222
- lowercase
2323
- my_ngram
24+
- word_delimit
2425
filter:
2526
my_ngram:
2627
type: edgeNGram
2728
min_gram: 1
2829
max_gram: 15
2930
resolution:
3031
type: pattern_capture
31-
patterns: ["(\\d+)x(\\d+)"]
32+
patterns: ["(\\d+)[xX](\\d+)"]
33+
word_delimit:
34+
type: word_delimiter
35+
preserve_original: true
36+
split_on_numerics: false
3237
char_filter:
3338
my_char_filter:
3439
type: mapping

migrations/README

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Generic single-database configuration.

migrations/alembic.ini

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# A generic, single database configuration.
2+
3+
[alembic]
4+
# template used to generate migration files
5+
# file_template = %%(rev)s_%%(slug)s
6+
7+
# set to 'true' to run the environment during
8+
# the 'revision' command, regardless of autogenerate
9+
# revision_environment = false
10+
11+
12+
# Logging configuration
13+
[loggers]
14+
keys = root,sqlalchemy,alembic
15+
16+
[handlers]
17+
keys = console
18+
19+
[formatters]
20+
keys = generic
21+
22+
[logger_root]
23+
level = WARN
24+
handlers = console
25+
qualname =
26+
27+
[logger_sqlalchemy]
28+
level = WARN
29+
handlers =
30+
qualname = sqlalchemy.engine
31+
32+
[logger_alembic]
33+
level = INFO
34+
handlers =
35+
qualname = alembic
36+
37+
[handler_console]
38+
class = StreamHandler
39+
args = (sys.stderr,)
40+
level = NOTSET
41+
formatter = generic
42+
43+
[formatter_generic]
44+
format = %(levelname)-5.5s [%(name)s] %(message)s
45+
datefmt = %H:%M:%S

migrations/env.py

+87
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
from __future__ import with_statement
2+
from alembic import context
3+
from sqlalchemy import engine_from_config, pool
4+
from logging.config import fileConfig
5+
import logging
6+
7+
# this is the Alembic Config object, which provides
8+
# access to the values within the .ini file in use.
9+
config = context.config
10+
11+
# Interpret the config file for Python logging.
12+
# This line sets up loggers basically.
13+
fileConfig(config.config_file_name)
14+
logger = logging.getLogger('alembic.env')
15+
16+
# add your model's MetaData object here
17+
# for 'autogenerate' support
18+
# from myapp import mymodel
19+
# target_metadata = mymodel.Base.metadata
20+
from flask import current_app
21+
config.set_main_option('sqlalchemy.url',
22+
current_app.config.get('SQLALCHEMY_DATABASE_URI'))
23+
target_metadata = current_app.extensions['migrate'].db.metadata
24+
25+
# other values from the config, defined by the needs of env.py,
26+
# can be acquired:
27+
# my_important_option = config.get_main_option("my_important_option")
28+
# ... etc.
29+
30+
31+
def run_migrations_offline():
32+
"""Run migrations in 'offline' mode.
33+
34+
This configures the context with just a URL
35+
and not an Engine, though an Engine is acceptable
36+
here as well. By skipping the Engine creation
37+
we don't even need a DBAPI to be available.
38+
39+
Calls to context.execute() here emit the given string to the
40+
script output.
41+
42+
"""
43+
url = config.get_main_option("sqlalchemy.url")
44+
context.configure(url=url)
45+
46+
with context.begin_transaction():
47+
context.run_migrations()
48+
49+
50+
def run_migrations_online():
51+
"""Run migrations in 'online' mode.
52+
53+
In this scenario we need to create an Engine
54+
and associate a connection with the context.
55+
56+
"""
57+
58+
# this callback is used to prevent an auto-migration from being generated
59+
# when there are no changes to the schema
60+
# reference: http://alembic.readthedocs.org/en/latest/cookbook.html
61+
def process_revision_directives(context, revision, directives):
62+
if getattr(config.cmd_opts, 'autogenerate', False):
63+
script = directives[0]
64+
if script.upgrade_ops.is_empty():
65+
directives[:] = []
66+
logger.info('No changes in schema detected.')
67+
68+
engine = engine_from_config(config.get_section(config.config_ini_section),
69+
prefix='sqlalchemy.',
70+
poolclass=pool.NullPool)
71+
72+
connection = engine.connect()
73+
context.configure(connection=connection,
74+
target_metadata=target_metadata,
75+
process_revision_directives=process_revision_directives,
76+
**current_app.extensions['migrate'].configure_args)
77+
78+
try:
79+
with context.begin_transaction():
80+
context.run_migrations()
81+
finally:
82+
connection.close()
83+
84+
if context.is_offline_mode():
85+
run_migrations_offline()
86+
else:
87+
run_migrations_online()

migrations/script.py.mako

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
"""${message}
2+
3+
Revision ID: ${up_revision}
4+
Revises: ${down_revision | comma,n}
5+
Create Date: ${create_date}
6+
7+
"""
8+
from alembic import op
9+
import sqlalchemy as sa
10+
${imports if imports else ""}
11+
12+
# revision identifiers, used by Alembic.
13+
revision = ${repr(up_revision)}
14+
down_revision = ${repr(down_revision)}
15+
branch_labels = ${repr(branch_labels)}
16+
depends_on = ${repr(depends_on)}
17+
18+
19+
def upgrade():
20+
${upgrades if upgrades else "pass"}
21+
22+
23+
def downgrade():
24+
${downgrades if downgrades else "pass"}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
"""Add uploader_ip column to torrents table.
2+
3+
Revision ID: 3001f79b7722
4+
Revises:
5+
Create Date: 2017-05-21 18:01:35.472717
6+
7+
"""
8+
from alembic import op
9+
import sqlalchemy as sa
10+
11+
12+
# revision identifiers, used by Alembic.
13+
revision = '3001f79b7722'
14+
down_revision = None
15+
branch_labels = None
16+
depends_on = None
17+
18+
19+
def upgrade():
20+
# ### commands auto generated by Alembic - please adjust! ###
21+
op.add_column('nyaa_torrents', sa.Column('uploader_ip', sa.Binary(), nullable=True))
22+
op.add_column('sukebei_torrents', sa.Column('uploader_ip', sa.Binary(), nullable=True))
23+
# ### end Alembic commands ###
24+
25+
26+
def downgrade():
27+
# ### commands auto generated by Alembic - please adjust! ###
28+
op.drop_column('nyaa_torrents', 'uploader_ip')
29+
op.drop_column('sukebei_torrents', 'uploader_ip')
30+
# ### end Alembic commands ###

0 commit comments

Comments
 (0)