Giter Site home page Giter Site logo

sopds's Introduction

SimpleOPDS Catalog

Author: Dmitry V.Shelepnev

Version 0.47-devel

Инструкция на русском языке: README_RUS.md

1. Simple installation of SimpleOPDS (by using sqlite3 database)

1.1 Installing the project You can download the archive with the project from www.sopds.ru, or from github.com with the following command:

git clone https://github.com/mitshel/sopds.git

1.2 Dependencies.

  • Requires Python at least version 3.4
  • Django 1.10
  • Pillow 2.9.0
  • apscheduler 3.3.0
  • django-picklefield
  • lxml
  • python-telegram-bot 10

The following dependencies should be established for the project:

yum install python3                            # setup command for RHEL, Fedora, CentOS
python3 -m pip install -r requirements.txt

1.3 We initialize the database and fill in the initial data (genres)

python3 manage.py migrate
python3 manage.py sopds_util clear

1.4 Creating a Superuser

python3 manage.py createsuperuser

1.5 We adjust the path to your catalog with books and, if necessary, switch the interface language to English

python3 manage.py sopds_util setconf SOPDS_ROOT_LIB 'Path to the directory with books'
python3 manage.py sopds_util setconf SOPDS_LANGUAGE en-EN

1.6 Launch the SCANNER server (optional, required for automated periodic re-scanning of the collection) Please note that the default settings specify a periodic scan start 2 times a day 12:00 and 0:00.

python3 manage.py sopds_scanner start --daemon

1.7 Starting the built-in HTTP / OPDS server

python3 manage.py sopds_server start --daemon

However, the best way is still to configure the HTTP / OPDS servers as Apache or Nginx (entry point ./sopds/wsgi.py)

1.8 In order not to wait for the start of a scheduled scan, you can tell the sopds_scanner process about the need immediate scanning. You can do this by setting the configuration parameter SOPDS_SCAN_START_DIRECTLY = True two ways:

a) from the console using the command

python3 manage.py sopds_util setconf SOPDS_SCAN_START_DIRECTLY True

b) With the help of the Web-interface administration page http://:8001/admin/ (FCONSTANCE -> Settings -> 1. General Options -> SOPDS_SCAN_START_DIRECTLY)

1.9 Access to information If all previous steps were successful, then the library can be accessed by the following URLs:

OPDS-version: http://<Your server>:8001/opds/
HTTP-version: http://<Your server>:8001/

It should be taken into account that by default the project uses a simple sqlite3 database, which is one-user. Therefore, until the scanning process is completed, the attempts to access the server may result in an error "A server error occurred." Please contact the administrator. " To eliminate this problem, you need to use multi-user databases, for example MYSQL.

1.10 If necessary, configure and run Telegram-bot

The process of creating bots in telegrams is very simple, to create your bot in Telegram, you need to connect to channel [@BotFather] (https://telegram.me/botfather) and give the command to create a new bot /newbot. Then enter the name of the bot (for example: myopds), and then the user name for this bot, which necessarily ends with "bot" (for example: myopds_bot). As a result, you will be given API_TOKEN, which you need to use in the following commands that will start your personal telegram-bot, which will allow you, using the Telegram instant messenger to get quick access to your personal library.

python3 manage.py sopds_util setconf SOPDS_TELEBOT_API_TOKEN "<Telegram API Token>"
python3 manage.py sopds_util setconf SOPDS_TELEBOT_AUTH False
python3 manage.py sopds_telebot start --daemon

Team,

python3 manage.py sopds_util setconf SOPDS_TELEBOT_AUTH True

you can limit the use of your bot by Telegram users. In this case, your bot will serve only those users whose name in the telegram matches the existing user name in your Simple OPDS database.

2. Configuring the MySQL database (optional, but very desirable for increasing performance).

2.1 To work with a large number of books, it is highly advisable not to use sqlite, but to configure MySQL databases to work. MySQL is much faster than sqlite. In addition, SQLite is a single-user database, i.e. during scanning access to a DB it will be impossible.

To work with the Mysql database on different systems, you may need to install additional packages:

UBUNTU: sudo apt-get install python3-mysqldb
CENTOS-7: pip3 install mysqlclient

Next, you must first create a database "sopds" and a user with the necessary rights in the MySQL database, for example, as follows:

mysql -uroot -proot_pass mysql
mysql> create database if not exists sopds default charset = utf8;
mysql> grant all on sopds. * to 'sopds' @ 'localhost' identified by 'sopds';
mysql> commit;
mysql> ^ C

2.2 Then, in the configuration file, you need to comment out the connection strings to the sqlite database and uncomment the connection string to the Mysql database:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'sopds',
        'HOST': 'localhost',
        'USER': 'sopds',
        'PASSWORD' : 'sopds',
        'OPTIONS' : {
            'init_command': "SET default_storage_engine=MyISAM;\
                             SET sql_mode='';"
        }
    }
}


# DATABASES = {
#    'default': {
#        'ENGINE': 'django.db.backends.sqlite3',
#        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
#    }
#}

2.4 Using InnoDB instead of MyISAM. The above MySQL configuration uses MyISAM as the database engine, which works on most versions of MySQL or MariaDB. However, if you use a relatively new version of Mysql (MariaDB> = 10.2.2, Mysql> = 5.7.9), then you can use the more modern InnoDB engine. It is somewhat faster and supports transactions, which will positively affect the integrity of the database. (On older versions of MySQL, there are problems with it because of restrictions on the maximum length of indexes.) Thus, if you have a modern version of MySQL (MariaDB> = 10.2.2, Mysql> = 5.7.9), then in the Mysql database settings, simply use the following instead of the above OPTIONS parameters:

'OPTIONS' : {
    'init_command': """SET default_storage_engine=INNODB; \
                       SET sql_mode='STRICT_TRANS_TABLES'; \
                       SET NAMES UTF8 COLLATE utf8_general_ci; \
                       SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED
                    """
}

2.5 Further it is necessary to re-execute points 1.3 - 1.8 of this instruction in order to initialize and fill the newly created database However, if you have already started the HTTP/OPDS server and the SCANNER server, you must first stop them:

python3 manage.py sopds_server stop
python3 manage.py sopds_scanner stop

3. Configuring the PostgreSQL database (optional, a good option for using the SimpleOPDS program).

3.1 PostgreSQL is a good way to use SimpleOPDS. To use PostgreSQL, it is necessary to install this database and configure it (for a detailed description, see the Internet, for example: http://alexxkn.ru/node/42 or here: http://www.fight.org.ua/database/ install_posqgresql_ubuntu.html):

UBUNTU:
	sudo apt-get install postgresql postgresql-client postgresql-contrib libpq-dev
	sudo vi /etc/postgresql/9.5/main/pg_hba.conf
	sudo /etc/init.d/postgresql restart

CENTOS:
  yum install postgresql postgresql-server
   /usr/bin/postgresql-setup initdb
  vi /var/lib/pgsql/data/pg_hba.conf
  systemctl enable postgresql
  systemctl start postgresql

editing the hba.conf file, you need to fix the following lines:

- local   all             all                                     peer
- host    all             all             127.0.0.1/32            ident
+ local   all             all                                     md5
+ host    all             all             127.0.0.1/32            md5

To work with the PostgreSQL database, you probably need to install an additional package of psycopg2:

pip3 install psycopg2

Next, you must first create a database "sopds" and a user with the necessary rights in the PostgreSQL database, for example, as follows:

psql -U postgres
 Password for user postgres: *****
 postgres=# create role sopds with password 'sopds' login;
 postgres=# create database sopds with owner sopds;
 postgres=# \q

3.2 Next in the configuration file, you need to comment out the connection strings to the sqlite database and decompress it accordingly the connection string to the PostgreSQL database:

 DATABASES = {
    'default': {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'sopds',
    'USER': 'sopds',
    'PASSWORD': 'sopds',
    'HOST': '', # Set to empty string for localhost.
    'PORT': '', # Set to empty string for default.
    }
 }


 # DATABASES = {
 #    'default': {
 #        'ENGINE': 'django.db.backends.sqlite3',
 #        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
 #    }
 #}

3.4 Next, it is necessary to re-execute points 1.3 - 1.8 of this instruction in order to initialize and fill the newly created database However, if you have already started the HTTP/OPDS server and the SCANNER server, you must first stop them:

 python3 manage.py sopds_server stop
 python3 manage.py sopds_scanner stop

4. Setting the conversion of fb2 to EPUB or MOBI (optionally, you can not configure it)

4.1 fb2-to-epub converter http://code.google.com/p/fb2-to-epub-converter/

  • First you need to download the latest version of the fb2toepub converter from the link above (the current one is already in the project) unfortunately the converter is not perfect and not all books can be converted, but most still converted
  • Further, you need to copy the archive to the folder ./convert/fb2toepub and unzip
  • Next, we compile the project with the make command, as a result, the executable file fb2toepub appears in the unix_dist folder
  • Use the web interface of the administrator or the following console commands to specify the path to this converter:
python3 manage.py sopds_util setconf SOPDS_FB2TOEPUB "convert/fb2toepub/unix_dist/fb2toepub"
  • As a result, the OPDS client will be provided with links to the FB2-book in the epub format

4.2 fb2epub converter http://code.google.com/p/epub-tools/ (the converter is written in Java, so at least JDK 1.5 should be installed on your system)

  • also first download the latest version from the link above (the current one is already in the project)
  • copy the jar-file to the directory ./convert/fb2epub (There is already a shell script to run the jar-file)
  • Set the path to the shell script fb2epub (or fb2epub.cmd for Windows) using the web administrator interface or the following console commands:
python3 manage.py sopds_util setconf SOPDS_FB2TOEPUB "convert/fb2epub/fb2epub"

4.3 Converter fb2conv (converting to epub and mobi)
http://www.the-ebook.org/forum/viewtopic.php?t=28447
https://github.com/rupor-github/fb2mobi/releases

  • It is necessary to install python 2.7 (however, for the latest version with GitHub, you do not need to do this, since it uses the same as SOPDS python3) and the packages lxml, cssutils:

       yum install python
       yum install python-lxml
       yum install python-cssutils
    
  • download the latest version of the converter from the link above (the current one is already in the fb2conv directory of the project)

  • download the KindleGen utility from the Amazon website http://www.amazon.com/gp/feature.html?ie=UTF8&docId=1000234621 (the current version of the utility is already in the fb2conv directory of the project)

  • copy the project archive to ./convert/fb2conv (There are already shell scripts for starting the converter) and unzip it

  • To convert to MOBI you need to archive the KindleGen utility in the directory with the converter and unzip it

  • Use the web-based administrator interface or the following console commands to specify paths to the corresponding scripts:

python3 manage.py sopds_util setconf SOPDS_FB2TOEPUB "convert/fb2conv/fb2epub"
python3 manage.py sopds_util setconf SOPDS_FB2TOMOBI "convert/fb2conv/fb2mobi"

5. Console commands Simple OPDS

Show information about the book collection:

python3 manage.py sopds_util info

Clear the database with a collection of books, download the genre directory:

python3 manage.py sopds_util clear [--verbose]

Keep your genre directory in the file opds_catalog / fixtures / mygenres.json:

python3 manage.py sopds_util save_mygenres

Download your genre directory from the opds_catalog/fixtures/mygenres.json file:

python3 manage.py sopds_util load_mygenres

Only when using PostgerSQL. Optimization of the table opds_catalog_book (fillfactor = 50). After that, scanning is much faster:

python3 manage.py sopds_util pg_optimize

View all configuration options:

python3 manage.py sopds_util getconf

View the value of a specific configuration parameter:

python3 manage.py sopds_util getconf SOPDS_ROOT_LIB

Set the value of a specific configuration parameter:

python3 manage.py sopds_util setconf SOPDS_ROOT_LIB '\home\files\books'

Start a one-time scan of the book collection:

python3 manage.py sopds_scanner scan [--verbose] [--daemon]

Run the scan of the collection of books on a schedule:

python3 manage.py sopds_scanner start [--verbose] [--daemon]

Run the embedded web server:

python3 manage.py sopds_server start [--host <IP address>] [--port <port N>] [--daemon]

6. Options of the cataloger Simple OPDS (www.sopds.ru)

The Simple OPDS cataloger has additional settings that can be changed using the admin interface http:///admin/

SOPDS_LANGUAGE - change the interface language.

SOPDS_ROOT_LIB - contains the path to the directory where your book collection is located.

SOPDS_BOOK_EXTENSIONS - List of book formats that will be included in the catalog.
(by default SOPDS_BOOK_EXTENSIONS = '.pdf .djvu .fb2 .epub')

SOPDS_DOUBLES_HIDE - Hides found duplicates in book issues.
(by default SOPDS_DOUBLES_HIDE = True)

SOPDS_FB2SAX - The program can extract metadata from FB2 by two parsers

  • FB2sax is the regular parser used in SOPDS from version 0.01, this parser is faster, and retrieves metadata even from invalid FB2 files
  • FB2xpath - appeared in version 0.42, works less often, does not tolerate invalid FB2
    (by default SOPDS_FB2SAX = True)

SOPDS_COVER_SHOW - a way to show skins (False - do not show, True - extract covers on the fly and show).
(by default SOPDS COVER_SHOW = True)

SOPDS_ZIPSCAN - Configures the scanning of ZIP archives.
(by default SOPDS_ZIPSCAN = True)

SOPDS_ZIPCODEPAGE - Specify which encoding for file names is used in ZIP archives. Available encodings: cp437, cp866, cp1251, utf-8. The default encoding is cp437. Since there is no information about the encoding in which the file names are located in the ZIP archive, it is not possible to automatically determine the correct encoding for filenames, so cyrillic encodings should use cp866 encoding in order for Cyrillic file names to not look like croaks.
(default is SOPDS_ZIPCODEPAGE = "cp866")

SOPDS_INPX_ENABLE - If True, if an INPX file is found in the directory, the scanner does not scan its contents with the sub-htag, but loads the data from the found INPX file. The scanner believes that the archives of books themselves are located in the same directory. Those. INPX-file should be located in the folder with the archives of books. However, please note that using data from INPX will result in the absence of annotation in the library. INPX annotations are not present !!!
(by default SOPDS_INPX_ENABLE = True)

SOPDS_INPX_SKIP_UNCHANGED - If True, the scanner skips re-scanning if the size of INPX has not changed.
(by default SOPDS_INPX_SKIP_UNCHANGED = True)

SOPDS_INPX_TEST_ZIP - If True, the scanner tries to find the archive described in the INPX. If an archive is not found, the scanner will not add the data from INPX connected to it to the database, if SOPDS_INPX_TEST_ZIP = False, then the scanner does not perform any checks, but simply adds data from INPX to the database. It's much faster.
(by default SOPDS_INPX_TEST_ZIP = False)

SOPDS_INPX_TEST_FILES - If True, the scanner tries to find the specific file with the book described in INPX (already inside the archives). If a file is not found, the scanner will not add this book to the database, if INPX_TEST_FILES = False, then the scanner does not perform any checks, but simply adds a book from INPX to the database. It's much faster.
(by default SOPDS_TEST_FILES = False)

SOPDS_DELETE_LOGICAL - True will result in the fact that if the scanner detects that the book has been deleted, the entry in the database about this book will be deleted logically (avail = 0). If the value is False, then there will be a physical deletion of such records from the database. So far only SOPDS_DELETE_LOGICAL = False.
(by default SOPDS_DELETE_LOGICAL = False)

SOPDS_SPLITITEMS - Sets when the number of elements in the group is reached - the group will "expand". For issuing "By Title", "By Authors", "By Series".
(the default is SOPDS_SPLITITEMS = 300)

SOPDS_MAXITEMS - The number of results to be displayed per page.
(the default is SOPDS_MAXITEMS = 60)

SOPDS_FB2TOEPUB and SOPDS_FB2TOMOBI set the paths to the programs - converters from FB2 to EPUB and MOBI.
(by default SOPDS_FB2TOEPUB = "")
(by default SOPDS_FB2TOMOBI = "")

SOPDS_TEMP_DIR specifies the path to the temporary directory, which is used to copy the original and the conversion result.
(by default SOPDS_TEMP_DIR = os.path.join (BASE_DIR, 'tmp'))

SOPDS_TITLE_AS_FILENAME - If True, when downloading instead of the original file name, the book will produce a transliteration of the title of the book.
(by default SOPDS_TITLE_AS_FILENAME = True)

SOPDS_ALPHABET_MENU - Includes an additional menu for selecting the alphabet.
(by default SOPDS_ALPHABET_MENU = True)

SOPDS_NOCOVER_PATH - A cover file that will be displayed for books without covers.
(by default SOPDS_NOCOVER_PATH = os.path.join (BASE_DIR, 'static/images/nocover.jpg'))

SOPDS_AUTH - Enable BASIC - authorization.
(by default SOPDS_AUTH = True)

SOPDS_SERVER_LOG and SOPDS_SCANNER_LOG specify the location of LOG files of these processes.
(by default SOPDS_SERVER_LOG = os.path.join (BASE_DIR, 'opds_catalog/log/sopds_server.log'))
(by default SOPDS_SCANNER_LOG = os.path.join (BASE_DIR, 'opds_catalog/log/sopds_scanner.log'))

SOPDS_SERVER_PID and SOPDS_SCANNER_PID specify the location of the PID files of these processes during demonization.
(by default SOPDS_SERVER_PID = os.path.join (BASE_DIR, 'opds_catalog/tmp/sopds_server.pid'))
(by default SOPDS_SCANNER_PID = os.path.join (BASE_DIR, 'opds_catalog/tmp/ sopds_scanner.pid'))

Parameters SOPDS_SCAN_SHED_XXX set the values ​​of the template, to periodically scan the collection of books using ** manage.py sopds_scanner start **. Possible values ​​can be found on the following page: # https://apscheduler.readthedocs.io/en/latest/modules/triggers/cron.html#module-apscheduler.triggers.cron
Changes to the following parameters via the Web interface or the command line are checked by the sopds_scanner process every 10 minutes.
In case of detection of changes, sopds_scanner automatically makes the appropriate changes to the scheduler.

(default is SOPDS_SCAN_SHED_MIN = '0')
(the default is SOPDS_SCAN_SHED_HOUR = '0,12')
(default is SOPDS_SCAN_SHED_DAY = '')
(default is SOPDS_SCAN_SHED_DOW = '
')

SOPDS_SCAN_START_DIRECTLY - setting this parameter to True will cause the next check of the sopds_scanner flag (every 10 minutes)
an extraordinary scan of the collection will be launched, and the specified flag will again be reset to False.

SOPDS_CACHE_TIME - Pages cache time (default is SOPDS_CACHE_TIME = 1200)

SOPDS_TELEBOT_API_TOKEN - API TOKEN for Telegram Bot

SOPDS_TELEBOT_AUTH - If True, the Bot will grant access to the library, only to users whose name in the Telegram matches the name existing user in the Simple OPDS database. (by default SOPDS_TELEBOT_AUTH = True)

SOPDS_TELEBOT_MAXITEMS - The maximum number of simultaneously displayed items in the Telegram message (by default SOPDS_TELEBOT_MAXITEMS = 10)

sopds's People

Contributors

blacklion avatar fabrikant avatar mitshel avatar worldexception avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sopds's Issues

pdf cover image

Начинаю тихонько вникать в суть дела. Обложка pdf файла хранится в метафайле документа. Я не нашел метода записать картинку в pdf в виде обложки и пошел по другому пути. Думал вручную записать данные в cover и cover_type в базе. В каком виде там хранятся данные? Я пробовал url забить. Но по ходу это не то

MySQL обновился и такое

(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SET sql_mode='STRICT_TRANS_TABLES';                        SET NAMES UTF8 COL...' at line 1")
Request Method:	GET
Request URL:	http://bla.bla123.ru:4444/web/
Django Version:	2.1.15
Exception Type:	ProgrammingError
Exception Value:	
(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SET sql_mode='STRICT_TRANS_TABLES';                        SET NAMES UTF8 COL...' at line 1")
Exception Location:	/usr/lib/python3.9/site-packages/MySQLdb/connections.py in __init__, line 185
Python Executable:	/usr/bin/python3
Python Version:	3.9.6
Python Path:	
['/opt/sopds',
 '/usr/lib/python39.zip',
 '/usr/lib/python3.9',
 '/usr/lib/python3.9/lib-dynload',
 '/usr/lib/python3.9/site-packages']
Server time:	Tue, 24 Aug 2021 17:13:06 +0300

Совместимость с Django 2.0

OS: Ubuntu 16.04
Сейчас после команды python3 -m pip install -r requirements.txt устанавливается Django 2.0.
При попытке выполнить python3 manage.py migrate вылезает ошибки типа

File "/home/alex/sopds/opds_catalog/models.py", line 59, in Catalog
  parent = models.ForeignKey('self', null=True, db_index=True)
TypeError: __init__() missing 1 required positional argument: 'on_delete'

В Django 2.0 появилось требования указывать on_delete, раньше считалось что он по умолчанию равен cascade.

Я думаю, стоит ограничить версию django в requirements версией 1.9, или поправить файлы на соответствие к django 2.0 )

Спасибо за отличный проект!

При поиске иногда получаем "list index out of range"

Никаких virtualenv.
sopds в sub-uri '/sopds' на nginx. в urls.py внесены соответствующие правки.

Ошибка возникает как через nginx, так и через runserver джанги напрямую, так что nginx исключаем, ошибка чисто питоническая.

При поиске по названию "обход" ищет нормально, при поисковом запросе "обходим" получаем

Environment:

Request Method: GET
Request URL: https://example.com/sopds/web/search/books/?csrfmiddlewaretoken=TOKEN&searchterms=%D0%BE%D0%B1%D1%85%D0%BE%D0%B4%D0%B8%D0%BC&submit=&page=0&searchtype=m

Django Version: 1.10.4
Python Version: 3.4.2
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'opds_catalog',
 'sopds_web_backend']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback:
File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/exception.py" in inner
  39.             response = get_response(request)
File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/base.py" in _legacy_get_response
  249.             response = self._get_response(request)
File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.4/dist-packages/django/contrib/auth/decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)
File "./sopds_web_backend/views.py" in SearchBooksView
  211.                 if books[finish].title==prev_title and {a['id'] for a in books[finish].authors.values()}==prev_authors_set:
File "/usr/local/lib/python3.4/dist-packages/django/db/models/query.py" in __getitem__
  295.         return list(qs)[0]

Exception Type: IndexError at /sopds/web/search/books/
Exception Value: list index out of range

Если sopds в sub-uri, то неверные ссылки на обложку книги и на удаление в модальном окне при удалении книги с книжной полки

Продолжаем чистку хардкода :)

sopds в example.com/sopds.
На книжной полке и вообще везде правильная ссылка на картинку /sopds/opds/cover/NUMBER/, но в модальном окне книжной полки, появляющемся при подтверждении удаления книги с книжной полки, ссылка на обложку /opds/cover/NUMBER/.

Править тут.

Что-то мне подсказывает, что в коде надо править все ссылки, начинающиеся с /...

Некорректное сканирование inpx

В коде формат inp-файлов inpx-каталого жёстко задан, а ведь он может задаваться в structure.info, лежащем в inpx-каталоге. Раз.
Два. Книги могут (внезапно) лежать не в inp-файлах-архивах внутри каталога, а в сторонней директории (zip), которая указывается в соответствующей строке inp-файла. Два.

Счас я попробую это сделать. Изменить inpx_parser.py

Ошибка скачивания в FBReader

При попытке скачивания книги из OPDS в FBReader под андроид выдает 404 ошибку.
В логах
GET /opds/convert/3156/epub/ HTTP/1.1" 404 866 "-" "FBReader/3.0.29 (Android 8.1.0, vince, Redmi 5 Plus)
Сама книга в fb2, зачем пытаться конвертировать в epub?

Актуальная версия

На сайте программы указано, что последняя версия 0.47 от 27.02.2019
В информации git указано, что 'Latest commit 2a25702 on 7 Apr 2018'

Где можно взять версию 0.47

Can not create database with MySQL 5.6.37 and InnoDB

I'm migrating from very old version (0.23) to latest one and re-create mysql database.

[opds@onlyone ~/sopds]$ python3 manage.py migrate
Operations to perform:
  Synchronize unmigrated apps: constance, staticfiles, messages
  Apply all migrations: sessions, contenttypes, admin, database, auth, opds_catalog
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying database.0001_initial... OK
  Applying opds_catalog.0001_initial...Traceback (most recent call last):
  File "/usr/local/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python3.4/site-packages/django/db/backends/mysql/base.py", line 124, in execute
    return self.cursor.execute(query, args)
  File "/usr/local/lib/python3.4/site-packages/MySQLdb/cursors.py", line 250, in execute
    self.errorhandler(self, exc, value)
  File "/usr/local/lib/python3.4/site-packages/MySQLdb/connections.py", line 42, in defaulterrorhandler
    raise errorvalue
  File "/usr/local/lib/python3.4/site-packages/MySQLdb/cursors.py", line 247, in execute
    res = self._query(query)
  File "/usr/local/lib/python3.4/site-packages/MySQLdb/cursors.py", line 411, in _query
    rowcount = self._do_query(q)
  File "/usr/local/lib/python3.4/site-packages/MySQLdb/cursors.py", line 374, in _do_query
    db.query(q)
  File "/usr/local/lib/python3.4/site-packages/MySQLdb/connections.py", line 277, in query
    _mysql.connection.query(self, query)
_mysql_exceptions.OperationalError: (1071, 'Specified key was too long; max key length is 767 bytes')

getcounter function need update

Сделать так, чтобы при не инициализированном Counter возвращалось не 0-значение а не runtime-error

English version

Hi,

Is it possible to have an english version of the README because I'm French and I don't understand anything in cyrillic :) ?

Thanks

python-telegram-bot

Система не работает с python-telegram-bot версии 13
Заработало после корректировки 'requirements.txt'
прописал 'python-telegram-bot>=10,<13'

Запуск в Docker

Пытаюсь оформить в контейнер код из master, но похоже что #36 не вмержен,
не могу пробросить параметры авторизации

    SOPDS_USER='admin' \
    SOPDS_PASSWORD='admin' \

и может быть есть какая-нибудь опция, чтобы имя книги всегда бралось от имени файла (без учёта расширения), а не из метаданных?

Странная работа opds

День добрый, началось все с проблемы в читалке kyBook
добавив свой сервер на котором развернут opds)
ничего не предвещало беды, но как только я пытаюсь работать с opds из читалки вылезает ряд проблем
например. По Авторам - (Рус) - нажав на любую букву из списка я вылетаю на www.мое_зеркало.pro/web
и читалка пишет мне ошибку
opds каталог вернул неправильный content-type text/html charset=utf-8
раньше был телеграмм бот, и в приницпе особо не парило это, сейчас телеграмм бот не работает.
web версия для читалки на ios это тот еще танец с бубнами.

заметил особенность
если перейти по url вида www.мое_зеркало.pro/opds нас редиректит на ****/web
если перейти по url ****.pro/opds/ мы получаем полноценный xml который кормится читалке на ура.
так вот быть может из за этого и происходит ошибка, т.к. opds каталог перестает отображаться в читалке и я в этот момент вижу стартовую страницу своего sopds сервера.

смущает еще такая история

?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:dcterms="http://purl.org/dc/terms">
<id>http://192.168.10.205/opds/</id><icon>/static/images/favicon.ico</icon>
<link href="http://192.168.10.205/opds/" rel="self" type="application/atom+xml;profile=opds-catalog;kind=navigation"/>
<link href="/opds/" rel="start" type="application/atom+xml;profile=opds-catalog;kind=navigation"/>
<title>SimpleOPDS</title>
<subtitle>SimpleOPDS Catalog by www.sopds.ru. Version 0.46.</subtitle>
<updated>2018-10-19T12:46:50+00:00</updated>
<link href="/opds/search/{searchTerms}/" rel="search" type="application/atom+xml"/>
<entry>
<id>m:1</id>
<title>По каталогам</title>
<link href="http://192.168.10.205/opds/catalogs/" rel="alternate"/>
<link href="/opds/catalogs/" rel="subsection" type="application/atom+xml;profile=opds-catalog;kind=navigation"/>
<updated>2018-10-19T12:46:50+00:00</updated>
<content type="text">Каталогов: 121, книг: 349928.</content>

"http://192.168.10.205/opds/catalogs/"
ip локальной машины а не внешний ip или домен
при попытках запустить sopds_server start --host **** --deamon
сервер не запускается

Поддержка скачивания книг после авторизации

Здравствуйте, уважаемые,

Возможно ли прикрутить к проекту поддержку авторизации и скачивания книг только после успешной авторизации?

Собственно, вопрос возник из желания прикрутить одному из писателей вместо его "персонального сайта" нормальный OPDS каталог для продажи им книг своим читателям.
А то делает все по старинке - с ручной отправкой архивов книги во всех форматах разом.

Благодарю за ответ.

Добавление описания настройки Apache в README(_RUS)

Было бы здорово добавить в README описание запуска SOPDS с помощью Apache веб сервера (в т.ч. с использованием имеющихся SSL сертификатов). Как например существующие инструкции по использованию разных БД.

Ну или если это выходит за рамки проекта, буду очень признателен, если кто-нибудь сможет написать мне инструкцию для выше описанного вопроса.

MySQL Ошибка при Clear book database.

При очистки MySQL БД с помощью команды 'python3 manage.py sopds_util clear'
Выдает ошибку
Traceback (most recent call last):
File "manage.py", line 10, in
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.7/site-packages/django/core/management/init.py", line 381, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.7/site-packages/django/core/management/init.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 353, in execute
output = self.handle(*args, **options)
File "/home/baks/sopds/opds_catalog/management/commands/sopds_util.py", line 30, in handle
self.clear()
File "/home/baks/sopds/opds_catalog/management/commands/sopds_util.py", line 49, in clear
opdsdb.clear_all(self.verbose)
File "/home/baks/sopds/opds_catalog/opdsdb.py", line 59, in clear_all
cursor.execute('delete from opds_catalog_bseries')
File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 100, in execute
return super().execute(sql, params)
File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 83, in _execute
return self.cursor.execute(sql)
File "/usr/local/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 71, in execute
return self.cursor.execute(query, args)
File "/usr/local/lib64/python3.7/site-packages/MySQLdb/cursors.py", line 206, in execute
res = self._query(query)
File "/usr/local/lib64/python3.7/site-packages/MySQLdb/cursors.py", line 312, in _query
db.query(q)
File "/usr/local/lib64/python3.7/site-packages/MySQLdb/connections.py", line 224, in query
_mysql.connection.query(self, query)
KeyboardInterrupt

В конфиге 'settings.py' прописаны настройки БД
...
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'sopds',
'HOST': 'localhost',
'USER': 'sopds',
'PASSWORD' : 'sopds',
'OPTIONS' : {
'init_command': """SET default_storage_engine=INNODB;
SET sql_mode='STRICT_TRANS_TABLES';
SET NAMES UTF8 COLLATE utf8_general_ci;
SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED
"""
}
}
}
...

[feature request]Сортировка в серии

Сейчас при показе книг в серии они отсортированы по алфавиту. Возможно стоит их показывать согласно номеру в серии. Хотя бы в качестве опции. Заранее спасибо.

Ошибка запуска после обновления- Fedora32

Планово провёл обвление с Fedora31 на Fedora32
SOPDS перестал запускаться.
Как я понял - отсутсвует модуль six в django 3.1.0.

Traceback (most recent call last):
File "manage.py", line 10, in
execute_from_command_line(sys.argv)
File "/usr/lib/python3.8/site-packages/django/core/management/init.py", line 401, in execute_from_command_line
utility.execute()
File "/usr/lib/python3.8/site-packages/django/core/management/init.py", line 377, in execute
django.setup()
File "/usr/lib/python3.8/site-packages/django/init.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/lib/python3.8/site-packages/django/apps/registry.py", line 122, in populate
app_config.ready()
File "/usr/lib/python3.8/site-packages/django/contrib/admin/apps.py", line 24, in ready
self.module.autodiscover()
File "/usr/lib/python3.8/site-packages/django/contrib/admin/init.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "/usr/lib/python3.8/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "/usr/lib64/python3.8/importlib/init.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 1014, in _gcd_import
File "", line 991, in _find_and_load
File "", line 975, in _find_and_load_unlocked
File "", line 671, in _load_unlocked
File "", line 783, in exec_module
File "", line 219, in _call_with_frames_removed
File "/var/www/html/sopds/constance/admin.py", line 20, in
from django.utils import six
ImportError: cannot import name 'six' from 'django.utils' (/usr/lib/python3.8/site-packages/django/utils/init.py)

An error when on of the Telegram Bot 'download book' button is pressed

When trying to download a book in the Telegram bot, the bug trace appeared. No download is possible

2022-08-23 16:35:14,457 ERROR An uncaught error was raised while processing the update
Traceback (most recent call last):
File "/home/se/src/me/sopds/.env/lib/python3.8/site-packages/telegram/ext/dispatcher.py", line 279, in process_update
handler.handle_update(update, self)
File "/home/se/src/me/sopds/.env/lib/python3.8/site-packages/telegram/ext/callbackqueryhandler.py", line 143, in handle_update
return self.callback(dispatcher.bot, update, **optional_args)
File "/home/se/src/me/sopds/opds_catalog/management/commands/sopds_telebot.py", line 30, in wrapper
result = func(self, bot, update)
File "/home/se/src/me/sopds/opds_catalog/management/commands/sopds_telebot.py", line 40, in wrapper
return func(self, bot, update)
File "/home/se/src/me/sopds/opds_catalog/management/commands/sopds_telebot.py", line 336, in botCallback
return self.getBookFile(bot, update)
File "/home/se/src/me/sopds/opds_catalog/management/commands/sopds_telebot.py", line 30, in wrapper
result = func(self, bot, update)
File "/home/se/src/me/sopds/opds_catalog/management/commands/sopds_telebot.py", line 40, in wrapper
return func(self, bot, update)
File "/home/se/src/me/sopds/opds_catalog/management/commands/sopds_telebot.py", line 309, in getBookFile
document = dl.getFileDataEpub(book)
File "/home/se/src/me/sopds/opds_catalog/dl.py", line 137, in getFileDataEpub
return getFileDataConv(book,'epub')
File "/home/se/src/me/sopds/opds_catalog/dl.py", line 90, in getFileDataConv
fo = getFileData(book)
File "/home/se/src/me/sopds/opds_catalog/dl.py", line 65, in getFileData
dio.write(fo.read())
AttributeError: 'NoneType' object has no attribute 'read'

Сканирование по расписанию не работает

Sopds на nginx + uWSGI.

manage.py:
-rwxr--r-- 1 www-data www-data 248 Dec 14 11:11 manage.py

sopds/settings.py:

USE_TZ = False
SOPDS_SCAN_SHED_MIN = '/5'
SOPDS_SCAN_SHED_HOUR = '*'
SOPDS_SCAN_SHED_DAY = '*'
SOPDS_SCAN_SHED_DOW = '*'

systemctl uwsgi restart,
страница в браузере обновлена.

Сканирования не происходит ни через 5, ни через 10 минут.

Или сканирование по расписанию из коробки не работает и надо где-то чего-то включить?
Можно, конечно, и кроном дёргать, но раз функционал заявлен в программе, то как добиться сканирования по расписанию?

Связка nginx + uWSGI ни при чем. Запускал сервер standalone, то же самое.
Менял параметры SOPDS_SCAN_SHED_XXX на простые, типа в 13 часов 12 минут - то же самое. Не сканирует в заданное время, независимо от таймзоны (выставлял 2 часовых параметра - местный и GMT).

Inner ZIPs

Dmitry,
thank you for useful application.

I got a trouble with one quite large book collection.
There are books inside ZIP-files inside topmost ZIP-files (2 levels) 😄
As a result SOPDS reports that it scanned, but found no any books.

Would it be possible to add recursive (with some limit of course) books scanning inside inner ZIP-archives?

Am I right in understanding that such function should be modified to find the books recursively?

Thanks beforehand.

Небольшой баг при сканировании inpx

В сканировании inpx-коллекции Либрусека есть маленькая проблема.
Итоговый путь к файлу записывается в виде bla-bla.inpx/bla-bla.inp/blabla.zip
Использую мускуль в режиме innodb
Спасаюсь командами в консоли

sudo mysql -uroot sopds

и в мускуле

update opds_catalog_book set path = substring(path, instr(path,'/') + 1);

Повторить два раза. (отбросить имя inpx и имя inp)

Не находит книги во вложенных zip файлах в архивах либрусека

Архив книг имеет такую структуру

fb2-000065-005477.zip
    - xxxx.zip (Внутри один fb2 файл)
    - xxxx.zip (Внутри один fb2 файл)

Сканер проходит по всем файлам fb2-xxxxxxx-yyyyyyy.zip, но не заглядывает во вложенные zip файлы.

Потом догадался добавить расширение .zip в параметр SOPDS_BOOK_EXTENSIONS (Список расширений файлов, для включения в коллекцию книг по умолчанию содержит: .pdf .djvu .fb2 .epub .mobi)

После чего сканер начал парсить внутренние zip файлы.
Только начал ругаться что у объекта tree нет метода getroot

src/book_tools/format/fb2.py:73

def __detect_namespaces(self, tree):
    if tree.getroot().tag.find(Namespace.FICTION_BOOK21) > 0:
        self.__namespaces['fb'] = Namespace.FICTION_BOOK21
    return None

И действительно в классе FB2Zip в методе __create_tree__ объект tree создается методом etree.fromstring (создает объект класса Element), тогда как в классе FB2 в __create_tree__ объект tree создается методом etree.parse (создает объект класса ElementTree)

Может в классе FB2Zip сделать так чтобы метод __create_tree__ возвращал Element

class FB2(FB2Base):
    def __init__(self, file, original_filename):
        FB2Base.__init__(self, file, original_filename, Mimetype.FB2)

    def __create_tree__(self):
        try:
            self.file.seek(0,0)
            # Было так return etree.parse(self.file)
            return etree.parse(self.file).getroot()
        except Exception as err:
            raise FB2StructureException('the file is not a valid XML (%s)'%err)

    def __exit__(self, kind, value, traceback):
        pass

Тогда __detect_namespaces(self, tree) можно было изменить на такое

def __detect_namespaces(self, tree):
    # Было так if tree.getroot().tag.find(Namespace.FICTION_BOOK21) > 0:
    if tree.tag.find(Namespace.FICTION_BOOK21) > 0:
        self.__namespaces['fb'] = Namespace.FICTION_BOOK21
    return None

invalid byte sequence for encoding "UTF8": 0xd0

hello,
after adding couple of books, got an error listed below:
DataError at /web/book/

invalid byte sequence for encoding "UTF8": 0xd0

Request Method: GET
Request URL: http://localhost:8081/web/book/?lang=0
Django Version: 1.11
Exception Type: DataError
Exception Value:

invalid byte sequence for encoding "UTF8": 0xd0

Exception Location: /usr/lib/python3.5/site-packages/django/db/backends/utils.py in execute, line 65
Python Executable: /usr/bin/python3
Python Version: 3.5.3
Python Path:

['/sopds',
'/usr/lib64/python35.zip',
'/usr/lib64/python3.5',
'/usr/lib64/python3.5/plat-linux',
'/usr/lib64/python3.5/lib-dynload',
'/usr/lib64/python3.5/site-packages',
'/usr/lib/python3.5/site-packages']

Server time: Ср, 19 Апр 2017 22:04:57 +0300

Full error:
http://dpaste.com/1W5AYDT

TelegramDeprecationWarning

Я так понимаю в телеграм боте API поменялось, он больше не запускается (version = '12.8') ,сыплет ошибками TelegramDeprecationWarning
Quit the sopds_telebot with CONTROL-C. /opt/sopds/opds_catalog/management/commands/sopds_telebot.py:348: TelegramDeprecationWarning: R> download_handler = RegexHandler('^/download\d+$',self.downloadBooks) /home/bravo123/.local/lib/python3.8/site-packages/telegram/ext/regexhandler.py:113: TelegramDep> super().__init__(Filters.regex(pattern), /home/bravo123/.local/lib/python3.8/site-packages/telegram/ext/regexhandler.py:113: TelegramDep> super().__init__(Filters.regex(pattern), /home/bravo123/.local/lib/python3.8/site-packages/telegram/ext/regexhandler.py:113: TelegramDep> super().__init__(Filters.regex(pattern), 2020-09-14 09:58:18,390 ERROR Error while getting Updates: Conflict: terminated by other get> 2020-09-14 09:58:18,391 ERROR No error handlers are registered, logging exception. Traceback (most recent call last): File "/home/bravo123/.local/lib/python3.8/site-packages/telegram/ext/updater.py", line 379, i> if not action_cb(): File "/home/bravo123/.local/lib/python3.8/site-packages/telegram/ext/updater.py", line 337, i> updates = self.bot.get_updates(self.last_update_id, File "<decorator-gen-31>", line 2, in get_updates File "/home/bravo123/.local/lib/python3.8/site-packages/telegram/bot.py", line 67, in decorat> result = func(*args, **kwargs) File "/home/bravo123/.local/lib/python3.8/site-packages/telegram/bot.py", line 2138, in get_u> result = self._request.post(url, data, timeout=float(read_latency) + float(timeout)) File "/home/bravo123/.local/lib/python3.8/site-packages/telegram/utils/request.py", line 330,> result = self._request_wrapper('POST', url, File "/home/bravo123/.local/lib/python3.8/site-packages/telegram/utils/request.py", line 248,> raise Conflict(message) telegram.error.Conflict: Conflict: terminated by other getUpdates request; make sure that only > 2020-09-14 09:58:24,022 ERROR Error while getting Updates: Conflict: terminated by other get> 2020-09-14 09:58:24,023 ERROR No error handlers are registered, logging exception. Traceback (most recent call last): File "/home/bravo123/.local/lib/python3.8/site-packages/telegram/ext/updater.py", line 379, i> if not action_cb(): File "/home/bravo123/.local/lib/python3.8/site-packages/telegram/ext/updater.py", line 337, i> updates = self.bot.get_updates(self.last_update_id, File "<decorator-gen-31>", line 2, in get_updates File "/home/bravo123/.local/lib/python3.8/site-packages/telegram/bot.py", line 67, in decorat> result = func(*args, **kwargs) .......

сканирование падает на call sp_mark_dbl(1)

sopds-scan.py падает при вызове процедуры sp_mark_dbl()

вывод в консоли

2016-11-06 12:55:42,621 INFO     Starting mark_double proc with DUBLICATES_FIND param = 1
Traceback (most recent call last):
  File "/opt/sopds/py/sopds-scan.py", line 40, in <module>
    scanner.scan_all()
  File "/opt/sopds/py/sopdscan.py", line 102, in scan_all
    self.opdsdb.mark_double(self.cfg.DUBLICATES_FIND)
  File "/opt/sopds/py/sopdsdb.py", line 893, in mark_double
    cursor.execute(sql,data)
  File "/usr/lib/python3.4/site-packages/mysql/connector/cursor.py", line 507, in execute
    self._handle_result(self._connection.cmd_query(stmt))
  File "/usr/lib/python3.4/site-packages/mysql/connector/connection.py", line 722, in cmd_query
    result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
  File "/usr/lib/python3.4/site-packages/mysql/connector/connection.py", line 640, in _handle_result
    raise errors.get_exception(packet)
mysql.connector.errors.DataError: 1406 (22001): Data too long for column 'AUTHORS' at row 56

Опциональное отображение блоков с данными в веб-интерфейсе

Предлагаю сделать опциональными:

  • отображение в футере веб-страниц информации о кол-ве книг, авторов, жанров, серий (одной опцией);
  • дату последней проверки;
  • показ случайной книги.

Также предлагаю сделать настройку, отключающую показ вышеперечисленной информации для незарегистрированных пользователей (в том числе гостей).
Это поможет избежать возможных проблем с правообладателями и прочими любителями поживиться за чужой счет.

Обновление на 0.47

При ручном обновлении до версии 0.47 (обновление файлов из архива), на стартовой странице остаётся версия 0.46.

Ошибки в описании проекта

В ридми указано:

SOPDS_SCAN_SHED_MIN  = '0,12'
SOPDS_SCAN_SHED_HOUR = '0'

Что означает, что сканирование в 0 и 12 минут всей библиотеки (что излишне)
По факту же в конфиге

SOPDS_SCAN_SHED_MIN  = '0'
SOPDS_SCAN_SHED_HOUR = '0,12'

Что означает, что сканирование в 0 и 12 часов всей библиотеки (что логично и правильно).

Для debian 8 jessie для установки pillow потребовалось установить пакет: libjpeg62-turbo-dev (иначе не компилилось)
Для работы с MYSQL так же понадобилось установить не python3-mysqldb (такого пакета в дебиане нет), а python3-mysql.connector
А так же прописать в папке ./sopds/init.py

import pymysql
pymysql.install_as_MySQLdb()

и в директории с sopds написать
pip3 install pymysql

Поддержка скачивания книги в формате html в web каталоге (web-читалка)

Прошу рассмотреть возможность наряду с epub и mobi добавить еще скачивание книги в html для web-интерфейса.
fb2conv напрямую этого делать не умеет, но генерирует html в процессе создания epub.
Может этим можно воспользоваться?

incompatible with sql_mode=only_full_group_by

Словил ошибку:
AH01215: mysql.connector.errors.ProgrammingError: 1055 (42000): Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'sopds.authors.last_name' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

mysql-server=5.7.13-0ubuntu0.16.04.2

Лечится sql_mode=STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION

запуск в docker

Сделал возможным запуск sopds в docker, теперь достаточно пары команд что бы получить готовый сервер.
https://github.com/WorldException/sopds-docker
и
https://hub.docker.com/r/quickes/sopds-docker/

Пришлось подменять settings.py
WorldException@8320cca
Закомитил в master и потом только понял, что надо было сделать отдельную ветку, может решите поправить в своем репозитарии

Сборка пока что нормально работает только с postgres, на mysql возникают проблемы с кодировкой и с размером ключа. Вариант с sqlite не рассматривал, т.к. использую очень большие коллекции.

P.S. Давно пользуюсь этим сервером, он похоже единственный кто понимает большой архив с кучей книг внутри.

LDAP авторизация

Добавьте плззз LDAP авторизация
Вроде модуль в Django модуль вроде есть

Ошибка формирования xml

вот исправление:

--- a/py/sopdstempl.py
+++ b/py/sopdstempl.py
@@ -151,7 +151,7 @@ class opdsTemplate():
 #                                     '<link type="application/atom+xml" rel="alternate" href="%(modulepath)s?id=%(link_id)s%(nl)s"/>'
                                )
        self.document_entry_nav_info=('<content type="text">%(e_nav_info)s</content>')
-       self.document_entry_nav_finish='</entry>>'
+       self.document_entry_nav_finish='</entry>'

        self.document_entry_acq_start='<entry>'
        self.document_entry_acq_link_start=''

Some updates and fixes

Colleagues, if you interested in some fixes - please see the my forkwith small fixes:

  1. Telebot compatible with version 13.5 of the used api
  2. Fix working with extensions in telebot
  3. Fixes in OPDS - authentication is now fully work for me from CoolReader
  4. Cosmetic fix for bookshelf

Appropriate PR

Лог авторизации

Добавьте пожалуйста лог неудачных попыток авторизации, что бы можно было скармливать его fail2ban'у.

Если sopds в sub-uri, то неверная ссылка на поиск в каталоге opds

Пример:

Сайт http://example.com
Sopds развернут в sub-uri sopds (nginx + uWSGI), полный путь http://example.com/sopds.
Путь к каталогу opds будет http://example.com/sopds/opds/

При входе в каталог в отдаваемом xml ссылка на поиск имеет вид
/opds/search/{searchTerms}/ вместо корректной
/sopds/opds/search/{searchTerms}/

Править
opds_catalog/templates/opensearch.html#L6 и
opds_catalog/feeds.py#L148
Ну и в opds_catalog/tests/test_feeds.py при необходимости.

Дополнительные функции

Прошу рассмотреть добавление новых возможностей

Ручное редактирование названия названий. Подборка журналов в pdf формате выглядит не ахти.

Возможность удалять архивы из каталога. Сейчас удаленные архивы продолжают висеть в каталоге.

LANGUAGE_CODE = 'ru-RU'

а нельзя это привести к виду python3 manage.py sopds_util setconf LANGUAGE_CODE 'ru-RU' ?

Если sopds в sub-uri сайта, то ссылка "Настройки" некорректная.

Пример:

Сайт http://example.com
Sopds развернут в sub-uri sopds (nginx + uWSGI), полный путь http://example.com/sopds.

При логине пользователя со статусом персонала ссылка на настройки в Header'е веб-страницы ведёт на http://example.com/admin/ вместо http://example.com/sopds/admin/.

Надо править ссылку в файле sopds_web_backend/templates/sopds_top.html#L21

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.