diff --git a/.gitattributes b/.gitattributes index f4bb7a9f..92739fe9 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,4 +1,4 @@ -updater.py ident export-subst +constants.py ident export-subst /test export-ignore cps/static/css/libs/* linguist-vendored cps/static/js/libs/* linguist-vendored diff --git a/.gitignore b/.gitignore index 09bf3faa..981158fe 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,8 @@ __pycache__/ .Python env/ eggs/ +dist/ +build/ .eggs/ *.egg-info/ .installed.cfg diff --git a/MANIFEST.in b/MANIFEST.in index f4dcc845..b667159c 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,3 +1 @@ -include cps/static/* -include cps/templates/* -include cps/translations/* +graft src/calibreweb diff --git a/readme.md b/README.md similarity index 97% rename from readme.md rename to README.md index 32afff07..3ea98034 100644 --- a/readme.md +++ b/README.md @@ -4,7 +4,7 @@ Calibre-Web is a web app providing a clean interface for browsing, reading and d *This software is a fork of [library](https://github.com/mutschler/calibreserver) and licensed under the GPL v3 License.* -![Main screen](../../wiki/images/main_screen.png) +![Main screen](https://github.com/janeczku/calibre-web/wiki/images/main_screen.png) ## Features @@ -82,4 +82,4 @@ Pre-built Docker images are available in these Docker Hub repositories: # Wiki -For further informations, How To's and FAQ please check the [Wiki](../../wiki) +For further informations, How To's and FAQ please check the [Wiki](https://github.com/janeczku/calibre-web/wiki) diff --git a/cps.py b/cps.py index 055c0ffe..ca7d7230 100755 --- a/cps.py +++ b/cps.py @@ -1,21 +1,68 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -import os +# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web) +# Copyright (C) 2012-2019 OzzieIsaacs +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from __future__ import absolute_import, division, print_function, unicode_literals import sys +import os -base_path = os.path.dirname(os.path.abspath(__file__)) -# Insert local directories into path -sys.path.append(base_path) -sys.path.append(os.path.join(base_path, 'cps')) -sys.path.append(os.path.join(base_path, 'vendor')) -from cps.server import Server +# Insert local directories into path +if sys.version_info < (3, 0): + sys.path.append(os.path.dirname(os.path.abspath(__file__.decode('utf-8')))) + sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__.decode('utf-8'))), 'vendor')) +else: + sys.path.append(os.path.dirname(os.path.abspath(__file__))) + sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'vendor')) -if __name__ == '__main__': - Server.startServer() +from cps import create_app +from cps import web_server +from cps.opds import opds +from cps.web import web +from cps.jinjia import jinjia +from cps.about import about +from cps.shelf import shelf +from cps.admin import admi +from cps.gdrive import gdrive +from cps.editbooks import editbook +try: + from cps.oauth_bb import oauth + oauth_available = True +except ImportError: + oauth_available = False +def main(): + app = create_app() + app.register_blueprint(web) + app.register_blueprint(opds) + app.register_blueprint(jinjia) + app.register_blueprint(about) + app.register_blueprint(shelf) + app.register_blueprint(admi) + app.register_blueprint(gdrive) + app.register_blueprint(editbook) + if oauth_available: + app.register_blueprint(oauth) + success = web_server.start() + sys.exit(0 if success else 1) +if __name__ == '__main__': + main() diff --git a/cps/__init__.py b/cps/__init__.py index faa18be5..5808f8ae 100755 --- a/cps/__init__.py +++ b/cps/__init__.py @@ -1,2 +1,149 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- + +# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web) +# Copyright (C) 2018-2019 OzzieIsaacs, cervinko, jkrehm, bodybybuddha, ok11, +# andy29485, idalin, Kyosfonica, wuqi, Kennyl, lemmsh, +# falgh1, grunjol, csitko, ytils, xybydy, trasba, vrabe, +# ruben-herold, marblepebble, JackED42, SiphonSquirrel, +# apetresc, nanu-c, mutschler +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from __future__ import division, print_function, unicode_literals +import sys +import os +import mimetypes + +from babel import Locale as LC +from babel import negotiate_locale +from babel.core import UnknownLocaleError +from flask import Flask, request, g +from flask_login import LoginManager +from flask_babel import Babel +from flask_principal import Principal + +from . import logger, cache_buster, cli, config_sql, ub +from .reverseproxy import ReverseProxied + + +mimetypes.init() +mimetypes.add_type('application/xhtml+xml', '.xhtml') +mimetypes.add_type('application/epub+zip', '.epub') +mimetypes.add_type('application/fb2+zip', '.fb2') +mimetypes.add_type('application/x-mobipocket-ebook', '.mobi') +mimetypes.add_type('application/x-mobipocket-ebook', '.prc') +mimetypes.add_type('application/vnd.amazon.ebook', '.azw') +mimetypes.add_type('application/x-cbr', '.cbr') +mimetypes.add_type('application/x-cbz', '.cbz') +mimetypes.add_type('application/x-cbt', '.cbt') +mimetypes.add_type('image/vnd.djvu', '.djvu') +mimetypes.add_type('application/mpeg', '.mpeg') +mimetypes.add_type('application/mpeg', '.mp3') +mimetypes.add_type('application/mp4', '.m4a') +mimetypes.add_type('application/mp4', '.m4b') +mimetypes.add_type('application/ogg', '.ogg') +mimetypes.add_type('application/ogg', '.oga') + +app = Flask(__name__) + +lm = LoginManager() +lm.login_view = 'web.login' +lm.anonymous_user = ub.Anonymous + + +ub.init_db(cli.settingspath) +config = config_sql.load_configuration(ub.session) +from . import db, services + +searched_ids = {} + +from .worker import WorkerThread +global_WorkerThread = WorkerThread() + +from .server import WebServer +web_server = WebServer() + +babel = Babel() +_BABEL_TRANSLATIONS = set() + +log = logger.create() + + +def create_app(): + app.wsgi_app = ReverseProxied(app.wsgi_app) + # For python2 convert path to unicode + if sys.version_info < (3, 0): + app.static_folder = app.static_folder.decode('utf-8') + app.root_path = app.root_path.decode('utf-8') + app.instance_path = app.instance_path .decode('utf-8') + + cache_buster.init_cache_busting(app) + + log.info('Starting Calibre Web...') + Principal(app) + lm.init_app(app) + app.secret_key = os.getenv('SECRET_KEY', 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT') + + web_server.init_app(app, config) + db.setup_db(config) + + babel.init_app(app) + _BABEL_TRANSLATIONS.update(str(item) for item in babel.list_translations()) + _BABEL_TRANSLATIONS.add('en') + + if services.ldap: + services.ldap.init_app(app, config) + if services.goodreads: + services.goodreads.connect(config.config_goodreads_api_key, config.config_goodreads_api_secret, config.config_use_goodreads) + + global_WorkerThread.start() + return app + +@babel.localeselector +def negociate_locale(): + # if a user is logged in, use the locale from the user settings + user = getattr(g, 'user', None) + # user = None + if user is not None and hasattr(user, "locale"): + if user.nickname != 'Guest': # if the account is the guest account bypass the config lang settings + return user.locale + + preferred = set() + if request.accept_languages: + for x in request.accept_languages.values(): + try: + preferred.add(str(LC.parse(x.replace('-', '_')))) + except (UnknownLocaleError, ValueError) as e: + log.warning('Could not parse locale "%s": %s', x, e) + # preferred.append('en') + + return negotiate_locale(preferred or ['en'], _BABEL_TRANSLATIONS) + + +def get_locale(): + return request._locale + + +@babel.timezoneselector +def get_timezone(): + user = getattr(g, 'user', None) + if user is not None: + return user.timezone + +from .updater import Updater +updater_thread = Updater() + + +__all__ = ['app'] diff --git a/cps/about.py b/cps/about.py new file mode 100644 index 00000000..42ffe559 --- /dev/null +++ b/cps/about.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web) +# Copyright (C) 2018-2019 OzzieIsaacs, cervinko, jkrehm, bodybybuddha, ok11, +# andy29485, idalin, Kyosfonica, wuqi, Kennyl, lemmsh, +# falgh1, grunjol, csitko, ytils, xybydy, trasba, vrabe, +# ruben-herold, marblepebble, JackED42, SiphonSquirrel, +# apetresc, nanu-c, mutschler +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from __future__ import division, print_function, unicode_literals +import sys +import requests + +from flask import Blueprint +from flask import __version__ as flaskVersion +from flask_babel import gettext as _ +from flask_principal import __version__ as flask_principalVersion +from flask_login import login_required +try: + from flask_login import __version__ as flask_loginVersion +except ImportError: + from flask_login.__about__ import __version__ as flask_loginVersion +from werkzeug import __version__ as werkzeugVersion + +from babel import __version__ as babelVersion +from jinja2 import __version__ as jinja2Version +from pytz import __version__ as pytzVersion +from sqlalchemy import __version__ as sqlalchemyVersion + +from . import db, converter, uploader +from .isoLanguages import __version__ as iso639Version +from .server import VERSION as serverVersion +from .web import render_title_template + + +about = Blueprint('about', __name__) + + +@about.route("/stats") +@login_required +def stats(): + counter = db.session.query(db.Books).count() + authors = db.session.query(db.Authors).count() + categorys = db.session.query(db.Tags).count() + series = db.session.query(db.Series).count() + versions = uploader.get_versions() + versions['Babel'] = 'v' + babelVersion + versions['Sqlalchemy'] = 'v' + sqlalchemyVersion + versions['Werkzeug'] = 'v' + werkzeugVersion + versions['Jinja2'] = 'v' + jinja2Version + versions['Flask'] = 'v' + flaskVersion + versions['Flask Login'] = 'v' + flask_loginVersion + versions['Flask Principal'] = 'v' + flask_principalVersion + versions['Iso 639'] = 'v' + iso639Version + versions['pytz'] = 'v' + pytzVersion + + versions['Requests'] = 'v' + requests.__version__ + versions['pySqlite'] = 'v' + db.session.bind.dialect.dbapi.version + versions['Sqlite'] = 'v' + db.session.bind.dialect.dbapi.sqlite_version + versions.update(converter.versioncheck()) + versions.update(serverVersion) + versions['Python'] = sys.version + return render_title_template('stats.html', bookcounter=counter, authorcounter=authors, versions=versions, + categorycounter=categorys, seriecounter=series, title=_(u"Statistics"), page="stat") diff --git a/cps/admin.py b/cps/admin.py new file mode 100644 index 00000000..69aee9d5 --- /dev/null +++ b/cps/admin.py @@ -0,0 +1,695 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web) +# Copyright (C) 2018-2019 OzzieIsaacs, cervinko, jkrehm, bodybybuddha, ok11, +# andy29485, idalin, Kyosfonica, wuqi, Kennyl, lemmsh, +# falgh1, grunjol, csitko, ytils, xybydy, trasba, vrabe, +# ruben-herold, marblepebble, JackED42, SiphonSquirrel, +# apetresc, nanu-c, mutschler +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from __future__ import division, print_function, unicode_literals +import os +import base64 +import json +import time +from datetime import datetime, timedelta +# try: +# from imp import reload +# except ImportError: +# pass + +from babel import Locale as LC +from babel.dates import format_datetime +from flask import Blueprint, flash, redirect, url_for, abort, request, make_response, send_from_directory +from flask_login import login_required, current_user, logout_user +from flask_babel import gettext as _ +from sqlalchemy import and_ +from sqlalchemy.exc import IntegrityError +from sqlalchemy.sql.expression import func +from werkzeug.security import generate_password_hash + +from . import constants, logger, helper, services +from . import db, ub, web_server, get_locale, config, updater_thread, babel, gdriveutils +from .helper import speaking_language, check_valid_domain, send_test_mail, generate_random_password, send_registration_mail +from .gdriveutils import is_gdrive_ready, gdrive_support +from .web import admin_required, render_title_template, before_request, unconfigured, login_required_if_no_ano + +feature_support = { + 'ldap': bool(services.ldap), + 'goodreads': bool(services.goodreads) + } + +# try: +# import rarfile +# feature_support['rar'] = True +# except ImportError: +# feature_support['rar'] = False + +try: + from .oauth_bb import oauth_check + feature_support['oauth'] = True +except ImportError: + feature_support['oauth'] = False + oauth_check = {} + + +feature_support['gdrive'] = gdrive_support +admi = Blueprint('admin', __name__) +log = logger.create() + + +@admi.route("/admin") +@login_required +def admin_forbidden(): + abort(403) + + +@admi.route("/shutdown") +@login_required +@admin_required +def shutdown(): + task = int(request.args.get("parameter").strip()) + if task in (0, 1): # valid commandos received + # close all database connections + db.dispose() + ub.dispose() + + showtext = {} + if task == 0: + showtext['text'] = _(u'Server restarted, please reload page') + else: + showtext['text'] = _(u'Performing shutdown of server, please close window') + # stop gevent/tornado server + web_server.stop(task == 0) + return json.dumps(showtext) + + if task == 2: + log.warning("reconnecting to calibre database") + db.setup_db(config) + return '{}' + + abort(404) + + +@admi.route("/admin/view") +@login_required +@admin_required +def admin(): + version = updater_thread.get_current_version_info() + if version is False: + commit = _(u'Unknown') + else: + if 'datetime' in version: + commit = version['datetime'] + + tz = timedelta(seconds=time.timezone if (time.localtime().tm_isdst == 0) else time.altzone) + form_date = datetime.strptime(commit[:19], "%Y-%m-%dT%H:%M:%S") + if len(commit) > 19: # check if string has timezone + if commit[19] == '+': + form_date -= timedelta(hours=int(commit[20:22]), minutes=int(commit[23:])) + elif commit[19] == '-': + form_date += timedelta(hours=int(commit[20:22]), minutes=int(commit[23:])) + commit = format_datetime(form_date - tz, format='short', locale=get_locale()) + else: + commit = version['version'] + + allUser = ub.session.query(ub.User).all() + email_settings = config.get_mail_settings() + return render_title_template("admin.html", allUser=allUser, email=email_settings, config=config, commit=commit, + title=_(u"Admin page"), page="admin") + + +@admi.route("/admin/config", methods=["GET", "POST"]) +@login_required +@admin_required +def configuration(): + if request.method == "POST": + return _configuration_update_helper() + return _configuration_result() + + +@admi.route("/admin/viewconfig") +@login_required +@admin_required +def view_configuration(): + readColumn = db.session.query(db.Custom_Columns)\ + .filter(and_(db.Custom_Columns.datatype == 'bool',db.Custom_Columns.mark_for_delete == 0)).all() + return render_title_template("config_view_edit.html", conf=config, readColumns=readColumn, + title=_(u"UI Configuration"), page="uiconfig") + + +@admi.route("/admin/viewconfig", methods=["POST"]) +@login_required +@admin_required +def update_view_configuration(): + reboot_required = False + to_save = request.form.to_dict() + + _config_string = lambda x: config.set_from_dictionary(to_save, x, lambda y: y.strip() if y else y) + _config_int = lambda x: config.set_from_dictionary(to_save, x, int) + + _config_string("config_calibre_web_title") + _config_string("config_columns_to_ignore") + _config_string("config_mature_content_tags") + reboot_required |= _config_string("config_title_regex") + + _config_int("config_read_column") + _config_int("config_theme") + _config_int("config_random_books") + _config_int("config_books_per_page") + _config_int("config_authors_max") + + config.config_default_role = constants.selected_roles(to_save) + config.config_default_role &= ~constants.ROLE_ANONYMOUS + + config.config_default_show = sum(int(k[5:]) for k in to_save if k.startswith('show_')) + if "Show_mature_content" in to_save: + config.config_default_show |= constants.MATURE_CONTENT + + config.save() + flash(_(u"Calibre-Web configuration updated"), category="success") + before_request() + if reboot_required: + db.dispose() + ub.dispose() + web_server.stop(True) + + return view_configuration() + + +@admi.route("/ajax/editdomain", methods=['POST']) +@login_required +@admin_required +def edit_domain(): + # POST /post + # name: 'username', //name of field (column in db) + # pk: 1 //primary key (record id) + # value: 'superuser!' //new value + vals = request.form.to_dict() + answer = ub.session.query(ub.Registration).filter(ub.Registration.id == vals['pk']).first() + # domain_name = request.args.get('domain') + answer.domain = vals['value'].replace('*', '%').replace('?', '_').lower() + ub.session.commit() + return "" + + +@admi.route("/ajax/adddomain", methods=['POST']) +@login_required +@admin_required +def add_domain(): + domain_name = request.form.to_dict()['domainname'].replace('*', '%').replace('?', '_').lower() + check = ub.session.query(ub.Registration).filter(ub.Registration.domain == domain_name).first() + if not check: + new_domain = ub.Registration(domain=domain_name) + ub.session.add(new_domain) + ub.session.commit() + return "" + + +@admi.route("/ajax/deletedomain", methods=['POST']) +@login_required +@admin_required +def delete_domain(): + domain_id = request.form.to_dict()['domainid'].replace('*', '%').replace('?', '_').lower() + ub.session.query(ub.Registration).filter(ub.Registration.id == domain_id).delete() + ub.session.commit() + # If last domain was deleted, add all domains by default + if not ub.session.query(ub.Registration).count(): + new_domain = ub.Registration(domain="%.%") + ub.session.add(new_domain) + ub.session.commit() + return "" + + +@admi.route("/ajax/domainlist") +@login_required +@admin_required +def list_domain(): + answer = ub.session.query(ub.Registration).all() + json_dumps = json.dumps([{"domain": r.domain.replace('%', '*').replace('_', '?'), "id": r.id} for r in answer]) + js = json.dumps(json_dumps.replace('"', "'")).lstrip('"').strip('"') + response = make_response(js.replace("'", '"')) + response.headers["Content-Type"] = "application/json; charset=utf-8" + return response + + +@admi.route("/config", methods=["GET", "POST"]) +@unconfigured +def basic_configuration(): + logout_user() + if request.method == "POST": + return _configuration_update_helper() + return _configuration_result() + + +def _configuration_update_helper(): + reboot_required = False + db_change = False + to_save = request.form.to_dict() + + _config_string = lambda x: config.set_from_dictionary(to_save, x, lambda y: y.strip() if y else y) + _config_int = lambda x: config.set_from_dictionary(to_save, x, int) + _config_checkbox = lambda x: config.set_from_dictionary(to_save, x, lambda y: y == "on", False) + _config_checkbox_int = lambda x: config.set_from_dictionary(to_save, x, lambda y: 1 if (y == "on") else 0, 0) + + db_change |= _config_string("config_calibre_dir") + + # Google drive setup + if not os.path.isfile(gdriveutils.SETTINGS_YAML): + config.config_use_google_drive = False + + gdrive_secrets = {} + gdriveError = gdriveutils.get_error_text(gdrive_secrets) + if "config_use_google_drive" in to_save and not config.config_use_google_drive and not gdriveError: + if not gdrive_secrets: + return _configuration_result('client_secrets.json is not configured for web application') + gdriveutils.update_settings( + gdrive_secrets['client_id'], + gdrive_secrets['client_secret'], + gdrive_secrets['redirect_uris'][0] + ) + + # always show google drive settings, but in case of error deny support + config.config_use_google_drive = (not gdriveError) and ("config_use_google_drive" in to_save) + if _config_string("config_google_drive_folder"): + gdriveutils.deleteDatabaseOnChange() + + reboot_required |= _config_int("config_port") + + reboot_required |= _config_string("config_keyfile") + if config.config_keyfile and not os.path.isfile(config.config_keyfile): + return _configuration_result('Keyfile location is not valid, please enter correct path', gdriveError) + + reboot_required |= _config_string("config_certfile") + if config.config_certfile and not os.path.isfile(config.config_certfile): + return _configuration_result('Certfile location is not valid, please enter correct path', gdriveError) + + _config_checkbox_int("config_uploading") + _config_checkbox_int("config_anonbrowse") + _config_checkbox_int("config_public_reg") + + _config_int("config_ebookconverter") + _config_string("config_calibre") + _config_string("config_converterpath") + + if _config_int("config_login_type"): + reboot_required |= config.config_login_type != constants.LOGIN_STANDARD + + #LDAP configurator, + if config.config_login_type == constants.LOGIN_LDAP: + _config_string("config_ldap_provider_url") + _config_int("config_ldap_port") + _config_string("config_ldap_schema") + _config_string("config_ldap_dn") + _config_string("config_ldap_user_object") + if not config.config_ldap_provider_url or not config.config_ldap_port or not config.config_ldap_dn or not config.config_ldap_user_object: + return _configuration_result('Please enter a LDAP provider, port, DN and user object identifier', gdriveError) + + _config_string("config_ldap_serv_username") + if not config.config_ldap_serv_username or "config_ldap_serv_password" not in to_save: + return _configuration_result('Please enter a LDAP service account and password', gdriveError) + config.set_from_dictionary(to_save, "config_ldap_serv_password", base64.b64encode) + + _config_checkbox("config_ldap_use_ssl") + _config_checkbox("config_ldap_use_tls") + _config_checkbox("config_ldap_openldap") + _config_checkbox("config_ldap_require_cert") + _config_string("config_ldap_cert_path") + if config.config_ldap_cert_path and not os.path.isfile(config.config_ldap_cert_path): + return _configuration_result('LDAP Certfile location is not valid, please enter correct path', gdriveError) + + # Remote login configuration + _config_checkbox("config_remote_login") + if not config.config_remote_login: + ub.session.query(ub.RemoteAuthToken).delete() + + # Goodreads configuration + _config_checkbox("config_use_goodreads") + _config_string("config_goodreads_api_key") + _config_string("config_goodreads_api_secret") + if services.goodreads: + services.goodreads.connect(config.config_goodreads_api_key, config.config_goodreads_api_secret, config.config_use_goodreads) + + _config_int("config_updatechannel") + + # GitHub OAuth configuration + if config.config_login_type == constants.LOGIN_OAUTH_GITHUB: + _config_string("config_github_oauth_client_id") + _config_string("config_github_oauth_client_secret") + if not config.config_github_oauth_client_id or not config.config_github_oauth_client_secret: + return _configuration_result('Please enter Github oauth credentials', gdriveError) + + # Google OAuth configuration + if config.config_login_type == constants.LOGIN_OAUTH_GOOGLE: + _config_string("config_google_oauth_client_id") + _config_string("config_google_oauth_client_secret") + if not config.config_google_oauth_client_id or not config.config_google_oauth_client_secret: + return _configuration_result('Please enter Google oauth credentials', gdriveError) + + _config_int("config_log_level") + _config_string("config_logfile") + if not logger.is_valid_logfile(config.config_logfile): + return _configuration_result('Logfile location is not valid, please enter correct path', gdriveError) + + reboot_required |= _config_checkbox_int("config_access_log") + reboot_required |= _config_string("config_access_logfile") + if not logger.is_valid_logfile(config.config_access_logfile): + return _configuration_result('Access Logfile location is not valid, please enter correct path', gdriveError) + + # Rarfile Content configuration + _config_string("config_rarfile_location") + unrar_status = helper.check_unrar(config.config_rarfile_location) + if unrar_status: + return _configuration_result(unrar_status, gdriveError) + + try: + metadata_db = os.path.join(config.config_calibre_dir, "metadata.db") + if config.config_use_google_drive and is_gdrive_ready() and not os.path.exists(metadata_db): + gdriveutils.downloadFile(None, "metadata.db", metadata_db) + db_change = True + except Exception as e: + return _configuration_result('%s' % e, gdriveError) + + if db_change: + # reload(db) + if not db.setup_db(config): + return _configuration_result('DB location is not valid, please enter correct path', gdriveError) + + config.save() + flash(_(u"Calibre-Web configuration updated"), category="success") + if reboot_required: + web_server.stop(True) + + return _configuration_result(None, gdriveError) + + +def _configuration_result(error_flash=None, gdriveError=None): + gdrive_authenticate = not is_gdrive_ready() + gdrivefolders = [] + if gdriveError is None: + gdriveError = gdriveutils.get_error_text() + if gdriveError: + gdriveError = _(gdriveError) + else: + gdrivefolders = gdriveutils.listRootFolders() + + show_back_button = current_user.is_authenticated + show_login_button = config.db_configured and not current_user.is_authenticated + if error_flash: + config.load() + flash(_(error_flash), category="error") + show_login_button = False + + return render_title_template("config_edit.html", config=config, + show_back_button=show_back_button, show_login_button=show_login_button, + show_authenticate_google_drive=gdrive_authenticate, + gdriveError=gdriveError, gdrivefolders=gdrivefolders, feature_support=feature_support, + title=_(u"Basic Configuration"), page="config") + + +@admi.route("/admin/user/new", methods=["GET", "POST"]) +@login_required +@admin_required +def new_user(): + content = ub.User() + languages = speaking_language() + translations = [LC('en')] + babel.list_translations() + if request.method == "POST": + to_save = request.form.to_dict() + content.default_language = to_save["default_language"] + content.mature_content = "Show_mature_content" in to_save + content.locale = to_save.get("locale", content.locale) + + content.sidebar_view = sum(int(key[5:]) for key in to_save if key.startswith('show_')) + if "show_detail_random" in to_save: + content.sidebar_view |= constants.DETAIL_RANDOM + + content.role = constants.selected_roles(to_save) + + if not to_save["nickname"] or not to_save["email"] or not to_save["password"]: + flash(_(u"Please fill out all fields!"), category="error") + return render_title_template("user_edit.html", new_user=1, content=content, translations=translations, + registered_oauth=oauth_check, title=_(u"Add new user")) + content.password = generate_password_hash(to_save["password"]) + existing_user = ub.session.query(ub.User).filter(func.lower(ub.User.nickname) == to_save["nickname"].lower())\ + .first() + existing_email = ub.session.query(ub.User).filter(ub.User.email == to_save["email"].lower())\ + .first() + if not existing_user and not existing_email: + content.nickname = to_save["nickname"] + if config.config_public_reg and not check_valid_domain(to_save["email"]): + flash(_(u"E-mail is not from valid domain"), category="error") + return render_title_template("user_edit.html", new_user=1, content=content, translations=translations, + registered_oauth=oauth_check, title=_(u"Add new user")) + else: + content.email = to_save["email"] + else: + flash(_(u"Found an existing account for this e-mail address or nickname."), category="error") + return render_title_template("user_edit.html", new_user=1, content=content, translations=translations, + languages=languages, title=_(u"Add new user"), page="newuser", + registered_oauth=oauth_check) + try: + ub.session.add(content) + ub.session.commit() + flash(_(u"User '%(user)s' created", user=content.nickname), category="success") + return redirect(url_for('admin.admin')) + except IntegrityError: + ub.session.rollback() + flash(_(u"Found an existing account for this e-mail address or nickname."), category="error") + else: + content.role = config.config_default_role + content.sidebar_view = config.config_default_show + content.mature_content = bool(config.config_default_show & constants.MATURE_CONTENT) + return render_title_template("user_edit.html", new_user=1, content=content, translations=translations, + languages=languages, title=_(u"Add new user"), page="newuser", + registered_oauth=oauth_check) + + +@admi.route("/admin/mailsettings") +@login_required +@admin_required +def edit_mailsettings(): + content = config.get_mail_settings() + # log.debug("edit_mailsettings %r", content) + return render_title_template("email_edit.html", content=content, title=_(u"Edit e-mail server settings"), + page="mailset") + + +@admi.route("/admin/mailsettings", methods=["POST"]) +@login_required +@admin_required +def update_mailsettings(): + to_save = request.form.to_dict() + log.debug("update_mailsettings %r", to_save) + + _config_string = lambda x: config.set_from_dictionary(to_save, x, lambda y: y.strip() if y else y) + _config_int = lambda x: config.set_from_dictionary(to_save, x, int) + + _config_string("mail_server") + _config_int("mail_port") + _config_int("mail_use_ssl") + _config_string("mail_login") + _config_string("mail_password") + _config_string("mail_from") + config.save() + + if to_save.get("test"): + if current_user.kindle_mail: + result = send_test_mail(current_user.kindle_mail, current_user.nickname) + if result is None: + flash(_(u"Test e-mail successfully send to %(kindlemail)s", kindlemail=current_user.kindle_mail), + category="success") + else: + flash(_(u"There was an error sending the Test e-mail: %(res)s", res=result), category="error") + else: + flash(_(u"Please configure your kindle e-mail address first..."), category="error") + else: + flash(_(u"E-mail server settings updated"), category="success") + + return edit_mailsettings() + + +@admi.route("/admin/user/", methods=["GET", "POST"]) +@login_required +@admin_required +def edit_user(user_id): + content = ub.session.query(ub.User).filter(ub.User.id == int(user_id)).first() # type: ub.User + downloads = list() + languages = speaking_language() + translations = babel.list_translations() + [LC('en')] + for book in content.downloads: + downloadbook = db.session.query(db.Books).filter(db.Books.id == book.book_id).first() + if downloadbook: + downloads.append(downloadbook) + else: + ub.delete_download(book.book_id) + # ub.session.query(ub.Downloads).filter(book.book_id == ub.Downloads.book_id).delete() + # ub.session.commit() + if request.method == "POST": + to_save = request.form.to_dict() + if "delete" in to_save: + if ub.session.query(ub.User).filter(and_(ub.User.role.op('&') + (constants.ROLE_ADMIN)== constants.ROLE_ADMIN, + ub.User.id != content.id)).count(): + ub.session.query(ub.User).filter(ub.User.id == content.id).delete() + ub.session.commit() + flash(_(u"User '%(nick)s' deleted", nick=content.nickname), category="success") + return redirect(url_for('admin.admin')) + else: + flash(_(u"No admin user remaining, can't delete user", nick=content.nickname), category="error") + return redirect(url_for('admin.admin')) + else: + if "password" in to_save and to_save["password"]: + content.password = generate_password_hash(to_save["password"]) + + anonymous = content.is_anonymous + content.role = constants.selected_roles(to_save) + if anonymous: + content.role |= constants.ROLE_ANONYMOUS + else: + content.role &= ~constants.ROLE_ANONYMOUS + + val = [int(k[5:]) for k in to_save if k.startswith('show_')] + sidebar = ub.get_sidebar_config() + for element in sidebar: + value = element['visibility'] + if value in val and not content.check_visibility(value): + content.sidebar_view |= value + elif not value in val and content.check_visibility(value): + content.sidebar_view &= ~value + + if "Show_detail_random" in to_save: + content.sidebar_view |= constants.DETAIL_RANDOM + else: + content.sidebar_view &= ~constants.DETAIL_RANDOM + + content.mature_content = "Show_mature_content" in to_save + + if "default_language" in to_save: + content.default_language = to_save["default_language"] + if "locale" in to_save and to_save["locale"]: + content.locale = to_save["locale"] + if to_save["email"] and to_save["email"] != content.email: + existing_email = ub.session.query(ub.User).filter(ub.User.email == to_save["email"].lower()) \ + .first() + if not existing_email: + content.email = to_save["email"] + else: + flash(_(u"Found an existing account for this e-mail address."), category="error") + return render_title_template("user_edit.html", translations=translations, languages=languages, + new_user=0, content=content, downloads=downloads, registered_oauth=oauth_check, + title=_(u"Edit User %(nick)s", nick=content.nickname), page="edituser") + + if "kindle_mail" in to_save and to_save["kindle_mail"] != content.kindle_mail: + content.kindle_mail = to_save["kindle_mail"] + try: + ub.session.commit() + flash(_(u"User '%(nick)s' updated", nick=content.nickname), category="success") + except IntegrityError: + ub.session.rollback() + flash(_(u"An unknown error occured."), category="error") + return render_title_template("user_edit.html", translations=translations, languages=languages, new_user=0, + content=content, downloads=downloads, registered_oauth=oauth_check, + title=_(u"Edit User %(nick)s", nick=content.nickname), page="edituser") + + +@admi.route("/admin/resetpassword/") +@login_required +@admin_required +def reset_password(user_id): + if not config.config_public_reg: + abort(404) + if current_user is not None and current_user.is_authenticated: + existing_user = ub.session.query(ub.User).filter(ub.User.id == user_id).first() + password = generate_random_password() + existing_user.password = generate_password_hash(password) + try: + ub.session.commit() + send_registration_mail(existing_user.email, existing_user.nickname, password, True) + flash(_(u"Password for user %(user)s reset", user=existing_user.nickname), category="success") + except Exception: + ub.session.rollback() + flash(_(u"An unknown error occurred. Please try again later."), category="error") + return redirect(url_for('admin.admin')) + + +@admi.route("/admin/logfile") +@login_required +@admin_required +def view_logfile(): + logfiles = {} + logfiles[0] = logger.get_logfile(config.config_logfile) + logfiles[1] = logger.get_accesslogfile(config.config_access_logfile) + return render_title_template("logviewer.html",title=_(u"Logfile viewer"), accesslog_enable=config.config_access_log, + logfiles=logfiles, page="logfile") + + +@admi.route("/ajax/log/") +@login_required +@admin_required +def send_logfile(logtype): + if logtype == 1: + logfile = logger.get_accesslogfile(config.config_access_logfile) + return send_from_directory(os.path.dirname(logfile), + os.path.basename(logfile)) + if logtype == 0: + logfile = logger.get_logfile(config.config_logfile) + return send_from_directory(os.path.dirname(logfile), + os.path.basename(logfile)) + else: + return "" + + +@admi.route("/get_update_status", methods=['GET']) +@login_required_if_no_ano +def get_update_status(): + return updater_thread.get_available_updates(request.method) + + +@admi.route("/get_updater_status", methods=['GET', 'POST']) +@login_required +@admin_required +def get_updater_status(): + status = {} + if request.method == "POST": + commit = request.form.to_dict() + if "start" in commit and commit['start'] == 'True': + text = { + "1": _(u'Requesting update package'), + "2": _(u'Downloading update package'), + "3": _(u'Unzipping update package'), + "4": _(u'Replacing files'), + "5": _(u'Database connections are closed'), + "6": _(u'Stopping server'), + "7": _(u'Update finished, please press okay and reload page'), + "8": _(u'Update failed:') + u' ' + _(u'HTTP Error'), + "9": _(u'Update failed:') + u' ' + _(u'Connection error'), + "10": _(u'Update failed:') + u' ' + _(u'Timeout while establishing connection'), + "11": _(u'Update failed:') + u' ' + _(u'General error') + } + status['text'] = text + updater_thread.status = 0 + updater_thread.start() + status['status'] = updater_thread.get_update_status() + elif request.method == "GET": + try: + status['status'] = updater_thread.get_update_status() + if status['status'] == -1: + status['status'] = 7 + except Exception: + status['status'] = 11 + return json.dumps(status) diff --git a/cps/book_formats.py b/cps/book_formats.py deleted file mode 100644 index 125e0b99..00000000 --- a/cps/book_formats.py +++ /dev/null @@ -1,217 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web) -# Copyright (C) 2016-2019 lemmsh cervinko Kennyl matthazinski OzzieIsaacs -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program. If not, see . - -import logging -import uploader -import os -from flask_babel import gettext as _ -import comic - -try: - from lxml.etree import LXML_VERSION as lxmlversion -except ImportError: - lxmlversion = None - -__author__ = 'lemmsh' - -logger = logging.getLogger("book_formats") - -try: - from wand.image import Image - from wand import version as ImageVersion - from wand.exceptions import PolicyError - use_generic_pdf_cover = False -except (ImportError, RuntimeError) as e: - logger.warning('cannot import Image, generating pdf covers for pdf uploads will not work: %s', e) - use_generic_pdf_cover = True -try: - from PyPDF2 import PdfFileReader - from PyPDF2 import __version__ as PyPdfVersion - use_pdf_meta = True -except ImportError as e: - logger.warning('cannot import PyPDF2, extracting pdf metadata will not work: %s', e) - use_pdf_meta = False - -try: - import epub - use_epub_meta = True -except ImportError as e: - logger.warning('cannot import epub, extracting epub metadata will not work: %s', e) - use_epub_meta = False - -try: - import fb2 - use_fb2_meta = True -except ImportError as e: - logger.warning('cannot import fb2, extracting fb2 metadata will not work: %s', e) - use_fb2_meta = False - -try: - from PIL import Image - from PIL import __version__ as PILversion - use_PIL = True -except ImportError: - use_PIL = False - - -def process(tmp_file_path, original_file_name, original_file_extension): - meta = None - try: - if ".PDF" == original_file_extension.upper(): - meta = pdf_meta(tmp_file_path, original_file_name, original_file_extension) - if ".EPUB" == original_file_extension.upper() and use_epub_meta is True: - meta = epub.get_epub_info(tmp_file_path, original_file_name, original_file_extension) - if ".FB2" == original_file_extension.upper() and use_fb2_meta is True: - meta = fb2.get_fb2_info(tmp_file_path, original_file_extension) - if original_file_extension.upper() in ['.CBZ', '.CBT']: - meta = comic.get_comic_info(tmp_file_path, original_file_name, original_file_extension) - - except Exception as ex: - logger.warning('cannot parse metadata, using default: %s', ex) - - if meta and meta.title.strip() and meta.author.strip(): - return meta - else: - return default_meta(tmp_file_path, original_file_name, original_file_extension) - - -def default_meta(tmp_file_path, original_file_name, original_file_extension): - return uploader.BookMeta( - file_path=tmp_file_path, - extension=original_file_extension, - title=original_file_name, - author=u"Unknown", - cover=None, - description="", - tags="", - series="", - series_id="", - languages="") - - -def pdf_meta(tmp_file_path, original_file_name, original_file_extension): - - if use_pdf_meta: - pdf = PdfFileReader(open(tmp_file_path, 'rb'), strict=False) - doc_info = pdf.getDocumentInfo() - else: - doc_info = None - - if doc_info is not None: - author = doc_info.author if doc_info.author else u"Unknown" - title = doc_info.title if doc_info.title else original_file_name - subject = doc_info.subject - else: - author = u"Unknown" - title = original_file_name - subject = "" - return uploader.BookMeta( - file_path=tmp_file_path, - extension=original_file_extension, - title=title, - author=author, - cover=pdf_preview(tmp_file_path, original_file_name), - description=subject, - tags="", - series="", - series_id="", - languages="") - - -def pdf_preview(tmp_file_path, tmp_dir): - if use_generic_pdf_cover: - return None - else: - if use_PIL: - try: - input1 = PdfFileReader(open(tmp_file_path, 'rb'), strict=False) - page0 = input1.getPage(0) - xObject = page0['/Resources']['/XObject'].getObject() - - for obj in xObject: - if xObject[obj]['/Subtype'] == '/Image': - size = (xObject[obj]['/Width'], xObject[obj]['/Height']) - data = xObject[obj]._data # xObject[obj].getData() - if xObject[obj]['/ColorSpace'] == '/DeviceRGB': - mode = "RGB" - else: - mode = "P" - if '/Filter' in xObject[obj]: - if xObject[obj]['/Filter'] == '/FlateDecode': - img = Image.frombytes(mode, size, data) - cover_file_name = os.path.splitext(tmp_file_path)[0] + ".cover.png" - img.save(filename=os.path.join(tmp_dir, cover_file_name)) - return cover_file_name - # img.save(obj[1:] + ".png") - elif xObject[obj]['/Filter'] == '/DCTDecode': - cover_file_name = os.path.splitext(tmp_file_path)[0] + ".cover.jpg" - img = open(cover_file_name, "wb") - img.write(data) - img.close() - return cover_file_name - elif xObject[obj]['/Filter'] == '/JPXDecode': - cover_file_name = os.path.splitext(tmp_file_path)[0] + ".cover.jp2" - img = open(cover_file_name, "wb") - img.write(data) - img.close() - return cover_file_name - else: - img = Image.frombytes(mode, size, data) - cover_file_name = os.path.splitext(tmp_file_path)[0] + ".cover.png" - img.save(filename=os.path.join(tmp_dir, cover_file_name)) - return cover_file_name - except Exception as ex: - print(ex) - try: - cover_file_name = os.path.splitext(tmp_file_path)[0] + ".cover.jpg" - with Image(filename=tmp_file_path + "[0]", resolution=150) as img: - img.compression_quality = 88 - img.save(filename=os.path.join(tmp_dir, cover_file_name)) - return cover_file_name - except PolicyError as ex: - logger.warning('Pdf extraction forbidden by Imagemagick policy: %s', ex) - return None - except Exception as ex: - logger.warning('Cannot extract cover image, using default: %s', ex) - return None - -def get_versions(): - if not use_generic_pdf_cover: - IVersion = ImageVersion.MAGICK_VERSION - WVersion = ImageVersion.VERSION - else: - IVersion = _(u'not installed') - WVersion = _(u'not installed') - if use_pdf_meta: - PVersion='v'+PyPdfVersion - else: - PVersion=_(u'not installed') - if lxmlversion: - XVersion = 'v'+'.'.join(map(str, lxmlversion)) - else: - XVersion = _(u'not installed') - if use_PIL: - PILVersion = 'v' + PILversion - else: - PILVersion = _(u'not installed') - return {'Image Magick': IVersion, - 'PyPdf': PVersion, - 'lxml':XVersion, - 'Wand': WVersion, - 'Pillow': PILVersion} diff --git a/cps/cache_buster.py b/cps/cache_buster.py index edd73cec..02aa7187 100644 --- a/cps/cache_buster.py +++ b/cps/cache_buster.py @@ -17,8 +17,14 @@ # Inspired by https://github.com/ChrisTM/Flask-CacheBust # Uses query strings so CSS font files are found without having to resort to absolute URLs -import hashlib +from __future__ import division, print_function, unicode_literals import os +import hashlib + +from . import logger + + +log = logger.create() def init_cache_busting(app): @@ -34,7 +40,7 @@ def init_cache_busting(app): hash_table = {} # map of file hashes - app.logger.debug('Computing cache-busting values...') + log.debug('Computing cache-busting values...') # compute file hashes for dirpath, __, filenames in os.walk(static_folder): for filename in filenames: @@ -47,7 +53,7 @@ def init_cache_busting(app): file_path = rooted_filename.replace(static_folder, "") file_path = file_path.replace("\\", "/") # Convert Windows path to web path hash_table[file_path] = file_hash - app.logger.debug('Finished computing cache-busting values') + log.debug('Finished computing cache-busting values') def bust_filename(filename): return hash_table.get(filename, "") diff --git a/cps/cli.py b/cps/cli.py index 26741c57..de12be5a 100644 --- a/cps/cli.py +++ b/cps/cli.py @@ -18,30 +18,87 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -import argparse -import os +from __future__ import division, print_function, unicode_literals import sys +import os +import argparse + +from .constants import CONFIG_DIR as _CONFIG_DIR +from .constants import STABLE_VERSION as _STABLE_VERSION +from .constants import NIGHTLY_VERSION as _NIGHTLY_VERSION + +VALID_CHARACTERS = 'ABCDEFabcdef:0123456789' + +ipv6 = False + + +def version_info(): + if _NIGHTLY_VERSION[1].startswith('$Format'): + return "Calibre-Web version: %s - unkown git-clone" % _STABLE_VERSION['version'] + else: + return "Calibre-Web version: %s -%s" % (_STABLE_VERSION['version'],_NIGHTLY_VERSION[1]) + + +def validate_ip4(address): + address_list = address.split('.') + if len(address_list) != 4: + return False + for val in address_list: + if not val.isdigit(): + return False + i = int(val) + if i < 0 or i > 255: + return False + return True + + +def validate_ip6(address): + address_list = address.split(':') + return ( + len(address_list) == 8 + and all(len(current) <= 4 for current in address_list) + and all(current in VALID_CHARACTERS for current in address) + ) + + +def validate_ip(address): + if validate_ip4(address) or ipv6: + return address + print("IP address is invalid. Exiting") + sys.exit(1) + parser = argparse.ArgumentParser(description='Calibre Web is a web app' ' providing a interface for browsing, reading and downloading eBooks\n', prog='cps.py') parser.add_argument('-p', metavar='path', help='path and name to settings db, e.g. /opt/cw.db') parser.add_argument('-g', metavar='path', help='path and name to gdrive db, e.g. /opt/gd.db') -parser.add_argument('-c', metavar='path', help='path and name to SSL certfile, e.g. /opt/test.cert, works only in combination with keyfile') -parser.add_argument('-k', metavar='path', help='path and name to SSL keyfile, e.g. /opt/test.key, works only in combination with certfile') +parser.add_argument('-c', metavar='path', + help='path and name to SSL certfile, e.g. /opt/test.cert, works only in combination with keyfile') +parser.add_argument('-k', metavar='path', + help='path and name to SSL keyfile, e.g. /opt/test.key, works only in combination with certfile') +parser.add_argument('-v', '--version', action='version', help='Shows version number and exits Calibre-web', + version=version_info()) +parser.add_argument('-i', metavar='ip-adress', help='Server IP-Adress to listen') +parser.add_argument('-s', metavar='user:pass', help='Sets specific username to new password') args = parser.parse_args() -generalPath = os.path.normpath(os.getenv("CALIBRE_DBPATH", - os.path.dirname(os.path.realpath(__file__)) + os.sep + ".." + os.sep)) -if args.p: - settingspath = args.p -else: - settingspath = os.path.join(generalPath, "app.db") +if sys.version_info < (3, 0): + if args.p: + args.p = args.p.decode('utf-8') + if args.g: + args.g = args.g.decode('utf-8') + if args.k: + args.k = args.k.decode('utf-8') + if args.c: + args.c = args.c.decode('utf-8') + if args.s: + args.s = args.s.decode('utf-8') -if args.g: - gdpath = args.g -else: - gdpath = os.path.join(generalPath, "gdrive.db") +settingspath = args.p or os.path.join(_CONFIG_DIR, "app.db") +gdpath = args.g or os.path.join(_CONFIG_DIR, "gdrive.db") + +# handle and check parameter for ssl encryption certfilepath = None keyfilepath = None if args.c: @@ -67,3 +124,13 @@ if (args.k and not args.c) or (not args.k and args.c): if args.k is "": keyfilepath = "" + +# handle and check ipadress argument +if args.i: + ipv6 = validate_ip6(args.i) + ipadress = validate_ip(args.i) +else: + ipadress = None + +# handle and check user password argument +user_password = args.s or None diff --git a/cps/comic.py b/cps/comic.py index 0b7d4f1f..738b2a89 100755 --- a/cps/comic.py +++ b/cps/comic.py @@ -17,19 +17,21 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . +from __future__ import division, print_function, unicode_literals import os -import uploader -import logging -from iso639 import languages as isoLanguages +from . import logger, isoLanguages +from .constants import BookMeta + + +log = logger.create() -logger = logging.getLogger("book_formats") try: from comicapi.comicarchive import ComicArchive, MetaDataStyle use_comic_meta = True except ImportError as e: - logger.warning('cannot import comicapi, extracting comic metadata will not work: %s', e) + log.warning('cannot import comicapi, extracting comic metadata will not work: %s', e) import zipfile import tarfile use_comic_meta = False @@ -96,7 +98,7 @@ def get_comic_info(tmp_file_path, original_file_name, original_file_extension): else: loadedMetadata.language = "" - return uploader.BookMeta( + return BookMeta( file_path=tmp_file_path, extension=original_file_extension, title=loadedMetadata.title or original_file_name, @@ -109,7 +111,7 @@ def get_comic_info(tmp_file_path, original_file_name, original_file_extension): languages=loadedMetadata.language) else: - return uploader.BookMeta( + return BookMeta( file_path=tmp_file_path, extension=original_file_extension, title=original_file_name, diff --git a/cps/config_sql.py b/cps/config_sql.py new file mode 100644 index 00000000..37ea77e5 --- /dev/null +++ b/cps/config_sql.py @@ -0,0 +1,287 @@ +# -*- coding: utf-8 -*- + +# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web) +# Copyright (C) 2019 OzzieIsaacs, pwr +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + + +from __future__ import division, print_function, unicode_literals +import os +import json + +from sqlalchemy import exc, Column, String, Integer, SmallInteger, Boolean +from sqlalchemy.ext.declarative import declarative_base + +from . import constants, cli, logger + + +log = logger.create() +_Base = declarative_base() + + +# Baseclass for representing settings in app.db with email server settings and Calibre database settings +# (application settings) +class _Settings(_Base): + __tablename__ = 'settings' + + id = Column(Integer, primary_key=True) + mail_server = Column(String, default='mail.example.org') + mail_port = Column(Integer, default=25) + mail_use_ssl = Column(SmallInteger, default=0) + mail_login = Column(String, default='mail@example.com') + mail_password = Column(String, default='mypassword') + mail_from = Column(String, default='automailer ') + config_calibre_dir = Column(String) + config_port = Column(Integer, default=constants.DEFAULT_PORT) + config_certfile = Column(String) + config_keyfile = Column(String) + config_calibre_web_title = Column(String, default=u'Calibre-Web') + config_books_per_page = Column(Integer, default=60) + config_random_books = Column(Integer, default=4) + config_authors_max = Column(Integer, default=0) + config_read_column = Column(Integer, default=0) + config_title_regex = Column(String, default=u'^(A|The|An|Der|Die|Das|Den|Ein|Eine|Einen|Dem|Des|Einem|Eines)\s+') + config_log_level = Column(SmallInteger, default=logger.DEFAULT_LOG_LEVEL) + config_access_log = Column(SmallInteger, default=0) + config_uploading = Column(SmallInteger, default=0) + config_anonbrowse = Column(SmallInteger, default=0) + config_public_reg = Column(SmallInteger, default=0) + config_default_role = Column(SmallInteger, default=0) + config_default_show = Column(SmallInteger, default=6143) + config_columns_to_ignore = Column(String) + config_use_google_drive = Column(Boolean, default=False) + config_google_drive_folder = Column(String) + config_google_drive_watch_changes_response = Column(String) + config_remote_login = Column(Boolean, default=False) + config_use_goodreads = Column(Boolean, default=False) + config_goodreads_api_key = Column(String) + config_goodreads_api_secret = Column(String) + config_login_type = Column(Integer, default=0) + # config_use_ldap = Column(Boolean) + config_ldap_provider_url = Column(String) + config_ldap_dn = Column(String) + # config_use_github_oauth = Column(Boolean) + config_github_oauth_client_id = Column(String) + config_github_oauth_client_secret = Column(String) + # config_use_google_oauth = Column(Boolean) + config_google_oauth_client_id = Column(String) + config_google_oauth_client_secret = Column(String) + config_ldap_provider_url = Column(String, default='localhost') + config_ldap_port = Column(SmallInteger, default=389) + config_ldap_schema = Column(String, default='ldap') + config_ldap_serv_username = Column(String) + config_ldap_serv_password = Column(String) + config_ldap_use_ssl = Column(Boolean, default=False) + config_ldap_use_tls = Column(Boolean, default=False) + config_ldap_require_cert = Column(Boolean, default=False) + config_ldap_cert_path = Column(String) + config_ldap_dn = Column(String) + config_ldap_user_object = Column(String) + config_ldap_openldap = Column(Boolean, default=False) + config_mature_content_tags = Column(String, default='') + config_logfile = Column(String) + config_access_logfile = Column(String) + config_ebookconverter = Column(Integer, default=0) + config_converterpath = Column(String) + config_calibre = Column(String) + config_rarfile_location = Column(String) + config_theme = Column(Integer, default=0) + config_updatechannel = Column(Integer, default=constants.UPDATE_STABLE) + + def __repr__(self): + return self.__class__.__name__ + + +# Class holds all application specific settings in calibre-web +class _ConfigSQL(object): + # pylint: disable=no-member + def __init__(self, session): + self._session = session + self._settings = None + self.db_configured = None + self.config_calibre_dir = None + self.load() + + def _read_from_storage(self): + if self._settings is None: + log.debug("_ConfigSQL._read_from_storage") + self._settings = self._session.query(_Settings).first() + return self._settings + + def get_config_certfile(self): + if cli.certfilepath: + return cli.certfilepath + if cli.certfilepath == "": + return None + return self.config_certfile + + def get_config_keyfile(self): + if cli.keyfilepath: + return cli.keyfilepath + if cli.certfilepath == "": + return None + return self.config_keyfile + + def get_config_ipaddress(self): + return cli.ipadress or "" + + def get_ipaddress_type(self): + return cli.ipv6 + + def _has_role(self, role_flag): + return constants.has_flag(self.config_default_role, role_flag) + + def role_admin(self): + return self._has_role(constants.ROLE_ADMIN) + + def role_download(self): + return self._has_role(constants.ROLE_DOWNLOAD) + + def role_viewer(self): + return self._has_role(constants.ROLE_VIEWER) + + def role_upload(self): + return self._has_role(constants.ROLE_UPLOAD) + + def role_edit(self): + return self._has_role(constants.ROLE_EDIT) + + def role_passwd(self): + return self._has_role(constants.ROLE_PASSWD) + + def role_edit_shelfs(self): + return self._has_role(constants.ROLE_EDIT_SHELFS) + + def role_delete_books(self): + return self._has_role(constants.ROLE_DELETE_BOOKS) + + def show_element_new_user(self, value): + return constants.has_flag(self.config_default_show, value) + + def show_detail_random(self): + return self.show_element_new_user(constants.DETAIL_RANDOM) + + def show_mature_content(self): + return self.show_element_new_user(constants.MATURE_CONTENT) + + def mature_content_tags(self): + mct = self.config_mature_content_tags.split(",") + return [t.strip() for t in mct] + + def get_log_level(self): + return logger.get_level_name(self.config_log_level) + + def get_mail_settings(self): + return {k:v for k, v in self.__dict__.items() if k.startswith('mail_')} + + def set_from_dictionary(self, dictionary, field, convertor=None, default=None): + '''Possibly updates a field of this object. + The new value, if present, is grabbed from the given dictionary, and optionally passed through a convertor. + + :returns: `True` if the field has changed value + ''' + new_value = dictionary.get(field, default) + if new_value is None: + # log.debug("_ConfigSQL set_from_dictionary field '%s' not found", field) + return False + + if field not in self.__dict__: + log.warning("_ConfigSQL trying to set unknown field '%s' = %r", field, new_value) + return False + + if convertor is not None: + new_value = convertor(new_value) + + current_value = self.__dict__.get(field) + if current_value == new_value: + return False + + # log.debug("_ConfigSQL set_from_dictionary '%s' = %r (was %r)", field, new_value, current_value) + setattr(self, field, new_value) + return True + + def load(self): + '''Load all configuration values from the underlying storage.''' + s = self._read_from_storage() # type: _Settings + for k, v in s.__dict__.items(): + if k[0] != '_': + if v is None: + # if the storage column has no value, apply the (possible) default + column = s.__class__.__dict__.get(k) + if column.default is not None: + v = column.default.arg + setattr(self, k, v) + + if self.config_google_drive_watch_changes_response: + self.config_google_drive_watch_changes_response = json.loads(self.config_google_drive_watch_changes_response) + self.db_configured = (self.config_calibre_dir and + (not self.config_use_google_drive or os.path.exists(self.config_calibre_dir + '/metadata.db'))) + logger.setup(self.config_logfile, self.config_log_level) + + def save(self): + '''Apply all configuration values to the underlying storage.''' + s = self._read_from_storage() # type: _Settings + + for k, v in self.__dict__.items(): + if k[0] == '_': + continue + if hasattr(s, k): # and getattr(s, k, None) != v: + # log.debug("_Settings save '%s' = %r", k, v) + setattr(s, k, v) + + log.debug("_ConfigSQL updating storage") + self._session.merge(s) + self._session.commit() + self.load() + + def invalidate(self): + log.warning("invalidating configuration") + self.db_configured = False + self.config_calibre_dir = None + self.save() + + +def _migrate_table(session, orm_class): + changed = False + + for column_name, column in orm_class.__dict__.items(): + if column_name[0] != '_': + try: + session.query(column).first() + except exc.OperationalError as err: + log.debug("%s: %s", column_name, err) + column_default = "" if column.default is None else ("DEFAULT %r" % column.default.arg) + alter_table = "ALTER TABLE %s ADD COLUMN `%s` %s %s" % (orm_class.__tablename__, column_name, column.type, column_default) + session.execute(alter_table) + changed = True + + if changed: + session.commit() + + +def _migrate_database(session): + # make sure the table is created, if it does not exist + _Base.metadata.create_all(session.bind) + _migrate_table(session, _Settings) + + +def load_configuration(session): + _migrate_database(session) + + if not session.query(_Settings).count(): + session.add(_Settings()) + session.commit() + + return _ConfigSQL(session) diff --git a/cps/constants.py b/cps/constants.py new file mode 100644 index 00000000..8d0002f1 --- /dev/null +++ b/cps/constants.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web) +# Copyright (C) 2019 OzzieIsaacs, pwr +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from __future__ import division, print_function, unicode_literals +import sys +import os +from collections import namedtuple + + +# Base dir is parent of current file, necessary if called from different folder +if sys.version_info < (3, 0): + BASE_DIR = os.path.abspath(os.path.join( + os.path.dirname(os.path.abspath(__file__)),os.pardir)).decode('utf-8') +else: + BASE_DIR = os.path.abspath(os.path.join( + os.path.dirname(os.path.abspath(__file__)),os.pardir)) +STATIC_DIR = os.path.join(BASE_DIR, 'cps', 'static') +TEMPLATES_DIR = os.path.join(BASE_DIR, 'cps', 'templates') +TRANSLATIONS_DIR = os.path.join(BASE_DIR, 'cps', 'translations') +CONFIG_DIR = os.environ.get('CALIBRE_DBPATH', BASE_DIR) + + +ROLE_USER = 0 << 0 +ROLE_ADMIN = 1 << 0 +ROLE_DOWNLOAD = 1 << 1 +ROLE_UPLOAD = 1 << 2 +ROLE_EDIT = 1 << 3 +ROLE_PASSWD = 1 << 4 +ROLE_ANONYMOUS = 1 << 5 +ROLE_EDIT_SHELFS = 1 << 6 +ROLE_DELETE_BOOKS = 1 << 7 +ROLE_VIEWER = 1 << 8 + +ALL_ROLES = { + "admin_role": ROLE_ADMIN, + "download_role": ROLE_DOWNLOAD, + "upload_role": ROLE_UPLOAD, + "edit_role": ROLE_EDIT, + "passwd_role": ROLE_PASSWD, + "edit_shelf_role": ROLE_EDIT_SHELFS, + "delete_role": ROLE_DELETE_BOOKS, + "viewer_role": ROLE_VIEWER, + } + +DETAIL_RANDOM = 1 << 0 +SIDEBAR_LANGUAGE = 1 << 1 +SIDEBAR_SERIES = 1 << 2 +SIDEBAR_CATEGORY = 1 << 3 +SIDEBAR_HOT = 1 << 4 +SIDEBAR_RANDOM = 1 << 5 +SIDEBAR_AUTHOR = 1 << 6 +SIDEBAR_BEST_RATED = 1 << 7 +SIDEBAR_READ_AND_UNREAD = 1 << 8 +SIDEBAR_RECENT = 1 << 9 +SIDEBAR_SORTED = 1 << 10 +MATURE_CONTENT = 1 << 11 +SIDEBAR_PUBLISHER = 1 << 12 +SIDEBAR_RATING = 1 << 13 +SIDEBAR_FORMAT = 1 << 14 + +ADMIN_USER_ROLES = sum(r for r in ALL_ROLES.values()) & ~ROLE_EDIT_SHELFS & ~ROLE_ANONYMOUS +ADMIN_USER_SIDEBAR = (SIDEBAR_FORMAT << 1) - 1 + +UPDATE_STABLE = 0 << 0 +AUTO_UPDATE_STABLE = 1 << 0 +UPDATE_NIGHTLY = 1 << 1 +AUTO_UPDATE_NIGHTLY = 1 << 2 + +LOGIN_STANDARD = 0 +LOGIN_LDAP = 1 +LOGIN_OAUTH_GITHUB = 2 +LOGIN_OAUTH_GOOGLE = 3 + + +DEFAULT_PASSWORD = "admin123" +DEFAULT_PORT = 8083 +try: + env_CALIBRE_PORT = os.environ.get("CALIBRE_PORT", DEFAULT_PORT) + DEFAULT_PORT = int(env_CALIBRE_PORT) +except ValueError: + print('Environment variable CALIBRE_PORT has invalid value (%s), faling back to default (8083)' % env_CALIBRE_PORT) +del env_CALIBRE_PORT + + +EXTENSIONS_AUDIO = {'mp3', 'm4a', 'm4b'} +EXTENSIONS_CONVERT = {'pdf', 'epub', 'mobi', 'azw3', 'docx', 'rtf', 'fb2', 'lit', 'lrf', 'txt', 'htmlz', 'rtf', 'odt'} +EXTENSIONS_UPLOAD = {'txt', 'pdf', 'epub', 'mobi', 'azw', 'azw3', 'cbr', 'cbz', 'cbt', 'djvu', 'prc', 'doc', 'docx', + 'fb2', 'html', 'rtf', 'odt', 'mp3', 'm4a', 'm4b'} +# EXTENSIONS_READER = set(['txt', 'pdf', 'epub', 'zip', 'cbz', 'tar', 'cbt'] + +# (['rar','cbr'] if feature_support['rar'] else [])) + + +def has_flag(value, bit_flag): + return bit_flag == (bit_flag & (value or 0)) + +def selected_roles(dictionary): + return sum(v for k, v in ALL_ROLES.items() if k in dictionary) + + +# :rtype: BookMeta +BookMeta = namedtuple('BookMeta', 'file_path, extension, title, author, cover, description, tags, series, ' + 'series_id, languages') + +STABLE_VERSION = {'version': '0.6.4 Beta'} + +NIGHTLY_VERSION = {} +NIGHTLY_VERSION[0] = '$Format:%H$' +NIGHTLY_VERSION[1] = '$Format:%cI$' +# NIGHTLY_VERSION[0] = 'bb7d2c6273ae4560e83950d36d64533343623a57' +# NIGHTLY_VERSION[1] = '2018-09-09T10:13:08+02:00' + + +# clean-up the module namespace +del sys, os, namedtuple + diff --git a/cps/converter.py b/cps/converter.py index bfcf0879..6dc44383 100644 --- a/cps/converter.py +++ b/cps/converter.py @@ -17,23 +17,21 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . - +from __future__ import division, print_function, unicode_literals import os -import subprocess -import ub import re + from flask_babel import gettext as _ +from . import config +from .subproc_wrapper import process_wait + def versionKindle(): versions = _(u'not installed') - if os.path.exists(ub.config.config_converterpath): + if os.path.exists(config.config_converterpath): try: - p = subprocess.Popen(ub.config.config_converterpath, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - p.wait() - for lines in p.stdout.readlines(): - if isinstance(lines, bytes): - lines = lines.decode('utf-8') + for lines in process_wait(config.config_converterpath): if re.search('Amazon kindlegen\(', lines): versions = lines except Exception: @@ -43,13 +41,9 @@ def versionKindle(): def versionCalibre(): versions = _(u'not installed') - if os.path.exists(ub.config.config_converterpath): + if os.path.exists(config.config_converterpath): try: - p = subprocess.Popen([ub.config.config_converterpath, '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) - p.wait() - for lines in p.stdout.readlines(): - if isinstance(lines, bytes): - lines = lines.decode('utf-8') + for lines in process_wait([config.config_converterpath, '--version']): if re.search('ebook-convert.*\(calibre', lines): versions = lines except Exception: @@ -58,9 +52,9 @@ def versionCalibre(): def versioncheck(): - if ub.config.config_ebookconverter == 1: + if config.config_ebookconverter == 1: return versionKindle() - elif ub.config.config_ebookconverter == 2: + elif config.config_ebookconverter == 2: return versionCalibre() else: return {'ebook_converter':_(u'not configured')} diff --git a/cps/db.py b/cps/db.py index 688f7fde..edcdef63 100755 --- a/cps/db.py +++ b/cps/db.py @@ -18,40 +18,22 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -from sqlalchemy import * -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import * +from __future__ import division, print_function, unicode_literals +import sys import os import re import ast -from ub import config -import ub -import sys -import unidecode - -session = None -cc_exceptions = ['datetime', 'comments', 'float', 'composite', 'series'] -cc_classes = None -engine = None - -# user defined sort function for calibre databases (Series, etc.) -def title_sort(title): - # calibre sort stuff - title_pat = re.compile(config.config_title_regex, re.IGNORECASE) - match = title_pat.search(title) - if match: - prep = match.group(1) - title = title.replace(prep, '') + ', ' + prep - return title.strip() - - -def lcase(s): - return unidecode.unidecode(s.lower()) +from sqlalchemy import create_engine +from sqlalchemy import Table, Column, ForeignKey +from sqlalchemy import String, Integer, Boolean +from sqlalchemy.orm import relationship, sessionmaker, scoped_session +from sqlalchemy.ext.declarative import declarative_base -def ucase(s): - return s.upper() +session = None +cc_exceptions = ['datetime', 'comments', 'float', 'composite', 'series'] +cc_classes = {} Base = declarative_base() @@ -329,37 +311,45 @@ class Custom_Columns(Base): return display_dict -def setup_db(): - global engine - global session - global cc_classes - - if config.config_calibre_dir is None or config.config_calibre_dir == u'': - content = ub.session.query(ub.Settings).first() - content.config_calibre_dir = None - content.db_configured = False - ub.session.commit() - config.loadSettings() +def update_title_sort(config, conn=None): + # user defined sort function for calibre databases (Series, etc.) + def _title_sort(title): + # calibre sort stuff + title_pat = re.compile(config.config_title_regex, re.IGNORECASE) + match = title_pat.search(title) + if match: + prep = match.group(1) + title = title.replace(prep, '') + ', ' + prep + return title.strip() + + conn = conn or session.connection().connection.connection + conn.create_function("title_sort", 1, _title_sort) + + +def setup_db(config): + dispose() + + if not config.config_calibre_dir: + config.invalidate() return False dbpath = os.path.join(config.config_calibre_dir, "metadata.db") + if not os.path.exists(dbpath): + config.invalidate() + return False + try: - if not os.path.exists(dbpath): - raise - engine = create_engine('sqlite:///' + dbpath, echo=False, isolation_level="SERIALIZABLE", connect_args={'check_same_thread': False}) + engine = create_engine('sqlite:///{0}'.format(dbpath), + echo=False, + isolation_level="SERIALIZABLE", + connect_args={'check_same_thread': False}) conn = engine.connect() - except Exception: - content = ub.session.query(ub.Settings).first() - content.config_calibre_dir = None - content.db_configured = False - ub.session.commit() - config.loadSettings() + except: + config.invalidate() return False - content = ub.session.query(ub.Settings).first() - content.db_configured = True - ub.session.commit() - config.loadSettings() - conn.connection.create_function('title_sort', 1, title_sort) + + config.db_configured = True + update_title_sort(config, conn.connection) # conn.connection.create_function('lower', 1, lcase) # conn.connection.create_function('upper', 1, ucase) @@ -368,7 +358,6 @@ def setup_db(): cc_ids = [] books_custom_column_links = {} - cc_classes = {} for row in cc: if row.datatype not in cc_exceptions: books_custom_column_links[row.id] = Table('books_custom_column_' + str(row.id) + '_link', Base.metadata, @@ -393,7 +382,7 @@ def setup_db(): ccdict = {'__tablename__': 'custom_column_' + str(row.id), 'id': Column(Integer, primary_key=True), 'value': Column(String)} - cc_classes[row.id] = type('Custom_Column_' + str(row.id), (Base,), ccdict) + cc_classes[row.id] = type(str('Custom_Column_' + str(row.id)), (Base,), ccdict) for cc_id in cc_ids: if (cc_id[1] == 'bool') or (cc_id[1] == 'int'): @@ -407,8 +396,38 @@ def setup_db(): backref='books')) + global session Session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) session = Session() return True + + +def dispose(): + global session + + engine = None + if session: + engine = session.bind + try: session.close() + except: pass + session = None + + if engine: + try: engine.dispose() + except: pass + + for attr in list(Books.__dict__.keys()): + if attr.startswith("custom_column_"): + delattr(Books, attr) + + for db_class in cc_classes.values(): + Base.metadata.remove(db_class.__table__) + cc_classes.clear() + + for table in reversed(Base.metadata.sorted_tables): + name = table.key + if name.startswith("custom_column_") or name.startswith("books_custom_column_"): + if table is not None: + Base.metadata.remove(table) diff --git a/cps/editbooks.py b/cps/editbooks.py new file mode 100644 index 00000000..7f850254 --- /dev/null +++ b/cps/editbooks.py @@ -0,0 +1,711 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web) +# Copyright (C) 2018-2019 OzzieIsaacs, cervinko, jkrehm, bodybybuddha, ok11, +# andy29485, idalin, Kyosfonica, wuqi, Kennyl, lemmsh, +# falgh1, grunjol, csitko, ytils, xybydy, trasba, vrabe, +# ruben-herold, marblepebble, JackED42, SiphonSquirrel, +# apetresc, nanu-c, mutschler +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from __future__ import division, print_function, unicode_literals +import os +import datetime +import json +from shutil import move, copyfile +from uuid import uuid4 + +from flask import Blueprint, request, flash, redirect, url_for, abort, Markup, Response +from flask_babel import gettext as _ +from flask_login import current_user + +from . import constants, logger, isoLanguages, gdriveutils, uploader, helper +from . import config, get_locale, db, ub, global_WorkerThread +from .helper import order_authors, common_filters +from .web import login_required_if_no_ano, render_title_template, edit_required, upload_required, login_required + + +editbook = Blueprint('editbook', __name__) +log = logger.create() + + +# Modifies different Database objects, first check if elements have to be added to database, than check +# if elements have to be deleted, because they are no longer used +def modify_database_object(input_elements, db_book_object, db_object, db_session, db_type): + # passing input_elements not as a list may lead to undesired results + if not isinstance(input_elements, list): + raise TypeError(str(input_elements) + " should be passed as a list") + + input_elements = [x for x in input_elements if x != ''] + # we have all input element (authors, series, tags) names now + # 1. search for elements to remove + del_elements = [] + for c_elements in db_book_object: + found = False + if db_type == 'languages': + type_elements = c_elements.lang_code + elif db_type == 'custom': + type_elements = c_elements.value + else: + type_elements = c_elements.name + for inp_element in input_elements: + if inp_element.lower() == type_elements.lower(): + # if inp_element == type_elements: + found = True + break + # if the element was not found in the new list, add it to remove list + if not found: + del_elements.append(c_elements) + # 2. search for elements that need to be added + add_elements = [] + for inp_element in input_elements: + found = False + for c_elements in db_book_object: + if db_type == 'languages': + type_elements = c_elements.lang_code + elif db_type == 'custom': + type_elements = c_elements.value + else: + type_elements = c_elements.name + if inp_element == type_elements: + found = True + break + if not found: + add_elements.append(inp_element) + # if there are elements to remove, we remove them now + if len(del_elements) > 0: + for del_element in del_elements: + db_book_object.remove(del_element) + if len(del_element.books) == 0: + db_session.delete(del_element) + # if there are elements to add, we add them now! + if len(add_elements) > 0: + if db_type == 'languages': + db_filter = db_object.lang_code + elif db_type == 'custom': + db_filter = db_object.value + else: + db_filter = db_object.name + for add_element in add_elements: + # check if a element with that name exists + db_element = db_session.query(db_object).filter(db_filter == add_element).first() + # if no element is found add it + # if new_element is None: + if db_type == 'author': + new_element = db_object(add_element, helper.get_sorted_author(add_element.replace('|', ',')), "") + elif db_type == 'series': + new_element = db_object(add_element, add_element) + elif db_type == 'custom': + new_element = db_object(value=add_element) + elif db_type == 'publisher': + new_element = db_object(add_element, None) + else: # db_type should be tag or language + new_element = db_object(add_element) + if db_element is None: + db_session.add(new_element) + db_book_object.append(new_element) + else: + if db_type == 'custom': + if db_element.value != add_element: + new_element.value = add_element + # new_element = db_element + elif db_type == 'languages': + if db_element.lang_code != add_element: + db_element.lang_code = add_element + # new_element = db_element + elif db_type == 'series': + if db_element.name != add_element: + db_element.name = add_element # = add_element # new_element = db_object(add_element, add_element) + db_element.sort = add_element + # new_element = db_element + elif db_type == 'author': + if db_element.name != add_element: + db_element.name = add_element + db_element.sort = add_element.replace('|', ',') + # new_element = db_element + elif db_type == 'publisher': + if db_element.name != add_element: + db_element.name = add_element + db_element.sort = None + # new_element = db_element + elif db_element.name != add_element: + db_element.name = add_element + # new_element = db_element + # add element to book + db_book_object.append(db_element) + + +@editbook.route("/delete//", defaults={'book_format': ""}) +@editbook.route("/delete///") +@login_required +def delete_book(book_id, book_format): + if current_user.role_delete_books(): + book = db.session.query(db.Books).filter(db.Books.id == book_id).first() + if book: + helper.delete_book(book, config.config_calibre_dir, book_format=book_format.upper()) + if not book_format: + # delete book from Shelfs, Downloads, Read list + ub.session.query(ub.BookShelf).filter(ub.BookShelf.book_id == book_id).delete() + ub.session.query(ub.ReadBook).filter(ub.ReadBook.book_id == book_id).delete() + ub.delete_download(book_id) + ub.session.commit() + + # check if only this book links to: + # author, language, series, tags, custom columns + modify_database_object([u''], book.authors, db.Authors, db.session, 'author') + modify_database_object([u''], book.tags, db.Tags, db.session, 'tags') + modify_database_object([u''], book.series, db.Series, db.session, 'series') + modify_database_object([u''], book.languages, db.Languages, db.session, 'languages') + modify_database_object([u''], book.publishers, db.Publishers, db.session, 'publishers') + + cc = db.session.query(db.Custom_Columns).filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all() + for c in cc: + cc_string = "custom_column_" + str(c.id) + if not c.is_multiple: + if len(getattr(book, cc_string)) > 0: + if c.datatype == 'bool' or c.datatype == 'integer': + del_cc = getattr(book, cc_string)[0] + getattr(book, cc_string).remove(del_cc) + db.session.delete(del_cc) + elif c.datatype == 'rating': + del_cc = getattr(book, cc_string)[0] + getattr(book, cc_string).remove(del_cc) + if len(del_cc.books) == 0: + db.session.delete(del_cc) + else: + del_cc = getattr(book, cc_string)[0] + getattr(book, cc_string).remove(del_cc) + db.session.delete(del_cc) + else: + modify_database_object([u''], getattr(book, cc_string), db.cc_classes[c.id], + db.session, 'custom') + db.session.query(db.Books).filter(db.Books.id == book_id).delete() + else: + db.session.query(db.Data).filter(db.Data.book == book.id).filter(db.Data.format == book_format).delete() + db.session.commit() + else: + # book not found + log.error('Book with id "%s" could not be deleted: not found', book_id) + if book_format: + return redirect(url_for('editbook.edit_book', book_id=book_id)) + else: + return redirect(url_for('web.index')) + + +def render_edit_book(book_id): + db.update_title_sort(config) + cc = db.session.query(db.Custom_Columns).filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all() + book = db.session.query(db.Books)\ + .filter(db.Books.id == book_id).filter(common_filters()).first() + + if not book: + flash(_(u"Error opening eBook. File does not exist or file is not accessible"), category="error") + return redirect(url_for("web.index")) + + for lang in book.languages: + lang.language_name = isoLanguages.get_language_name(get_locale(), lang.lang_code) + + book = order_authors(book) + + author_names = [] + for authr in book.authors: + author_names.append(authr.name.replace('|', ',')) + + # Option for showing convertbook button + valid_source_formats=list() + if config.config_ebookconverter == 2: + for file in book.data: + if file.format.lower() in constants.EXTENSIONS_CONVERT: + valid_source_formats.append(file.format.lower()) + + # Determine what formats don't already exist + allowed_conversion_formats = constants.EXTENSIONS_CONVERT.copy() + for file in book.data: + try: + allowed_conversion_formats.remove(file.format.lower()) + except Exception: + log.warning('%s already removed from list.', file.format.lower()) + + return render_title_template('book_edit.html', book=book, authors=author_names, cc=cc, + title=_(u"edit metadata"), page="editbook", + conversion_formats=allowed_conversion_formats, + source_formats=valid_source_formats) + + +def edit_cc_data(book_id, book, to_save): + cc = db.session.query(db.Custom_Columns).filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all() + for c in cc: + cc_string = "custom_column_" + str(c.id) + if not c.is_multiple: + if len(getattr(book, cc_string)) > 0: + cc_db_value = getattr(book, cc_string)[0].value + else: + cc_db_value = None + if to_save[cc_string].strip(): + if c.datatype == 'int' or c.datatype == 'bool': + if to_save[cc_string] == 'None': + to_save[cc_string] = None + elif c.datatype == 'bool': + to_save[cc_string] = 1 if to_save[cc_string] == 'True' else 0 + + if to_save[cc_string] != cc_db_value: + if cc_db_value is not None: + if to_save[cc_string] is not None: + setattr(getattr(book, cc_string)[0], 'value', to_save[cc_string]) + else: + del_cc = getattr(book, cc_string)[0] + getattr(book, cc_string).remove(del_cc) + db.session.delete(del_cc) + else: + cc_class = db.cc_classes[c.id] + new_cc = cc_class(value=to_save[cc_string], book=book_id) + db.session.add(new_cc) + + else: + if c.datatype == 'rating': + to_save[cc_string] = str(int(float(to_save[cc_string]) * 2)) + if to_save[cc_string].strip() != cc_db_value: + if cc_db_value is not None: + # remove old cc_val + del_cc = getattr(book, cc_string)[0] + getattr(book, cc_string).remove(del_cc) + if len(del_cc.books) == 0: + db.session.delete(del_cc) + cc_class = db.cc_classes[c.id] + new_cc = db.session.query(cc_class).filter( + cc_class.value == to_save[cc_string].strip()).first() + # if no cc val is found add it + if new_cc is None: + new_cc = cc_class(value=to_save[cc_string].strip()) + db.session.add(new_cc) + db.session.flush() + new_cc = db.session.query(cc_class).filter( + cc_class.value == to_save[cc_string].strip()).first() + # add cc value to book + getattr(book, cc_string).append(new_cc) + else: + if cc_db_value is not None: + # remove old cc_val + del_cc = getattr(book, cc_string)[0] + getattr(book, cc_string).remove(del_cc) + if len(del_cc.books) == 0: + db.session.delete(del_cc) + else: + input_tags = to_save[cc_string].split(',') + input_tags = list(map(lambda it: it.strip(), input_tags)) + modify_database_object(input_tags, getattr(book, cc_string), db.cc_classes[c.id], db.session, + 'custom') + return cc + +def upload_single_file(request, book, book_id): + # Check and handle Uploaded file + if 'btn-upload-format' in request.files: + requested_file = request.files['btn-upload-format'] + # check for empty request + if requested_file.filename != '': + if '.' in requested_file.filename: + file_ext = requested_file.filename.rsplit('.', 1)[-1].lower() + if file_ext not in constants.EXTENSIONS_UPLOAD: + flash(_("File extension '%(ext)s' is not allowed to be uploaded to this server", ext=file_ext), + category="error") + return redirect(url_for('web.show_book', book_id=book.id)) + else: + flash(_('File to be uploaded must have an extension'), category="error") + return redirect(url_for('web.show_book', book_id=book.id)) + + file_name = book.path.rsplit('/', 1)[-1] + filepath = os.path.normpath(os.path.join(config.config_calibre_dir, book.path)) + saved_filename = os.path.join(filepath, file_name + '.' + file_ext) + + # check if file path exists, otherwise create it, copy file to calibre path and delete temp file + if not os.path.exists(filepath): + try: + os.makedirs(filepath) + except OSError: + flash(_(u"Failed to create path %(path)s (Permission denied).", path=filepath), category="error") + return redirect(url_for('web.show_book', book_id=book.id)) + try: + requested_file.save(saved_filename) + except OSError: + flash(_(u"Failed to store file %(file)s.", file=saved_filename), category="error") + return redirect(url_for('web.show_book', book_id=book.id)) + + file_size = os.path.getsize(saved_filename) + is_format = db.session.query(db.Data).filter(db.Data.book == book_id).\ + filter(db.Data.format == file_ext.upper()).first() + + # Format entry already exists, no need to update the database + if is_format: + log.warning('Book format %s already existing', file_ext.upper()) + else: + db_format = db.Data(book_id, file_ext.upper(), file_size, file_name) + db.session.add(db_format) + db.session.commit() + db.update_title_sort(config) + + # Queue uploader info + uploadText=_(u"File format %(ext)s added to %(book)s", ext=file_ext.upper(), book=book.title) + global_WorkerThread.add_upload(current_user.nickname, + "" + uploadText + "") + + +def upload_cover(request, book): + if 'btn-upload-cover' in request.files: + requested_file = request.files['btn-upload-cover'] + # check for empty request + if requested_file.filename != '': + if helper.save_cover(requested_file, book.path) is True: + return True + else: + # ToDo Message not always coorect + flash(_(u"Cover is not a supported imageformat (jpg/png/webp), can't save"), category="error") + return False + return None + + +@editbook.route("/admin/book/", methods=['GET', 'POST']) +@login_required_if_no_ano +@edit_required +def edit_book(book_id): + # Show form + if request.method != 'POST': + return render_edit_book(book_id) + + # create the function for sorting... + db.update_title_sort(config) + book = db.session.query(db.Books)\ + .filter(db.Books.id == book_id).filter(common_filters()).first() + + # Book not found + if not book: + flash(_(u"Error opening eBook. File does not exist or file is not accessible"), category="error") + return redirect(url_for("web.index")) + + upload_single_file(request, book, book_id) + if upload_cover(request, book) is True: + book.has_cover = 1 + try: + to_save = request.form.to_dict() + # Update book + edited_books_id = None + #handle book title + if book.title != to_save["book_title"].rstrip().strip(): + if to_save["book_title"] == '': + to_save["book_title"] = _(u'unknown') + book.title = to_save["book_title"].rstrip().strip() + edited_books_id = book.id + + # handle author(s) + input_authors = to_save["author_name"].split('&') + input_authors = list(map(lambda it: it.strip().replace(',', '|'), input_authors)) + # we have all author names now + if input_authors == ['']: + input_authors = [_(u'unknown')] # prevent empty Author + + modify_database_object(input_authors, book.authors, db.Authors, db.session, 'author') + + # Search for each author if author is in database, if not, authorname and sorted authorname is generated new + # everything then is assembled for sorted author field in database + sort_authors_list = list() + for inp in input_authors: + stored_author = db.session.query(db.Authors).filter(db.Authors.name == inp).first() + if not stored_author: + stored_author = helper.get_sorted_author(inp) + else: + stored_author = stored_author.sort + sort_authors_list.append(helper.get_sorted_author(stored_author)) + sort_authors = ' & '.join(sort_authors_list) + if book.author_sort != sort_authors: + edited_books_id = book.id + book.author_sort = sort_authors + + + if config.config_use_google_drive: + gdriveutils.updateGdriveCalibreFromLocal() + + error = False + if edited_books_id: + error = helper.update_dir_stucture(edited_books_id, config.config_calibre_dir, input_authors[0]) + + if not error: + if to_save["cover_url"]: + if helper.save_cover_from_url(to_save["cover_url"], book.path) is True: + book.has_cover = 1 + else: + flash(_(u"Cover is not a jpg file, can't save"), category="error") + + if book.series_index != to_save["series_index"]: + book.series_index = to_save["series_index"] + + # Handle book comments/description + if len(book.comments): + book.comments[0].text = to_save["description"] + else: + book.comments.append(db.Comments(text=to_save["description"], book=book.id)) + + # Handle book tags + input_tags = to_save["tags"].split(',') + input_tags = list(map(lambda it: it.strip(), input_tags)) + modify_database_object(input_tags, book.tags, db.Tags, db.session, 'tags') + + # Handle book series + input_series = [to_save["series"].strip()] + input_series = [x for x in input_series if x != ''] + modify_database_object(input_series, book.series, db.Series, db.session, 'series') + + if to_save["pubdate"]: + try: + book.pubdate = datetime.datetime.strptime(to_save["pubdate"], "%Y-%m-%d") + except ValueError: + book.pubdate = db.Books.DEFAULT_PUBDATE + else: + book.pubdate = db.Books.DEFAULT_PUBDATE + + if to_save["publisher"]: + publisher = to_save["publisher"].rstrip().strip() + if len(book.publishers) == 0 or (len(book.publishers) > 0 and publisher != book.publishers[0].name): + modify_database_object([publisher], book.publishers, db.Publishers, db.session, 'publisher') + elif len(book.publishers): + modify_database_object([], book.publishers, db.Publishers, db.session, 'publisher') + + + # handle book languages + input_languages = to_save["languages"].split(',') + unknown_languages = [] + input_l = isoLanguages.get_language_codes(get_locale(), input_languages, unknown_languages) + for l in unknown_languages: + log.error('%s is not a valid language', l) + flash(_(u"%(langname)s is not a valid language", langname=l), category="error") + modify_database_object(list(input_l), book.languages, db.Languages, db.session, 'languages') + + # handle book ratings + if to_save["rating"].strip(): + old_rating = False + if len(book.ratings) > 0: + old_rating = book.ratings[0].rating + ratingx2 = int(float(to_save["rating"]) * 2) + if ratingx2 != old_rating: + is_rating = db.session.query(db.Ratings).filter(db.Ratings.rating == ratingx2).first() + if is_rating: + book.ratings.append(is_rating) + else: + new_rating = db.Ratings(rating=ratingx2) + book.ratings.append(new_rating) + if old_rating: + book.ratings.remove(book.ratings[0]) + else: + if len(book.ratings) > 0: + book.ratings.remove(book.ratings[0]) + + # handle cc data + edit_cc_data(book_id, book, to_save) + + db.session.commit() + if config.config_use_google_drive: + gdriveutils.updateGdriveCalibreFromLocal() + if "detail_view" in to_save: + return redirect(url_for('web.show_book', book_id=book.id)) + else: + flash(_("Metadata successfully updated"), category="success") + return render_edit_book(book_id) + else: + db.session.rollback() + flash(error, category="error") + return render_edit_book(book_id) + except Exception as e: + log.exception(e) + db.session.rollback() + flash(_("Error editing book, please check logfile for details"), category="error") + return redirect(url_for('web.show_book', book_id=book.id)) + + +@editbook.route("/upload", methods=["GET", "POST"]) +@login_required_if_no_ano +@upload_required +def upload(): + if not config.config_uploading: + abort(404) + if request.method == 'POST' and 'btn-upload' in request.files: + for requested_file in request.files.getlist("btn-upload"): + # create the function for sorting... + db.update_title_sort(config) + db.session.connection().connection.connection.create_function('uuid4', 0, lambda: str(uuid4())) + + # check if file extension is correct + if '.' in requested_file.filename: + file_ext = requested_file.filename.rsplit('.', 1)[-1].lower() + if file_ext not in constants.EXTENSIONS_UPLOAD: + flash( + _("File extension '%(ext)s' is not allowed to be uploaded to this server", + ext=file_ext), category="error") + return redirect(url_for('web.index')) + else: + flash(_('File to be uploaded must have an extension'), category="error") + return redirect(url_for('web.index')) + + # extract metadata from file + meta = uploader.upload(requested_file) + title = meta.title + authr = meta.author + tags = meta.tags + series = meta.series + series_index = meta.series_id + title_dir = helper.get_valid_filename(title) + author_dir = helper.get_valid_filename(authr) + filepath = os.path.join(config.config_calibre_dir, author_dir, title_dir) + saved_filename = os.path.join(filepath, title_dir + meta.extension.lower()) + + # check if file path exists, otherwise create it, copy file to calibre path and delete temp file + if not os.path.exists(filepath): + try: + os.makedirs(filepath) + except OSError: + flash(_(u"Failed to create path %(path)s (Permission denied).", path=filepath), category="error") + return redirect(url_for('web.index')) + try: + copyfile(meta.file_path, saved_filename) + except OSError: + flash(_(u"Failed to store file %(file)s (Permission denied).", file=saved_filename), category="error") + return redirect(url_for('web.index')) + try: + os.unlink(meta.file_path) + except OSError: + flash(_(u"Failed to delete file %(file)s (Permission denied).", file= meta.file_path), + category="warning") + + if meta.cover is None: + has_cover = 0 + copyfile(os.path.join(constants.STATIC_DIR, 'generic_cover.jpg'), + os.path.join(filepath, "cover.jpg")) + else: + has_cover = 1 + move(meta.cover, os.path.join(filepath, "cover.jpg")) + + # handle authors + is_author = db.session.query(db.Authors).filter(db.Authors.name == authr).first() + if is_author: + db_author = is_author + else: + db_author = db.Authors(authr, helper.get_sorted_author(authr), "") + db.session.add(db_author) + + # handle series + db_series = None + is_series = db.session.query(db.Series).filter(db.Series.name == series).first() + if is_series: + db_series = is_series + elif series != '': + db_series = db.Series(series, "") + db.session.add(db_series) + + # add language actually one value in list + input_language = meta.languages + db_language = None + if input_language != "": + input_language = isoLanguages.get(name=input_language).part3 + hasLanguage = db.session.query(db.Languages).filter(db.Languages.lang_code == input_language).first() + if hasLanguage: + db_language = hasLanguage + else: + db_language = db.Languages(input_language) + db.session.add(db_language) + + # combine path and normalize path from windows systems + path = os.path.join(author_dir, title_dir).replace('\\', '/') + db_book = db.Books(title, "", db_author.sort, datetime.datetime.now(), datetime.datetime(101, 1, 1), + series_index, datetime.datetime.now(), path, has_cover, db_author, [], db_language) + db_book.authors.append(db_author) + if db_series: + db_book.series.append(db_series) + if db_language is not None: + db_book.languages.append(db_language) + file_size = os.path.getsize(saved_filename) + db_data = db.Data(db_book, meta.extension.upper()[1:], file_size, title_dir) + + # handle tags + input_tags = tags.split(',') + input_tags = list(map(lambda it: it.strip(), input_tags)) + if input_tags[0] !="": + modify_database_object(input_tags, db_book.tags, db.Tags, db.session, 'tags') + + # flush content, get db_book.id available + db_book.data.append(db_data) + db.session.add(db_book) + db.session.flush() + + # add comment + book_id = db_book.id + upload_comment = Markup(meta.description).unescape() + if upload_comment != "": + db.session.add(db.Comments(upload_comment, book_id)) + + # save data to database, reread data + db.session.commit() + db.update_title_sort(config) + book = db.session.query(db.Books).filter(db.Books.id == book_id).filter(common_filters()).first() + + # upload book to gdrive if nesseccary and add "(bookid)" to folder name + if config.config_use_google_drive: + gdriveutils.updateGdriveCalibreFromLocal() + error = helper.update_dir_stucture(book.id, config.config_calibre_dir) + db.session.commit() + if config.config_use_google_drive: + gdriveutils.updateGdriveCalibreFromLocal() + if error: + flash(error, category="error") + uploadText=_(u"File %(file)s uploaded", file=book.title) + global_WorkerThread.add_upload(current_user.nickname, + "" + uploadText + "") + + # create data for displaying display Full language name instead of iso639.part3language + if db_language is not None: + book.languages[0].language_name = _(meta.languages) + author_names = [] + for author in db_book.authors: + author_names.append(author.name) + if len(request.files.getlist("btn-upload")) < 2: + if current_user.role_edit() or current_user.role_admin(): + resp = {"location": url_for('editbook.edit_book', book_id=db_book.id)} + return Response(json.dumps(resp), mimetype='application/json') + else: + resp = {"location": url_for('web.show_book', book_id=db_book.id)} + return Response(json.dumps(resp), mimetype='application/json') + return Response(json.dumps({"location": url_for("web.index")}), mimetype='application/json') + + +@editbook.route("/admin/book/convert/", methods=['POST']) +@login_required_if_no_ano +@edit_required +def convert_bookformat(book_id): + # check to see if we have form fields to work with - if not send user back + book_format_from = request.form.get('book_format_from', None) + book_format_to = request.form.get('book_format_to', None) + + if (book_format_from is None) or (book_format_to is None): + flash(_(u"Source or destination format for conversion missing"), category="error") + return redirect(request.environ["HTTP_REFERER"]) + + log.info('converting: book id: %s from: %s to: %s', book_id, book_format_from, book_format_to) + rtn = helper.convert_book_format(book_id, config.config_calibre_dir, book_format_from.upper(), + book_format_to.upper(), current_user.nickname) + + if rtn is None: + flash(_(u"Book successfully queued for converting to %(book_format)s", + book_format=book_format_to), + category="success") + else: + flash(_(u"There was an error converting this book: %(res)s", res=rtn), category="error") + return redirect(request.environ["HTTP_REFERER"]) diff --git a/cps/epub.py b/cps/epub.py index 913feaca..d9129646 100644 --- a/cps/epub.py +++ b/cps/epub.py @@ -17,11 +17,13 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . +from __future__ import division, print_function, unicode_literals +import os import zipfile from lxml import etree -import os -import uploader -import isoLanguages + +from . import isoLanguages +from .constants import BookMeta def extractCover(zipFile, coverFile, coverpath, tmp_file_name): @@ -125,7 +127,7 @@ def get_epub_info(tmp_file_path, original_file_name, original_file_extension): else: title = epub_metadata['title'] - return uploader.BookMeta( + return BookMeta( file_path=tmp_file_path, extension=original_file_extension, title=title.encode('utf-8').decode('utf-8'), diff --git a/cps/fb2.py b/cps/fb2.py index adcac758..cd61b511 100644 --- a/cps/fb2.py +++ b/cps/fb2.py @@ -17,8 +17,10 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . +from __future__ import division, print_function, unicode_literals from lxml import etree -import uploader + +from .constants import BookMeta def get_fb2_info(tmp_file_path, original_file_extension): @@ -66,7 +68,7 @@ def get_fb2_info(tmp_file_path, original_file_extension): else: description = u'' - return uploader.BookMeta( + return BookMeta( file_path=tmp_file_path, extension=original_file_extension, title=title.decode('utf-8'), diff --git a/cps/gdrive.py b/cps/gdrive.py new file mode 100644 index 00000000..263c829b --- /dev/null +++ b/cps/gdrive.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web) +# Copyright (C) 2018-2019 OzzieIsaacs, cervinko, jkrehm, bodybybuddha, ok11, +# andy29485, idalin, Kyosfonica, wuqi, Kennyl, lemmsh, +# falgh1, grunjol, csitko, ytils, xybydy, trasba, vrabe, +# ruben-herold, marblepebble, JackED42, SiphonSquirrel, +# apetresc, nanu-c, mutschler +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from __future__ import division, print_function, unicode_literals +import os +import hashlib +import json +import tempfile +from uuid import uuid4 +from time import time +from shutil import move, copyfile + +from flask import Blueprint, flash, request, redirect, url_for, abort +from flask_babel import gettext as _ +from flask_login import login_required + +try: + from googleapiclient.errors import HttpError +except ImportError: + pass + +from . import logger, gdriveutils, config, db +from .web import admin_required + + +gdrive = Blueprint('gdrive', __name__) +log = logger.create() + +current_milli_time = lambda: int(round(time() * 1000)) + +gdrive_watch_callback_token = 'target=calibreweb-watch_files' + + +@gdrive.route("/gdrive/authenticate") +@login_required +@admin_required +def authenticate_google_drive(): + try: + authUrl = gdriveutils.Gauth.Instance().auth.GetAuthUrl() + except gdriveutils.InvalidConfigError: + flash(_(u'Google Drive setup not completed, try to deactivate and activate Google Drive again'), + category="error") + return redirect(url_for('web.index')) + return redirect(authUrl) + + +@gdrive.route("/gdrive/callback") +def google_drive_callback(): + auth_code = request.args.get('code') + if not auth_code: + abort(403) + try: + credentials = gdriveutils.Gauth.Instance().auth.flow.step2_exchange(auth_code) + with open(gdriveutils.CREDENTIALS, 'w') as f: + f.write(credentials.to_json()) + except ValueError as error: + log.error(error) + return redirect(url_for('admin.configuration')) + + +@gdrive.route("/gdrive/watch/subscribe") +@login_required +@admin_required +def watch_gdrive(): + if not config.config_google_drive_watch_changes_response: + with open(gdriveutils.CLIENT_SECRETS, 'r') as settings: + filedata = json.load(settings) + if filedata['web']['redirect_uris'][0].endswith('/'): + filedata['web']['redirect_uris'][0] = filedata['web']['redirect_uris'][0][:-((len('/gdrive/callback')+1))] + else: + filedata['web']['redirect_uris'][0] = filedata['web']['redirect_uris'][0][:-(len('/gdrive/callback'))] + address = '%s/gdrive/watch/callback' % filedata['web']['redirect_uris'][0] + notification_id = str(uuid4()) + try: + result = gdriveutils.watchChange(gdriveutils.Gdrive.Instance().drive, notification_id, + 'web_hook', address, gdrive_watch_callback_token, current_milli_time() + 604800*1000) + config.config_google_drive_watch_changes_response = json.dumps(result) + # after save(), config_google_drive_watch_changes_response will be a json object, not string + config.save() + except HttpError as e: + reason=json.loads(e.content)['error']['errors'][0] + if reason['reason'] == u'push.webhookUrlUnauthorized': + flash(_(u'Callback domain is not verified, please follow steps to verify domain in google developer console'), category="error") + else: + flash(reason['message'], category="error") + + return redirect(url_for('admin.configuration')) + + +@gdrive.route("/gdrive/watch/revoke") +@login_required +@admin_required +def revoke_watch_gdrive(): + last_watch_response = config.config_google_drive_watch_changes_response + if last_watch_response: + try: + gdriveutils.stopChannel(gdriveutils.Gdrive.Instance().drive, last_watch_response['id'], + last_watch_response['resourceId']) + except HttpError: + pass + config.config_google_drive_watch_changes_response = None + config.save() + return redirect(url_for('admin.configuration')) + + +@gdrive.route("/gdrive/watch/callback", methods=['GET', 'POST']) +def on_received_watch_confirmation(): + log.debug('%r', request.headers) + if request.headers.get('X-Goog-Channel-Token') == gdrive_watch_callback_token \ + and request.headers.get('X-Goog-Resource-State') == 'change' \ + and request.data: + + data = request.data + + def updateMetaData(): + log.info('Change received from gdrive') + log.debug('%r', data) + try: + j = json.loads(data) + log.info('Getting change details') + response = gdriveutils.getChangeById(gdriveutils.Gdrive.Instance().drive, j['id']) + log.debug('%r', response) + if response: + dbpath = os.path.join(config.config_calibre_dir, "metadata.db") + if not response['deleted'] and response['file']['title'] == 'metadata.db' and response['file']['md5Checksum'] != hashlib.md5(dbpath): + tmpDir = tempfile.gettempdir() + log.info('Database file updated') + copyfile(dbpath, os.path.join(tmpDir, "metadata.db_" + str(current_milli_time()))) + log.info('Backing up existing and downloading updated metadata.db') + gdriveutils.downloadFile(None, "metadata.db", os.path.join(tmpDir, "tmp_metadata.db")) + log.info('Setting up new DB') + # prevent error on windows, as os.rename does on exisiting files + move(os.path.join(tmpDir, "tmp_metadata.db"), dbpath) + db.setup_db(config) + except Exception as e: + log.exception(e) + updateMetaData() + return '' diff --git a/cps/gdriveutils.py b/cps/gdriveutils.py index cacddfbd..4ec7f68e 100644 --- a/cps/gdriveutils.py +++ b/cps/gdriveutils.py @@ -17,24 +17,37 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . +from __future__ import division, print_function, unicode_literals +import os +import json +import shutil + +from flask import Response, stream_with_context +from sqlalchemy import create_engine +from sqlalchemy import Column, UniqueConstraint +from sqlalchemy import String, Integer +from sqlalchemy.orm import sessionmaker, scoped_session +from sqlalchemy.ext.declarative import declarative_base + try: from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive - from pydrive.auth import RefreshError, InvalidConfigError + from pydrive.auth import RefreshError from apiclient import errors gdrive_support = True except ImportError: gdrive_support = False -import os -from ub import config -import cli -import shutil -from flask import Response, stream_with_context -from sqlalchemy import * -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import * -import web +from . import logger, cli, config +from .constants import BASE_DIR as _BASE_DIR + + +SETTINGS_YAML = os.path.join(_BASE_DIR, 'settings.yaml') +CREDENTIALS = os.path.join(_BASE_DIR, 'gdrive_credentials') +CLIENT_SECRETS = os.path.join(_BASE_DIR, 'client_secrets.json') + +log = logger.create() + class Singleton: """ @@ -67,6 +80,9 @@ class Singleton: except AttributeError: self._instance = self._decorated() return self._instance + except ImportError as e: + log.debug(e) + return None def __call__(self): raise TypeError('Singletons must be accessed through `Instance()`.') @@ -78,7 +94,7 @@ class Singleton: @Singleton class Gauth: def __init__(self): - self.auth = GoogleAuth(settings_file=os.path.join(config.get_main_dir,'settings.yaml')) + self.auth = GoogleAuth(settings_file=SETTINGS_YAML) @Singleton @@ -86,6 +102,9 @@ class Gdrive: def __init__(self): self.drive = getDrive(gauth=Gauth.Instance().auth) +def is_gdrive_ready(): + return os.path.exists(SETTINGS_YAML) and os.path.exists(CREDENTIALS) + engine = create_engine('sqlite:///{0}'.format(cli.gdpath), echo=False) Base = declarative_base() @@ -146,17 +165,17 @@ migrate() def getDrive(drive=None, gauth=None): if not drive: if not gauth: - gauth = GoogleAuth(settings_file=os.path.join(config.get_main_dir,'settings.yaml')) + gauth = GoogleAuth(settings_file=SETTINGS_YAML) # Try to load saved client credentials - gauth.LoadCredentialsFile(os.path.join(config.get_main_dir,'gdrive_credentials')) + gauth.LoadCredentialsFile(CREDENTIALS) if gauth.access_token_expired: # Refresh them if expired try: gauth.Refresh() except RefreshError as e: - web.app.logger.error("Google Drive error: " + e.message) + log.error("Google Drive error: %s", e) except Exception as e: - web.app.logger.exception(e) + log.exception(e) else: # Initialize the saved creds gauth.Authorize() @@ -166,7 +185,7 @@ def getDrive(drive=None, gauth=None): try: drive.auth.Refresh() except RefreshError as e: - web.app.logger.error("Google Drive error: " + e.message) + log.error("Google Drive error: %s", e) return drive def listRootFolders(): @@ -203,7 +222,7 @@ def getEbooksFolderId(drive=None): try: gDriveId.gdrive_id = getEbooksFolder(drive)['id'] except Exception: - web.app.logger.error('Error gDrive, root ID not found') + log.error('Error gDrive, root ID not found') gDriveId.path = '/' session.merge(gDriveId) session.commit() @@ -443,10 +462,10 @@ def getChangeById (drive, change_id): change = drive.auth.service.changes().get(changeId=change_id).execute() return change except (errors.HttpError) as error: - web.app.logger.info(error.message) + log.error(error) return None except Exception as e: - web.app.logger.info(e) + log.error(e) return None @@ -516,6 +535,54 @@ def do_gdrive_download(df, headers): if resp.status == 206: yield content else: - web.app.logger.info('An error occurred: %s' % resp) + log.warning('An error occurred: %s', resp) return return Response(stream_with_context(stream()), headers=headers) + + +_SETTINGS_YAML_TEMPLATE = """ +client_config_backend: settings +client_config_file: %(client_file)s +client_config: + client_id: %(client_id)s + client_secret: %(client_secret)s + redirect_uri: %(redirect_uri)s + +save_credentials: True +save_credentials_backend: file +save_credentials_file: %(credential)s + +get_refresh_token: True + +oauth_scope: + - https://www.googleapis.com/auth/drive +""" + +def update_settings(client_id, client_secret, redirect_uri): + if redirect_uri.endswith('/'): + redirect_uri = redirect_uri[:-1] + config_params = { + 'client_file': CLIENT_SECRETS, + 'client_id': client_id, + 'client_secret': client_secret, + 'redirect_uri': redirect_uri, + 'credential': CREDENTIALS + } + + with open(SETTINGS_YAML, 'w') as f: + f.write(_SETTINGS_YAML_TEMPLATE % config_params) + + +def get_error_text(client_secrets=None): + if not gdrive_support: + return 'Import of optional Google Drive requirements missing' + + if not os.path.isfile(CLIENT_SECRETS): + return 'client_secrets.json is missing or not readable' + + with open(CLIENT_SECRETS, 'r') as settings: + filedata = json.load(settings) + if 'web' not in filedata: + return 'client_secrets.json is not configured for web application' + if client_secrets: + client_secrets.update(filedata['web']) diff --git a/cps/helper.py b/cps/helper.py index 1b233cad..1ceeb0b8 100644 --- a/cps/helper.py +++ b/cps/helper.py @@ -18,33 +18,35 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . - -import db -import ub -from flask import current_app as app -from tempfile import gettempdir +from __future__ import division, print_function, unicode_literals import sys -import io import os +import io +import json +import mimetypes +import random import re -import unicodedata -import worker +import shutil import time +import unicodedata +from datetime import datetime, timedelta +from tempfile import gettempdir + +import requests +from babel import Locale as LC +from babel.core import UnknownLocaleError +from babel.dates import format_datetime +from babel.units import format_unit from flask import send_from_directory, make_response, redirect, abort from flask_babel import gettext as _ from flask_login import current_user -from babel.dates import format_datetime -from babel.units import format_unit -from datetime import datetime, timedelta -import shutil -import requests +from sqlalchemy.sql.expression import true, false, and_, or_, text, func +from werkzeug.datastructures import Headers + try: - import gdriveutils as gd + from urllib.parse import quote except ImportError: - pass -import web -import random -import subprocess + from urllib import quote try: import unidecode @@ -58,10 +60,16 @@ try: except ImportError: use_PIL = False -# Global variables -# updater_thread = None -global_WorkerThread = worker.WorkerThread() -global_WorkerThread.start() +from . import logger, config, global_WorkerThread, get_locale, db, ub, isoLanguages +from . import gdriveutils as gd +from .constants import STATIC_DIR as _STATIC_DIR +from .pagination import Pagination +from .subproc_wrapper import process_wait +from .worker import STAT_WAITING, STAT_FAIL, STAT_STARTED, STAT_FINISH_SUCCESS +from .worker import TASK_EMAIL, TASK_CONVERT, TASK_UPLOAD, TASK_CONVERT_ANY + + +log = logger.create() def update_download(book_id, user_id): @@ -78,9 +86,9 @@ def convert_book_format(book_id, calibrepath, old_book_format, new_book_format, data = db.session.query(db.Data).filter(db.Data.book == book.id).filter(db.Data.format == old_book_format).first() if not data: error_message = _(u"%(format)s format not found for book id: %(book)d", format=old_book_format, book=book_id) - app.logger.error("convert_book_format: " + error_message) + log.error("convert_book_format: %s", error_message) return error_message - if ub.config.config_use_google_drive: + if config.config_use_google_drive: df = gd.getFileFromEbooksFolder(book.path, data.name + "." + old_book_format.lower()) if df: datafile = os.path.join(calibrepath, book.path, data.name + u"." + old_book_format.lower()) @@ -95,7 +103,7 @@ def convert_book_format(book_id, calibrepath, old_book_format, new_book_format, if os.path.exists(file_path + "." + old_book_format.lower()): # read settings and append converter task to queue if kindle_mail: - settings = ub.get_mail_settings() + settings = config.get_mail_settings() settings['subject'] = _('Send to Kindle') # pretranslate Subject for e-mail settings['body'] = _(u'This e-mail has been sent via Calibre-Web.') # text = _(u"%(format)s: %(book)s", format=new_book_format, book=book.title) @@ -113,7 +121,7 @@ def convert_book_format(book_id, calibrepath, old_book_format, new_book_format, def send_test_mail(kindle_mail, user_name): - global_WorkerThread.add_email(_(u'Calibre-Web test e-mail'),None, None, ub.get_mail_settings(), + global_WorkerThread.add_email(_(u'Calibre-Web test e-mail'),None, None, config.get_mail_settings(), kindle_mail, user_name, _(u"Test e-mail"), _(u'This e-mail has been sent via Calibre-Web.')) return @@ -130,17 +138,18 @@ def send_registration_mail(e_mail, user_name, default_password, resend=False): text += "Don't forget to change your password after first login.\r\n" text += "Sincerely\r\n\r\n" text += "Your Calibre-Web team" - global_WorkerThread.add_email(_(u'Get Started with Calibre-Web'),None, None, ub.get_mail_settings(), + global_WorkerThread.add_email(_(u'Get Started with Calibre-Web'),None, None, config.get_mail_settings(), e_mail, None, _(u"Registration e-mail for user: %(name)s", name=user_name), text) return + def check_send_to_kindle(entry): """ returns all available book formats for sending to Kindle """ if len(entry.data): bookformats=list() - if ub.config.config_ebookconverter == 0: + if config.config_ebookconverter == 0: # no converter - only for mobi and pdf formats for ele in iter(entry.data): if 'MOBI' in ele.format: @@ -161,17 +170,17 @@ def check_send_to_kindle(entry): bookformats.append({'format': 'Azw','convert':0,'text':_('Send %(format)s to Kindle',format='Azw')}) if 'PDF' in formats: bookformats.append({'format': 'Pdf','convert':0,'text':_('Send %(format)s to Kindle',format='Pdf')}) - if ub.config.config_ebookconverter >= 1: + if config.config_ebookconverter >= 1: if 'EPUB' in formats and not 'MOBI' in formats: bookformats.append({'format': 'Mobi','convert':1, 'text':_('Convert %(orig)s to %(format)s and send to Kindle',orig='Epub',format='Mobi')}) - '''if ub.config.config_ebookconverter == 2: + '''if config.config_ebookconverter == 2: if 'EPUB' in formats and not 'AZW3' in formats: bookformats.append({'format': 'Azw3','convert':1, 'text':_('Convert %(orig)s to %(format)s and send to Kindle',orig='Epub',format='Azw3')})''' return bookformats else: - app.logger.error(u'Cannot find book entry %d', entry.id) + log.error(u'Cannot find book entry %d', entry.id) return None @@ -202,7 +211,7 @@ def send_mail(book_id, book_format, convert, kindle_mail, calibrepath, user_id): for entry in iter(book.data): if entry.format.upper() == book_format.upper(): result = entry.name + '.' + book_format.lower() - global_WorkerThread.add_email(_(u"Send to Kindle"), book.path, result, ub.get_mail_settings(), + global_WorkerThread.add_email(_(u"Send to Kindle"), book.path, result, config.get_mail_settings(), kindle_mail, user_id, _(u"E-mail: %(book)s", book=book.title), _(u'This e-mail has been sent via Calibre-Web.')) return @@ -256,8 +265,8 @@ def get_sorted_author(value): value2 = value[-1] + ", " + " ".join(value[:-1]) else: value2 = value - except Exception: - web.app.logger.error("Sorting author " + str(value) + "failed") + except Exception as ex: + log.error("Sorting author %s failed: %s", value, ex) value2 = value return value2 @@ -274,13 +283,12 @@ def delete_book_file(book, calibrepath, book_format=None): else: if os.path.isdir(path): if len(next(os.walk(path))[1]): - web.app.logger.error( - "Deleting book " + str(book.id) + " failed, path has subfolders: " + book.path) + log.error("Deleting book %s failed, path has subfolders: %s", book.id, book.path) return False shutil.rmtree(path, ignore_errors=True) return True else: - web.app.logger.error("Deleting book " + str(book.id) + " failed, book path not valid: " + book.path) + log.error("Deleting book %s failed, book path not valid: %s", book.id, book.path) return False @@ -303,16 +311,16 @@ def update_dir_structure_file(book_id, calibrepath, first_author): if not os.path.exists(new_title_path): os.renames(path, new_title_path) else: - web.app.logger.info("Copying title: " + path + " into existing: " + new_title_path) - for dir_name, subdir_list, file_list in os.walk(path): + log.info("Copying title: %s into existing: %s", path, new_title_path) + for dir_name, __, file_list in os.walk(path): for file in file_list: os.renames(os.path.join(dir_name, file), os.path.join(new_title_path + dir_name[len(path):], file)) path = new_title_path localbook.path = localbook.path.split('/')[0] + '/' + new_titledir except OSError as ex: - web.app.logger.error("Rename title from: " + path + " to " + new_title_path + ": " + str(ex)) - web.app.logger.debug(ex, exc_info=True) + log.error("Rename title from: %s to %s: %s", path, new_title_path, ex) + log.debug(ex, exc_info=True) return _("Rename title from: '%(src)s' to '%(dest)s' failed with error: %(error)s", src=path, dest=new_title_path, error=str(ex)) if authordir != new_authordir: @@ -321,8 +329,8 @@ def update_dir_structure_file(book_id, calibrepath, first_author): os.renames(path, new_author_path) localbook.path = new_authordir + '/' + localbook.path.split('/')[1] except OSError as ex: - web.app.logger.error("Rename author from: " + path + " to " + new_author_path + ": " + str(ex)) - web.app.logger.debug(ex, exc_info=True) + log.error("Rename author from: %s to %s: %s", path, new_author_path, ex) + log.debug(ex, exc_info=True) return _("Rename author from: '%(src)s' to '%(dest)s' failed with error: %(error)s", src=path, dest=new_author_path, error=str(ex)) # Rename all files from old names to new names @@ -335,8 +343,8 @@ def update_dir_structure_file(book_id, calibrepath, first_author): os.path.join(path_name, new_name + '.' + file_format.format.lower())) file_format.name = new_name except OSError as ex: - web.app.logger.error("Rename file in path " + path + " to " + new_name + ": " + str(ex)) - web.app.logger.debug(ex, exc_info=True) + log.error("Rename file in path %s to %s: %s", path, new_name, ex) + log.debug(ex, exc_info=True) return _("Rename file in path '%(src)s' to '%(dest)s' failed with error: %(error)s", src=path, dest=new_name, error=str(ex)) return False @@ -415,37 +423,45 @@ def generate_random_password(): ################################## External interface def update_dir_stucture(book_id, calibrepath, first_author = None): - if ub.config.config_use_google_drive: + if config.config_use_google_drive: return update_dir_structure_gdrive(book_id, first_author) else: return update_dir_structure_file(book_id, calibrepath, first_author) def delete_book(book, calibrepath, book_format): - if ub.config.config_use_google_drive: + if config.config_use_google_drive: return delete_book_gdrive(book, book_format) else: return delete_book_file(book, calibrepath, book_format) -def get_book_cover(cover_path): - if ub.config.config_use_google_drive: - try: - if not web.is_gdrive_ready(): - return send_from_directory(os.path.join(os.path.dirname(__file__), "static"), "generic_cover.jpg") - path=gd.get_cover_via_gdrive(cover_path) - if path: - return redirect(path) +def get_book_cover(book_id): + book = db.session.query(db.Books).filter(db.Books.id == book_id).first() + if book.has_cover: + + if config.config_use_google_drive: + try: + if not gd.is_gdrive_ready(): + return send_from_directory(_STATIC_DIR, "generic_cover.jpg") + path=gd.get_cover_via_gdrive(book.path) + if path: + return redirect(path) + else: + log.error('%s/cover.jpg not found on Google Drive', book.path) + return send_from_directory(_STATIC_DIR, "generic_cover.jpg") + except Exception as e: + log.exception(e) + # traceback.print_exc() + return send_from_directory(_STATIC_DIR,"generic_cover.jpg") + else: + cover_file_path = os.path.join(config.config_calibre_dir, book.path) + if os.path.isfile(os.path.join(cover_file_path, "cover.jpg")): + return send_from_directory(cover_file_path, "cover.jpg") else: - web.app.logger.error(cover_path + '/cover.jpg not found on Google Drive') - return send_from_directory(os.path.join(os.path.dirname(__file__), "static"), "generic_cover.jpg") - except Exception as e: - web.app.logger.error("Error Message: " + e.message) - web.app.logger.exception(e) - # traceback.print_exc() - return send_from_directory(os.path.join(os.path.dirname(__file__), "static"),"generic_cover.jpg") + return send_from_directory(_STATIC_DIR,"generic_cover.jpg") else: - return send_from_directory(os.path.join(ub.config.config_calibre_dir, cover_path), "cover.jpg") + return send_from_directory(_STATIC_DIR,"generic_cover.jpg") # saves book cover from url @@ -455,7 +471,7 @@ def save_cover_from_url(url, book_path): def save_cover_from_filestorage(filepath, saved_filename, img): - if hasattr(img,'_content'): + if hasattr(img, '_content'): f = open(os.path.join(filepath, saved_filename), "wb") f.write(img._content) f.close() @@ -465,15 +481,15 @@ def save_cover_from_filestorage(filepath, saved_filename, img): try: os.makedirs(filepath) except OSError: - web.app.logger.error(u"Failed to create path for cover") + log.error(u"Failed to create path for cover") return False try: img.save(os.path.join(filepath, saved_filename)) - except OSError: - web.app.logger.error(u"Failed to store cover-file") - return False except IOError: - web.app.logger.error(u"Cover-file is not a valid image file") + log.error(u"Cover-file is not a valid image file") + return False + except OSError: + log.error(u"Failed to store cover-file") return False return True @@ -484,7 +500,7 @@ def save_cover(img, book_path): if use_PIL: if content_type not in ('image/jpeg', 'image/png', 'image/webp'): - web.app.logger.error("Only jpg/jpeg/png/webp files are supported as coverfile") + log.error("Only jpg/jpeg/png/webp files are supported as coverfile") return False # convert to jpg because calibre only supports jpg if content_type in ('image/png', 'image/webp'): @@ -498,7 +514,7 @@ def save_cover(img, book_path): img._content = tmp_bytesio.getvalue() else: if content_type not in ('image/jpeg'): - web.app.logger.error("Only jpg/jpeg files are supported as coverfile") + log.error("Only jpg/jpeg files are supported as coverfile") return False if ub.config.config_use_google_drive: @@ -506,29 +522,29 @@ def save_cover(img, book_path): if save_cover_from_filestorage(tmpDir, "uploaded_cover.jpg", img) is True: gd.uploadFileToEbooksFolder(os.path.join(book_path, 'cover.jpg'), os.path.join(tmpDir, "uploaded_cover.jpg")) - web.app.logger.info("Cover is saved on Google Drive") + log.info("Cover is saved on Google Drive") return True else: return False else: - return save_cover_from_filestorage(os.path.join(ub.config.config_calibre_dir, book_path), "cover.jpg", img) + return save_cover_from_filestorage(os.path.join(config.config_calibre_dir, book_path), "cover.jpg", img) def do_download_file(book, book_format, data, headers): - if ub.config.config_use_google_drive: + if config.config_use_google_drive: startTime = time.time() df = gd.getFileFromEbooksFolder(book.path, data.name + "." + book_format) - web.app.logger.debug(time.time() - startTime) + log.debug('%s', time.time() - startTime) if df: return gd.do_gdrive_download(df, headers) else: abort(404) else: - filename = os.path.join(ub.config.config_calibre_dir, book.path) + filename = os.path.join(config.config_calibre_dir, book.path) if not os.path.isfile(os.path.join(filename, data.name + "." + book_format)): # ToDo: improve error handling - web.app.logger.error('File not found: %s' % os.path.join(filename, data.name + "." + book_format)) + log.error('File not found: %s', os.path.join(filename, data.name + "." + book_format)) response = make_response(send_from_directory(filename, data.name + "." + book_format)) response.headers = headers return response @@ -538,27 +554,23 @@ def do_download_file(book, book_format, data, headers): def check_unrar(unrarLocation): - error = False - if os.path.exists(unrarLocation): - try: - if sys.version_info < (3, 0): - unrarLocation = unrarLocation.encode(sys.getfilesystemencoding()) - p = subprocess.Popen(unrarLocation, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - p.wait() - for lines in p.stdout.readlines(): - if isinstance(lines, bytes): - lines = lines.decode('utf-8') - value=re.search('UNRAR (.*) freeware', lines) - if value: - version = value.group(1) - except OSError as e: - error = True - web.app.logger.exception(e) - version =_(u'Error excecuting UnRar') - else: - version = _(u'Unrar binary file not found') - error=True - return (error, version) + if not unrarLocation: + return + + if not os.path.exists(unrarLocation): + return 'Unrar binary file not found' + + try: + if sys.version_info < (3, 0): + unrarLocation = unrarLocation.encode(sys.getfilesystemencoding()) + for lines in process_wait(unrarLocation): + value = re.search('UNRAR (.*) freeware', lines) + if value: + version = value.group(1) + log.debug("unrar version %s", version) + except OSError as err: + log.exception(err) + return 'Error excecuting UnRar' @@ -574,6 +586,7 @@ def json_serial(obj): 'seconds': obj.seconds, 'microseconds': obj.microseconds, } + # return obj.isoformat() raise TypeError ("Type %s not serializable" % type(obj)) @@ -581,7 +594,7 @@ def json_serial(obj): def format_runtime(runtime): retVal = "" if runtime.days: - retVal = format_unit(runtime.days, 'duration-day', length="long", locale=web.get_locale()) + ', ' + retVal = format_unit(runtime.days, 'duration-day', length="long", locale=get_locale()) + ', ' mins, seconds = divmod(runtime.seconds, 60) hours, minutes = divmod(mins, 60) # ToDo: locale.number_symbols._data['timeSeparator'] -> localize time separator ? @@ -600,7 +613,8 @@ def render_task_status(tasklist): for task in tasklist: if task['user'] == current_user.nickname or current_user.role_admin(): if task['formStarttime']: - task['starttime'] = format_datetime(task['formStarttime'], format='short', locale=web.get_locale()) + task['starttime'] = format_datetime(task['formStarttime'], format='short', locale=get_locale()) + # task2['formStarttime'] = "" else: if 'starttime' not in task: task['starttime'] = "" @@ -612,26 +626,26 @@ def render_task_status(tasklist): # localize the task status if isinstance( task['stat'], int ): - if task['stat'] == worker.STAT_WAITING: + if task['stat'] == STAT_WAITING: task['status'] = _(u'Waiting') - elif task['stat'] == worker.STAT_FAIL: + elif task['stat'] == STAT_FAIL: task['status'] = _(u'Failed') - elif task['stat'] == worker.STAT_STARTED: + elif task['stat'] == STAT_STARTED: task['status'] = _(u'Started') - elif task['stat'] == worker.STAT_FINISH_SUCCESS: + elif task['stat'] == STAT_FINISH_SUCCESS: task['status'] = _(u'Finished') else: task['status'] = _(u'Unknown Status') # localize the task type if isinstance( task['taskType'], int ): - if task['taskType'] == worker.TASK_EMAIL: + if task['taskType'] == TASK_EMAIL: task['taskMessage'] = _(u'E-mail: ') + task['taskMess'] - elif task['taskType'] == worker.TASK_CONVERT: + elif task['taskType'] == TASK_CONVERT: task['taskMessage'] = _(u'Convert: ') + task['taskMess'] - elif task['taskType'] == worker.TASK_UPLOAD: + elif task['taskType'] == TASK_UPLOAD: task['taskMessage'] = _(u'Upload: ') + task['taskMess'] - elif task['taskType'] == worker.TASK_CONVERT_ANY: + elif task['taskType'] == TASK_CONVERT_ANY: task['taskMessage'] = _(u'Convert: ') + task['taskMess'] else: task['taskMessage'] = _(u'Unknown Task: ') + task['taskMess'] @@ -639,3 +653,135 @@ def render_task_status(tasklist): renderedtasklist.append(task) return renderedtasklist + + +# Language and content filters for displaying in the UI +def common_filters(): + if current_user.filter_language() != "all": + lang_filter = db.Books.languages.any(db.Languages.lang_code == current_user.filter_language()) + else: + lang_filter = true() + content_rating_filter = false() if current_user.mature_content else \ + db.Books.tags.any(db.Tags.name.in_(config.mature_content_tags())) + return and_(lang_filter, ~content_rating_filter) + + +# Creates for all stored languages a translated speaking name in the array for the UI +def speaking_language(languages=None): + if not languages: + languages = db.session.query(db.Languages).all() + for lang in languages: + try: + cur_l = LC.parse(lang.lang_code) + lang.name = cur_l.get_language_name(get_locale()) + except UnknownLocaleError: + lang.name = _(isoLanguages.get(part3=lang.lang_code).name) + return languages + +# checks if domain is in database (including wildcards) +# example SELECT * FROM @TABLE WHERE 'abcdefg' LIKE Name; +# from https://code.luasoftware.com/tutorials/flask/execute-raw-sql-in-flask-sqlalchemy/ +def check_valid_domain(domain_text): + domain_text = domain_text.split('@', 1)[-1].lower() + sql = "SELECT * FROM registration WHERE :domain LIKE domain;" + result = ub.session.query(ub.Registration).from_statement(text(sql)).params(domain=domain_text).all() + return len(result) + + +# Orders all Authors in the list according to authors sort +def order_authors(entry): + sort_authors = entry.author_sort.split('&') + authors_ordered = list() + error = False + for auth in sort_authors: + # ToDo: How to handle not found authorname + result = db.session.query(db.Authors).filter(db.Authors.sort == auth.lstrip().strip()).first() + if not result: + error = True + break + authors_ordered.append(result) + if not error: + entry.authors = authors_ordered + return entry + + +# Fill indexpage with all requested data from database +def fill_indexpage(page, database, db_filter, order, *join): + if current_user.show_detail_random(): + randm = db.session.query(db.Books).filter(common_filters())\ + .order_by(func.random()).limit(config.config_random_books) + else: + randm = false() + off = int(int(config.config_books_per_page) * (page - 1)) + pagination = Pagination(page, config.config_books_per_page, + len(db.session.query(database).filter(db_filter).filter(common_filters()).all())) + entries = db.session.query(database).join(*join, isouter=True).filter(db_filter).filter(common_filters()).\ + order_by(*order).offset(off).limit(config.config_books_per_page).all() + for book in entries: + book = order_authors(book) + return entries, randm, pagination + + +def get_typeahead(database, query, replace=('','')): + db.session.connection().connection.connection.create_function("lower", 1, lcase) + entries = db.session.query(database).filter(func.lower(database.name).ilike("%" + query + "%")).all() + json_dumps = json.dumps([dict(name=r.name.replace(*replace)) for r in entries]) + return json_dumps + +# read search results from calibre-database and return it (function is used for feed and simple search +def get_search_results(term): + db.session.connection().connection.connection.create_function("lower", 1, lcase) + q = list() + authorterms = re.split("[, ]+", term) + for authorterm in authorterms: + q.append(db.Books.authors.any(func.lower(db.Authors.name).ilike("%" + authorterm + "%"))) + + db.Books.authors.any(func.lower(db.Authors.name).ilike("%" + term + "%")) + + return db.session.query(db.Books).filter(common_filters()).filter( + or_(db.Books.tags.any(func.lower(db.Tags.name).ilike("%" + term + "%")), + db.Books.series.any(func.lower(db.Series.name).ilike("%" + term + "%")), + db.Books.authors.any(and_(*q)), + db.Books.publishers.any(func.lower(db.Publishers.name).ilike("%" + term + "%")), + func.lower(db.Books.title).ilike("%" + term + "%") + )).all() + +def get_cc_columns(): + tmpcc = db.session.query(db.Custom_Columns).filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all() + if config.config_columns_to_ignore: + cc = [] + for col in tmpcc: + r = re.compile(config.config_columns_to_ignore) + if r.match(col.label): + cc.append(col) + else: + cc = tmpcc + return cc + +def get_download_link(book_id, book_format): + book_format = book_format.split(".")[0] + book = db.session.query(db.Books).filter(db.Books.id == book_id).first() + data = db.session.query(db.Data).filter(db.Data.book == book.id)\ + .filter(db.Data.format == book_format.upper()).first() + if data: + # collect downloaded books only for registered user and not for anonymous user + if current_user.is_authenticated: + ub.update_download(book_id, int(current_user.id)) + file_name = book.title + if len(book.authors) > 0: + file_name = book.authors[0].name + '_' + file_name + file_name = get_valid_filename(file_name) + headers = Headers() + headers["Content-Type"] = mimetypes.types_map.get('.' + book_format, "application/octet-stream") + headers["Content-Disposition"] = "attachment; filename*=UTF-8''%s.%s" % (quote(file_name.encode('utf-8')), + book_format) + return do_download_file(book, book_format, data, headers) + else: + abort(404) + + + +############### Database Helper functions + +def lcase(s): + return unidecode.unidecode(s.lower()) diff --git a/cps/isoLanguages.py b/cps/isoLanguages.py index 31ef341e..808d3761 100644 --- a/cps/isoLanguages.py +++ b/cps/isoLanguages.py @@ -17,6 +17,17 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . +from __future__ import division, print_function, unicode_literals +import sys +import os +try: + import cPickle +except ImportError: + import pickle as cPickle + +from .constants import TRANSLATIONS_DIR as _TRANSLATIONS_DIR + + try: from iso639 import languages, __version__ get = languages.get @@ -30,14 +41,43 @@ except ImportError: __version__ = "? (PyCountry)" def _copy_fields(l): - l.part1 = l.alpha_2 - l.part3 = l.alpha_3 + l.part1 = getattr(l, 'alpha_2', None) + l.part3 = getattr(l, 'alpha_3', None) return l def get(name=None, part1=None, part3=None): - if (part3 is not None): + if part3 is not None: return _copy_fields(pyc_languages.get(alpha_3=part3)) - if (part1 is not None): + if part1 is not None: return _copy_fields(pyc_languages.get(alpha_2=part1)) - if (name is not None): + if name is not None: return _copy_fields(pyc_languages.get(name=name)) + + +try: + with open(os.path.join(_TRANSLATIONS_DIR, 'iso639.pickle'), 'rb') as f: + _LANGUAGES = cPickle.load(f) +except cPickle.UnpicklingError as error: + print("Can't read file cps/translations/iso639.pickle: %s" % error) + sys.exit(1) + + +def get_language_names(locale): + return _LANGUAGES.get(locale) + + +def get_language_name(locale, lang_code): + return get_language_names(locale)[lang_code] + + +def get_language_codes(locale, language_names, remainder=None): + language_names = set(x.strip().lower() for x in language_names if x) + + for k, v in get_language_names(locale).items(): + v = v.lower() + if v in language_names: + language_names.remove(v) + yield k + + if remainder is not None: + remainder.extend(language_names) diff --git a/cps/jinjia.py b/cps/jinjia.py new file mode 100644 index 00000000..ffd6832c --- /dev/null +++ b/cps/jinjia.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web) +# Copyright (C) 2018-2019 OzzieIsaacs, cervinko, jkrehm, bodybybuddha, ok11, +# andy29485, idalin, Kyosfonica, wuqi, Kennyl, lemmsh, +# falgh1, grunjol, csitko, ytils, xybydy, trasba, vrabe, +# ruben-herold, marblepebble, JackED42, SiphonSquirrel, +# apetresc, nanu-c, mutschler +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +# custom jinja filters + +from __future__ import division, print_function, unicode_literals +import datetime +import mimetypes +import re + +from babel.dates import format_date +from flask import Blueprint, request, url_for +from flask_babel import get_locale +from flask_login import current_user + +from . import logger + + +jinjia = Blueprint('jinjia', __name__) +log = logger.create() + + +# pagination links in jinja +@jinjia.app_template_filter('url_for_other_page') +def url_for_other_page(page): + args = request.view_args.copy() + args['page'] = page + return url_for(request.endpoint, **args) + + +# shortentitles to at longest nchar, shorten longer words if necessary +@jinjia.app_template_filter('shortentitle') +def shortentitle_filter(s, nchar=20): + text = s.split() + res = "" # result + suml = 0 # overall length + for line in text: + if suml >= 60: + res += '...' + break + # if word longer than 20 chars truncate line and append '...', otherwise add whole word to result + # string, and summarize total length to stop at chars given by nchar + if len(line) > nchar: + res += line[:(nchar-3)] + '[..] ' + suml += nchar+3 + else: + res += line + ' ' + suml += len(line) + 1 + return res.strip() + + +@jinjia.app_template_filter('mimetype') +def mimetype_filter(val): + return mimetypes.types_map.get('.' + val, 'application/octet-stream') + + +@jinjia.app_template_filter('formatdate') +def formatdate_filter(val): + try: + conformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', val) + formatdate = datetime.datetime.strptime(conformed_timestamp[:15], "%Y%m%d %H%M%S") + return format_date(formatdate, format='medium', locale=get_locale()) + except AttributeError as e: + log.error('Babel error: %s, Current user locale: %s, Current User: %s', e, current_user.locale, current_user.nickname) + return formatdate + +@jinjia.app_template_filter('formatdateinput') +def format_date_input(val): + conformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', val) + date_obj = datetime.datetime.strptime(conformed_timestamp[:15], "%Y%m%d %H%M%S") + input_date = date_obj.isoformat().split('T', 1)[0] # Hack to support dates <1900 + return '' if input_date == "0101-01-01" else input_date + + +@jinjia.app_template_filter('strftime') +def timestamptodate(date, fmt=None): + date = datetime.datetime.fromtimestamp( + int(date)/1000 + ) + native = date.replace(tzinfo=None) + if fmt: + time_format = fmt + else: + time_format = '%d %m %Y - %H:%S' + return native.strftime(time_format) + + +@jinjia.app_template_filter('yesno') +def yesno(value, yes, no): + return yes if value else no + + +'''@jinjia.app_template_filter('canread') +def canread(ext): + if isinstance(ext, db.Data): + ext = ext.format + return ext.lower() in EXTENSIONS_READER''' diff --git a/cps/logger.py b/cps/logger.py new file mode 100644 index 00000000..3a540683 --- /dev/null +++ b/cps/logger.py @@ -0,0 +1,164 @@ +# -*- coding: utf-8 -*- + +# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web) +# Copyright (C) 2019 pwr +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from __future__ import division, print_function, unicode_literals +import os +import inspect +import logging +from logging import Formatter, StreamHandler +from logging.handlers import RotatingFileHandler + +from .constants import BASE_DIR as _BASE_DIR + + +ACCESS_FORMATTER_GEVENT = Formatter("%(message)s") +ACCESS_FORMATTER_TORNADO = Formatter("[%(asctime)s] %(message)s") + +FORMATTER = Formatter("[%(asctime)s] %(levelname)5s {%(name)s:%(lineno)d} %(message)s") +DEFAULT_LOG_LEVEL = logging.INFO +DEFAULT_LOG_FILE = os.path.join(_BASE_DIR, "calibre-web.log") +DEFAULT_ACCESS_LOG = os.path.join(_BASE_DIR, "access.log") +LOG_TO_STDERR = '/dev/stderr' + +logging.addLevelName(logging.WARNING, "WARN") +logging.addLevelName(logging.CRITICAL, "CRIT") + + +def get(name=None): + return logging.getLogger(name) + + +def create(): + parent_frame = inspect.stack(0)[1] + if hasattr(parent_frame, 'frame'): + parent_frame = parent_frame.frame + else: + parent_frame = parent_frame[0] + parent_module = inspect.getmodule(parent_frame) + return get(parent_module.__name__) + + +def is_debug_enabled(): + return logging.root.level <= logging.DEBUG + +def is_info_enabled(logger): + return logging.getLogger(logger).level <= logging.INFO + + +def get_level_name(level): + return logging.getLevelName(level) + + +def is_valid_logfile(file_path): + if not file_path: + return True + if os.path.isdir(file_path): + return False + log_dir = os.path.dirname(file_path) + return (not log_dir) or os.path.isdir(log_dir) + + +def _absolute_log_file(log_file, default_log_file): + if log_file: + if not os.path.dirname(log_file): + log_file = os.path.join(_BASE_DIR, log_file) + return os.path.abspath(log_file) + + return default_log_file + + +def get_logfile(log_file): + return _absolute_log_file(log_file, DEFAULT_LOG_FILE) + + +def get_accesslogfile(log_file): + return _absolute_log_file(log_file, DEFAULT_ACCESS_LOG) + + +def setup(log_file, log_level=None): + ''' + Configure the logging output. + May be called multiple times. + ''' + log_file = _absolute_log_file(log_file, DEFAULT_LOG_FILE) + + r = logging.root + r.setLevel(log_level or DEFAULT_LOG_LEVEL) + + previous_handler = r.handlers[0] if r.handlers else None + if previous_handler: + # if the log_file has not changed, don't create a new handler + if getattr(previous_handler, 'baseFilename', None) == log_file: + return + r.debug("logging to %s level %s", log_file, r.level) + + if log_file == LOG_TO_STDERR: + file_handler = StreamHandler() + file_handler.baseFilename = LOG_TO_STDERR + else: + try: + file_handler = RotatingFileHandler(log_file, maxBytes=50000, backupCount=2) + except IOError: + if log_file == DEFAULT_LOG_FILE: + raise + file_handler = RotatingFileHandler(DEFAULT_LOG_FILE, maxBytes=50000, backupCount=2) + file_handler.setFormatter(FORMATTER) + + for h in r.handlers: + r.removeHandler(h) + h.close() + r.addHandler(file_handler) + + +def create_access_log(log_file, log_name, formatter): + ''' + One-time configuration for the web server's access log. + ''' + log_file = _absolute_log_file(log_file, DEFAULT_ACCESS_LOG) + logging.debug("access log: %s", log_file) + + access_log = logging.getLogger(log_name) + access_log.propagate = False + access_log.setLevel(logging.INFO) + + file_handler = RotatingFileHandler(log_file, maxBytes=50000, backupCount=2) + file_handler.setFormatter(formatter) + access_log.addHandler(file_handler) + return access_log + + +# Enable logging of smtp lib debug output +class StderrLogger(object): + def __init__(self, name=None): + self.log = get(name or self.__class__.__name__) + self.buffer = '' + + def write(self, message): + try: + if message == '\n': + self.log.debug(self.buffer.replace('\n', '\\n')) + self.buffer = '' + else: + self.buffer += message + except Exception: + self.log.debug("Logging Error") + + +# if debugging, start logging to stderr immediately +if os.environ.get('FLASK_DEBUG', None): + setup(LOG_TO_STDERR, logging.DEBUG) diff --git a/cps/oauth.py b/cps/oauth.py new file mode 100644 index 00000000..35362dbf --- /dev/null +++ b/cps/oauth.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +from __future__ import division, print_function, unicode_literals +from flask import session + + +try: + from flask_dance.consumer.backend.sqla import SQLAlchemyBackend, first, _get_real_user + from sqlalchemy.orm.exc import NoResultFound + + class OAuthBackend(SQLAlchemyBackend): + """ + Stores and retrieves OAuth tokens using a relational database through + the `SQLAlchemy`_ ORM. + + .. _SQLAlchemy: http://www.sqlalchemy.org/ + """ + def __init__(self, model, session, + user=None, user_id=None, user_required=None, anon_user=None, + cache=None): + super(OAuthBackend, self).__init__(model, session, user, user_id, user_required, anon_user, cache) + + def get(self, blueprint, user=None, user_id=None): + if blueprint.name + '_oauth_token' in session and session[blueprint.name + '_oauth_token'] != '': + return session[blueprint.name + '_oauth_token'] + # check cache + cache_key = self.make_cache_key(blueprint=blueprint, user=user, user_id=user_id) + token = self.cache.get(cache_key) + if token: + return token + + # if not cached, make database queries + query = ( + self.session.query(self.model) + .filter_by(provider=blueprint.name) + ) + uid = first([user_id, self.user_id, blueprint.config.get("user_id")]) + u = first(_get_real_user(ref, self.anon_user) + for ref in (user, self.user, blueprint.config.get("user"))) + + use_provider_user_id = False + if blueprint.name + '_oauth_user_id' in session and session[blueprint.name + '_oauth_user_id'] != '': + query = query.filter_by(provider_user_id=session[blueprint.name + '_oauth_user_id']) + use_provider_user_id = True + + if self.user_required and not u and not uid and not use_provider_user_id: + #raise ValueError("Cannot get OAuth token without an associated user") + return None + # check for user ID + if hasattr(self.model, "user_id") and uid: + query = query.filter_by(user_id=uid) + # check for user (relationship property) + elif hasattr(self.model, "user") and u: + query = query.filter_by(user=u) + # if we have the property, but not value, filter by None + elif hasattr(self.model, "user_id"): + query = query.filter_by(user_id=None) + # run query + try: + token = query.one().token + except NoResultFound: + token = None + + # cache the result + self.cache.set(cache_key, token) + + return token + + def set(self, blueprint, token, user=None, user_id=None): + uid = first([user_id, self.user_id, blueprint.config.get("user_id")]) + u = first(_get_real_user(ref, self.anon_user) + for ref in (user, self.user, blueprint.config.get("user"))) + + if self.user_required and not u and not uid: + raise ValueError("Cannot set OAuth token without an associated user") + + # if there was an existing model, delete it + existing_query = ( + self.session.query(self.model) + .filter_by(provider=blueprint.name) + ) + # check for user ID + has_user_id = hasattr(self.model, "user_id") + if has_user_id and uid: + existing_query = existing_query.filter_by(user_id=uid) + # check for user (relationship property) + has_user = hasattr(self.model, "user") + if has_user and u: + existing_query = existing_query.filter_by(user=u) + # queue up delete query -- won't be run until commit() + existing_query.delete() + # create a new model for this token + kwargs = { + "provider": blueprint.name, + "token": token, + } + if has_user_id and uid: + kwargs["user_id"] = uid + if has_user and u: + kwargs["user"] = u + self.session.add(self.model(**kwargs)) + # commit to delete and add simultaneously + self.session.commit() + # invalidate cache + self.cache.delete(self.make_cache_key( + blueprint=blueprint, user=user, user_id=user_id + )) + + def delete(self, blueprint, user=None, user_id=None): + query = ( + self.session.query(self.model) + .filter_by(provider=blueprint.name) + ) + uid = first([user_id, self.user_id, blueprint.config.get("user_id")]) + u = first(_get_real_user(ref, self.anon_user) + for ref in (user, self.user, blueprint.config.get("user"))) + + if self.user_required and not u and not uid: + raise ValueError("Cannot delete OAuth token without an associated user") + + # check for user ID + if hasattr(self.model, "user_id") and uid: + query = query.filter_by(user_id=uid) + # check for user (relationship property) + elif hasattr(self.model, "user") and u: + query = query.filter_by(user=u) + # if we have the property, but not value, filter by None + elif hasattr(self.model, "user_id"): + query = query.filter_by(user_id=None) + # run query + query.delete() + self.session.commit() + # invalidate cache + self.cache.delete(self.make_cache_key( + blueprint=blueprint, user=user, user_id=user_id, + )) + +except ImportError: + pass diff --git a/cps/oauth_bb.py b/cps/oauth_bb.py new file mode 100644 index 00000000..39777911 --- /dev/null +++ b/cps/oauth_bb.py @@ -0,0 +1,344 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web) +# Copyright (C) 2018-2019 OzzieIsaacs, cervinko, jkrehm, bodybybuddha, ok11, +# andy29485, idalin, Kyosfonica, wuqi, Kennyl, lemmsh, +# falgh1, grunjol, csitko, ytils, xybydy, trasba, vrabe, +# ruben-herold, marblepebble, JackED42, SiphonSquirrel, +# apetresc, nanu-c, mutschler +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see + +from __future__ import division, print_function, unicode_literals +import json +from functools import wraps + +from flask import session, request, make_response, abort +from flask import Blueprint, flash, redirect, url_for +from flask_babel import gettext as _ +from flask_dance.consumer import oauth_authorized, oauth_error +from flask_dance.contrib.github import make_github_blueprint, github +from flask_dance.contrib.google import make_google_blueprint, google +from flask_login import login_user, current_user +from sqlalchemy.orm.exc import NoResultFound + +from . import constants, logger, config, app, ub +from .web import login_required +from .oauth import OAuthBackend +# from .web import github_oauth_required + + +oauth_check = {} +oauth = Blueprint('oauth', __name__) +log = logger.create() + + +def github_oauth_required(f): + @wraps(f) + def inner(*args, **kwargs): + if config.config_login_type == constants.LOGIN_OAUTH_GITHUB: + return f(*args, **kwargs) + if request.is_xhr: + data = {'status': 'error', 'message': 'Not Found'} + response = make_response(json.dumps(data, ensure_ascii=False)) + response.headers["Content-Type"] = "application/json; charset=utf-8" + return response, 404 + abort(404) + + return inner + + +def google_oauth_required(f): + @wraps(f) + def inner(*args, **kwargs): + if config.config_use_google_oauth == constants.LOGIN_OAUTH_GOOGLE: + return f(*args, **kwargs) + if request.is_xhr: + data = {'status': 'error', 'message': 'Not Found'} + response = make_response(json.dumps(data, ensure_ascii=False)) + response.headers["Content-Type"] = "application/json; charset=utf-8" + return response, 404 + abort(404) + + return inner + + +def register_oauth_blueprint(blueprint, show_name): + if blueprint.name != "": + oauth_check[blueprint.name] = show_name + + +def register_user_with_oauth(user=None): + all_oauth = {} + for oauth in oauth_check.keys(): + if oauth + '_oauth_user_id' in session and session[oauth + '_oauth_user_id'] != '': + all_oauth[oauth] = oauth_check[oauth] + if len(all_oauth.keys()) == 0: + return + if user is None: + flash(_(u"Register with %(provider)s", provider=", ".join(list(all_oauth.values()))), category="success") + else: + for oauth in all_oauth.keys(): + # Find this OAuth token in the database, or create it + query = ub.session.query(ub.OAuth).filter_by( + provider=oauth, + provider_user_id=session[oauth + "_oauth_user_id"], + ) + try: + oauth = query.one() + oauth.user_id = user.id + except NoResultFound: + # no found, return error + return + try: + ub.session.commit() + except Exception as e: + log.exception(e) + ub.session.rollback() + + +def logout_oauth_user(): + for oauth in oauth_check.keys(): + if oauth + '_oauth_user_id' in session: + session.pop(oauth + '_oauth_user_id') + +if ub.oauth_support: + github_blueprint = make_github_blueprint( + client_id=config.config_github_oauth_client_id, + client_secret=config.config_github_oauth_client_secret, + redirect_to="oauth.github_login",) + + google_blueprint = make_google_blueprint( + client_id=config.config_google_oauth_client_id, + client_secret=config.config_google_oauth_client_secret, + redirect_to="oauth.google_login", + scope=[ + "https://www.googleapis.com/auth/plus.me", + "https://www.googleapis.com/auth/userinfo.email", + ] + ) + + app.register_blueprint(google_blueprint, url_prefix="/login") + app.register_blueprint(github_blueprint, url_prefix='/login') + + github_blueprint.backend = OAuthBackend(ub.OAuth, ub.session, user=current_user, user_required=True) + google_blueprint.backend = OAuthBackend(ub.OAuth, ub.session, user=current_user, user_required=True) + + + if config.config_login_type == constants.LOGIN_OAUTH_GITHUB: + register_oauth_blueprint(github_blueprint, 'GitHub') + if config.config_login_type == constants.LOGIN_OAUTH_GOOGLE: + register_oauth_blueprint(google_blueprint, 'Google') + + + @oauth_authorized.connect_via(github_blueprint) + def github_logged_in(blueprint, token): + if not token: + flash(_(u"Failed to log in with GitHub."), category="error") + return False + + resp = blueprint.session.get("/user") + if not resp.ok: + flash(_(u"Failed to fetch user info from GitHub."), category="error") + return False + + github_info = resp.json() + github_user_id = str(github_info["id"]) + return oauth_update_token(blueprint, token, github_user_id) + + + @oauth_authorized.connect_via(google_blueprint) + def google_logged_in(blueprint, token): + if not token: + flash(_(u"Failed to log in with Google."), category="error") + return False + + resp = blueprint.session.get("/oauth2/v2/userinfo") + if not resp.ok: + flash(_(u"Failed to fetch user info from Google."), category="error") + return False + + google_info = resp.json() + google_user_id = str(google_info["id"]) + + return oauth_update_token(blueprint, token, google_user_id) + + + def oauth_update_token(blueprint, token, provider_user_id): + session[blueprint.name + "_oauth_user_id"] = provider_user_id + session[blueprint.name + "_oauth_token"] = token + + # Find this OAuth token in the database, or create it + query = ub.session.query(ub.OAuth).filter_by( + provider=blueprint.name, + provider_user_id=provider_user_id, + ) + try: + oauth = query.one() + # update token + oauth.token = token + except NoResultFound: + oauth = ub.OAuth( + provider=blueprint.name, + provider_user_id=provider_user_id, + token=token, + ) + try: + ub.session.add(oauth) + ub.session.commit() + except Exception as e: + log.exception(e) + ub.session.rollback() + + # Disable Flask-Dance's default behavior for saving the OAuth token + return False + + + def bind_oauth_or_register(provider, provider_user_id, redirect_url): + query = ub.session.query(ub.OAuth).filter_by( + provider=provider, + provider_user_id=provider_user_id, + ) + try: + oauth = query.one() + # already bind with user, just login + if oauth.user: + login_user(oauth.user) + return redirect(url_for('web.index')) + else: + # bind to current user + if current_user and current_user.is_authenticated: + oauth.user = current_user + try: + ub.session.add(oauth) + ub.session.commit() + except Exception as e: + log.exception(e) + ub.session.rollback() + return redirect(url_for('web.login')) + #if config.config_public_reg: + # return redirect(url_for('web.register')) + #else: + # flash(_(u"Public registration is not enabled"), category="error") + # return redirect(url_for(redirect_url)) + except NoResultFound: + return redirect(url_for(redirect_url)) + + + def get_oauth_status(): + status = [] + query = ub.session.query(ub.OAuth).filter_by( + user_id=current_user.id, + ) + try: + oauths = query.all() + for oauth in oauths: + status.append(oauth.provider) + return status + except NoResultFound: + return None + + + def unlink_oauth(provider): + if request.host_url + 'me' != request.referrer: + pass + query = ub.session.query(ub.OAuth).filter_by( + provider=provider, + user_id=current_user.id, + ) + try: + oauth = query.one() + if current_user and current_user.is_authenticated: + oauth.user = current_user + try: + ub.session.delete(oauth) + ub.session.commit() + logout_oauth_user() + flash(_(u"Unlink to %(oauth)s success.", oauth=oauth_check[provider]), category="success") + except Exception as e: + log.exception(e) + ub.session.rollback() + flash(_(u"Unlink to %(oauth)s failed.", oauth=oauth_check[provider]), category="error") + except NoResultFound: + log.warning("oauth %s for user %d not fount", provider, current_user.id) + flash(_(u"Not linked to %(oauth)s.", oauth=oauth_check[provider]), category="error") + return redirect(url_for('web.profile')) + + + # notify on OAuth provider error + @oauth_error.connect_via(github_blueprint) + def github_error(blueprint, error, error_description=None, error_uri=None): + msg = ( + u"OAuth error from {name}! " + u"error={error} description={description} uri={uri}" + ).format( + name=blueprint.name, + error=error, + description=error_description, + uri=error_uri, + ) # ToDo: Translate + flash(msg, category="error") + + + @oauth.route('/github') + @github_oauth_required + def github_login(): + if not github.authorized: + return redirect(url_for('github.login')) + account_info = github.get('/user') + if account_info.ok: + account_info_json = account_info.json() + return bind_oauth_or_register(github_blueprint.name, account_info_json['id'], 'github.login') + flash(_(u"GitHub Oauth error, please retry later."), category="error") + return redirect(url_for('web.login')) + + + @oauth.route('/unlink/github', methods=["GET"]) + @login_required + def github_login_unlink(): + return unlink_oauth(github_blueprint.name) + + + @oauth.route('/login/google') + @google_oauth_required + def google_login(): + if not google.authorized: + return redirect(url_for("google.login")) + resp = google.get("/oauth2/v2/userinfo") + if resp.ok: + account_info_json = resp.json() + return bind_oauth_or_register(google_blueprint.name, account_info_json['id'], 'google.login') + flash(_(u"Google Oauth error, please retry later."), category="error") + return redirect(url_for('web.login')) + + + @oauth_error.connect_via(google_blueprint) + def google_error(blueprint, error, error_description=None, error_uri=None): + msg = ( + u"OAuth error from {name}! " + u"error={error} description={description} uri={uri}" + ).format( + name=blueprint.name, + error=error, + description=error_description, + uri=error_uri, + ) # ToDo: Translate + flash(msg, category="error") + + + @oauth.route('/unlink/google', methods=["GET"]) + @login_required + def google_login_unlink(): + return unlink_oauth(google_blueprint.name) diff --git a/cps/opds.py b/cps/opds.py new file mode 100644 index 00000000..657b3861 --- /dev/null +++ b/cps/opds.py @@ -0,0 +1,328 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web) +# Copyright (C) 2018-2019 OzzieIsaacs, cervinko, jkrehm, bodybybuddha, ok11, +# andy29485, idalin, Kyosfonica, wuqi, Kennyl, lemmsh, +# falgh1, grunjol, csitko, ytils, xybydy, trasba, vrabe, +# ruben-herold, marblepebble, JackED42, SiphonSquirrel, +# apetresc, nanu-c, mutschler +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from __future__ import division, print_function, unicode_literals +import sys +import datetime +from functools import wraps + +from flask import Blueprint, request, render_template, Response, g, make_response +from flask_login import current_user +from sqlalchemy.sql.expression import func, text, or_, and_ +from werkzeug.security import check_password_hash + +from . import constants, logger, config, db, ub, services +from .helper import fill_indexpage, get_download_link, get_book_cover +from .pagination import Pagination +from .web import common_filters, get_search_results, render_read_books, download_required + + +opds = Blueprint('opds', __name__) + +log = logger.create() + + +def requires_basic_auth_if_no_ano(f): + @wraps(f) + def decorated(*args, **kwargs): + auth = request.authorization + if config.config_anonbrowse != 1: + if not auth or not check_auth(auth.username, auth.password): + return authenticate() + return f(*args, **kwargs) + if config.config_login_type == constants.LOGIN_LDAP and services.ldap: + return services.ldap.basic_auth_required(f) + return decorated + + +@opds.route("/opds/") +@requires_basic_auth_if_no_ano +def feed_index(): + return render_xml_template('index.xml') + + +@opds.route("/opds/osd") +@requires_basic_auth_if_no_ano +def feed_osd(): + return render_xml_template('osd.xml', lang='en-EN') + + +@opds.route("/opds/search", defaults={'query': ""}) +@opds.route("/opds/search/") +@requires_basic_auth_if_no_ano +def feed_cc_search(query): + return feed_search(query.strip()) + + +@opds.route("/opds/search", methods=["GET"]) +@requires_basic_auth_if_no_ano +def feed_normal_search(): + return feed_search(request.args.get("query").strip()) + + +@opds.route("/opds/new") +@requires_basic_auth_if_no_ano +def feed_new(): + off = request.args.get("offset") or 0 + entries, __, pagination = fill_indexpage((int(off) / (int(config.config_books_per_page)) + 1), + db.Books, True, [db.Books.timestamp.desc()]) + return render_xml_template('feed.xml', entries=entries, pagination=pagination) + + +@opds.route("/opds/discover") +@requires_basic_auth_if_no_ano +def feed_discover(): + entries = db.session.query(db.Books).filter(common_filters()).order_by(func.random())\ + .limit(config.config_books_per_page) + pagination = Pagination(1, config.config_books_per_page, int(config.config_books_per_page)) + return render_xml_template('feed.xml', entries=entries, pagination=pagination) + + +@opds.route("/opds/rated") +@requires_basic_auth_if_no_ano +def feed_best_rated(): + off = request.args.get("offset") or 0 + entries, __, pagination = fill_indexpage((int(off) / (int(config.config_books_per_page)) + 1), + db.Books, db.Books.ratings.any(db.Ratings.rating > 9), [db.Books.timestamp.desc()]) + return render_xml_template('feed.xml', entries=entries, pagination=pagination) + + +@opds.route("/opds/hot") +@requires_basic_auth_if_no_ano +def feed_hot(): + off = request.args.get("offset") or 0 + all_books = ub.session.query(ub.Downloads, func.count(ub.Downloads.book_id)).order_by( + func.count(ub.Downloads.book_id).desc()).group_by(ub.Downloads.book_id) + hot_books = all_books.offset(off).limit(config.config_books_per_page) + entries = list() + for book in hot_books: + downloadBook = db.session.query(db.Books).filter(db.Books.id == book.Downloads.book_id).first() + if downloadBook: + entries.append( + db.session.query(db.Books).filter(common_filters()) + .filter(db.Books.id == book.Downloads.book_id).first() + ) + else: + ub.delete_download(book.Downloads.book_id) + # ub.session.query(ub.Downloads).filter(book.Downloads.book_id == ub.Downloads.book_id).delete() + # ub.session.commit() + numBooks = entries.__len__() + pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), + config.config_books_per_page, numBooks) + return render_xml_template('feed.xml', entries=entries, pagination=pagination) + + +@opds.route("/opds/author") +@requires_basic_auth_if_no_ano +def feed_authorindex(): + off = request.args.get("offset") or 0 + entries = db.session.query(db.Authors).join(db.books_authors_link).join(db.Books).filter(common_filters())\ + .group_by(text('books_authors_link.author')).order_by(db.Authors.sort).limit(config.config_books_per_page).offset(off) + pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page, + len(db.session.query(db.Authors).all())) + return render_xml_template('feed.xml', listelements=entries, folder='opds.feed_author', pagination=pagination) + + +@opds.route("/opds/author/") +@requires_basic_auth_if_no_ano +def feed_author(book_id): + off = request.args.get("offset") or 0 + entries, __, pagination = fill_indexpage((int(off) / (int(config.config_books_per_page)) + 1), + db.Books, db.Books.authors.any(db.Authors.id == book_id), [db.Books.timestamp.desc()]) + return render_xml_template('feed.xml', entries=entries, pagination=pagination) + + +@opds.route("/opds/publisher") +@requires_basic_auth_if_no_ano +def feed_publisherindex(): + off = request.args.get("offset") or 0 + entries = db.session.query(db.Publishers).join(db.books_publishers_link).join(db.Books).filter(common_filters())\ + .group_by(text('books_publishers_link.publisher')).order_by(db.Publishers.sort).limit(config.config_books_per_page).offset(off) + pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page, + len(db.session.query(db.Publishers).all())) + return render_xml_template('feed.xml', listelements=entries, folder='opds.feed_publisher', pagination=pagination) + + +@opds.route("/opds/publisher/") +@requires_basic_auth_if_no_ano +def feed_publisher(book_id): + off = request.args.get("offset") or 0 + entries, __, pagination = fill_indexpage((int(off) / (int(config.config_books_per_page)) + 1), + db.Books, db.Books.publishers.any(db.Publishers.id == book_id), + [db.Books.timestamp.desc()]) + return render_xml_template('feed.xml', entries=entries, pagination=pagination) + + +@opds.route("/opds/category") +@requires_basic_auth_if_no_ano +def feed_categoryindex(): + off = request.args.get("offset") or 0 + entries = db.session.query(db.Tags).join(db.books_tags_link).join(db.Books).filter(common_filters())\ + .group_by(text('books_tags_link.tag')).order_by(db.Tags.name).offset(off).limit(config.config_books_per_page) + pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page, + len(db.session.query(db.Tags).all())) + return render_xml_template('feed.xml', listelements=entries, folder='opds.feed_category', pagination=pagination) + + +@opds.route("/opds/category/") +@requires_basic_auth_if_no_ano +def feed_category(book_id): + off = request.args.get("offset") or 0 + entries, __, pagination = fill_indexpage((int(off) / (int(config.config_books_per_page)) + 1), + db.Books, db.Books.tags.any(db.Tags.id == book_id), [db.Books.timestamp.desc()]) + return render_xml_template('feed.xml', entries=entries, pagination=pagination) + + +@opds.route("/opds/series") +@requires_basic_auth_if_no_ano +def feed_seriesindex(): + off = request.args.get("offset") or 0 + entries = db.session.query(db.Series).join(db.books_series_link).join(db.Books).filter(common_filters())\ + .group_by(text('books_series_link.series')).order_by(db.Series.sort).offset(off).all() + pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page, + len(db.session.query(db.Series).all())) + return render_xml_template('feed.xml', listelements=entries, folder='opds.feed_series', pagination=pagination) + + +@opds.route("/opds/series/") +@requires_basic_auth_if_no_ano +def feed_series(book_id): + off = request.args.get("offset") or 0 + entries, __, pagination = fill_indexpage((int(off) / (int(config.config_books_per_page)) + 1), + db.Books, db.Books.series.any(db.Series.id == book_id), [db.Books.series_index]) + return render_xml_template('feed.xml', entries=entries, pagination=pagination) + + +@opds.route("/opds/shelfindex/", defaults={'public': 0}) +@opds.route("/opds/shelfindex/") +@requires_basic_auth_if_no_ano +def feed_shelfindex(public): + off = request.args.get("offset") or 0 + if public is not 0: + shelf = g.public_shelfes + number = len(shelf) + else: + shelf = g.user.shelf + number = shelf.count() + pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page, + number) + return render_xml_template('feed.xml', listelements=shelf, folder='opds.feed_shelf', pagination=pagination) + + +@opds.route("/opds/shelf/") +@requires_basic_auth_if_no_ano +def feed_shelf(book_id): + off = request.args.get("offset") or 0 + if current_user.is_anonymous: + shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.is_public == 1, ub.Shelf.id == book_id).first() + else: + shelf = ub.session.query(ub.Shelf).filter(or_(and_(ub.Shelf.user_id == int(current_user.id), + ub.Shelf.id == book_id), + and_(ub.Shelf.is_public == 1, + ub.Shelf.id == book_id))).first() + result = list() + # user is allowed to access shelf + if shelf: + books_in_shelf = ub.session.query(ub.BookShelf).filter(ub.BookShelf.shelf == book_id).order_by( + ub.BookShelf.order.asc()).all() + for book in books_in_shelf: + cur_book = db.session.query(db.Books).filter(db.Books.id == book.book_id).first() + result.append(cur_book) + pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page, + len(result)) + return render_xml_template('feed.xml', entries=result, pagination=pagination) + + +@opds.route("/opds/download///") +@requires_basic_auth_if_no_ano +@download_required +def opds_download_link(book_id, book_format): + return get_download_link(book_id,book_format) + + +@opds.route("/ajax/book/") +@requires_basic_auth_if_no_ano +def get_metadata_calibre_companion(uuid): + entry = db.session.query(db.Books).filter(db.Books.uuid.like("%" + uuid + "%")).first() + if entry is not None: + js = render_template('json.txt', entry=entry) + response = make_response(js) + response.headers["Content-Type"] = "application/json; charset=utf-8" + return response + else: + return "" + + +def feed_search(term): + if term: + term = term.strip().lower() + entries = get_search_results( term) + entriescount = len(entries) if len(entries) > 0 else 1 + pagination = Pagination(1, entriescount, entriescount) + return render_xml_template('feed.xml', searchterm=term, entries=entries, pagination=pagination) + else: + return render_xml_template('feed.xml', searchterm="") + +def check_auth(username, password): + if sys.version_info.major == 3: + username=username.encode('windows-1252') + user = ub.session.query(ub.User).filter(func.lower(ub.User.nickname) == + username.decode('utf-8').lower()).first() + return bool(user and check_password_hash(user.password, password)) + + +def authenticate(): + return Response( + 'Could not verify your access level for that URL.\n' + 'You have to login with proper credentials', 401, + {'WWW-Authenticate': 'Basic realm="Login Required"'}) + + +def render_xml_template(*args, **kwargs): + #ToDo: return time in current timezone similar to %z + currtime = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S+00:00") + xml = render_template(current_time=currtime, instance=config.config_calibre_web_title, *args, **kwargs) + response = make_response(xml) + response.headers["Content-Type"] = "application/atom+xml; charset=utf-8" + return response + +@opds.route("/opds/thumb_240_240/") +@opds.route("/opds/cover_240_240/") +@opds.route("/opds/cover_90_90/") +@opds.route("/opds/cover/") +@requires_basic_auth_if_no_ano +def feed_get_cover(book_id): + return get_book_cover(book_id) + +@opds.route("/opds/readbooks/") +@requires_basic_auth_if_no_ano +def feed_read_books(): + off = request.args.get("offset") or 0 + return render_read_books(int(off) / (int(config.config_books_per_page)) + 1, True, True) + + +@opds.route("/opds/unreadbooks/") +@requires_basic_auth_if_no_ano +def feed_unread_books(): + off = request.args.get("offset") or 0 + return render_read_books(int(off) / (int(config.config_books_per_page)) + 1, False, True) diff --git a/cps/pagination.py b/cps/pagination.py new file mode 100644 index 00000000..0a138a64 --- /dev/null +++ b/cps/pagination.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web) +# Copyright (C) 2018-2019 OzzieIsaacs, cervinko, jkrehm, bodybybuddha, ok11, +# andy29485, idalin, Kyosfonica, wuqi, Kennyl, lemmsh, +# falgh1, grunjol, csitko, ytils, xybydy, trasba, vrabe, +# ruben-herold, marblepebble, JackED42, SiphonSquirrel, +# apetresc, nanu-c, mutschler +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from __future__ import division, print_function, unicode_literals +from math import ceil + + +# simple pagination for the feed +class Pagination(object): + def __init__(self, page, per_page, total_count): + self.page = int(page) + self.per_page = int(per_page) + self.total_count = int(total_count) + + @property + def next_offset(self): + return int(self.page * self.per_page) + + @property + def previous_offset(self): + return int((self.page - 2) * self.per_page) + + @property + def last_offset(self): + last = int(self.total_count) - int(self.per_page) + if last < 0: + last = 0 + return int(last) + + @property + def pages(self): + return int(ceil(self.total_count / float(self.per_page))) + + @property + def has_prev(self): + return self.page > 1 + + @property + def has_next(self): + return self.page < self.pages + + # right_edge: last right_edges count of all pages are shown as number, means, if 10 pages are paginated -> 9,10 shwn + # left_edge: first left_edges count of all pages are shown as number -> 1,2 shwn + # left_current: left_current count below current page are shown as number, means if current page 5 -> 3,4 shwn + # left_current: right_current count above current page are shown as number, means if current page 5 -> 6,7 shwn + def iter_pages(self, left_edge=2, left_current=2, + right_current=4, right_edge=2): + last = 0 + left_current = self.page - left_current - 1 + right_current = self.page + right_current + 1 + right_edge = self.pages - right_edge + for num in range(1, (self.pages + 1)): + if num <= left_edge or (left_current < num < right_current) or num > right_edge: + if last + 1 != num: + yield None + yield num + last = num diff --git a/cps/redirect.py b/cps/redirect.py index 7b3981c4..324c4b20 100644 --- a/cps/redirect.py +++ b/cps/redirect.py @@ -28,10 +28,12 @@ # http://flask.pocoo.org/snippets/62/ +from __future__ import division, print_function, unicode_literals try: from urllib.parse import urlparse, urljoin except ImportError: from urlparse import urlparse, urljoin + from flask import request, url_for, redirect diff --git a/cps/reverseproxy.py b/cps/reverseproxy.py index 8a44062a..25bbe77b 100644 --- a/cps/reverseproxy.py +++ b/cps/reverseproxy.py @@ -37,6 +37,9 @@ # # Inspired by http://flask.pocoo.org/snippets/35/ +from __future__ import division, print_function, unicode_literals + + class ReverseProxied(object): """Wrap the application in this middleware and configure the front-end server to add these headers, to let you quietly bind diff --git a/cps/server.py b/cps/server.py index 98baddf3..1d564824 100644 --- a/cps/server.py +++ b/cps/server.py @@ -17,149 +17,190 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . - -from socket import error as SocketError +from __future__ import division, print_function, unicode_literals import sys import os +import errno import signal -import web +import socket try: from gevent.pywsgi import WSGIServer from gevent.pool import Pool - from gevent import __version__ as geventVersion - gevent_present = True + from gevent import __version__ as _version + VERSION = {'Gevent': 'v' + _version} + _GEVENT = True except ImportError: from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop - from tornado import version as tornadoVersion - gevent_present = False + from tornado import version as _version + VERSION = {'Tornado': 'v' + _version} + _GEVENT = False + +from . import logger, global_WorkerThread +log = logger.create() -class server: - wsgiserver = None - restart= False +class WebServer: def __init__(self): - signal.signal(signal.SIGINT, self.killServer) - signal.signal(signal.SIGTERM, self.killServer) + signal.signal(signal.SIGINT, self._killServer) + signal.signal(signal.SIGTERM, self._killServer) + + self.wsgiserver = None + self.access_logger = None + self.restart = False + self.app = None + self.listen_address = None + self.listen_port = None + self.IPV6 = False + self.unix_socket_file = None + self.ssl_args = None + + def init_app(self, application, config): + self.app = application + self.listen_address = config.get_config_ipaddress() + self.IPV6 = config.get_ipaddress_type() + self.listen_port = config.config_port + + if config.config_access_log: + log_name = "gevent.access" if _GEVENT else "tornado.access" + formatter = logger.ACCESS_FORMATTER_GEVENT if _GEVENT else logger.ACCESS_FORMATTER_TORNADO + self.access_logger = logger.create_access_log(config.config_access_logfile, log_name, formatter) + else: + if not _GEVENT: + logger.get('tornado.access').disabled = True + + certfile_path = config.get_config_certfile() + keyfile_path = config.get_config_keyfile() + if certfile_path and keyfile_path: + if os.path.isfile(certfile_path) and os.path.isfile(keyfile_path): + self.ssl_args = {"certfile": certfile_path, + "keyfile": keyfile_path} + else: + log.warning('The specified paths for the ssl certificate file and/or key file seem to be broken. Ignoring ssl.') + log.warning('Cert path: %s', certfile_path) + log.warning('Key path: %s', keyfile_path) + + def _make_gevent_unix_socket(self, socket_file): + # the socket file must not exist prior to bind() + if os.path.exists(socket_file): + # avoid nuking regular files and symbolic links (could be a mistype or security issue) + if os.path.isfile(socket_file) or os.path.islink(socket_file): + raise OSError(errno.EEXIST, os.strerror(errno.EEXIST), socket_file) + os.remove(socket_file) + + unix_sock = WSGIServer.get_listener(socket_file, family=socket.AF_UNIX) + self.unix_socket_file = socket_file + + # ensure current user and group have r/w permissions, no permissions for other users + # this way the socket can be shared in a semi-secure manner + # between the user running calibre-web and the user running the fronting webserver + os.chmod(socket_file, 0o660) + + return unix_sock + + def _make_gevent_socket(self): + if os.name != 'nt': + unix_socket_file = os.environ.get("CALIBRE_UNIX_SOCKET") + if unix_socket_file: + output = "socket:" + unix_socket_file + ":" + str(self.listen_port) + return self._make_gevent_unix_socket(unix_socket_file), output + + if self.listen_address: + return (self.listen_address, self.listen_port), self._get_readable_listen_address() + + if os.name == 'nt': + self.listen_address = '0.0.0.0' + return (self.listen_address, self.listen_port), self._get_readable_listen_address() + + address = ('', self.listen_port) + try: + sock = WSGIServer.get_listener(address, family=socket.AF_INET6) + output = self._get_readable_listen_address(True) + except socket.error as ex: + log.error('%s', ex) + log.warning('Unable to listen on "", trying on IPv4 only...') + output = self._get_readable_listen_address(False) + sock = WSGIServer.get_listener(address, family=socket.AF_INET) + return sock, output + + def _start_gevent(self): + ssl_args = self.ssl_args or {} - def start_gevent(self): try: - ssl_args = dict() - certfile_path = web.ub.config.get_config_certfile() - keyfile_path = web.ub.config.get_config_keyfile() - if certfile_path and keyfile_path: - if os.path.isfile(certfile_path) and os.path.isfile(keyfile_path): - ssl_args = {"certfile": certfile_path, - "keyfile": keyfile_path} - else: - web.app.logger.info('The specified paths for the ssl certificate file and/or key file seem to be broken. Ignoring ssl. Cert path: %s | Key path: %s' % (certfile_path, keyfile_path)) - if os.name == 'nt': - self.wsgiserver= WSGIServer(('0.0.0.0', web.ub.config.config_port), web.app, spawn=Pool(), **ssl_args) - else: - self.wsgiserver = WSGIServer(('', web.ub.config.config_port), web.app, spawn=Pool(), **ssl_args) - web.py3_gevent_link = self.wsgiserver + sock, output = self._make_gevent_socket() + log.info('Starting Gevent server on %s', output) + self.wsgiserver = WSGIServer(sock, self.app, log=self.access_logger, spawn=Pool(), **ssl_args) self.wsgiserver.serve_forever() - - except SocketError: - try: - web.app.logger.info('Unable to listen on \'\', trying on IPv4 only...') - self.wsgiserver = WSGIServer(('0.0.0.0', web.ub.config.config_port), web.app, spawn=Pool(), **ssl_args) - web.py3_gevent_link = self.wsgiserver - self.wsgiserver.serve_forever() - except (OSError, SocketError) as e: - web.app.logger.info("Error starting server: %s" % e.strerror) - print("Error starting server: %s" % e.strerror) - web.helper.global_WorkerThread.stop() - sys.exit(1) - except Exception: - web.app.logger.info("Unknown error while starting gevent") - - def startServer(self): - if gevent_present: - web.app.logger.info('Starting Gevent server') - # leave subprocess out to allow forking for fetchers and processors - self.start_gevent() + finally: + if self.unix_socket_file: + os.remove(self.unix_socket_file) + self.unix_socket_file = None + + def _start_tornado(self): + log.info('Starting Tornado server on %s', self._get_readable_listen_address()) + + # Max Buffersize set to 200MB ) + http_server = HTTPServer(WSGIContainer(self.app), + max_buffer_size = 209700000, + ssl_options=self.ssl_args) + http_server.listen(self.listen_port, self.listen_address) + self.wsgiserver=IOLoop.instance() + self.wsgiserver.start() + # wait for stop signal + self.wsgiserver.close(True) + + def _get_readable_listen_address(self, ipV6=False): + if self.listen_address == "": + listen_string = '""' else: - try: - ssl = None - web.app.logger.info('Starting Tornado server') - certfile_path = web.ub.config.get_config_certfile() - keyfile_path = web.ub.config.get_config_keyfile() - if certfile_path and keyfile_path: - if os.path.isfile(certfile_path) and os.path.isfile(keyfile_path): - ssl = {"certfile": certfile_path, - "keyfile": keyfile_path} - else: - web.app.logger.info('The specified paths for the ssl certificate file and/or key file seem to be broken. Ignoring ssl. Cert path: %s | Key path: %s' % (certfile_path, keyfile_path)) - - # Max Buffersize set to 200MB - http_server = HTTPServer(WSGIContainer(web.app), - max_buffer_size = 209700000, - ssl_options=ssl) - http_server.listen(web.ub.config.config_port) - self.wsgiserver=IOLoop.instance() - web.py3_gevent_link = self.wsgiserver - self.wsgiserver.start() - # wait for stop signal - self.wsgiserver.close(True) - except SocketError as e: - web.app.logger.info("Error starting server: %s" % e.strerror) - print("Error starting server: %s" % e.strerror) - web.helper.global_WorkerThread.stop() - sys.exit(1) - - # ToDo: Somehow caused by circular import under python3 refactor - if sys.version_info > (3, 0): - self.restart = web.py3_restart_Typ - if self.restart == True: - web.app.logger.info("Performing restart of Calibre-Web") - web.helper.global_WorkerThread.stop() - if os.name == 'nt': - arguments = ["\"" + sys.executable + "\""] - for e in sys.argv: - arguments.append("\"" + e + "\"") - os.execv(sys.executable, arguments) - else: - os.execl(sys.executable, sys.executable, *sys.argv) + ipV6 = self.IPV6 + listen_string = self.listen_address + if ipV6: + adress = "[" + listen_string + "]" else: - web.app.logger.info("Performing shutdown of Calibre-Web") - web.helper.global_WorkerThread.stop() - sys.exit(0) - - def setRestartTyp(self,starttyp): - self.restart = starttyp - # ToDo: Somehow caused by circular import under python3 refactor - web.py3_restart_Typ = starttyp - - def killServer(self, signum, frame): - self.stopServer() - - def stopServer(self): - # ToDo: Somehow caused by circular import under python3 refactor - if sys.version_info > (3, 0): - if not self.wsgiserver: - # if gevent_present: - self.wsgiserver = web.py3_gevent_link - #else: - # self.wsgiserver = IOLoop.instance() + adress = listen_string + return adress + ":" + str(self.listen_port) + + def start(self): + try: + if _GEVENT: + # leave subprocess out to allow forking for fetchers and processors + self._start_gevent() + else: + self._start_tornado() + except Exception as ex: + log.error("Error starting server: %s", ex) + print("Error starting server: %s" % ex) + return False + finally: + self.wsgiserver = None + global_WorkerThread.stop() + + if not self.restart: + log.info("Performing shutdown of Calibre-Web") + return True + + log.info("Performing restart of Calibre-Web") + arguments = list(sys.argv) + arguments.insert(0, sys.executable) + if os.name == 'nt': + arguments = ["\"%s\"" % a for a in arguments] + os.execv(sys.executable, arguments) + return True + + def _killServer(self, signum, frame): + self.stop() + + def stop(self, restart=False): + log.info("webserver stop (restart=%s)", restart) + self.restart = restart if self.wsgiserver: - if gevent_present: + if _GEVENT: self.wsgiserver.close() else: self.wsgiserver.add_callback(self.wsgiserver.stop) - - @staticmethod - def getNameVersion(): - if gevent_present: - return {'Gevent':'v'+geventVersion} - else: - return {'Tornado':'v'+tornadoVersion} - - -# Start Instance of Server -Server=server() diff --git a/cps/services/__init__.py b/cps/services/__init__.py new file mode 100644 index 00000000..90607160 --- /dev/null +++ b/cps/services/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web) +# Copyright (C) 2019 pwr +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from __future__ import division, print_function, unicode_literals + +from .. import logger + + +log = logger.create() + + +try: from . import goodreads +except ImportError as err: + log.warning("goodreads: %s", err) + goodreads = None + + +try: from . import simpleldap as ldap +except ImportError as err: + log.warning("simpleldap: %s", err) + ldap = None diff --git a/cps/services/goodreads.py b/cps/services/goodreads.py new file mode 100644 index 00000000..55161c7a --- /dev/null +++ b/cps/services/goodreads.py @@ -0,0 +1,106 @@ +# -*- coding: utf-8 -*- + +# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web) +# Copyright (C) 2018-2019 OzzieIsaacs, pwr +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from __future__ import division, print_function, unicode_literals +import time +from functools import reduce + +from goodreads.client import GoodreadsClient + +try: import Levenshtein +except ImportError: Levenshtein = False + +from .. import logger + + +log = logger.create() +_client = None # type: GoodreadsClient + +# GoodReads TOS allows for 24h caching of data +_CACHE_TIMEOUT = 23 * 60 * 60 # 23 hours (in seconds) +_AUTHORS_CACHE = {} + + +def connect(key=None, secret=None, enabled=True): + global _client + + if not enabled or not key or not secret: + _client = None + return + + if _client: + # make sure the configuration has not changed since last we used the client + if _client.client_key != key or _client.client_secret != secret: + _client = None + + if not _client: + _client = GoodreadsClient(key, secret) + + +def get_author_info(author_name): + now = time.time() + author_info = _AUTHORS_CACHE.get(author_name, None) + if author_info: + if now < author_info._timestamp + _CACHE_TIMEOUT: + return author_info + # clear expired entries + del _AUTHORS_CACHE[author_name] + + if not _client: + log.warning("failed to get a Goodreads client") + return + + try: + author_info = _client.find_author(author_name=author_name) + except Exception as ex: + # Skip goodreads, if site is down/inaccessible + log.warning('Goodreads website is down/inaccessible? %s', ex) + return + + if author_info: + author_info._timestamp = now + _AUTHORS_CACHE[author_name] = author_info + return author_info + + +def get_other_books(author_info, library_books=None): + # Get all identifiers (ISBN, Goodreads, etc) and filter author's books by that list so we show fewer duplicates + # Note: Not all images will be shown, even though they're available on Goodreads.com. + # See https://www.goodreads.com/topic/show/18213769-goodreads-book-images + + if not author_info: + return + + identifiers = [] + library_titles = [] + if library_books: + identifiers = list(reduce(lambda acc, book: acc + [i.val for i in book.identifiers if i.val], library_books, [])) + library_titles = [book.title for book in library_books] + + for book in author_info.books: + if book.isbn in identifiers: + continue + if book.gid["#text"] in identifiers: + continue + + if Levenshtein and library_titles: + goodreads_title = book._book_dict['title_without_series'] + if any(Levenshtein.ratio(goodreads_title, title) > 0.7 for title in library_titles): + continue + + yield book diff --git a/cps/services/simpleldap.py b/cps/services/simpleldap.py new file mode 100644 index 00000000..f9d0dfff --- /dev/null +++ b/cps/services/simpleldap.py @@ -0,0 +1,82 @@ +# -*- coding: utf-8 -*- + +# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web) +# Copyright (C) 2018-2019 OzzieIsaacs, pwr +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from __future__ import division, print_function, unicode_literals +import base64 + +from flask_simpleldap import LDAP, LDAPException + +from .. import constants, logger + + +log = logger.create() +_ldap = LDAP() + + +def init_app(app, config): + global _ldap + + if config.config_login_type != constants.LOGIN_LDAP: + _ldap = None + return + + app.config['LDAP_HOST'] = config.config_ldap_provider_url + app.config['LDAP_PORT'] = config.config_ldap_port + app.config['LDAP_SCHEMA'] = config.config_ldap_schema + app.config['LDAP_USERNAME'] = config.config_ldap_user_object.replace('%s', config.config_ldap_serv_username)\ + + ',' + config.config_ldap_dn + app.config['LDAP_PASSWORD'] = base64.b64decode(config.config_ldap_serv_password) + app.config['LDAP_REQUIRE_CERT'] = bool(config.config_ldap_require_cert) + if config.config_ldap_require_cert: + app.config['LDAP_CERT_PATH'] = config.config_ldap_cert_path + app.config['LDAP_BASE_DN'] = config.config_ldap_dn + app.config['LDAP_USER_OBJECT_FILTER'] = config.config_ldap_user_object + app.config['LDAP_USE_SSL'] = bool(config.config_ldap_use_ssl) + app.config['LDAP_USE_TLS'] = bool(config.config_ldap_use_tls) + app.config['LDAP_OPENLDAP'] = bool(config.config_ldap_openldap) + + # app.config['LDAP_BASE_DN'] = 'ou=users,dc=yunohost,dc=org' + # app.config['LDAP_USER_OBJECT_FILTER'] = '(uid=%s)' + _ldap.init_app(app) + + + +def basic_auth_required(func): + return _ldap.basic_auth_required(func) + + +def bind_user(username, password): + # ulf= _ldap.get_object_details('admin') + '''Attempts a LDAP login. + + :returns: True if login succeeded, False if login failed, None if server unavailable. + ''' + try: + result = _ldap.bind_user(username, password) + log.debug("LDAP login '%s': %r", username, result) + return result is not None + except LDAPException as ex: + if ex.message == 'Invalid credentials': + log.info("LDAP login '%s' failed: %s", username, ex) + return False + if ex.message == "Can't contact LDAP server": + log.warning('LDAP Server down: %s', ex) + return None + else: + log.warning('LDAP Server error: %s', ex.message) + return None diff --git a/cps/shelf.py b/cps/shelf.py new file mode 100644 index 00000000..a34dbfed --- /dev/null +++ b/cps/shelf.py @@ -0,0 +1,331 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web) +# Copyright (C) 2018-2019 OzzieIsaacs, cervinko, jkrehm, bodybybuddha, ok11, +# andy29485, idalin, Kyosfonica, wuqi, Kennyl, lemmsh, +# falgh1, grunjol, csitko, ytils, xybydy, trasba, vrabe, +# ruben-herold, marblepebble, JackED42, SiphonSquirrel, +# apetresc, nanu-c, mutschler +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from __future__ import division, print_function, unicode_literals + +from flask import Blueprint, request, flash, redirect, url_for +from flask_babel import gettext as _ +from flask_login import login_required, current_user +from sqlalchemy.sql.expression import func, or_, and_ + +from . import logger, ub, searched_ids, db +from .web import render_title_template + + +shelf = Blueprint('shelf', __name__) +log = logger.create() + + +@shelf.route("/shelf/add//") +@login_required +def add_to_shelf(shelf_id, book_id): + shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.id == shelf_id).first() + if shelf is None: + log.error("Invalid shelf specified: %s", shelf_id) + if not request.is_xhr: + flash(_(u"Invalid shelf specified"), category="error") + return redirect(url_for('web.index')) + return "Invalid shelf specified", 400 + + if not shelf.is_public and not shelf.user_id == int(current_user.id): + log.error("User %s not allowed to add a book to %s", current_user, shelf) + if not request.is_xhr: + flash(_(u"Sorry you are not allowed to add a book to the the shelf: %(shelfname)s", shelfname=shelf.name), + category="error") + return redirect(url_for('web.index')) + return "Sorry you are not allowed to add a book to the the shelf: %s" % shelf.name, 403 + + if shelf.is_public and not current_user.role_edit_shelfs(): + log.info("User %s not allowed to edit public shelves", current_user) + if not request.is_xhr: + flash(_(u"You are not allowed to edit public shelves"), category="error") + return redirect(url_for('web.index')) + return "User is not allowed to edit public shelves", 403 + + book_in_shelf = ub.session.query(ub.BookShelf).filter(ub.BookShelf.shelf == shelf_id, + ub.BookShelf.book_id == book_id).first() + if book_in_shelf: + log.error("Book %s is already part of %s", book_id, shelf) + if not request.is_xhr: + flash(_(u"Book is already part of the shelf: %(shelfname)s", shelfname=shelf.name), category="error") + return redirect(url_for('web.index')) + return "Book is already part of the shelf: %s" % shelf.name, 400 + + maxOrder = ub.session.query(func.max(ub.BookShelf.order)).filter(ub.BookShelf.shelf == shelf_id).first() + if maxOrder[0] is None: + maxOrder = 0 + else: + maxOrder = maxOrder[0] + + ins = ub.BookShelf(shelf=shelf.id, book_id=book_id, order=maxOrder + 1) + ub.session.add(ins) + ub.session.commit() + if not request.is_xhr: + flash(_(u"Book has been added to shelf: %(sname)s", sname=shelf.name), category="success") + if "HTTP_REFERER" in request.environ: + return redirect(request.environ["HTTP_REFERER"]) + else: + return redirect(url_for('web.index')) + return "", 204 + + +@shelf.route("/shelf/massadd/") +@login_required +def search_to_shelf(shelf_id): + shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.id == shelf_id).first() + if shelf is None: + log.error("Invalid shelf specified: %s", shelf_id) + flash(_(u"Invalid shelf specified"), category="error") + return redirect(url_for('web.index')) + + if not shelf.is_public and not shelf.user_id == int(current_user.id): + log.error("User %s not allowed to add a book to %s", current_user, shelf) + flash(_(u"You are not allowed to add a book to the the shelf: %(name)s", name=shelf.name), category="error") + return redirect(url_for('web.index')) + + if shelf.is_public and not current_user.role_edit_shelfs(): + log.error("User %s not allowed to edit public shelves", current_user) + flash(_(u"User is not allowed to edit public shelves"), category="error") + return redirect(url_for('web.index')) + + if current_user.id in searched_ids and searched_ids[current_user.id]: + books_for_shelf = list() + books_in_shelf = ub.session.query(ub.BookShelf).filter(ub.BookShelf.shelf == shelf_id).all() + if books_in_shelf: + book_ids = list() + for book_id in books_in_shelf: + book_ids.append(book_id.book_id) + for searchid in searched_ids[current_user.id]: + if searchid not in book_ids: + books_for_shelf.append(searchid) + else: + books_for_shelf = searched_ids[current_user.id] + + if not books_for_shelf: + log.error("Books are already part of %s", shelf) + flash(_(u"Books are already part of the shelf: %(name)s", name=shelf.name), category="error") + return redirect(url_for('web.index')) + + maxOrder = ub.session.query(func.max(ub.BookShelf.order)).filter(ub.BookShelf.shelf == shelf_id).first() + if maxOrder[0] is None: + maxOrder = 0 + else: + maxOrder = maxOrder[0] + + for book in books_for_shelf: + maxOrder = maxOrder + 1 + ins = ub.BookShelf(shelf=shelf.id, book_id=book, order=maxOrder) + ub.session.add(ins) + ub.session.commit() + flash(_(u"Books have been added to shelf: %(sname)s", sname=shelf.name), category="success") + else: + flash(_(u"Could not add books to shelf: %(sname)s", sname=shelf.name), category="error") + return redirect(url_for('web.index')) + + +@shelf.route("/shelf/remove//") +@login_required +def remove_from_shelf(shelf_id, book_id): + shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.id == shelf_id).first() + if shelf is None: + log.error("Invalid shelf specified: %s", shelf_id) + if not request.is_xhr: + return redirect(url_for('web.index')) + return "Invalid shelf specified", 400 + + # if shelf is public and use is allowed to edit shelfs, or if shelf is private and user is owner + # allow editing shelfs + # result shelf public user allowed user owner + # false 1 0 x + # true 1 1 x + # true 0 x 1 + # false 0 x 0 + + if (not shelf.is_public and shelf.user_id == int(current_user.id)) \ + or (shelf.is_public and current_user.role_edit_shelfs()): + book_shelf = ub.session.query(ub.BookShelf).filter(ub.BookShelf.shelf == shelf_id, + ub.BookShelf.book_id == book_id).first() + + if book_shelf is None: + log.error("Book %s already removed from %s", book_id, shelf) + if not request.is_xhr: + return redirect(url_for('web.index')) + return "Book already removed from shelf", 410 + + ub.session.delete(book_shelf) + ub.session.commit() + + if not request.is_xhr: + flash(_(u"Book has been removed from shelf: %(sname)s", sname=shelf.name), category="success") + return redirect(request.environ["HTTP_REFERER"]) + return "", 204 + else: + log.error("User %s not allowed to remove a book from %s", current_user, shelf) + if not request.is_xhr: + flash(_(u"Sorry you are not allowed to remove a book from this shelf: %(sname)s", sname=shelf.name), + category="error") + return redirect(url_for('web.index')) + return "Sorry you are not allowed to remove a book from this shelf: %s" % shelf.name, 403 + + + +@shelf.route("/shelf/create", methods=["GET", "POST"]) +@login_required +def create_shelf(): + shelf = ub.Shelf() + if request.method == "POST": + to_save = request.form.to_dict() + if "is_public" in to_save: + shelf.is_public = 1 + shelf.name = to_save["title"] + shelf.user_id = int(current_user.id) + existing_shelf = ub.session.query(ub.Shelf).filter( + or_((ub.Shelf.name == to_save["title"]) & (ub.Shelf.is_public == 1), + (ub.Shelf.name == to_save["title"]) & (ub.Shelf.user_id == int(current_user.id)))).first() + if existing_shelf: + flash(_(u"A shelf with the name '%(title)s' already exists.", title=to_save["title"]), category="error") + else: + try: + ub.session.add(shelf) + ub.session.commit() + flash(_(u"Shelf %(title)s created", title=to_save["title"]), category="success") + except Exception: + flash(_(u"There was an error"), category="error") + return render_title_template('shelf_edit.html', shelf=shelf, title=_(u"create a shelf"), page="shelfcreate") + else: + return render_title_template('shelf_edit.html', shelf=shelf, title=_(u"create a shelf"), page="shelfcreate") + + +@shelf.route("/shelf/edit/", methods=["GET", "POST"]) +@login_required +def edit_shelf(shelf_id): + shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.id == shelf_id).first() + if request.method == "POST": + to_save = request.form.to_dict() + existing_shelf = ub.session.query(ub.Shelf).filter( + or_((ub.Shelf.name == to_save["title"]) & (ub.Shelf.is_public == 1), + (ub.Shelf.name == to_save["title"]) & (ub.Shelf.user_id == int(current_user.id)))).filter( + ub.Shelf.id != shelf_id).first() + if existing_shelf: + flash(_(u"A shelf with the name '%(title)s' already exists.", title=to_save["title"]), category="error") + else: + shelf.name = to_save["title"] + if "is_public" in to_save: + shelf.is_public = 1 + else: + shelf.is_public = 0 + try: + ub.session.commit() + flash(_(u"Shelf %(title)s changed", title=to_save["title"]), category="success") + except Exception: + flash(_(u"There was an error"), category="error") + return render_title_template('shelf_edit.html', shelf=shelf, title=_(u"Edit a shelf"), page="shelfedit") + else: + return render_title_template('shelf_edit.html', shelf=shelf, title=_(u"Edit a shelf"), page="shelfedit") + + +@shelf.route("/shelf/delete/") +@login_required +def delete_shelf(shelf_id): + cur_shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.id == shelf_id).first() + deleted = None + if current_user.role_admin(): + deleted = ub.session.query(ub.Shelf).filter(ub.Shelf.id == shelf_id).delete() + else: + if (not cur_shelf.is_public and cur_shelf.user_id == int(current_user.id)) \ + or (cur_shelf.is_public and current_user.role_edit_shelfs()): + deleted = ub.session.query(ub.Shelf).filter(or_(and_(ub.Shelf.user_id == int(current_user.id), + ub.Shelf.id == shelf_id), + and_(ub.Shelf.is_public == 1, + ub.Shelf.id == shelf_id))).delete() + + if deleted: + ub.session.query(ub.BookShelf).filter(ub.BookShelf.shelf == shelf_id).delete() + ub.session.commit() + log.info("successfully deleted %s", cur_shelf) + return redirect(url_for('web.index')) + +# @shelf.route("/shelfdown/") +@shelf.route("/shelf/", defaults={'shelf_type': 1}) +@shelf.route("/shelf//") +@login_required +def show_shelf(shelf_type, shelf_id): + if current_user.is_anonymous: + shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.is_public == 1, ub.Shelf.id == shelf_id).first() + else: + shelf = ub.session.query(ub.Shelf).filter(or_(and_(ub.Shelf.user_id == int(current_user.id), + ub.Shelf.id == shelf_id), + and_(ub.Shelf.is_public == 1, + ub.Shelf.id == shelf_id))).first() + result = list() + # user is allowed to access shelf + if shelf: + page = "shelf.html" if shelf_type == 1 else 'shelfdown.html' + + books_in_shelf = ub.session.query(ub.BookShelf).filter(ub.BookShelf.shelf == shelf_id).order_by( + ub.BookShelf.order.asc()).all() + for book in books_in_shelf: + cur_book = db.session.query(db.Books).filter(db.Books.id == book.book_id).first() + if cur_book: + result.append(cur_book) + else: + log.info('Not existing book %s in %s deleted', book.book_id, shelf) + ub.session.query(ub.BookShelf).filter(ub.BookShelf.book_id == book.book_id).delete() + ub.session.commit() + return render_title_template(page, entries=result, title=_(u"Shelf: '%(name)s'", name=shelf.name), + shelf=shelf, page="shelf") + else: + flash(_(u"Error opening shelf. Shelf does not exist or is not accessible"), category="error") + return redirect(url_for("web.index")) + + + +@shelf.route("/shelf/order/", methods=["GET", "POST"]) +@login_required +def order_shelf(shelf_id): + if request.method == "POST": + to_save = request.form.to_dict() + books_in_shelf = ub.session.query(ub.BookShelf).filter(ub.BookShelf.shelf == shelf_id).order_by( + ub.BookShelf.order.asc()).all() + counter = 0 + for book in books_in_shelf: + setattr(book, 'order', to_save[str(book.book_id)]) + counter += 1 + ub.session.commit() + if current_user.is_anonymous: + shelf = ub.session.query(ub.Shelf).filter(ub.Shelf.is_public == 1, ub.Shelf.id == shelf_id).first() + else: + shelf = ub.session.query(ub.Shelf).filter(or_(and_(ub.Shelf.user_id == int(current_user.id), + ub.Shelf.id == shelf_id), + and_(ub.Shelf.is_public == 1, + ub.Shelf.id == shelf_id))).first() + result = list() + if shelf: + books_in_shelf2 = ub.session.query(ub.BookShelf).filter(ub.BookShelf.shelf == shelf_id) \ + .order_by(ub.BookShelf.order.asc()).all() + for book in books_in_shelf2: + cur_book = db.session.query(db.Books).filter(db.Books.id == book.book_id).first() + result.append(cur_book) + return render_title_template('shelf_order.html', entries=result, + title=_(u"Change order of Shelf: '%(name)s'", name=shelf.name), + shelf=shelf, page="shelforder") diff --git a/cps/static/css/images/black-10.png b/cps/static/css/images/black-10.png new file mode 100644 index 00000000..fe545ed8 Binary files /dev/null and b/cps/static/css/images/black-10.png differ diff --git a/cps/static/css/images/black-25.png b/cps/static/css/images/black-25.png new file mode 100644 index 00000000..a498b981 Binary files /dev/null and b/cps/static/css/images/black-25.png differ diff --git a/cps/static/css/images/black-33.png b/cps/static/css/images/black-33.png new file mode 100644 index 00000000..cfb1cb6b Binary files /dev/null and b/cps/static/css/images/black-33.png differ diff --git a/cps/static/css/images/icomoon/credits.txt b/cps/static/css/images/icomoon/credits.txt new file mode 100644 index 00000000..34c4b3ab --- /dev/null +++ b/cps/static/css/images/icomoon/credits.txt @@ -0,0 +1,6 @@ +SVG icons via Icomoon +https://icomoon.io/app + +Icons used from the following sets: +* Entypo - Creative Commons BY-SA 3.0 http://creativecommons.org/licenses/by-sa/3.0/us/ +* IcoMoon - Free (GPL) http://www.gnu.org/licenses/gpl.html \ No newline at end of file diff --git a/cps/static/css/images/icomoon/entypo-25px-000000/PNG/arrow.png b/cps/static/css/images/icomoon/entypo-25px-000000/PNG/arrow.png new file mode 100644 index 00000000..e77449bc Binary files /dev/null and b/cps/static/css/images/icomoon/entypo-25px-000000/PNG/arrow.png differ diff --git a/cps/static/css/images/icomoon/entypo-25px-000000/PNG/cart.png b/cps/static/css/images/icomoon/entypo-25px-000000/PNG/cart.png new file mode 100644 index 00000000..70e74a14 Binary files /dev/null and b/cps/static/css/images/icomoon/entypo-25px-000000/PNG/cart.png differ diff --git a/cps/static/css/images/icomoon/entypo-25px-000000/PNG/first.png b/cps/static/css/images/icomoon/entypo-25px-000000/PNG/first.png new file mode 100644 index 00000000..0947734a Binary files /dev/null and b/cps/static/css/images/icomoon/entypo-25px-000000/PNG/first.png differ diff --git a/cps/static/css/images/icomoon/entypo-25px-000000/PNG/last.png b/cps/static/css/images/icomoon/entypo-25px-000000/PNG/last.png new file mode 100644 index 00000000..3621d331 Binary files /dev/null and b/cps/static/css/images/icomoon/entypo-25px-000000/PNG/last.png differ diff --git a/cps/static/css/images/icomoon/entypo-25px-000000/PNG/list.png b/cps/static/css/images/icomoon/entypo-25px-000000/PNG/list.png new file mode 100644 index 00000000..2684aaf3 Binary files /dev/null and b/cps/static/css/images/icomoon/entypo-25px-000000/PNG/list.png differ diff --git a/cps/static/css/images/icomoon/entypo-25px-000000/PNG/list2.png b/cps/static/css/images/icomoon/entypo-25px-000000/PNG/list2.png new file mode 100644 index 00000000..601413b7 Binary files /dev/null and b/cps/static/css/images/icomoon/entypo-25px-000000/PNG/list2.png differ diff --git a/cps/static/css/images/icomoon/entypo-25px-000000/PNG/loop.png b/cps/static/css/images/icomoon/entypo-25px-000000/PNG/loop.png new file mode 100644 index 00000000..6f9aba04 Binary files /dev/null and b/cps/static/css/images/icomoon/entypo-25px-000000/PNG/loop.png differ diff --git a/cps/static/css/images/icomoon/entypo-25px-000000/PNG/music.png b/cps/static/css/images/icomoon/entypo-25px-000000/PNG/music.png new file mode 100644 index 00000000..6e1ae083 Binary files /dev/null and b/cps/static/css/images/icomoon/entypo-25px-000000/PNG/music.png differ diff --git a/cps/static/css/images/icomoon/entypo-25px-000000/PNG/pause.png b/cps/static/css/images/icomoon/entypo-25px-000000/PNG/pause.png new file mode 100644 index 00000000..e9fe4b9e Binary files /dev/null and b/cps/static/css/images/icomoon/entypo-25px-000000/PNG/pause.png differ diff --git a/cps/static/css/images/icomoon/entypo-25px-000000/PNG/play.png b/cps/static/css/images/icomoon/entypo-25px-000000/PNG/play.png new file mode 100644 index 00000000..6fcf7770 Binary files /dev/null and b/cps/static/css/images/icomoon/entypo-25px-000000/PNG/play.png differ diff --git a/cps/static/css/images/icomoon/entypo-25px-000000/PNG/shuffle.png b/cps/static/css/images/icomoon/entypo-25px-000000/PNG/shuffle.png new file mode 100644 index 00000000..7eb8f6cb Binary files /dev/null and b/cps/static/css/images/icomoon/entypo-25px-000000/PNG/shuffle.png differ diff --git a/cps/static/css/images/icomoon/entypo-25px-000000/PNG/volume.png b/cps/static/css/images/icomoon/entypo-25px-000000/PNG/volume.png new file mode 100644 index 00000000..e5c077f5 Binary files /dev/null and b/cps/static/css/images/icomoon/entypo-25px-000000/PNG/volume.png differ diff --git a/cps/static/css/images/icomoon/entypo-25px-000000/SVG/arrow.svg b/cps/static/css/images/icomoon/entypo-25px-000000/SVG/arrow.svg new file mode 100644 index 00000000..e6f2a0bd --- /dev/null +++ b/cps/static/css/images/icomoon/entypo-25px-000000/SVG/arrow.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/cps/static/css/images/icomoon/entypo-25px-000000/SVG/cart.svg b/cps/static/css/images/icomoon/entypo-25px-000000/SVG/cart.svg new file mode 100644 index 00000000..590ffa8c --- /dev/null +++ b/cps/static/css/images/icomoon/entypo-25px-000000/SVG/cart.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/cps/static/css/images/icomoon/entypo-25px-000000/SVG/first.svg b/cps/static/css/images/icomoon/entypo-25px-000000/SVG/first.svg new file mode 100644 index 00000000..e69482d1 --- /dev/null +++ b/cps/static/css/images/icomoon/entypo-25px-000000/SVG/first.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/cps/static/css/images/icomoon/entypo-25px-000000/SVG/last.svg b/cps/static/css/images/icomoon/entypo-25px-000000/SVG/last.svg new file mode 100644 index 00000000..9a958b23 --- /dev/null +++ b/cps/static/css/images/icomoon/entypo-25px-000000/SVG/last.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/cps/static/css/images/icomoon/entypo-25px-000000/SVG/list.svg b/cps/static/css/images/icomoon/entypo-25px-000000/SVG/list.svg new file mode 100644 index 00000000..88c39810 --- /dev/null +++ b/cps/static/css/images/icomoon/entypo-25px-000000/SVG/list.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/cps/static/css/images/icomoon/entypo-25px-000000/SVG/list2.svg b/cps/static/css/images/icomoon/entypo-25px-000000/SVG/list2.svg new file mode 100644 index 00000000..0c9ea62f --- /dev/null +++ b/cps/static/css/images/icomoon/entypo-25px-000000/SVG/list2.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/cps/static/css/images/icomoon/entypo-25px-000000/SVG/loop.svg b/cps/static/css/images/icomoon/entypo-25px-000000/SVG/loop.svg new file mode 100644 index 00000000..7b0c90ce --- /dev/null +++ b/cps/static/css/images/icomoon/entypo-25px-000000/SVG/loop.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/cps/static/css/images/icomoon/entypo-25px-000000/SVG/music.svg b/cps/static/css/images/icomoon/entypo-25px-000000/SVG/music.svg new file mode 100644 index 00000000..135ccded --- /dev/null +++ b/cps/static/css/images/icomoon/entypo-25px-000000/SVG/music.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/cps/static/css/images/icomoon/entypo-25px-000000/SVG/pause.svg b/cps/static/css/images/icomoon/entypo-25px-000000/SVG/pause.svg new file mode 100644 index 00000000..d08ab5ad --- /dev/null +++ b/cps/static/css/images/icomoon/entypo-25px-000000/SVG/pause.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/cps/static/css/images/icomoon/entypo-25px-000000/SVG/play.svg b/cps/static/css/images/icomoon/entypo-25px-000000/SVG/play.svg new file mode 100644 index 00000000..352ccad2 --- /dev/null +++ b/cps/static/css/images/icomoon/entypo-25px-000000/SVG/play.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/cps/static/css/images/icomoon/entypo-25px-000000/SVG/shuffle.svg b/cps/static/css/images/icomoon/entypo-25px-000000/SVG/shuffle.svg new file mode 100644 index 00000000..a6fc25f4 --- /dev/null +++ b/cps/static/css/images/icomoon/entypo-25px-000000/SVG/shuffle.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/cps/static/css/images/icomoon/entypo-25px-000000/SVG/volume.svg b/cps/static/css/images/icomoon/entypo-25px-000000/SVG/volume.svg new file mode 100644 index 00000000..dcc4a3c2 --- /dev/null +++ b/cps/static/css/images/icomoon/entypo-25px-000000/SVG/volume.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/arrow.png b/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/arrow.png new file mode 100644 index 00000000..2452d288 Binary files /dev/null and b/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/arrow.png differ diff --git a/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/cart.png b/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/cart.png new file mode 100644 index 00000000..611a3966 Binary files /dev/null and b/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/cart.png differ diff --git a/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/first.png b/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/first.png new file mode 100644 index 00000000..09de90ac Binary files /dev/null and b/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/first.png differ diff --git a/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/last.png b/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/last.png new file mode 100644 index 00000000..e0dd9323 Binary files /dev/null and b/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/last.png differ diff --git a/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/list.png b/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/list.png new file mode 100644 index 00000000..79b32069 Binary files /dev/null and b/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/list.png differ diff --git a/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/list2.png b/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/list2.png new file mode 100644 index 00000000..a8892c26 Binary files /dev/null and b/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/list2.png differ diff --git a/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/loop.png b/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/loop.png new file mode 100644 index 00000000..60b071a6 Binary files /dev/null and b/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/loop.png differ diff --git a/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/music.png b/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/music.png new file mode 100644 index 00000000..c1a64a6c Binary files /dev/null and b/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/music.png differ diff --git a/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/pause.png b/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/pause.png new file mode 100644 index 00000000..70b4f860 Binary files /dev/null and b/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/pause.png differ diff --git a/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/play.png b/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/play.png new file mode 100644 index 00000000..3c720426 Binary files /dev/null and b/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/play.png differ diff --git a/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/shuffle.png b/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/shuffle.png new file mode 100644 index 00000000..60f58686 Binary files /dev/null and b/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/shuffle.png differ diff --git a/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/volume.png b/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/volume.png new file mode 100644 index 00000000..7c251ddd Binary files /dev/null and b/cps/static/css/images/icomoon/entypo-25px-ffffff/PNG/volume.png differ diff --git a/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/arrow.svg b/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/arrow.svg new file mode 100644 index 00000000..ea2a59ae --- /dev/null +++ b/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/arrow.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/cart.svg b/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/cart.svg new file mode 100644 index 00000000..4b08a94b --- /dev/null +++ b/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/cart.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/first.svg b/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/first.svg new file mode 100644 index 00000000..ac3cf397 --- /dev/null +++ b/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/first.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/last.svg b/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/last.svg new file mode 100644 index 00000000..4e3b833d --- /dev/null +++ b/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/last.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/list.svg b/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/list.svg new file mode 100644 index 00000000..fa2f7174 --- /dev/null +++ b/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/list.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/list2.svg b/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/list2.svg new file mode 100644 index 00000000..7cec36cb --- /dev/null +++ b/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/list2.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/loop.svg b/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/loop.svg new file mode 100644 index 00000000..79c89573 --- /dev/null +++ b/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/loop.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/music.svg b/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/music.svg new file mode 100644 index 00000000..9a6fd461 --- /dev/null +++ b/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/music.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/pause.svg b/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/pause.svg new file mode 100644 index 00000000..77ca91bb --- /dev/null +++ b/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/pause.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/play.svg b/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/play.svg new file mode 100644 index 00000000..b98385f7 --- /dev/null +++ b/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/play.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/shuffle.svg b/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/shuffle.svg new file mode 100644 index 00000000..13a4007d --- /dev/null +++ b/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/shuffle.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/volume.svg b/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/volume.svg new file mode 100644 index 00000000..9d708435 --- /dev/null +++ b/cps/static/css/images/icomoon/entypo-25px-ffffff/SVG/volume.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/cps/static/css/images/icomoon/free-25px-000000/PNG/spinner.png b/cps/static/css/images/icomoon/free-25px-000000/PNG/spinner.png new file mode 100644 index 00000000..bd6d1a4c Binary files /dev/null and b/cps/static/css/images/icomoon/free-25px-000000/PNG/spinner.png differ diff --git a/cps/static/css/images/icomoon/free-25px-000000/SVG/spinner.svg b/cps/static/css/images/icomoon/free-25px-000000/SVG/spinner.svg new file mode 100644 index 00000000..1fa2d52b --- /dev/null +++ b/cps/static/css/images/icomoon/free-25px-000000/SVG/spinner.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/cps/static/css/images/icomoon/free-25px-ffffff/PNG/spinner.png b/cps/static/css/images/icomoon/free-25px-ffffff/PNG/spinner.png new file mode 100644 index 00000000..7db55258 Binary files /dev/null and b/cps/static/css/images/icomoon/free-25px-ffffff/PNG/spinner.png differ diff --git a/cps/static/css/images/icomoon/free-25px-ffffff/SVG/spinner.svg b/cps/static/css/images/icomoon/free-25px-ffffff/SVG/spinner.svg new file mode 100644 index 00000000..eac5df26 --- /dev/null +++ b/cps/static/css/images/icomoon/free-25px-ffffff/SVG/spinner.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/cps/static/css/images/patterns/credits.txt b/cps/static/css/images/patterns/credits.txt new file mode 100644 index 00000000..fb3d6673 --- /dev/null +++ b/cps/static/css/images/patterns/credits.txt @@ -0,0 +1,2 @@ +Patterns from subtlepatterns.com. +"If you need more, that's where to get 'em." \ No newline at end of file diff --git a/cps/static/css/images/patterns/pinstriped_suit_vertical.png b/cps/static/css/images/patterns/pinstriped_suit_vertical.png new file mode 100644 index 00000000..26d547a6 Binary files /dev/null and b/cps/static/css/images/patterns/pinstriped_suit_vertical.png differ diff --git a/cps/static/css/images/patterns/pool_table.png b/cps/static/css/images/patterns/pool_table.png new file mode 100644 index 00000000..4183efa5 Binary files /dev/null and b/cps/static/css/images/patterns/pool_table.png differ diff --git a/cps/static/css/images/patterns/rubber_grip.png b/cps/static/css/images/patterns/rubber_grip.png new file mode 100644 index 00000000..076b9606 Binary files /dev/null and b/cps/static/css/images/patterns/rubber_grip.png differ diff --git a/cps/static/css/images/patterns/tasky_pattern.png b/cps/static/css/images/patterns/tasky_pattern.png new file mode 100644 index 00000000..81d218bc Binary files /dev/null and b/cps/static/css/images/patterns/tasky_pattern.png differ diff --git a/cps/static/css/images/patterns/textured_paper.png b/cps/static/css/images/patterns/textured_paper.png new file mode 100644 index 00000000..856ad372 Binary files /dev/null and b/cps/static/css/images/patterns/textured_paper.png differ diff --git a/cps/static/css/images/patterns/tweed.png b/cps/static/css/images/patterns/tweed.png new file mode 100644 index 00000000..03fb7968 Binary files /dev/null and b/cps/static/css/images/patterns/tweed.png differ diff --git a/cps/static/css/images/patterns/wood_pattern.png b/cps/static/css/images/patterns/wood_pattern.png new file mode 100644 index 00000000..47903e43 Binary files /dev/null and b/cps/static/css/images/patterns/wood_pattern.png differ diff --git a/cps/static/css/images/patterns/wood_pattern_dark.png b/cps/static/css/images/patterns/wood_pattern_dark.png new file mode 100644 index 00000000..1f5fc7fe Binary files /dev/null and b/cps/static/css/images/patterns/wood_pattern_dark.png differ diff --git a/cps/static/css/images/patterns/woven.png b/cps/static/css/images/patterns/woven.png new file mode 100644 index 00000000..ab692435 Binary files /dev/null and b/cps/static/css/images/patterns/woven.png differ diff --git a/cps/static/css/libs/bar-ui.css b/cps/static/css/libs/bar-ui.css new file mode 100644 index 00000000..e2e9f44a --- /dev/null +++ b/cps/static/css/libs/bar-ui.css @@ -0,0 +1,1001 @@ +/** + * SoundManager 2: "Bar UI" player - CSS + * Copyright (c) 2014, Scott Schiller. All rights reserved. + * http://www.schillmania.com/projects/soundmanager2/ + * Code provided under BSD license. + * http://schillmania.com/projects/soundmanager2/license.txt + */ + +.sm2-bar-ui { + position: relative; + display: inline-block; + width: 100%; + font-family: helvetica, arial, verdana, sans-serif; + font-weight: normal; + /* prevent background border bleed */ + -webkit-background-clip: padding-box; + background-clip: padding-box; + /* because indeed, fonts do look pretty "fat" otherwise in this case. */ + -moz-osx-font-smoothing: grayscale; + -webkit-font-smoothing: antialiased; + /* general font niceness? */ + font-smoothing: antialiased; + text-rendering: optimizeLegibility; + min-width: 20em; + max-width: 30em; + /* take out overflow if you want an absolutely-positioned playlist dropdown. */ + border-radius: 2px; + overflow: hidden; + /* just for fun (animate normal / full-width) */ + transition: max-width 0.2s ease-in-out; +} + +.sm2-bar-ui .sm2-playlist li { + text-align: center; + margin-top: -2px; + font-size: 95%; + line-height: 1em; +} + +.sm2-bar-ui.compact { + min-width: 1em; + max-width: 15em; +} + +.sm2-bar-ui ul { + line-height: 1em; +} + +/* want things left-aligned? */ +.sm2-bar-ui.left .sm2-playlist li { + text-align: left; +} + +.sm2-bar-ui .sm2-playlist li .load-error { + cursor: help; +} + +.sm2-bar-ui.full-width { + max-width: 100%; + z-index: 5; +} + +.sm2-bar-ui.fixed { + position: fixed; + top: auto; + bottom: 0px; + left: 0px; + border-radius: 0px; + /* so the absolutely-positioned playlist can show... */ + overflow: visible; + /* and this should probably have a high z-index. tweak as needed. */ + z-index: 999; +} + +.sm2-bar-ui.fixed .bd, +.sm2-bar-ui.bottom .bd { + /* display: table; */ + border-radius: 0px; + border-bottom: none; +} + +.sm2-bar-ui.bottom { + /* absolute bottom-aligned UI */ + top: auto; + bottom: 0px; + left: 0px; + border-radius: 0px; + /* so the absolutely-positioned playlist can show... */ + overflow: visible; +} + +.sm2-bar-ui.playlist-open .bd { + border-bottom-left-radius: 0px; + border-bottom-right-radius: 0px; + border-bottom-color: transparent; +} + +.sm2-bar-ui .bd, +.sm2-bar-ui .sm2-extra-controls { + position: relative; + background-color: #2288cc; + /* + transition: background 0.2s ease-in-out; + */ +} + +.sm2-bar-ui .sm2-inline-gradient { + /* gradient */ + position: absolute; + left: 0px; + top: 0px; + width: 100%; + height: 100%; + background-image: linear-gradient(to bottom, rgba(255,255,255,0.125) 5%, rgba(255,255,255,0.125) 45%, rgba(255,255,255,0.15) 50%, rgba(0,0,0,0.1) 51%, rgba(0,0,0,0.1) 95%); /* W3C */ +} + +.sm2-bar-ui.flat .sm2-inline-gradient { + background-image: none; +} + +.sm2-bar-ui.flat .sm2-box-shadow { + display: none; + box-shadow: none; +} + +.sm2-bar-ui.no-volume .sm2-volume { + /* mobile devices (android + iOS) ignore attempts to set volume. */ + display: none; +} + +.sm2-bar-ui.textured .sm2-inline-texture { + position: absolute; + top: 0px; + left: 0px; + width: 100%; + height: 100%; + /* for example */ + /* background-image: url(../image/wood_pattern_dark.png); */ + /* additional opacity effects can be applied here. */ + opacity: 0.75; + +} + +.sm2-bar-ui.textured.dark-text .sm2-inline-texture { + /* dark text + textured case: use light wood background (for example.) */ + /* background-image: url(../image/patterns/wood_pattern.png); */ +} + +.sm2-bar-ui.textured.dark-text .sm2-playlist-wrapper { + /* dark text + textured case: ditch 10% dark on playlist body. */ + background-color: transparent; +} + +.sm2-bar-ui.textured.dark-text .sm2-playlist-wrapper ul li:hover a, +.sm2-bar-ui.textured.dark-text .sm2-playlist-wrapper ul li.selected a { + /* dark + textured case: dark highlights */ + background-color: rgba(0,0,0,0.1); + background-image: url(../images/black-10.png); + /* modern browsers don't neeed the image */ + background-image: none, none; +} + +.sm2-bar-ui .bd { + display: table; + border-bottom: none; +} + +.sm2-bar-ui .sm2-playlist-wrapper { + background-color: rgba(0,0,0,0.1); +} + +.sm2-bar-ui .sm2-extra-controls .bd { + background-color: rgba(0,0,0,0.2); +} + + +.sm2-bar-ui.textured .sm2-extra-controls .bd { + /* lighten extra color overlays */ + background-color: rgba(0,0,0,0.05); +} + +.sm2-bar-ui .sm2-extra-controls { + background-color: transparent; + border: none; +} + +.sm2-bar-ui .sm2-extra-controls .bd { + /* override full-width table behaviour */ + display: block; + border: none; +} + +.sm2-bar-ui .sm2-extra-controls .sm2-inline-element { + display: inline-block; +} + +.sm2-bar-ui, +.sm2-bar-ui .bd a { + color: #fff; +} + +.sm2-bar-ui.dark-text, +.sm2-bar-ui.dark-text .bd a { + color: #000; +} + +.sm2-bar-ui.dark-text .sm2-inline-button { + /* Warning/disclaimer: SVG might be fuzzy when inverted on Chrome, losing resolution on hi-DPI displays. */ + -webkit-filter: invert(1); + /* SVG-based invert filter for Firefox */ + filter: url("data:image/svg+xml;utf8,#invert"); + /* IE 8 inverse filter, may only match pure black/white */ + /* filter: xray; */ + /* pending W3 standard */ + filter: invert(1); + /* not you, IE < 10. */ + filter: none\9; +} + +.sm2-bar-ui .bd a { + text-decoration: none; +} + +.sm2-bar-ui .bd .sm2-button-element:hover { + background-color: rgba(0,0,0,0.1); + background-image: url(../images/black-10.png); + background-image: none, none; +} + +.sm2-bar-ui .bd .sm2-button-element:active { + background-color: rgba(0,0,0,0.25); + background-image: url(../images/black-25.png); + background-image: none, none; +} + +.sm2-bar-ui .bd .sm2-extra-controls .sm2-button-element:active .sm2-inline-button, +.sm2-bar-ui .bd .active .sm2-inline-button/*, +.sm2-bar-ui.playlist-open .sm2-menu a */{ + -ms-transform: scale(0.9); + -webkit-transform: scale(0.9); + -webkit-transform-origin: 50% 50%; + /* firefox doesn't scale quite right. */ + transform: scale(0.9); + transform-origin: 50% 50%; + /* firefox doesn't scale quite right. */ + -moz-transform: none; +} + +.sm2-bar-ui .bd .sm2-extra-controls .sm2-button-element:hover, +.sm2-bar-ui .bd .sm2-extra-controls .sm2-button-element:active, +.sm2-bar-ui .bd .active { + background-color: rgba(0,0,0,0.1); + background-image: url(../images/black-10.png); + background-image: none, none; +} + +.sm2-bar-ui .bd .sm2-extra-controls .sm2-button-element:active { + /* box shadow is excessive on smaller elements. */ + box-shadow: none; +} + +.sm2-bar-ui { + /* base font size */ + font-size: 15px; + text-shadow: none; +} + +.sm2-bar-ui .sm2-inline-element { + position: relative; + display: inline-block; + vertical-align: middle; + padding: 0px; + overflow: hidden; +} + +.sm2-bar-ui .sm2-inline-element, +.sm2-bar-ui .sm2-button-element .sm2-button-bd { + position: relative; + /** + * .sm2-button-bd exists because of a Firefox bug from 2000 + * re: nested relative / absolute elements inside table cells. + * https://bugzilla.mozilla.org/show_bug.cgi?id=63895 + */ +} + +.sm2-bar-ui .sm2-inline-element, +.sm2-bar-ui .sm2-button-element .sm2-button-bd { + /** + * if you play with UI width/height, these are the important ones. + * NOTE: match these values if you want square UI buttons. + */ + min-width: 2.8em; + min-height: 2.8em; +} + +.sm2-bar-ui .sm2-inline-button { + position: absolute; + top: 0px; + left: 0px; + width: 100%; + height: 100%; +} + +.sm2-bar-ui .sm2-extra-controls .bd { + /* don't double-layer. */ + background-image: none; + background-color: rgba(0,0,0,0.15); +} + +.sm2-bar-ui .sm2-extra-controls .sm2-inline-element { + width: 25px; /* bare minimum */ + min-height: 1.75em; + min-width: 2.5em; +} + +.sm2-bar-ui .sm2-inline-status { + line-height: 100%; + /* how much to allow before truncating song artist / title with ellipsis */ + display: inline-block; + min-width: 200px; + max-width: 20em; + /* a little more spacing */ + padding-left: 0.75em; + padding-right: 0.75em; +} + +.sm2-bar-ui .sm2-inline-element { + /* extra-small em scales up nicely, vs. 1px which gets fat */ + border-right: 0.075em dotted #666; /* legacy */ + border-right: 0.075em solid rgba(0,0,0,0.1); +} + +.sm2-bar-ui .sm2-inline-element.noborder { + border-right: none; +} + +.sm2-bar-ui .sm2-inline-element.compact { + min-width: 2em; + padding: 0px 0.25em; +} + +.sm2-bar-ui .sm2-inline-element:first-of-type { + border-top-left-radius: 3px; + border-bottom-left-radius: 3px; + overflow: hidden; +} + +.sm2-bar-ui .sm2-inline-element:last-of-type { + border-right: none; + border-top-right-radius: 3px; + border-bottom-right-radius: 3px; +} + +.sm2-bar-ui .sm2-inline-status a:hover { + background-color: transparent; + text-decoration: underline; +} + +.sm2-inline-time, +.sm2-inline-duration { + display: table-cell; + width: 1%; + font-size: 75%; + line-height: 0.9em; + min-width: 2em; /* if you have sounds > 10:00 in length, make this bigger. */ + vertical-align: middle; +} + +.sm2-bar-ui .sm2-playlist { + position: relative; + height: 1.45em; +} + +.sm2-bar-ui .sm2-playlist-target { + /* initial render / empty case */ + position: relative; + min-height: 1em; +} + +.sm2-bar-ui .sm2-playlist ul { + position: absolute; + left: 0px; + top: 0px; + width: 100%; + list-style-type: none; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} + +.sm2-bar-ui p, +.sm2-bar-ui .sm2-playlist ul, +.sm2-bar-ui .sm2-playlist ul li { + margin: 0px; + padding: 0px; +} + +.sm2-bar-ui .sm2-playlist ul li { + position: relative; +} + +.sm2-bar-ui .sm2-playlist ul li, +.sm2-bar-ui .sm2-playlist ul li a { + position: relative; + display: block; + /* prevent clipping of characters like "g" */ + height: 1.5em; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + text-align: center; +} + +.sm2-row { + position: relative; + display: table-row; +} + +.sm2-progress-bd { + /* spacing between progress track/ball and time (position) */ + padding: 0px 0.8em; +} + +.sm2-progress .sm2-progress-track, +.sm2-progress .sm2-progress-ball, +.sm2-progress .sm2-progress-bar { + position: relative; + width: 100%; + height: 0.65em; + border-radius: 0.65em; +} + +.sm2-progress .sm2-progress-bar { + /* element which follows the progres "ball" as it moves */ + position: absolute; + left: 0px; + top: 0px; + width: 0px; + background-color: rgba(0,0,0,0.33); + background-image: url(../images/black-33.png); + background-image: none, none; +} + +.volume-shade, +.playing .sm2-progress .sm2-progress-track, +.paused .sm2-progress .sm2-progress-track { + cursor: pointer; +} + +.playing .sm2-progress .sm2-progress-ball { + cursor: -moz-grab; + cursor: -webkit-grab; + cursor: grab; +} + +.sm2-progress .sm2-progress-ball { + position: absolute; + top: 0px; + left: 0px; + width: 1em; + height: 1em; + margin: -0.2em 0px 0px -0.5em; + width: 14px; + height: 14px; + margin: -2px 0px 0px -7px; + width: 0.9333em; + height: 0.9333em; + margin: -0.175em 0px 0px -0.466em; + background-color: #fff; + padding: 0px; +/* + z-index: 1; +*/ + transition: transform 0.15s ease-in-out; +} + +/* +.sm2-bar-ui.dark-text .sm2-progress .sm2-progress-ball { + background-color: #000; +} +*/ + +.sm2-progress .sm2-progress-track { + background-color: rgba(0,0,0,0.4); + background-image: url(../images/black-33.png); /* legacy */ + background-image: none, none; /* modern browsers */ +} + +/* scrollbar rules have to be separate, browsers not supporting this syntax will skip them when combined. */ +.sm2-playlist-wrapper ul::-webkit-scrollbar-track { + background-color: rgba(0,0,0,0.4); +} + +.playing.grabbing .sm2-progress .sm2-progress-track, +.playing.grabbing .sm2-progress .sm2-progress-ball { + cursor: -moz-grabbing; + cursor: -webkit-grabbing; + cursor: grabbing; +} + +.sm2-bar-ui.grabbing .sm2-progress .sm2-progress-ball { + -webkit-transform: scale(1.15); + transform: scale(1.15); +} + +.sm2-inline-button { + background-position: 50% 50%; + background-repeat: no-repeat; + /* hide inner text */ + line-height: 10em; + /** + * image-rendering seems to apply mostly to Firefox in this case. Use with caution. + * https://developer.mozilla.org/en-US/docs/Web/CSS/image-rendering#Browser_compatibility + */ + image-rendering: -moz-crisp-edges; + image-rendering: -webkit-optimize-contrast; + image-rendering: crisp-edges; + -ms-interpolation-mode: nearest-neighbor; + -ms-interpolation-mode: bicubic; +} + +.sm2-icon-play-pause, +.sm2-icon-play-pause:hover, +.paused .sm2-icon-play-pause:hover { + background-image: url(../images/icomoon/entypo-25px-ffffff/PNG/play.png); + background-image: none, url(../images/icomoon/entypo-25px-ffffff/SVG/play.svg); + background-size: 67.5%; + background-position: 40% 53%; +} + +.playing .sm2-icon-play-pause { + background-image: url(../images/icomoon/entypo-25px-ffffff/PNG/pause.png); + background-image: none, url(../images/icomoon/entypo-25px-ffffff/SVG/pause.svg); + background-size: 57.6%; + background-position: 50% 53%; +} + +.sm2-volume-control { + background-image: url(../images/icomoon/entypo-25px-ffffff/PNG/volume.png); + background-image: none, url(../images/icomoon/entypo-25px-ffffff/SVG/volume.svg); +} + +.sm2-volume-control, +.sm2-volume-shade { + background-position: 42% 50%; + background-size: 56%; +} + +.volume-shade { + filter: alpha(opacity=33); /* <= IE 8 */ + opacity: 0.33; +/* -webkit-filter: invert(1);*/ + background-image: url(../images/icomoon/entypo-25px-000000/PNG/volume.png); + background-image: none, url(../images/icomoon/entypo-25px-000000/SVG/volume.svg); +} + +.sm2-icon-menu { + background-image: url(../images/icomoon/entypo-25px-ffffff/PNG/list2.png); + background-image: none, url(../images/icomoon/entypo-25px-ffffff/SVG/list2.svg); + background-size: 58%; + background-position: 54% 51%; +} + +.sm2-icon-previous { + background-image: url(../images/icomoon/entypo-25px-ffffff/PNG/first.png); + background-image: none, url(../images/icomoon/entypo-25px-ffffff/SVG/first.svg); +} + +.sm2-icon-next { + background-image: url(../images/icomoon/entypo-25px-ffffff/PNG/last.png); + background-image: none, url(../images/icomoon/entypo-25px-ffffff/SVG/last.svg); +} + +.sm2-icon-previous, +.sm2-icon-next { + background-size: 49.5%; + background-position: 50% 50%; +} + + +.sm2-extra-controls .sm2-icon-previous, +.sm2-extra-controls .sm2-icon-next { + backgound-size: 53%; +} + +.sm2-icon-shuffle { + background-image: url(../images/icomoon/entypo-25px-ffffff/PNG/shuffle.png); + background-image: none, url(../images/icomoon/entypo-25px-ffffff/SVG/shuffle.svg); + background-size: 45%; + background-position: 50% 50%; +} + +.sm2-icon-repeat { + background-image: url(../images/icomoon/entypo-25px-ffffff/PNG/loop.png); + background-image: none, url(../images/icomoon/entypo-25px-ffffff/SVG/loop.svg); + background-position: 50% 43%; + background-size: 54%; +} + +.sm2-extra-controls .sm2-icon-repeat { + background-position: 50% 45%; +} + +.sm2-playlist-wrapper ul li .sm2-row { + display: table; + width: 100%; +} + +.sm2-playlist-wrapper ul li .sm2-col { + display: table-cell; + vertical-align: top; + /* by default, collapse. */ + width: 0%; +} + +.sm2-playlist-wrapper ul li .sm2-col.sm2-wide { + /* take 100% width. */ + width: 100%; +} + +.sm2-playlist-wrapper ul li .sm2-icon { + display: inline-block; + overflow: hidden; + width: 2em; + color: transparent !important; /* hide text */ + white-space: nowrap; /* don't let text affect height */ + padding-left: 0px; + padding-right: 0px; + text-indent: 2em; /* IE 8, mostly */ +} + +.sm2-playlist-wrapper ul li .sm2-icon, +.sm2-playlist-wrapper ul li:hover .sm2-icon, +.sm2-playlist-wrapper ul li.selected .sm2-icon { + background-size: 55%; + background-position: 50% 50%; + background-repeat: no-repeat; +} + +.sm2-playlist-wrapper ul li .sm2-col { + /* sibling table cells get borders. */ + border-right: 1px solid rgba(0,0,0,0.075); +} + +.sm2-playlist-wrapper ul li.selected .sm2-col { + border-color: rgba(255,255,255,0.075); +} + +.sm2-playlist-wrapper ul li .sm2-col:last-of-type { + border-right: none; +} + +.sm2-playlist-wrapper ul li .sm2-cart, +.sm2-playlist-wrapper ul li:hover .sm2-cart, +.sm2-playlist-wrapper ul li.selected .sm2-cart { + background-image: url(../images/icomoon/entypo-25px-ffffff/PNG/cart.png); + background-image: none, url(../images/icomoon/entypo-25px-ffffff/SVG/cart.svg); + /* slight alignment tweak */ + background-position: 48% 50%; +} + +.sm2-playlist-wrapper ul li .sm2-music, +.sm2-playlist-wrapper ul li:hover .sm2-music, +.sm2-playlist-wrapper ul li.selected .sm2-music { + background-image: url(../images/icomoon/entypo-25px-ffffff/PNG/music.png); + background-image: none, url(../images/icomoon/entypo-25px-ffffff/SVG/music.svg); +} + +.sm2-bar-ui.dark-text .sm2-playlist-wrapper ul li .sm2-cart, +.sm2-bar-ui.dark-text .sm2-playlist-wrapper ul li:hover .sm2-cart, +.sm2-bar-ui.dark-text .sm2-playlist-wrapper ul li.selected .sm2-cart { + background-image: url(../images/icomoon/entypo-25px-000000/PNG/cart.png); + background-image: none, url(../images/icomoon/entypo-25px-000000/SVG/cart.svg); +} + +.sm2-bar-ui.dark-text .sm2-playlist-wrapper ul li .sm2-music, +.sm2-bar-ui.dark-text .sm2-playlist-wrapper ul li:hover .sm2-music, +.sm2-bar-ui.dark-text .sm2-playlist-wrapper ul li.selected .sm2-music { + background-image: url(../images/icomoon/entypo-25px-000000/PNG/music.png); + background-image: none, url(../images/icomoon/entypo-25px-000000/SVG/music.svg); +} + + +.sm2-bar-ui.dark-text .sm2-playlist-wrapper ul li .sm2-col { + border-left-color: rgba(0,0,0,0.15); +} + +.sm2-playlist-wrapper ul li .sm2-icon:hover { + background-color: rgba(0,0,0,0.33); +} + +.sm2-bar-ui .sm2-playlist-wrapper ul li .sm2-icon:hover { + background-color: rgba(0,0,0,0.45); +} + +.sm2-bar-ui.dark-text .sm2-playlist-wrapper ul li.selected .sm2-icon:hover { + background-color: rgba(255,255,255,0.25); + border-color: rgba(0,0,0,0.125); +} + +.sm2-progress-ball .icon-overlay { + position: absolute; + width: 100%; + height: 100%; + top: 0px; + left: 0px; + background: none, url(../image/icomoon/free-25px-000000/SVG/spinner.svg); + background-size: 72%; + background-position: 50%; + background-repeat: no-repeat; + display: none; +} + +.playing.buffering .sm2-progress-ball .icon-overlay { + display: block; + -webkit-animation: spin 0.6s linear infinite; + animation: spin 0.6s linear infinite; +} + +@-webkit-keyframes spin { + 0% { + -webkit-transform: rotate(0deg); + } + 100% { + -webkit-transform: rotate(360deg); + } +} + +@-moz-keyframes spin { + 0% { + transform: rotate(0deg); + } + 100% { + transform: rotate(360deg); + } +} + +@keyframes spin { + 0% { + transform: rotate(0deg); + } + 100% { + transform: rotate(360deg); + } +} + +.sm2-element ul { + font-size: 95%; + list-style-type: none; +} + +.sm2-element ul, +.sm2-element ul li { + margin: 0px; + padding: 0px; +} + +.bd.sm2-playlist-drawer { + /* optional: absolute positioning */ + /* position: absolute; */ + z-index: 3; + border-radius: 0px; + width: 100%; + height: 0px; + border: none; + background-image: none; + display: block; + overflow: hidden; + transition: height 0.2s ease-in-out; +} + +.sm2-bar-ui.fixed .bd.sm2-playlist-drawer, +.sm2-bar-ui.bottom .bd.sm2-playlist-drawer { + position: absolute; +} + +.sm2-bar-ui.fixed .sm2-playlist-wrapper, +.sm2-bar-ui.bottom .sm2-playlist-wrapper { + padding-bottom: 0px; +} + +.sm2-bar-ui.fixed .bd.sm2-playlist-drawer, +.sm2-bar-ui.bottom .bd.sm2-playlist-drawer { + /* show playlist on top */ + bottom: 2.8em; +} + +.sm2-bar-ui .bd.sm2-playlist-drawer { + opacity: 0.5; + /* redraw fix for Chrome, background color doesn't always draw when playlist drawer open. */ + transform: translateZ(0); +} + +/* experimental, may not perform well. */ +/* +.sm2-bar-ui .bd.sm2-playlist-drawer a { + -webkit-filter: blur(5px); +} +*/ + +.sm2-bar-ui.playlist-open .bd.sm2-playlist-drawer { + height: auto; + opacity: 1; +} + +.sm2-bar-ui.playlist-open .bd.sm2-playlist-drawer a { + -webkit-filter: none; /* blur(0px) was still blurred on retina displays, as of 07/2014 */ +} + +.sm2-bar-ui.fixed.playlist-open .bd.sm2-playlist-drawer .sm2-playlist-wrapper, +.sm2-bar-ui.bottom.playlist-open .bd.sm2-playlist-drawer .sm2-playlist-wrapper { + /* extra padding when open */ + padding-bottom: 0.5em; + box-shadow: none; +} + +.sm2-bar-ui .bd.sm2-playlist-drawer { + transition: all 0.2s ease-in-out; + transition-property: transform, height, opacity, background-color, -webkit-filter; +} + +.sm2-bar-ui .bd.sm2-playlist-drawer a { + transition: -webkit-filter 0.2s ease-in-out; +} + +.sm2-bar-ui .bd.sm2-playlist-drawer .sm2-inline-texture { + /* negative offset for height of top bar, so background is seamless. */ + background-position: 0px -2.8em; +} + +.sm2-box-shadow { + position: absolute; + left: 0px; + top: 0px; + width: 100%; + height: 100%; + box-shadow: inset 0px 1px 6px rgba(0,0,0,0.15); +} + +.sm2-playlist-wrapper { + position: relative; + padding: 0.5em 0.5em 0.5em 0.25em; + background-image: none, none; +} + +.sm2-playlist-wrapper ul { + max-height: 9.25em; + overflow: auto; +} + +.sm2-playlist-wrapper ul li { + border-bottom: 1px solid rgba(0,0,0,0.05); +} + +.sm2-playlist-wrapper ul li:nth-child(odd) { + background-color: rgba(255,255,255,0.03); +} + +.sm2-playlist-wrapper ul li a { + display: block; + padding: 0.5em 0.25em 0.5em 0.75em; + margin-right: 0px; + font-size: 90%; + vertical-align: middle; +} + +.sm2-playlist-wrapper ul li a.sm2-exclude { + display: inline-block; +} + +.sm2-playlist-wrapper ul li a.sm2-exclude .label { + font-size: 95%; + line-height: 1em; + margin-left: 0px; + padding: 2px 4px; +} + +.sm2-playlist-wrapper ul li:hover a { + background-color: rgba(0,0,0,0.20); + background-image: url(../images/black-20.png); + background-image: none, none; +} + +.sm2-bar-ui.dark-text .sm2-playlist-wrapper ul li:hover a { + background-color: rgba(255,255,255,0.1); + background-image: url(../images/black-10.png); + background-image: none, none; +} + +.sm2-playlist-wrapper ul li.selected a { + background-color: rgba(0,0,0,0.25); + background-image: url(../images/black-20.png); + background-image: none, none; +} + +.sm2-bar-ui.dark-text ul li.selected a { + background-color: rgba(255,255,255,0.1); + background-image: url(../images/black-10.png); + background-image: none, none; +} + +.sm2-bar-ui .disabled { + filter: alpha(opacity=33); /* <= IE 8 */ + opacity: 0.33; +} + +.sm2-bar-ui .bd .sm2-button-element.disabled:hover { + background-color: transparent; +} + +.sm2-bar-ui .active, +/*.sm2-bar-ui.playlist-open .sm2-menu,*/ +.sm2-bar-ui.playlist-open .sm2-menu:hover { + /* depressed / "on" state */ + box-shadow: inset 0px 0px 2px rgba(0,0,0,0.1); + background-image: none; +} + +.firefox-fix { + /** + * This exists because of a Firefox bug from 2000 + * re: nested relative / absolute elements inside table cells. + * https://bugzilla.mozilla.org/show_bug.cgi?id=63895 + */ + position: relative; + display: inline-block; + width: 100%; + height: 100%; +} + +/* some custom scrollbar trickery, where supported */ + +.sm2-playlist-wrapper ul::-webkit-scrollbar { + width: 10px; +} + +.sm2-playlist-wrapper ul::-webkit-scrollbar-track { + background: rgba(0,0,0,0.33); + border-radius: 10px; +} + +.sm2-playlist-wrapper ul::-webkit-scrollbar-thumb { + border-radius: 10px; + background: #fff; +} + +.sm2-extra-controls { + font-size: 0px; + text-align: center; +} + +.sm2-bar-ui .label { + position: relative; + display: inline-block; + font-size: 0.7em; + margin-left: 0.25em; + vertical-align: top; + background-color: rgba(0,0,0,0.25); + border-radius: 3px; + padding: 0px 3px; + box-sizing: padding-box; +} + +.sm2-bar-ui.dark-text .label { + background-color: rgba(0,0,0,0.1); + background-image: url(../images/black-10.png); + background-image: none, none; +} + +.sm2-bar-ui .sm2-playlist-drawer .label { + font-size: 0.8em; + padding: 0px 3px; +} + +/* --- full width stuff --- */ + +.sm2-bar-ui .sm2-inline-element { + display: table-cell; +} + +.sm2-bar-ui .sm2-inline-element { + /* collapse */ + width: 1%; +} + +.sm2-bar-ui .sm2-inline-status { + /* full width */ + width: 100%; + min-width: 100%; + max-width: 100%; +} + +.sm2-bar-ui > .bd { + width: 100%; +} + +.sm2-bar-ui .sm2-playlist-drawer { + /* re-hide playlist */ + display: block; + overflow: hidden; +} diff --git a/cps/static/css/listen.css b/cps/static/css/listen.css new file mode 100644 index 00000000..b08cc33c --- /dev/null +++ b/cps/static/css/listen.css @@ -0,0 +1,114 @@ +.sm2-bar-ui { + font-size: 20px; + } + + .sm2-bar-ui.compact { + max-width: 90%; + } + + .sm2-progress .sm2-progress-ball { + width: .5333em; + height: 1.9333em; + border-radius: 0em; + } + + .sm2-progress .sm2-progress-track { + height: 0.15em; + background: white; + } + + .sm2-bar-ui .sm2-main-controls, + .sm2-bar-ui .sm2-playlist-drawer { + background-color: transparent; + } + + .sm2-bar-ui .sm2-inline-texture { + background: transparent; + } + + .rating .glyphicon-star { + color: gray; + } + + .rating .glyphicon-star.good { + color: white; + } + + body { + overflow: hidden; + background: #272B30; + color: #aaa; + } + + #main { + position: absolute; + width: 100%; + height: 100%; + } + + #area { + width: 80%; + height: 80%; + margin: 5% auto; + max-width: 1250px; + } + + #area iframe { + border: none; + } + + #prev { + left: 40px; + } + + #next { + right: 40px; + } + + .arrow { + position: absolute; + top: 50%; + margin-top: -32px; + font-size: 64px; + color: #E2E2E2; + font-family: arial, sans-serif; + font-weight: bold; + cursor: pointer; + -webkit-user-select: none; + -moz-user-select: none; + user-select: none; + } + + .arrow:hover { + color: #777; + } + + .arrow:active { + color: #000; + } + + xmp, + pre, + plaintext { + display: block; + font-family: -moz-fixed; + white-space: pre; + margin: 1em 0; + } + + #area { + overflow: hidden; + } + + pre { + white-space: pre-wrap; + word-wrap: break-word; + font-family: -moz-fixed; + column-count: 2; + -webkit-columns: 2; + -moz-columns: 2; + column-gap: 20px; + -moz-column-gap: 20px; + -webkit-column-gap: 20px; + position: relative; + } \ No newline at end of file diff --git a/cps/static/css/style.css b/cps/static/css/style.css index c4a9b502..1880207a 100644 --- a/cps/static/css/style.css +++ b/cps/static/css/style.css @@ -1,3 +1,6 @@ + +.tooltip.bottom .tooltip-inner{font-size:13px;font-family:Open Sans Semibold,Helvetica Neue,Helvetica,Arial,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;padding:3px 10px;border-radius:4px;background-color:#fff;-webkit-box-shadow:0 4px 10px 0 rgba(0,0,0,.35);box-shadow:0 4px 10px 0 rgba(0,0,0,.35);opacity:1;white-space:nowrap;margin-top:-16px!important;line-height:1.71428571;color:#ddd} + @font-face { font-family: 'Grand Hotel'; font-style: normal; @@ -136,7 +139,20 @@ input.pill:not(:checked) + label .glyphicon { .editable-cancel { margin-bottom: 0px !important; margin-left: 7px !important;} .editable-submit { margin-bottom: 0px !important;} +.filterheader { margin-bottom: 20px; } + .modal-body .comments { max-height:300px; overflow-y: auto; } + +div.log { + font-family: Courier New; + font-size: 12px; + box-sizing: border-box; + height: 700px; + overflow-y: scroll; + border: 1px solid #ddd; + white-space: nowrap; + padding: 0.5em; +} diff --git a/cps/static/js/archive/archive.js b/cps/static/js/archive/archive.js index cfc7bd40..13e1d183 100644 --- a/cps/static/js/archive/archive.js +++ b/cps/static/js/archive/archive.js @@ -24,40 +24,45 @@ * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE * USE OR OTHER DEALINGS IN THE SOFTWARE. */ - /* ******************************************************************** - * Alphanum sort() function version - case insensitive - * - Slower, but easier to modify for arrays of objects which contain - * string properties - * - */ +/* ******************************************************************** +* Alphanum sort() function version - case insensitive +* - Slower, but easier to modify for arrays of objects which contain +* string properties +* +*/ +/* exported alphanumCase */ + + function alphanumCase(a, b) { - function chunkify(t) { - var tz = new Array(); - var x = 0, y = -1, n = 0, i, j; - - while (i = (j = t.charAt(x++)).charCodeAt(0)) { - var m = (i == 46 || (i >=48 && i <= 57)); - if (m !== n) { - tz[++y] = ""; - n = m; - } - tz[y] += j; + function chunkify(t) { + var tz = new Array(); + var x = 0, y = -1, n = 0, i, j; + + while (i = (j = t.charAt(x++)).charCodeAt(0)) { + var m = (i === 46 || (i >= 48 && i <= 57)); + if (m !== n) { + tz[++y] = ""; + n = m; + } + tz[y] += j; + } + return tz; } - return tz; - } - - var aa = chunkify(a.filename.toLowerCase()); - var bb = chunkify(b.filename.toLowerCase()); - - for (x = 0; aa[x] && bb[x]; x++) { - if (aa[x] !== bb[x]) { - var c = Number(aa[x]), d = Number(bb[x]); - if (c == aa[x] && d == bb[x]) { - return c - d; - } else return (aa[x] > bb[x]) ? 1 : -1; + + var aa = chunkify(a.filename.toLowerCase()); + var bb = chunkify(b.filename.toLowerCase()); + + for (var x = 0; aa[x] && bb[x]; x++) { + if (aa[x] !== bb[x]) { + var c = Number(aa[x]), d = Number(bb[x]); + if (c === aa[x] && d === bb[x]) { + return c - d; + } else { + return (aa[x] > bb[x]) ? 1 : -1; + } + } } - } - return aa.length - bb.length; + return aa.length - bb.length; } // =========================================================================== diff --git a/cps/static/js/archive/unzip.js b/cps/static/js/archive/unzip.js index a4cec8d0..886f4b80 100644 --- a/cps/static/js/archive/unzip.js +++ b/cps/static/js/archive/unzip.js @@ -74,8 +74,8 @@ var ZipLocalFile = function(bstream) { this.extraField = null; if (this.extraFieldLength > 0) { - this.extraField = bstream.readString(this.extraFieldLength); - info(" extra field=" + this.extraField); + this.extraField = bstream.readString(this.extraFieldLength); + info(" extra field=" + this.extraField); } // read in the compressed data diff --git a/cps/static/js/filter_list.js b/cps/static/js/filter_list.js new file mode 100644 index 00000000..0610bb86 --- /dev/null +++ b/cps/static/js/filter_list.js @@ -0,0 +1,195 @@ +/* This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web) + * Copyright (C) 2018 OzzieIsaacs + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +var direction = 0; // Descending order +var sort = 0; // Show sorted entries + +$("#sort_name").click(function() { + var count = 0; + var index = 0; + var store; + // Append 2nd half of list to first half for easier processing + var cnt = $("#second").contents(); + $("#list").append(cnt); + // Count no of elements + var listItems = $("#list").children(".row"); + var listlength = listItems.length; + // check for each element if its Starting character matches + $(".row").each(function() { + if ( sort === 1) { + store = this.attributes["data-name"]; + } else { + store = this.attributes["data-id"]; + } + $(this).find("a").html(store.value); + if ($(this).css("display") !== "none") { + count++; + } + }); + /*listItems.sort(function(a,b){ + return $(a).children()[1].innerText.localeCompare($(b).children()[1].innerText) + });*/ + // Find count of middle element + if (count > 20) { + var middle = parseInt(count / 2) + (count % 2); + // search for the middle of all visibe elements + $(".row").each(function() { + index++; + if ($(this).css("display") !== "none") { + middle--; + if (middle <= 0) { + return false; + } + } + }); + // Move second half of visible elements + $("#second").append(listItems.slice(index, listlength)); + } + sort = (sort + 1) % 2; +}); + +$("#desc").click(function() { + if (direction === 0) { + return; + } + var index = 0; + var list = $("#list"); + var second = $("#second"); + // var cnt = ; + list.append(second.contents()); + var listItems = list.children(".row"); + var reversed, elementLength, middle; + reversed = listItems.get().reverse(); + elementLength = reversed.length; + // Find count of middle element + var count = $(".row:visible").length; + if (count > 20) { + middle = parseInt(count / 2) + (count % 2); + + //var middle = parseInt(count / 2) + (count % 2); + // search for the middle of all visible elements + $(reversed).each(function() { + index++; + if ($(this).css("display") !== "none") { + middle--; + if (middle <= 0) { + return false; + } + } + }); + + list.append(reversed.slice(0, index)); + second.append(reversed.slice(index, elementLength)); + } else { + list.append(reversed.slice(0, elementLength)); + } + direction = 0; +}); + + +$("#asc").click(function() { + if (direction === 1) { + return; + } + var index = 0; + var list = $("#list"); + var second = $("#second"); + list.append(second.contents()); + var listItems = list.children(".row"); + var reversed = listItems.get().reverse(); + var elementLength = reversed.length; + + // Find count of middle element + var count = $(".row:visible").length; + if (count > 20) { + var middle = parseInt(count / 2) + (count % 2); + + //var middle = parseInt(count / 2) + (count % 2); + // search for the middle of all visible elements + $(reversed).each(function() { + index++; + if ($(this).css("display") !== "none") { + middle--; + if (middle <= 0) { + return false; + } + } + }); + + // middle = parseInt(elementLength / 2) + (elementLength % 2); + + list.append(reversed.slice(0, index)); + second.append(reversed.slice(index, elementLength)); + } else { + list.append(reversed.slice(0, elementLength)); + } + direction = 1; +}); + +$("#all").click(function() { + var cnt = $("#second").contents(); + $("#list").append(cnt); + // Find count of middle element + var listItems = $("#list").children(".row"); + var listlength = listItems.length; + var middle = parseInt(listlength / 2) + (listlength % 2); + // go through all elements and make them visible + listItems.each(function() { + $(this).show(); + }); + // Move second half of all elements + if (listlength > 20) { + $("#second").append(listItems.slice(middle, listlength)); + } +}); + +$(".char").click(function() { + var character = this.innerText; + var count = 0; + var index = 0; + // Append 2nd half of list to first half for easier processing + var cnt = $("#second").contents(); + $("#list").append(cnt); + // Count no of elements + var listItems = $("#list").children(".row"); + var listlength = listItems.length; + // check for each element if its Starting character matches + $(".row").each(function() { + if (this.attributes["data-id"].value.charAt(0).toUpperCase() !== character) { + $(this).hide(); + } else { + $(this).show(); + count++; + } + }); + if (count > 20) { + // Find count of middle element + var middle = parseInt(count / 2) + (count % 2); + // search for the middle of all visibe elements + $(".row").each(function() { + index++; + if ($(this).css("display") !== "none") { + middle--; + if (middle <= 0) { + return false; + } + } + }); + // Move second half of visible elements + $("#second").append(listItems.slice(index, listlength)); + } +}); diff --git a/cps/static/js/get_meta.js b/cps/static/js/get_meta.js index 95a28042..cf079ba7 100644 --- a/cps/static/js/get_meta.js +++ b/cps/static/js/get_meta.js @@ -141,6 +141,7 @@ $(function () { } }, complete: function complete() { + ggDone = true; showResult(); $("#show-google").trigger("change"); } diff --git a/cps/static/js/io/bitstream.js b/cps/static/js/io/bitstream.js old mode 100755 new mode 100644 diff --git a/cps/static/js/io/bytestream.js b/cps/static/js/io/bytestream.js index 55b14005..9372f648 100644 --- a/cps/static/js/io/bytestream.js +++ b/cps/static/js/io/bytestream.js @@ -101,6 +101,35 @@ bitjs.io = bitjs.io || {}; }; + /** + * ToDo: Returns the next n bytes as a signed number and advances the stream pointer. + * @param {number} n The number of bytes to read. + * @return {number} The bytes interpreted as a signed number. + */ + bitjs.io.ByteStream.prototype.movePointer = function(n) { + this.ptr += n; + // end of buffer reached + if ((this.bytes.byteLength - this.ptr) < 0 ) { + this.ptr = this.bytes.byteLength; + } + } + + /** + * ToDo: Returns the next n bytes as a signed number and advances the stream pointer. + * @param {number} n The number of bytes to read. + * @return {number} The bytes interpreted as a signed number. + */ + bitjs.io.ByteStream.prototype.moveTo = function(n) { + if ( n < 0 ) { + n = 0; + } + this.ptr = n; + // end of buffer reached + if ((this.bytes.byteLength - this.ptr) < 0 ) { + this.ptr = this.bytes.byteLength; + } + } + /** * This returns n bytes as a sub-array, advancing the pointer if movePointers * is true. diff --git a/cps/static/js/libs/bar-ui.js b/cps/static/js/libs/bar-ui.js new file mode 100644 index 00000000..e0d4b85c --- /dev/null +++ b/cps/static/js/libs/bar-ui.js @@ -0,0 +1,1745 @@ +(function (window) { + + /** + * SoundManager 2: "Bar UI" player + * Copyright (c) 2014, Scott Schiller. All rights reserved. + * http://www.schillmania.com/projects/soundmanager2/ + * Code provided under BSD license. + * http://schillmania.com/projects/soundmanager2/license.txt + */ + + /* global console, document, navigator, soundManager, window */ + + 'use strict'; + + var Player, + players = [], + // CSS selector that will get us the top-level DOM node for the player UI. + playerSelector = '.sm2-bar-ui', + playerOptions, + utils; + + /** + * The following are player object event callback examples. + * Override globally by setting window.sm2BarPlayers.on = {}, or individually by window.sm2BarPlayers[0].on = {} etc. + * soundObject is provided for whileplaying() etc., but playback control should be done via the player object. + */ + players.on = { + /* + play: function(player, soundObject) { + console.log('playing', player); + }, + whileplaying: function(player, soundObject) { + console.log('whileplaying', player, soundObject); + }, + finish: function(player, soundObject) { + // each sound + console.log('finish', player); + }, + pause: function(player, soundObject) { + console.log('pause', player); + }, + error: function(player, soundObject) { + console.log('error', player); + }, + end: function(player, soundObject) { + // end of playlist + console.log('end', player); + } + */ + }; + + playerOptions = { + // useful when multiple players are in use, or other SM2 sounds are active etc. + stopOtherSounds: true, + // CSS class to let the browser load the URL directly e.g., download foo.mp3 + excludeClass: 'sm2-exclude' + }; + + soundManager.setup({ + // trade-off: higher UI responsiveness (play/progress bar), but may use more CPU. + html5PollingInterval: 50, + flashVersion: 9 + }); + + soundManager.onready(function () { + + var nodes, i, j; + + nodes = utils.dom.getAll(playerSelector); + + if (nodes && nodes.length) { + for (i = 0, j = nodes.length; i < j; i++) { + players.push(new Player(nodes[i])); + } + } + + }); + + /** + * player bits + */ + + Player = function (playerNode) { + + var css, dom, extras, playlistController, soundObject, actions, actionData, defaultItem, defaultVolume, firstOpen, exports; + + css = { + disabled: 'disabled', + selected: 'selected', + active: 'active', + legacy: 'legacy', + noVolume: 'no-volume', + playlistOpen: 'playlist-open' + }; + + dom = { + o: null, + playlist: null, + playlistTarget: null, + playlistContainer: null, + time: null, + player: null, + progress: null, + progressTrack: null, + progressBar: null, + duration: null, + volume: null + }; + + // prepended to tracks when a sound fails to load/play + extras = { + loadFailedCharacter: '' + }; + + function stopOtherSounds() { + + if (playerOptions.stopOtherSounds) { + soundManager.stopAll(); + } + + } + + function callback(method, oSound) { + if (method) { + // fire callback, passing current player and sound objects + if (exports.on && exports.on[method]) { + exports.on[method](exports, oSound); + } else if (players.on[method]) { + players.on[method](exports, oSound); + } + } + } + + function getTime(msec, useString) { + + // convert milliseconds to hh:mm:ss, return as object literal or string + + var nSec = Math.floor(msec / 1000), + hh = Math.floor(nSec / 3600), + min = Math.floor(nSec / 60) - Math.floor(hh * 60), + sec = Math.floor(nSec - (hh * 3600) - (min * 60)); + + // if (min === 0 && sec === 0) return null; // return 0:00 as null + + return (useString ? ((hh ? hh + ':' : '') + (hh && min < 10 ? '0' + min : min) + ':' + (sec < 10 ? '0' + sec : sec)) : { min: min, sec: sec }); + + } + + function setTitle(item) { + + // given a link, update the "now playing" UI. + + // if this is an
  • with an inner link, grab and use the text from that. + var links = item.getElementsByTagName('a'); + + if (links.length) { + item = links[0]; + } + + // remove any failed character sequence, also + dom.playlistTarget.innerHTML = '
    • ' + item.innerHTML.replace(extras.loadFailedCharacter, '') + '
    '; + + if (dom.playlistTarget.getElementsByTagName('li')[0].scrollWidth > dom.playlistTarget.offsetWidth) { + // this item can use , in fact. + dom.playlistTarget.innerHTML = '
    • ' + item.innerHTML + '
    '; + } + + } + + function makeSound(url) { + + var sound = soundManager.createSound({ + + url: url, + + volume: defaultVolume, + + whileplaying: function () { + + + //This sends a bookmark update to calibreweb every 30 seconds. + if (this.progressBuffer == undefined) { + this.progressBuffer = 0; + } + + if (this.progressBuffer <= this.position) { + + $.ajax(calibre.bookmarkUrl, { + method: "post", + data: { bookmark: this.position } + }).fail(function (xhr, status, error) { + console.error(error); + }); + + this.progressBuffer = this.progressBuffer + 30000; + } + + var progressMaxLeft = 100, + left, + width; + + left = Math.min(progressMaxLeft, Math.max(0, (progressMaxLeft * (this.position / this.durationEstimate)))) + '%'; + width = Math.min(100, Math.max(0, (100 * (this.position / this.durationEstimate)))) + '%'; + + if (this.duration) { + + dom.progress.style.left = left; + dom.progressBar.style.width = width; + + // TODO: only write changes + dom.time.innerHTML = getTime(this.position, true); + + } + + callback('whileplaying', this); + + }, + + onbufferchange: function (isBuffering) { + + if (isBuffering) { + utils.css.add(dom.o, 'buffering'); + } else { + utils.css.remove(dom.o, 'buffering'); + } + + }, + + onplay: function () { + utils.css.swap(dom.o, 'paused', 'playing'); + callback('play', this); + }, + + onpause: function () { + + $.ajax(calibre.bookmarkUrl, { + method: "post", + data: { bookmark: this.position } + }).fail(function (xhr, status, error) { + console.error(error); + }); + + utils.css.swap(dom.o, 'playing', 'paused'); + callback('pause', this); + }, + + onresume: function () { + utils.css.swap(dom.o, 'paused', 'playing'); + }, + + whileloading: function () { + + if (!this.isHTML5) { + dom.duration.innerHTML = getTime(this.durationEstimate, true); + } + + }, + + onload: function (ok) { + + sound.setPosition(calibre.bookmark); + + if (ok) { + dom.duration.innerHTML = getTime(this.duration, true); + + } else if (this._iO && this._iO.onerror) { + + this._iO.onerror(); + + } + + }, + + onerror: function () { + + // sound failed to load. + var item, element, html; + + item = playlistController.getItem(); + + if (item) { + + // note error, delay 2 seconds and advance? + // playlistTarget.innerHTML = '
    • ' + item.innerHTML + '
    '; + + if (extras.loadFailedCharacter) { + dom.playlistTarget.innerHTML = dom.playlistTarget.innerHTML.replace('
  • ', '
  • ' + extras.loadFailedCharacter + ' '); + if (playlistController.data.playlist && playlistController.data.playlist[playlistController.data.selectedIndex]) { + element = playlistController.data.playlist[playlistController.data.selectedIndex].getElementsByTagName('a')[0]; + html = element.innerHTML; + if (html.indexOf(extras.loadFailedCharacter) === -1) { + element.innerHTML = extras.loadFailedCharacter + ' ' + html; + } + } + } + + } + + callback('error', this); + + // load next, possibly with delay. + + if (navigator.userAgent.match(/mobile/i)) { + // mobile will likely block the next play() call if there is a setTimeout() - so don't use one here. + actions.next(); + } else { + if (playlistController.data.timer) { + window.clearTimeout(playlistController.data.timer); + } + playlistController.data.timer = window.setTimeout(actions.next, 2000); + } + + }, + + onstop: function () { + + $.ajax(calibre.bookmarkUrl, { + method: "post", + data: { bookmark: this.position } + }).fail(function (xhr, status, error) { + console.error(error); + }); + + utils.css.remove(dom.o, 'playing'); + + }, + + onfinish: function () { + + $.ajax(calibre.bookmarkUrl, { + method: "post", + data: { bookmark: this.position } + }).fail(function (xhr, status, error) { + console.error(error); + }); + + var lastIndex, item; + + utils.css.remove(dom.o, 'playing'); + + dom.progress.style.left = '0%'; + + lastIndex = playlistController.data.selectedIndex; + + callback('finish', this); + + // next track? + item = playlistController.getNext(); + + // don't play the same item over and over again, if at end of playlist (excluding single item case.) + if (item && (playlistController.data.selectedIndex !== lastIndex || (playlistController.data.playlist.length === 1 && playlistController.data.loopMode))) { + + playlistController.select(item); + + setTitle(item); + + stopOtherSounds(); + + // play next + this.play({ + url: playlistController.getURL() + }); + + } else { + + // end of playlist case + + // explicitly stop? + // this.stop(); + + callback('end', this); + + } + + } + + }); + + return sound; + + } + + function playLink(link) { + + // if a link is OK, play it. + + if (soundManager.canPlayURL(link.href)) { + + // if there's a timer due to failure to play one track, cancel it. + // catches case when user may use previous/next after an error. + if (playlistController.data.timer) { + window.clearTimeout(playlistController.data.timer); + playlistController.data.timer = null; + } + + if (!soundObject) { + soundObject = makeSound(link.href); + } + + // required to reset pause/play state on iOS so whileplaying() works? odd. + soundObject.stop(); + + playlistController.select(link.parentNode); + + setTitle(link.parentNode); + + // reset the UI + // TODO: function that also resets/hides timing info. + dom.progress.style.left = '0px'; + dom.progressBar.style.width = '0px'; + + stopOtherSounds(); + + soundObject.play({ + url: link.href, + position: 0 + }); + + } + + } + + function PlaylistController() { + + var data; + + data = { + + // list of nodes? + playlist: [], + + // NOTE: not implemented yet. + // shuffledIndex: [], + // shuffleMode: false, + + // selection + selectedIndex: 0, + + loopMode: false, + + timer: null + + }; + + function getPlaylist() { + + return data.playlist; + + } + + function getItem(offset) { + + var list, + item; + + // given the current selection (or an offset), return the current item. + + // if currently null, may be end of list case. bail. + if (data.selectedIndex === null) { + return offset; + } + + list = getPlaylist(); + + // use offset if provided, otherwise take default selected. + offset = (offset !== undefined ? offset : data.selectedIndex); + + // safety check - limit to between 0 and list length + offset = Math.max(0, Math.min(offset, list.length)); + + item = list[offset]; + + return item; + + } + + function findOffsetFromItem(item) { + + // given an
  • item, find it in the playlist array and return the index. + var list, + i, + j, + offset; + + offset = -1; + + list = getPlaylist(); + + if (list) { + + for (i = 0, j = list.length; i < j; i++) { + if (list[i] === item) { + offset = i; + break; + } + } + + } + + return offset; + + } + + function getNext() { + + // don't increment if null. + if (data.selectedIndex !== null) { + data.selectedIndex++; + } + + if (data.playlist.length > 1) { + + if (data.selectedIndex >= data.playlist.length) { + + if (data.loopMode) { + + // loop to beginning + data.selectedIndex = 0; + + } else { + + // no change + data.selectedIndex--; + + // end playback + // data.selectedIndex = null; + + } + + } + + } else { + + data.selectedIndex = null; + + } + + return getItem(); + + } + + function getPrevious() { + + data.selectedIndex--; + + if (data.selectedIndex < 0) { + // wrapping around beginning of list? loop or exit. + if (data.loopMode) { + data.selectedIndex = data.playlist.length - 1; + } else { + // undo + data.selectedIndex++; + } + } + + return getItem(); + + } + + function resetLastSelected() { + + // remove UI highlight(s) on selected items. + var items, + i, j; + + items = utils.dom.getAll(dom.playlist, '.' + css.selected); + + for (i = 0, j = items.length; i < j; i++) { + utils.css.remove(items[i], css.selected); + } + + } + + function select(item) { + + var offset, + itemTop, + itemBottom, + containerHeight, + scrollTop, + itemPadding, + liElement; + + // remove last selected, if any + resetLastSelected(); + + if (item) { + + liElement = utils.dom.ancestor('li', item); + + utils.css.add(liElement, css.selected); + + itemTop = item.offsetTop; + itemBottom = itemTop + item.offsetHeight; + containerHeight = dom.playlistContainer.offsetHeight; + scrollTop = dom.playlist.scrollTop; + itemPadding = 8; + + if (itemBottom > containerHeight + scrollTop) { + // bottom-align + dom.playlist.scrollTop = (itemBottom - containerHeight) + itemPadding; + } else if (itemTop < scrollTop) { + // top-align + dom.playlist.scrollTop = item.offsetTop - itemPadding; + } + + } + + // update selected offset, too. + offset = findOffsetFromItem(liElement); + + data.selectedIndex = offset; + + } + + function playItemByOffset(offset) { + + var item; + + offset = (offset || 0); + + item = getItem(offset); + + if (item) { + playLink(item.getElementsByTagName('a')[0]); + } + + } + + function getURL() { + + // return URL of currently-selected item + var item, url; + + item = getItem(); + + if (item) { + url = item.getElementsByTagName('a')[0].href; + } + + return url; + + } + + function refreshDOM() { + + // get / update playlist from DOM + + if (!dom.playlist) { + if (window.console && console.warn) { + console.warn('refreshDOM(): playlist node not found?'); + } + return; + } + + data.playlist = dom.playlist.getElementsByTagName('li'); + + } + + function initDOM() { + + dom.playlistTarget = utils.dom.get(dom.o, '.sm2-playlist-target'); + dom.playlistContainer = utils.dom.get(dom.o, '.sm2-playlist-drawer'); + dom.playlist = utils.dom.get(dom.o, '.sm2-playlist-bd'); + + } + + function initPlaylistController() { + + // inherit the default SM2 volume + defaultVolume = soundManager.defaultOptions.volume; + + initDOM(); + refreshDOM(); + + // animate playlist open, if HTML classname indicates so. + if (utils.css.has(dom.o, css.playlistOpen)) { + // hackish: run this after API has returned + window.setTimeout(function () { + actions.menu(true); + }, 1); + } + + } + + initPlaylistController(); + + return { + data: data, + refresh: refreshDOM, + getNext: getNext, + getPrevious: getPrevious, + getItem: getItem, + getURL: getURL, + playItemByOffset: playItemByOffset, + select: select + }; + + } + + function isRightClick(e) { + + // only pay attention to left clicks. old IE differs where there's no e.which, but e.button is 1 on left click. + if (e && ((e.which && e.which === 2) || (e.which === undefined && e.button !== 1))) { + // http://www.quirksmode.org/js/events_properties.html#button + return true; + } + + return false; + + } + + function getActionData(target) { + + // DOM measurements for volume slider + + if (!target) { + return; + } + + actionData.volume.x = utils.position.getOffX(target); + actionData.volume.y = utils.position.getOffY(target); + + actionData.volume.width = target.offsetWidth; + actionData.volume.height = target.offsetHeight; + + // potentially dangerous: this should, but may not be a percentage-based value. + actionData.volume.backgroundSize = parseInt(utils.style.get(target, 'background-size'), 10); + + // IE gives pixels even if background-size specified as % in CSS. Boourns. + if (window.navigator.userAgent.match(/msie|trident/i)) { + actionData.volume.backgroundSize = (actionData.volume.backgroundSize / actionData.volume.width) * 100; + } + + } + + function handleMouseDown(e) { + + var links, + target; + + target = e.target || e.srcElement; + + if (isRightClick(e)) { + return; + } + + // normalize to , if applicable. + if (target.nodeName.toLowerCase() !== 'a') { + + links = target.getElementsByTagName('a'); + if (links && links.length) { + target = target.getElementsByTagName('a')[0]; + } + + } + + if (utils.css.has(target, 'sm2-volume-control')) { + + // drag case for volume + + getActionData(target); + + utils.events.add(document, 'mousemove', actions.adjustVolume); + utils.events.add(document, 'touchmove', actions.adjustVolume); + utils.events.add(document, 'mouseup', actions.releaseVolume); + utils.events.add(document, 'touchend', actions.releaseVolume); + + // and apply right away + actions.adjustVolume(e); + + } + + } + + function handleMouse(e) { + + var target, barX, barWidth, x, clientX, newPosition, sound; + + target = dom.progressTrack; + + barX = utils.position.getOffX(target); + barWidth = target.offsetWidth; + clientX = utils.events.getClientX(e); + + x = (clientX - barX); + + newPosition = (x / barWidth); + + sound = soundObject; + + if (sound && sound.duration) { + + sound.setPosition(sound.duration * newPosition); + + // a little hackish: ensure UI updates immediately with current position, even if audio is buffering and hasn't moved there yet. + if (sound._iO && sound._iO.whileplaying) { + sound._iO.whileplaying.apply(sound); + } + + } + + if (e.preventDefault) { + e.preventDefault(); + } + + return false; + + } + + function releaseMouse(e) { + + utils.events.remove(document, 'mousemove', handleMouse); + utils.events.remove(document, 'touchmove', handleMouse); + + utils.css.remove(dom.o, 'grabbing'); + + utils.events.remove(document, 'mouseup', releaseMouse); + utils.events.remove(document, 'touchend', releaseMouse); + + utils.events.preventDefault(e); + + return false; + + } + + function handleProgressMouseDown(e) { + + if (isRightClick(e)) { + return; + } + + utils.css.add(dom.o, 'grabbing'); + + utils.events.add(document, 'mousemove', handleMouse); + utils.events.add(document, 'touchmove', handleMouse); + utils.events.add(document, 'mouseup', releaseMouse); + utils.events.add(document, 'touchend', releaseMouse); + + handleMouse(e); + + } + + function handleClick(e) { + + var evt, + target, + offset, + targetNodeName, + methodName, + href, + handled; + + evt = (e || window.event); + + target = evt.target || evt.srcElement; + + if (target && target.nodeName) { + + targetNodeName = target.nodeName.toLowerCase(); + + if (targetNodeName !== 'a') { + + // old IE (IE 8) might return nested elements inside the , eg., etc. Try to find the parent . + + if (target.parentNode) { + + do { + target = target.parentNode; + targetNodeName = target.nodeName.toLowerCase(); + } while (targetNodeName !== 'a' && target.parentNode); + + if (!target) { + // something went wrong. bail. + return false; + } + + } + + } + + if (targetNodeName === 'a') { + + // yep, it's a link. + + href = target.href; + + if (soundManager.canPlayURL(href)) { + + // not excluded + if (!utils.css.has(target, playerOptions.excludeClass)) { + + // find this in the playlist + + playLink(target); + + handled = true; + + } + + } else { + + // is this one of the action buttons, eg., play/pause, volume, etc.? + offset = target.href.lastIndexOf('#'); + + if (offset !== -1) { + + methodName = target.href.substr(offset + 1); + + if (methodName && actions[methodName]) { + handled = true; + actions[methodName](e); + } + + } + + } + + // fall-through case + + if (handled) { + // prevent browser fall-through + return utils.events.preventDefault(evt); + } + + } + + } + + return true; + + } + + function init() { + + // init DOM? + + if (!playerNode && window.console && console.warn) { + console.warn('init(): No playerNode element?'); + } + + dom.o = playerNode; + + // are we dealing with a crap browser? apply legacy CSS if so. + if (window.navigator.userAgent.match(/msie [678]/i)) { + utils.css.add(dom.o, css.legacy); + } + + if (window.navigator.userAgent.match(/mobile/i)) { + // majority of mobile devices don't let HTML5 audio set volume. + utils.css.add(dom.o, css.noVolume); + } + + dom.progress = utils.dom.get(dom.o, '.sm2-progress-ball'); + + dom.progressTrack = utils.dom.get(dom.o, '.sm2-progress-track'); + + dom.progressBar = utils.dom.get(dom.o, '.sm2-progress-bar'); + + dom.volume = utils.dom.get(dom.o, 'a.sm2-volume-control'); + + // measure volume control dimensions + if (dom.volume) { + getActionData(dom.volume); + } + + dom.duration = utils.dom.get(dom.o, '.sm2-inline-duration'); + + dom.time = utils.dom.get(dom.o, '.sm2-inline-time'); + + playlistController = new PlaylistController(); + + defaultItem = playlistController.getItem(0); + + playlistController.select(defaultItem); + + if (defaultItem) { + setTitle(defaultItem); + } + + utils.events.add(dom.o, 'mousedown', handleMouseDown); + utils.events.add(dom.o, 'touchstart', handleMouseDown); + utils.events.add(dom.o, 'click', handleClick); + utils.events.add(dom.progressTrack, 'mousedown', handleProgressMouseDown); + utils.events.add(dom.progressTrack, 'touchstart', handleProgressMouseDown); + + } + + // --- + + actionData = { + + volume: { + x: 0, + y: 0, + width: 0, + height: 0, + backgroundSize: 0 + } + + }; + + actions = { + + play: function (offsetOrEvent) { + + /** + * This is an overloaded function that takes mouse/touch events or offset-based item indices. + * Remember, "auto-play" will not work on mobile devices unless this function is called immediately from a touch or click event. + * If you have the link but not the offset, you can also pass a fake event object with a target of an inside the playlist - e.g. { target: someMP3Link } + */ + + var target, + href, + e; + + if (offsetOrEvent !== undefined && !isNaN(offsetOrEvent)) { + // smells like a number. + playlistController.playItemByOffset(offsetOrEvent); + return; + } + + // DRY things a bit + e = offsetOrEvent; + + if (e && e.target) { + + target = e.target || e.srcElement; + + href = target.href; + + } + + // haaaack - if null due to no event, OR '#' due to play/pause link, get first link from playlist + if (!href || href.indexOf('#') !== -1) { + href = dom.playlist.getElementsByTagName('a')[0].href; + } + + if (!soundObject) { + soundObject = makeSound(href); + } + + // edge case: if the current sound is not playing, stop all others. + if (!soundObject.playState) { + stopOtherSounds(); + } + + // TODO: if user pauses + unpauses a sound that had an error, try to play next? + soundObject.togglePause(); + + // special case: clear "play next" timeout, if one exists. + // edge case: user pauses after a song failed to load. + if (soundObject.paused && playlistController.data.timer) { + window.clearTimeout(playlistController.data.timer); + playlistController.data.timer = null; + } + + }, + + pause: function () { + + if (soundObject && soundObject.readyState) { + soundObject.pause(); + } + + }, + + resume: function () { + + if (soundObject && soundObject.readyState) { + soundObject.resume(); + } + + }, + + stop: function () { + + // just an alias for pause, really. + // don't actually stop because that will mess up some UI state, i.e., dragging the slider. + return actions.pause(); + + }, + + next: function (/* e */) { + + var item, lastIndex; + + // special case: clear "play next" timeout, if one exists. + if (playlistController.data.timer) { + window.clearTimeout(playlistController.data.timer); + playlistController.data.timer = null; + } + + lastIndex = playlistController.data.selectedIndex; + + item = playlistController.getNext(true); + + // don't play the same item again + if (item && playlistController.data.selectedIndex !== lastIndex) { + playLink(item.getElementsByTagName('a')[0]); + } + + }, + + prev: function (/* e */) { + + var item, lastIndex; + + lastIndex = playlistController.data.selectedIndex; + + item = playlistController.getPrevious(); + + // don't play the same item again + if (item && playlistController.data.selectedIndex !== lastIndex) { + playLink(item.getElementsByTagName('a')[0]); + } + + }, + + shuffle: function (e) { + + // NOTE: not implemented yet. + + var target = (e ? e.target || e.srcElement : utils.dom.get(dom.o, '.shuffle')); + + if (target && !utils.css.has(target, css.disabled)) { + utils.css.toggle(target.parentNode, css.active); + playlistController.data.shuffleMode = !playlistController.data.shuffleMode; + } + + }, + + repeat: function (e) { + + var target = (e ? e.target || e.srcElement : utils.dom.get(dom.o, '.repeat')); + + if (target && !utils.css.has(target, css.disabled)) { + utils.css.toggle(target.parentNode, css.active); + playlistController.data.loopMode = !playlistController.data.loopMode; + } + + }, + + menu: function (ignoreToggle) { + + var isOpen; + + isOpen = utils.css.has(dom.o, css.playlistOpen); + + // hackish: reset scrollTop in default first open case. odd, but some browsers have a non-zero scroll offset the first time the playlist opens. + if (playlistController && !playlistController.data.selectedIndex && !firstOpen) { + dom.playlist.scrollTop = 0; + firstOpen = true; + } + + // sniff out booleans from mouse events, as this is referenced directly by event handlers. + if (typeof ignoreToggle !== 'boolean' || !ignoreToggle) { + + if (!isOpen) { + // explicitly set height:0, so the first closed -> open animation runs properly + dom.playlistContainer.style.height = '0px'; + } + + isOpen = utils.css.toggle(dom.o, css.playlistOpen); + + } + + // playlist + dom.playlistContainer.style.height = (isOpen ? dom.playlistContainer.scrollHeight : 0) + 'px'; + + }, + + adjustVolume: function (e) { + + /** + * NOTE: this is the mousemove() event handler version. + * Use setVolume(50), etc., to assign volume directly. + */ + + var backgroundMargin, + pixelMargin, + target, + value, + volume; + + value = 0; + + target = dom.volume; + + // safety net + if (e === undefined) { + return false; + } + + // normalize between mouse and touch events + var clientX = utils.events.getClientX(e); + + if (!e || clientX === undefined) { + // called directly or with a non-mouseEvent object, etc. + // proxy to the proper method. + if (arguments.length && window.console && window.console.warn) { + console.warn('Bar UI: call setVolume(' + e + ') instead of adjustVolume(' + e + ').'); + } + return actions.setVolume.apply(this, arguments); + } + + // based on getStyle() result + // figure out spacing around background image based on background size, eg. 60% background size. + // 60% wide means 20% margin on each side. + backgroundMargin = (100 - actionData.volume.backgroundSize) / 2; + + // relative position of mouse over element + value = Math.max(0, Math.min(1, (clientX - actionData.volume.x) / actionData.volume.width)); + + target.style.clip = 'rect(0px, ' + (actionData.volume.width * value) + 'px, ' + actionData.volume.height + 'px, ' + (actionData.volume.width * (backgroundMargin / 100)) + 'px)'; + + // determine logical volume, including background margin + pixelMargin = ((backgroundMargin / 100) * actionData.volume.width); + + volume = Math.max(0, Math.min(1, ((clientX - actionData.volume.x) - pixelMargin) / (actionData.volume.width - (pixelMargin * 2)))) * 100; + + // set volume + if (soundObject) { + soundObject.setVolume(volume); + } + + defaultVolume = volume; + + return utils.events.preventDefault(e); + + }, + + releaseVolume: function (/* e */) { + + utils.events.remove(document, 'mousemove', actions.adjustVolume); + utils.events.remove(document, 'touchmove', actions.adjustVolume); + utils.events.remove(document, 'mouseup', actions.releaseVolume); + utils.events.remove(document, 'touchend', actions.releaseVolume); + + }, + + setVolume: function (volume) { + + // set volume (0-100) and update volume slider UI. + + var backgroundSize, + backgroundMargin, + backgroundOffset, + target, + from, + to; + + if (volume === undefined || isNaN(volume)) { + return; + } + + if (dom.volume) { + + target = dom.volume; + + // based on getStyle() result + backgroundSize = actionData.volume.backgroundSize; + + // figure out spacing around background image based on background size, eg. 60% background size. + // 60% wide means 20% margin on each side. + backgroundMargin = (100 - backgroundSize) / 2; + + // margin as pixel value relative to width + backgroundOffset = actionData.volume.width * (backgroundMargin / 100); + + from = backgroundOffset; + to = from + ((actionData.volume.width - (backgroundOffset * 2)) * (volume / 100)); + + target.style.clip = 'rect(0px, ' + to + 'px, ' + actionData.volume.height + 'px, ' + from + 'px)'; + + } + + // apply volume to sound, as applicable + if (soundObject) { + soundObject.setVolume(volume); + } + + defaultVolume = volume; + + } + + }; + + init(); + + // TODO: mixin actions -> exports + + exports = { + // Per-instance events: window.sm2BarPlayers[0].on = { ... } etc. See global players.on example above for reference. + on: null, + actions: actions, + dom: dom, + playlistController: playlistController + }; + + return exports; + + }; + + // barebones utilities for logic, CSS, DOM, events etc. + + utils = { + + array: (function () { + + function compare(property) { + + var result; + + return function (a, b) { + + if (a[property] < b[property]) { + result = -1; + } else if (a[property] > b[property]) { + result = 1; + } else { + result = 0; + } + return result; + }; + + } + + function shuffle(array) { + + // Fisher-Yates shuffle algo + + var i, j, temp; + + for (i = array.length - 1; i > 0; i--) { + j = Math.floor(Math.random() * (i + 1)); + temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + + return array; + + } + + return { + compare: compare, + shuffle: shuffle + }; + + }()), + + css: (function () { + + function hasClass(o, cStr) { + + return (o.className !== undefined ? new RegExp('(^|\\s)' + cStr + '(\\s|$)').test(o.className) : false); + + } + + function addClass(o, cStr) { + + if (!o || !cStr || hasClass(o, cStr)) { + return; // safety net + } + o.className = (o.className ? o.className + ' ' : '') + cStr; + + } + + function removeClass(o, cStr) { + + if (!o || !cStr || !hasClass(o, cStr)) { + return; + } + o.className = o.className.replace(new RegExp('( ' + cStr + ')|(' + cStr + ')', 'g'), ''); + + } + + function swapClass(o, cStr1, cStr2) { + + var tmpClass = { + className: o.className + }; + + removeClass(tmpClass, cStr1); + addClass(tmpClass, cStr2); + + o.className = tmpClass.className; + + } + + function toggleClass(o, cStr) { + + var found, + method; + + found = hasClass(o, cStr); + + method = (found ? removeClass : addClass); + + method(o, cStr); + + // indicate the new state... + return !found; + + } + + return { + has: hasClass, + add: addClass, + remove: removeClass, + swap: swapClass, + toggle: toggleClass + }; + + }()), + + dom: (function () { + + function getAll(param1, param2) { + + var node, + selector, + results; + + if (arguments.length === 1) { + + // .selector case + node = document.documentElement; + // first param is actually the selector + selector = param1; + + } else { + + // node, .selector + node = param1; + selector = param2; + + } + + // sorry, IE 7 users; IE 8+ required. + if (node && node.querySelectorAll) { + + results = node.querySelectorAll(selector); + + } + + return results; + + } + + function get(/* parentNode, selector */) { + + var results = getAll.apply(this, arguments); + + // hackish: if an array, return the last item. + if (results && results.length) { + return results[results.length - 1]; + } + + // handle "not found" case + return results && results.length === 0 ? null : results; + + } + + function ancestor(nodeName, element, checkCurrent) { + + if (!element || !nodeName) { + return element; + } + + nodeName = nodeName.toUpperCase(); + + // return if current node matches. + if (checkCurrent && element && element.nodeName === nodeName) { + return element; + } + + while (element && element.nodeName !== nodeName && element.parentNode) { + element = element.parentNode; + } + + return (element && element.nodeName === nodeName ? element : null); + + } + + return { + ancestor: ancestor, + get: get, + getAll: getAll + }; + + }()), + + position: (function () { + + function getOffX(o) { + + // http://www.xs4all.nl/~ppk/js/findpos.html + var curleft = 0; + + if (o.offsetParent) { + + while (o.offsetParent) { + + curleft += o.offsetLeft; + + o = o.offsetParent; + + } + + } else if (o.x) { + + curleft += o.x; + + } + + return curleft; + + } + + function getOffY(o) { + + // http://www.xs4all.nl/~ppk/js/findpos.html + var curtop = 0; + + if (o.offsetParent) { + + while (o.offsetParent) { + + curtop += o.offsetTop; + + o = o.offsetParent; + + } + + } else if (o.y) { + + curtop += o.y; + + } + + return curtop; + + } + + return { + getOffX: getOffX, + getOffY: getOffY + }; + + }()), + + style: (function () { + + function get(node, styleProp) { + + // http://www.quirksmode.org/dom/getstyles.html + var value; + + if (node.currentStyle) { + + value = node.currentStyle[styleProp]; + + } else if (window.getComputedStyle) { + + value = document.defaultView.getComputedStyle(node, null).getPropertyValue(styleProp); + + } + + return value; + + } + + return { + get: get + }; + + }()), + + events: (function () { + + var add, remove, preventDefault, getClientX; + + add = function (o, evtName, evtHandler) { + // return an object with a convenient detach method. + var eventObject = { + detach: function () { + return remove(o, evtName, evtHandler); + } + }; + if (window.addEventListener) { + o.addEventListener(evtName, evtHandler, false); + } else { + o.attachEvent('on' + evtName, evtHandler); + } + return eventObject; + }; + + remove = (window.removeEventListener !== undefined ? function (o, evtName, evtHandler) { + return o.removeEventListener(evtName, evtHandler, false); + } : function (o, evtName, evtHandler) { + return o.detachEvent('on' + evtName, evtHandler); + }); + + preventDefault = function (e) { + if (e.preventDefault) { + e.preventDefault(); + } else { + e.returnValue = false; + e.cancelBubble = true; + } + return false; + }; + + getClientX = function (e) { + // normalize between desktop (mouse) and touch (mobile/tablet/?) events. + // note pageX for touch, which normalizes zoom/scroll/pan vs. clientX. + return (e && (e.clientX || (e.touches && e.touches[0] && e.touches[0].pageX))); + }; + + return { + add: add, + preventDefault: preventDefault, + remove: remove, + getClientX: getClientX + }; + + }()), + + features: (function () { + + var getAnimationFrame, + localAnimationFrame, + localFeatures, + prop, + styles, + testDiv, + transform; + + testDiv = document.createElement('div'); + + /** + * hat tip: paul irish + * http://paulirish.com/2011/requestanimationframe-for-smart-animating/ + * https://gist.github.com/838785 + */ + + localAnimationFrame = (window.requestAnimationFrame + || window.webkitRequestAnimationFrame + || window.mozRequestAnimationFrame + || window.oRequestAnimationFrame + || window.msRequestAnimationFrame + || null); + + // apply to window, avoid "illegal invocation" errors in Chrome + getAnimationFrame = localAnimationFrame ? function () { + return localAnimationFrame.apply(window, arguments); + } : null; + + function has(propName) { + + // test for feature support + return (testDiv.style[propName] !== undefined ? propName : null); + + } + + // note local scope. + localFeatures = { + + transform: { + ie: has('-ms-transform'), + moz: has('MozTransform'), + opera: has('OTransform'), + webkit: has('webkitTransform'), + w3: has('transform'), + prop: null // the normalized property value + }, + + rotate: { + has3D: false, + prop: null + }, + + getAnimationFrame: getAnimationFrame + + }; + + localFeatures.transform.prop = ( + localFeatures.transform.w3 || + localFeatures.transform.moz || + localFeatures.transform.webkit || + localFeatures.transform.ie || + localFeatures.transform.opera + ); + + function attempt(style) { + + try { + testDiv.style[transform] = style; + } catch (e) { + // that *definitely* didn't work. + return false; + } + // if we can read back the style, it should be cool. + return !!testDiv.style[transform]; + + } + + if (localFeatures.transform.prop) { + + // try to derive the rotate/3D support. + transform = localFeatures.transform.prop; + styles = { + css_2d: 'rotate(0deg)', + css_3d: 'rotate3d(0,0,0,0deg)' + }; + + if (attempt(styles.css_3d)) { + localFeatures.rotate.has3D = true; + prop = 'rotate3d'; + } else if (attempt(styles.css_2d)) { + prop = 'rotate'; + } + + localFeatures.rotate.prop = prop; + + } + + testDiv = null; + + return localFeatures; + + }()) + + }; + + // --- + + // expose to global + window.sm2BarPlayers = players; + window.sm2BarPlayerOptions = playerOptions; + window.SM2BarPlayer = Player; + +}(window)); diff --git a/cps/static/js/libs/plugins.js b/cps/static/js/libs/plugins.js index 0ef33898..f69561a1 100644 --- a/cps/static/js/libs/plugins.js +++ b/cps/static/js/libs/plugins.js @@ -42,4 +42,77 @@ * Copyright 2018 Metafizzy */ -!function(t,e){"function"==typeof define&&define.amd?define("jquery-bridget/jquery-bridget",["jquery"],function(i){return e(t,i)}):"object"==typeof module&&module.exports?module.exports=e(t,require("jquery")):t.jQueryBridget=e(t,t.jQuery)}(window,function(t,e){"use strict";function i(i,r,l){function a(t,e,n){var o,r="$()."+i+'("'+e+'")';return t.each(function(t,a){var h=l.data(a,i);if(!h)return void s(i+" not initialized. Cannot call methods, i.e. "+r);var c=h[e];if(!c||"_"==e.charAt(0))return void s(r+" is not a valid method");var u=c.apply(h,n);o=void 0===o?u:o}),void 0!==o?o:t}function h(t,e){t.each(function(t,n){var o=l.data(n,i);o?(o.option(e),o._init()):(o=new r(n,e),l.data(n,i,o))})}l=l||e||t.jQuery,l&&(r.prototype.option||(r.prototype.option=function(t){l.isPlainObject(t)&&(this.options=l.extend(!0,this.options,t))}),l.fn[i]=function(t){if("string"==typeof t){var e=o.call(arguments,1);return a(this,t,e)}return h(this,t),this},n(l))}function n(t){!t||t&&t.bridget||(t.bridget=i)}var o=Array.prototype.slice,r=t.console,s="undefined"==typeof r?function(){}:function(t){r.error(t)};return n(e||t.jQuery),i}),function(t,e){"function"==typeof define&&define.amd?define("ev-emitter/ev-emitter",e):"object"==typeof module&&module.exports?module.exports=e():t.EvEmitter=e()}("undefined"!=typeof window?window:this,function(){function t(){}var e=t.prototype;return e.on=function(t,e){if(t&&e){var i=this._events=this._events||{},n=i[t]=i[t]||[];return n.indexOf(e)==-1&&n.push(e),this}},e.once=function(t,e){if(t&&e){this.on(t,e);var i=this._onceEvents=this._onceEvents||{},n=i[t]=i[t]||{};return n[e]=!0,this}},e.off=function(t,e){var i=this._events&&this._events[t];if(i&&i.length){var n=i.indexOf(e);return n!=-1&&i.splice(n,1),this}},e.emitEvent=function(t,e){var i=this._events&&this._events[t];if(i&&i.length){i=i.slice(0),e=e||[];for(var n=this._onceEvents&&this._onceEvents[t],o=0;o=0,this.isPrefilling?(this.log("prefill"),this.loadNextPage()):this.stopPrefill()},s.getPrefillDistance=function(){return this.options.elementScroll?this.scroller.clientHeight-this.scroller.scrollHeight:this.windowHeight-this.element.clientHeight},s.stopPrefill=function(){this.log("stopPrefill"),this.off("append",this.prefill)},e}),function(t,e){"function"==typeof define&&define.amd?define("infinite-scroll/js/scroll-watch",["./core","fizzy-ui-utils/utils"],function(i,n){return e(t,i,n)}):"object"==typeof module&&module.exports?module.exports=e(t,require("./core"),require("fizzy-ui-utils")):e(t,t.InfiniteScroll,t.fizzyUIUtils)}(window,function(t,e,i){var n=e.prototype;return e.defaults.scrollThreshold=400,e.create.scrollWatch=function(){this.pageScrollHandler=this.onPageScroll.bind(this),this.resizeHandler=this.onResize.bind(this);var t=this.options.scrollThreshold,e=t||0===t;e&&this.enableScrollWatch()},e.destroy.scrollWatch=function(){this.disableScrollWatch()},n.enableScrollWatch=function(){this.isScrollWatching||(this.isScrollWatching=!0,this.updateMeasurements(),this.updateScroller(),this.on("last",this.disableScrollWatch),this.bindScrollWatchEvents(!0))},n.disableScrollWatch=function(){this.isScrollWatching&&(this.bindScrollWatchEvents(!1),delete this.isScrollWatching)},n.bindScrollWatchEvents=function(e){var i=e?"addEventListener":"removeEventListener";this.scroller[i]("scroll",this.pageScrollHandler),t[i]("resize",this.resizeHandler)},n.onPageScroll=e.throttle(function(){var t=this.getBottomDistance();t<=this.options.scrollThreshold&&this.dispatchEvent("scrollThreshold")}),n.getBottomDistance=function(){return this.options.elementScroll?this.getElementBottomDistance():this.getWindowBottomDistance()},n.getWindowBottomDistance=function(){var e=this.top+this.element.clientHeight,i=t.pageYOffset+this.windowHeight;return e-i},n.getElementBottomDistance=function(){var t=this.scroller.scrollHeight,e=this.scroller.scrollTop+this.scroller.clientHeight;return t-e},n.onResize=function(){this.updateMeasurements()},i.debounceMethod(e,"onResize",150),e}),function(t,e){"function"==typeof define&&define.amd?define("infinite-scroll/js/history",["./core","fizzy-ui-utils/utils"],function(i,n){return e(t,i,n)}):"object"==typeof module&&module.exports?module.exports=e(t,require("./core"),require("fizzy-ui-utils")):e(t,t.InfiniteScroll,t.fizzyUIUtils)}(window,function(t,e,i){var n=e.prototype;e.defaults.history="replace";var o=document.createElement("a");return e.create.history=function(){if(this.options.history){o.href=this.getAbsolutePath();var t=o.origin||o.protocol+"//"+o.host,e=t==location.origin;return e?void(this.options.append?this.createHistoryAppend():this.createHistoryPageLoad()):void console.error("[InfiniteScroll] cannot set history with different origin: "+o.origin+" on "+location.origin+" . History behavior disabled.")}},n.createHistoryAppend=function(){this.updateMeasurements(),this.updateScroller(),this.scrollPages=[{top:0,path:location.href,title:document.title}],this.scrollPageIndex=0,this.scrollHistoryHandler=this.onScrollHistory.bind(this),this.unloadHandler=this.onUnload.bind(this),this.scroller.addEventListener("scroll",this.scrollHistoryHandler),this.on("append",this.onAppendHistory),this.bindHistoryAppendEvents(!0)},n.bindHistoryAppendEvents=function(e){var i=e?"addEventListener":"removeEventListener";this.scroller[i]("scroll",this.scrollHistoryHandler),t[i]("unload",this.unloadHandler)},n.createHistoryPageLoad=function(){this.on("load",this.onPageLoadHistory)},e.destroy.history=n.destroyHistory=function(){var t=this.options.history&&this.options.append;t&&this.bindHistoryAppendEvents(!1)},n.onAppendHistory=function(t,e,i){if(i&&i.length){var n=i[0],r=this.getElementScrollY(n);o.href=e,this.scrollPages.push({top:r,path:o.href,title:t.title})}},n.getElementScrollY=function(t){return this.options.elementScroll?this.getElementElementScrollY(t):this.getElementWindowScrollY(t)},n.getElementWindowScrollY=function(e){var i=e.getBoundingClientRect();return i.top+t.pageYOffset},n.getElementElementScrollY=function(t){return t.offsetTop-this.top},n.onScrollHistory=function(){for(var t,e,i=this.getScrollViewY(),n=0;n=i)break;t=n,e=o}t!=this.scrollPageIndex&&(this.scrollPageIndex=t,this.setHistory(e.title,e.path))},i.debounceMethod(e,"onScrollHistory",150),n.getScrollViewY=function(){return this.options.elementScroll?this.scroller.scrollTop+this.scroller.clientHeight/2:t.pageYOffset+this.windowHeight/2},n.setHistory=function(t,e){var i=this.options.history,n=i&&history[i+"State"];n&&(history[i+"State"](null,t,e),this.options.historyTitle&&(document.title=t),this.dispatchEvent("history",null,[t,e]))},n.onUnload=function(){var e=this.scrollPageIndex;if(0!==e){var i=this.scrollPages[e],n=t.pageYOffset-i.top+this.top;this.destroyHistory(),scrollTo(0,n)}},n.onPageLoadHistory=function(t,e){this.setHistory(t.title,e)},e}),function(t,e){"function"==typeof define&&define.amd?define("infinite-scroll/js/button",["./core","fizzy-ui-utils/utils"],function(i,n){return e(t,i,n)}):"object"==typeof module&&module.exports?module.exports=e(t,require("./core"),require("fizzy-ui-utils")):e(t,t.InfiniteScroll,t.fizzyUIUtils)}(window,function(t,e,i){function n(t,e){this.element=t,this.infScroll=e,this.clickHandler=this.onClick.bind(this),this.element.addEventListener("click",this.clickHandler),e.on("request",this.disable.bind(this)),e.on("load",this.enable.bind(this)),e.on("error",this.hide.bind(this)),e.on("last",this.hide.bind(this))}return e.create.button=function(){var t=i.getQueryElement(this.options.button);if(t)return void(this.button=new n(t,this))},e.destroy.button=function(){this.button&&this.button.destroy()},n.prototype.onClick=function(t){t.preventDefault(),this.infScroll.loadNextPage()},n.prototype.enable=function(){this.element.removeAttribute("disabled")},n.prototype.disable=function(){this.element.disabled="disabled"},n.prototype.hide=function(){this.element.style.display="none"},n.prototype.destroy=function(){this.element.removeEventListener("click",this.clickHandler)},e.Button=n,e}),function(t,e){"function"==typeof define&&define.amd?define("infinite-scroll/js/status",["./core","fizzy-ui-utils/utils"],function(i,n){return e(t,i,n)}):"object"==typeof module&&module.exports?module.exports=e(t,require("./core"),require("fizzy-ui-utils")):e(t,t.InfiniteScroll,t.fizzyUIUtils)}(window,function(t,e,i){function n(t){r(t,"none")}function o(t){r(t,"block")}function r(t,e){t&&(t.style.display=e)}var s=e.prototype;return e.create.status=function(){var t=i.getQueryElement(this.options.status);t&&(this.statusElement=t,this.statusEventElements={request:t.querySelector(".infinite-scroll-request"),error:t.querySelector(".infinite-scroll-error"),last:t.querySelector(".infinite-scroll-last")},this.on("request",this.showRequestStatus),this.on("error",this.showErrorStatus),this.on("last",this.showLastStatus),this.bindHideStatus("on"))},s.bindHideStatus=function(t){var e=this.options.append?"append":"load";this[t](e,this.hideAllStatus)},s.showRequestStatus=function(){this.showStatus("request")},s.showErrorStatus=function(){this.showStatus("error")},s.showLastStatus=function(){this.showStatus("last"),this.bindHideStatus("off")},s.showStatus=function(t){o(this.statusElement),this.hideStatusEventElements();var e=this.statusEventElements[t];o(e)},s.hideAllStatus=function(){n(this.statusElement),this.hideStatusEventElements()},s.hideStatusEventElements=function(){for(var t in this.statusEventElements){var e=this.statusEventElements[t];n(e)}},e}),function(t,e){"function"==typeof define&&define.amd?define(["infinite-scroll/js/core","infinite-scroll/js/page-load","infinite-scroll/js/scroll-watch","infinite-scroll/js/history","infinite-scroll/js/button","infinite-scroll/js/status"],e):"object"==typeof module&&module.exports&&(module.exports=e(require("./core"),require("./page-load"),require("./scroll-watch"),require("./history"),require("./button"),require("./status")))}(window,function(t){return t}),function(t,e){"use strict";"function"==typeof define&&define.amd?define("imagesloaded/imagesloaded",["ev-emitter/ev-emitter"],function(i){return e(t,i)}):"object"==typeof module&&module.exports?module.exports=e(t,require("ev-emitter")):t.imagesLoaded=e(t,t.EvEmitter)}("undefined"!=typeof window?window:this,function(t,e){function i(t,e){for(var i in e)t[i]=e[i];return t}function n(t){if(Array.isArray(t))return t;var e="object"==typeof t&&"number"==typeof t.length;return e?h.call(t):[t]}function o(t,e,r){if(!(this instanceof o))return new o(t,e,r);var s=t;return"string"==typeof t&&(s=document.querySelectorAll(t)),s?(this.elements=n(s),this.options=i({},this.options),"function"==typeof e?r=e:i(this.options,e),r&&this.on("always",r),this.getImages(),l&&(this.jqDeferred=new l.Deferred),void setTimeout(this.check.bind(this))):void a.error("Bad element for imagesLoaded "+(s||t))}function r(t){this.img=t}function s(t,e){this.url=t,this.element=e,this.img=new Image}var l=t.jQuery,a=t.console,h=Array.prototype.slice;o.prototype=Object.create(e.prototype),o.prototype.options={},o.prototype.getImages=function(){this.images=[],this.elements.forEach(this.addElementImages,this)},o.prototype.addElementImages=function(t){"IMG"==t.nodeName&&this.addImage(t),this.options.background===!0&&this.addElementBackgroundImages(t);var e=t.nodeType;if(e&&c[e]){for(var i=t.querySelectorAll("img"),n=0;n=0,this.isPrefilling?(this.log("prefill"),this.loadNextPage()):this.stopPrefill()},s.getPrefillDistance=function(){return this.options.elementScroll?this.scroller.clientHeight-this.scroller.scrollHeight:this.windowHeight-this.element.clientHeight},s.stopPrefill=function(){this.log("stopPrefill"),this.off("append",this.prefill)},e}),function(t,e){"function"==typeof define&&define.amd?define("infinite-scroll/js/scroll-watch",["./core","fizzy-ui-utils/utils"],function(i,n){return e(t,i,n)}):"object"==typeof module&&module.exports?module.exports=e(t,require("./core"),require("fizzy-ui-utils")):e(t,t.InfiniteScroll,t.fizzyUIUtils)}(window,function(t,e,i){var n=e.prototype;return e.defaults.scrollThreshold=400,e.create.scrollWatch=function(){this.pageScrollHandler=this.onPageScroll.bind(this),this.resizeHandler=this.onResize.bind(this);var t=this.options.scrollThreshold,e=t||0===t;e&&this.enableScrollWatch()},e.destroy.scrollWatch=function(){this.disableScrollWatch()},n.enableScrollWatch=function(){this.isScrollWatching||(this.isScrollWatching=!0,this.updateMeasurements(),this.updateScroller(),this.on("last",this.disableScrollWatch),this.bindScrollWatchEvents(!0))},n.disableScrollWatch=function(){this.isScrollWatching&&(this.bindScrollWatchEvents(!1),delete this.isScrollWatching)},n.bindScrollWatchEvents=function(e){var i=e?"addEventListener":"removeEventListener";this.scroller[i]("scroll",this.pageScrollHandler),t[i]("resize",this.resizeHandler)},n.onPageScroll=e.throttle(function(){var t=this.getBottomDistance();t<=this.options.scrollThreshold&&this.dispatchEvent("scrollThreshold")}),n.getBottomDistance=function(){return this.options.elementScroll?this.getElementBottomDistance():this.getWindowBottomDistance()},n.getWindowBottomDistance=function(){var e=this.top+this.element.clientHeight,i=t.pageYOffset+this.windowHeight;return e-i},n.getElementBottomDistance=function(){var t=this.scroller.scrollHeight,e=this.scroller.scrollTop+this.scroller.clientHeight;return t-e},n.onResize=function(){this.updateMeasurements()},i.debounceMethod(e,"onResize",150),e}),function(t,e){"function"==typeof define&&define.amd?define("infinite-scroll/js/history",["./core","fizzy-ui-utils/utils"],function(i,n){return e(t,i,n)}):"object"==typeof module&&module.exports?module.exports=e(t,require("./core"),require("fizzy-ui-utils")):e(t,t.InfiniteScroll,t.fizzyUIUtils)}(window,function(t,e,i){var n=e.prototype;e.defaults.history="replace";var o=document.createElement("a");return e.create.history=function(){if(this.options.history){o.href=this.getAbsolutePath();var t=o.origin||o.protocol+"//"+o.host,e=t==location.origin;return e?void(this.options.append?this.createHistoryAppend():this.createHistoryPageLoad()):void console.error("[InfiniteScroll] cannot set history with different origin: "+o.origin+" on "+location.origin+" . History behavior disabled.")}},n.createHistoryAppend=function(){this.updateMeasurements(),this.updateScroller(),this.scrollPages=[{top:0,path:location.href,title:document.title}],this.scrollPageIndex=0,this.scrollHistoryHandler=this.onScrollHistory.bind(this),this.unloadHandler=this.onUnload.bind(this),this.scroller.addEventListener("scroll",this.scrollHistoryHandler),this.on("append",this.onAppendHistory),this.bindHistoryAppendEvents(!0)},n.bindHistoryAppendEvents=function(e){var i=e?"addEventListener":"removeEventListener";this.scroller[i]("scroll",this.scrollHistoryHandler),t[i]("unload",this.unloadHandler)},n.createHistoryPageLoad=function(){this.on("load",this.onPageLoadHistory)},e.destroy.history=n.destroyHistory=function(){var t=this.options.history&&this.options.append;t&&this.bindHistoryAppendEvents(!1)},n.onAppendHistory=function(t,e,i){if(i&&i.length){var n=i[0],r=this.getElementScrollY(n);o.href=e,this.scrollPages.push({top:r,path:o.href,title:t.title})}},n.getElementScrollY=function(t){return this.options.elementScroll?this.getElementElementScrollY(t):this.getElementWindowScrollY(t)},n.getElementWindowScrollY=function(e){var i=e.getBoundingClientRect();return i.top+t.pageYOffset},n.getElementElementScrollY=function(t){return t.offsetTop-this.top},n.onScrollHistory=function(){for(var t,e,i=this.getScrollViewY(),n=0;n=i)break;t=n,e=o}t!=this.scrollPageIndex&&(this.scrollPageIndex=t,this.setHistory(e.title,e.path))},i.debounceMethod(e,"onScrollHistory",150),n.getScrollViewY=function(){return this.options.elementScroll?this.scroller.scrollTop+this.scroller.clientHeight/2:t.pageYOffset+this.windowHeight/2},n.setHistory=function(t,e){var i=this.options.history,n=i&&history[i+"State"];n&&(history[i+"State"](null,t,e),this.options.historyTitle&&(document.title=t),this.dispatchEvent("history",null,[t,e]))},n.onUnload=function(){var e=this.scrollPageIndex;if(0!==e){var i=this.scrollPages[e],n=t.pageYOffset-i.top+this.top;this.destroyHistory(),scrollTo(0,n)}},n.onPageLoadHistory=function(t,e){this.setHistory(t.title,e)},e}),function(t,e){"function"==typeof define&&define.amd?define("infinite-scroll/js/button",["./core","fizzy-ui-utils/utils"],function(i,n){return e(t,i,n)}):"object"==typeof module&&module.exports?module.exports=e(t,require("./core"),require("fizzy-ui-utils")):e(t,t.InfiniteScroll,t.fizzyUIUtils)}(window,function(t,e,i){function n(t,e){this.element=t,this.infScroll=e,this.clickHandler=this.onClick.bind(this),this.element.addEventListener("click",this.clickHandler),e.on("request",this.disable.bind(this)),e.on("load",this.enable.bind(this)),e.on("error",this.hide.bind(this)),e.on("last",this.hide.bind(this))}return e.create.button=function(){var t=i.getQueryElement(this.options.button);if(t)return void(this.button=new n(t,this))},e.destroy.button=function(){this.button&&this.button.destroy()},n.prototype.onClick=function(t){t.preventDefault(),this.infScroll.loadNextPage()},n.prototype.enable=function(){this.element.removeAttribute("disabled")},n.prototype.disable=function(){this.element.disabled="disabled"},n.prototype.hide=function(){this.element.style.display="none"},n.prototype.destroy=function(){this.element.removeEventListener("click",this.clickHandler)},e.Button=n,e}),function(t,e){"function"==typeof define&&define.amd?define("infinite-scroll/js/status",["./core","fizzy-ui-utils/utils"],function(i,n){return e(t,i,n)}):"object"==typeof module&&module.exports?module.exports=e(t,require("./core"),require("fizzy-ui-utils")):e(t,t.InfiniteScroll,t.fizzyUIUtils)}(window,function(t,e,i){function n(t){r(t,"none")}function o(t){r(t,"block")}function r(t,e){t&&(t.style.display=e)}var s=e.prototype;return e.create.status=function(){var t=i.getQueryElement(this.options.status);t&&(this.statusElement=t,this.statusEventElements={request:t.querySelector(".infinite-scroll-request"),error:t.querySelector(".infinite-scroll-error"),last:t.querySelector(".infinite-scroll-last")},this.on("request",this.showRequestStatus),this.on("error",this.showErrorStatus),this.on("last",this.showLastStatus),this.bindHideStatus("on"))},s.bindHideStatus=function(t){var e=this.options.append?"append":"load";this[t](e,this.hideAllStatus)},s.showRequestStatus=function(){this.showStatus("request")},s.showErrorStatus=function(){this.showStatus("error")},s.showLastStatus=function(){this.showStatus("last"),this.bindHideStatus("off")},s.showStatus=function(t){o(this.statusElement),this.hideStatusEventElements();var e=this.statusEventElements[t];o(e)},s.hideAllStatus=function(){n(this.statusElement),this.hideStatusEventElements()},s.hideStatusEventElements=function(){for(var t in this.statusEventElements){var e=this.statusEventElements[t];n(e)}},e}),function(t,e){"function"==typeof define&&define.amd?define(["infinite-scroll/js/core","infinite-scroll/js/page-load","infinite-scroll/js/scroll-watch","infinite-scroll/js/history","infinite-scroll/js/button","infinite-scroll/js/status"],e):"object"==typeof module&&module.exports&&(module.exports=e(require("./core"),require("./page-load"),require("./scroll-watch"),require("./history"),require("./button"),require("./status")))}(window,function(t){return t}),function(t,e){"use strict";"function"==typeof define&&define.amd?define("imagesloaded/imagesloaded",["ev-emitter/ev-emitter"],function(i){return e(t,i)}):"object"==typeof module&&module.exports?module.exports=e(t,require("ev-emitter")):t.imagesLoaded=e(t,t.EvEmitter)}("undefined"!=typeof window?window:this,function(t,e){function i(t,e){for(var i in e)t[i]=e[i];return t}function n(t){if(Array.isArray(t))return t;var e="object"==typeof t&&"number"==typeof t.length;return e?h.call(t):[t]}function o(t,e,r){if(!(this instanceof o))return new o(t,e,r);var s=t;return"string"==typeof t&&(s=document.querySelectorAll(t)),s?(this.elements=n(s),this.options=i({},this.options),"function"==typeof e?r=e:i(this.options,e),r&&this.on("always",r),this.getImages(),l&&(this.jqDeferred=new l.Deferred),void setTimeout(this.check.bind(this))):void a.error("Bad element for imagesLoaded "+(s||t))}function r(t){this.img=t}function s(t,e){this.url=t,this.element=e,this.img=new Image}var l=t.jQuery,a=t.console,h=Array.prototype.slice;o.prototype=Object.create(e.prototype),o.prototype.options={},o.prototype.getImages=function(){this.images=[],this.elements.forEach(this.addElementImages,this)},o.prototype.addElementImages=function(t){"IMG"==t.nodeName&&this.addImage(t),this.options.background===!0&&this.addElementBackgroundImages(t);var e=t.nodeType;if(e&&c[e]){for(var i=t.querySelectorAll("img"),n=0;n this.isotope.size.innerHeight ) { + this.y = 0; + this.x = this.maxX; + } + + var position = { + x: this.x, + y: this.y + }; + + this.maxX = Math.max( this.maxX, this.x + item.size.outerWidth ); + this.y += item.size.outerHeight; + + return position; + }; + + proto._getContainerSize = function() { + return { width: this.maxX }; + }; + + proto.needsResizeLayout = function() { + return this.needsVerticalResizeLayout(); + }; + + return FitColumns; + +})); diff --git a/cps/static/js/libs/soundmanager2.js b/cps/static/js/libs/soundmanager2.js new file mode 100644 index 00000000..87a751d3 --- /dev/null +++ b/cps/static/js/libs/soundmanager2.js @@ -0,0 +1,6294 @@ +/** @license + * + * SoundManager 2: JavaScript Sound for the Web + * ---------------------------------------------- + * http://schillmania.com/projects/soundmanager2/ + * + * Copyright (c) 2007, Scott Schiller. All rights reserved. + * Code provided under the BSD License: + * http://schillmania.com/projects/soundmanager2/license.txt + * + * V2.97a.20170601 + */ + +/** + * About this file + * ------------------------------------------------------------------------------------- + * This is the fully-commented source version of the SoundManager 2 API, + * recommended for use during development and testing. + * + * See soundmanager2-nodebug-jsmin.js for an optimized build (~11KB with gzip.) + * http://schillmania.com/projects/soundmanager2/doc/getstarted/#basic-inclusion + * Alternately, serve this file with gzip for 75% compression savings (~30KB over HTTP.) + * + * You may notice and comments in this source; these are delimiters for + * debug blocks which are removed in the -nodebug builds, further optimizing code size. + * + * Also, as you may note: Whoa, reliable cross-platform/device audio support is hard! ;) + */ + +(function SM2(window, _undefined) { + +/* global Audio, document, window, navigator, define, module, SM2_DEFER, opera, setTimeout, setInterval, clearTimeout, sm2Debugger */ + +'use strict'; + +if (!window || !window.document) { + + // Don't cross the [environment] streams. SM2 expects to be running in a browser, not under node.js etc. + // Additionally, if a browser somehow manages to fail this test, as Egon said: "It would be bad." + + throw new Error('SoundManager requires a browser with window and document objects.'); + +} + +var soundManager = null; + +/** + * The SoundManager constructor. + * + * @constructor + * @param {string} smURL Optional: Path to SWF files + * @param {string} smID Optional: The ID to use for the SWF container element + * @this {SoundManager} + * @return {SoundManager} The new SoundManager instance + */ + +function SoundManager(smURL, smID) { + + /** + * soundManager configuration options list + * defines top-level configuration properties to be applied to the soundManager instance (eg. soundManager.flashVersion) + * to set these properties, use the setup() method - eg., soundManager.setup({url: '/swf/', flashVersion: 9}) + */ + + this.setupOptions = { + + url: (smURL || null), // path (directory) where SoundManager 2 SWFs exist, eg., /path/to/swfs/ + flashVersion: 8, // flash build to use (8 or 9.) Some API features require 9. + debugMode: true, // enable debugging output (console.log() with HTML fallback) + debugFlash: false, // enable debugging output inside SWF, troubleshoot Flash/browser issues + useConsole: true, // use console.log() if available (otherwise, writes to #soundmanager-debug element) + consoleOnly: true, // if console is being used, do not create/write to #soundmanager-debug + waitForWindowLoad: false, // force SM2 to wait for window.onload() before trying to call soundManager.onload() + bgColor: '#ffffff', // SWF background color. N/A when wmode = 'transparent' + useHighPerformance: false, // position:fixed flash movie can help increase js/flash speed, minimize lag + flashPollingInterval: null, // msec affecting whileplaying/loading callback frequency. If null, default of 50 msec is used. + html5PollingInterval: null, // msec affecting whileplaying() for HTML5 audio, excluding mobile devices. If null, native HTML5 update events are used. + flashLoadTimeout: 1000, // msec to wait for flash movie to load before failing (0 = infinity) + wmode: null, // flash rendering mode - null, 'transparent', or 'opaque' (last two allow z-index to work) + allowScriptAccess: 'always', // for scripting the SWF (object/embed property), 'always' or 'sameDomain' + useFlashBlock: false, // *requires flashblock.css, see demos* - allow recovery from flash blockers. Wait indefinitely and apply timeout CSS to SWF, if applicable. + useHTML5Audio: true, // use HTML5 Audio() where API is supported (most Safari, Chrome versions), Firefox (MP3/MP4 support varies.) Ideally, transparent vs. Flash API where possible. + forceUseGlobalHTML5Audio: false, // if true, a single Audio() object is used for all sounds - and only one can play at a time. + ignoreMobileRestrictions: false, // if true, SM2 will not apply global HTML5 audio rules to mobile UAs. iOS > 7 and WebViews may allow multiple Audio() instances. + html5Test: /^(probably|maybe)$/i, // HTML5 Audio() format support test. Use /^probably$/i; if you want to be more conservative. + preferFlash: false, // overrides useHTML5audio, will use Flash for MP3/MP4/AAC if present. Potential option if HTML5 playback with these formats is quirky. + noSWFCache: false, // if true, appends ?ts={date} to break aggressive SWF caching. + idPrefix: 'sound' // if an id is not provided to createSound(), this prefix is used for generated IDs - 'sound0', 'sound1' etc. + + }; + + this.defaultOptions = { + + /** + * the default configuration for sound objects made with createSound() and related methods + * eg., volume, auto-load behaviour and so forth + */ + + autoLoad: false, // enable automatic loading (otherwise .load() will be called on demand with .play(), the latter being nicer on bandwidth - if you want to .load yourself, you also can) + autoPlay: false, // enable playing of file as soon as possible (much faster if "stream" is true) + from: null, // position to start playback within a sound (msec), default = beginning + loops: 1, // how many times to repeat the sound (position will wrap around to 0, setPosition() will break out of loop when >0) + onid3: null, // callback function for "ID3 data is added/available" + onerror: null, // callback function for "load failed" (or, playback/network/decode error under HTML5.) + onload: null, // callback function for "load finished" + whileloading: null, // callback function for "download progress update" (X of Y bytes received) + onplay: null, // callback for "play" start + onpause: null, // callback for "pause" + onresume: null, // callback for "resume" (pause toggle) + whileplaying: null, // callback during play (position update) + onposition: null, // object containing times and function callbacks for positions of interest + onstop: null, // callback for "user stop" + onfinish: null, // callback function for "sound finished playing" + multiShot: true, // let sounds "restart" or layer on top of each other when played multiple times, rather than one-shot/one at a time + multiShotEvents: false, // fire multiple sound events (currently onfinish() only) when multiShot is enabled + position: null, // offset (milliseconds) to seek to within loaded sound data. + pan: 0, // "pan" settings, left-to-right, -100 to 100 + playbackRate: 1, // rate at which to play the sound (HTML5-only) + stream: true, // allows playing before entire file has loaded (recommended) + to: null, // position to end playback within a sound (msec), default = end + type: null, // MIME-like hint for file pattern / canPlay() tests, eg. audio/mp3 + usePolicyFile: false, // enable crossdomain.xml request for audio on remote domains (for ID3/waveform access) + volume: 100 // self-explanatory. 0-100, the latter being the max. + + }; + + this.flash9Options = { + + /** + * flash 9-only options, + * merged into defaultOptions if flash 9 is being used + */ + + onfailure: null, // callback function for when playing fails (Flash 9, MovieStar + RTMP-only) + isMovieStar: null, // "MovieStar" MPEG4 audio mode. Null (default) = auto detect MP4, AAC etc. based on URL. true = force on, ignore URL + usePeakData: false, // enable left/right channel peak (level) data + useWaveformData: false, // enable sound spectrum (raw waveform data) - NOTE: May increase CPU load. + useEQData: false, // enable sound EQ (frequency spectrum data) - NOTE: May increase CPU load. + onbufferchange: null, // callback for "isBuffering" property change + ondataerror: null // callback for waveform/eq data access error (flash playing audio in other tabs/domains) + + }; + + this.movieStarOptions = { + + /** + * flash 9.0r115+ MPEG4 audio options, + * merged into defaultOptions if flash 9+movieStar mode is enabled + */ + + bufferTime: 3, // seconds of data to buffer before playback begins (null = flash default of 0.1 seconds - if AAC playback is gappy, try increasing.) + serverURL: null, // rtmp: FMS or FMIS server to connect to, required when requesting media via RTMP or one of its variants + onconnect: null, // rtmp: callback for connection to flash media server + duration: null // rtmp: song duration (msec) + + }; + + this.audioFormats = { + + /** + * determines HTML5 support + flash requirements. + * if no support (via flash and/or HTML5) for a "required" format, SM2 will fail to start. + * flash fallback is used for MP3 or MP4 if HTML5 can't play it (or if preferFlash = true) + */ + + mp3: { + type: ['audio/mpeg; codecs="mp3"', 'audio/mpeg', 'audio/mp3', 'audio/MPA', 'audio/mpa-robust'], + required: true + }, + + mp4: { + related: ['aac', 'm4a', 'm4b'], // additional formats under the MP4 container + type: ['audio/mp4; codecs="mp4a.40.2"', 'audio/aac', 'audio/x-m4a', 'audio/MP4A-LATM', 'audio/mpeg4-generic'], + required: false + }, + + ogg: { + type: ['audio/ogg; codecs=vorbis'], + required: false + }, + + opus: { + type: ['audio/ogg; codecs=opus', 'audio/opus'], + required: false + }, + + wav: { + type: ['audio/wav; codecs="1"', 'audio/wav', 'audio/wave', 'audio/x-wav'], + required: false + }, + + flac: { + type: ['audio/flac'], + required: false + } + + }; + + // HTML attributes (id + class names) for the SWF container + + this.movieID = 'sm2-container'; + this.id = (smID || 'sm2movie'); + + this.debugID = 'soundmanager-debug'; + this.debugURLParam = /([#?&])debug=1/i; + + // dynamic attributes + + this.versionNumber = 'V2.97a.20170601'; + this.version = null; + this.movieURL = null; + this.altURL = null; + this.swfLoaded = false; + this.enabled = false; + this.oMC = null; + this.sounds = {}; + this.soundIDs = []; + this.muted = false; + this.didFlashBlock = false; + this.filePattern = null; + + this.filePatterns = { + flash8: /\.mp3(\?.*)?$/i, + flash9: /\.mp3(\?.*)?$/i + }; + + // support indicators, set at init + + this.features = { + buffering: false, + peakData: false, + waveformData: false, + eqData: false, + movieStar: false + }; + + // flash sandbox info, used primarily in troubleshooting + + this.sandbox = { + // + type: null, + types: { + remote: 'remote (domain-based) rules', + localWithFile: 'local with file access (no internet access)', + localWithNetwork: 'local with network (internet access only, no local access)', + localTrusted: 'local, trusted (local+internet access)' + }, + description: null, + noRemote: null, + noLocal: null + // + }; + + /** + * format support (html5/flash) + * stores canPlayType() results based on audioFormats. + * eg. { mp3: boolean, mp4: boolean } + * treat as read-only. + */ + + this.html5 = { + usingFlash: null // set if/when flash fallback is needed + }; + + // file type support hash + this.flash = {}; + + // determined at init time + this.html5Only = false; + + // used for special cases (eg. iPad/iPhone/palm OS?) + this.ignoreFlash = false; + + /** + * a few private internals (OK, a lot. :D) + */ + + var SMSound, + sm2 = this, globalHTML5Audio = null, flash = null, sm = 'soundManager', smc = sm + ': ', h5 = 'HTML5::', id, ua = navigator.userAgent, wl = window.location.href.toString(), doc = document, doNothing, setProperties, init, fV, on_queue = [], debugOpen = true, debugTS, didAppend = false, appendSuccess = false, didInit = false, disabled = false, windowLoaded = false, _wDS, wdCount = 0, initComplete, mixin, assign, extraOptions, addOnEvent, processOnEvents, initUserOnload, delayWaitForEI, waitForEI, rebootIntoHTML5, setVersionInfo, handleFocus, strings, initMovie, domContentLoaded, winOnLoad, didDCLoaded, getDocument, createMovie, catchError, setPolling, initDebug, debugLevels = ['log', 'info', 'warn', 'error'], defaultFlashVersion = 8, disableObject, failSafely, normalizeMovieURL, oRemoved = null, oRemovedHTML = null, str, flashBlockHandler, getSWFCSS, swfCSS, toggleDebug, loopFix, policyFix, complain, idCheck, waitingForEI = false, initPending = false, startTimer, stopTimer, timerExecute, h5TimerCount = 0, h5IntervalTimer = null, parseURL, messages = [], + canIgnoreFlash, needsFlash = null, featureCheck, html5OK, html5CanPlay, html5ErrorCodes, html5Ext, html5Unload, domContentLoadedIE, testHTML5, event, slice = Array.prototype.slice, useGlobalHTML5Audio = false, lastGlobalHTML5URL, hasFlash, detectFlash, badSafariFix, html5_events, showSupport, flushMessages, wrapCallback, idCounter = 0, didSetup, msecScale = 1000, + is_iDevice = ua.match(/(ipad|iphone|ipod)/i), isAndroid = ua.match(/android/i), isIE = ua.match(/msie|trident/i), + isWebkit = ua.match(/webkit/i), + isSafari = (ua.match(/safari/i) && !ua.match(/chrome/i)), + isOpera = (ua.match(/opera/i)), + mobileHTML5 = (ua.match(/(mobile|pre\/|xoom)/i) || is_iDevice || isAndroid), + isBadSafari = (!wl.match(/usehtml5audio/i) && !wl.match(/sm2-ignorebadua/i) && isSafari && !ua.match(/silk/i) && ua.match(/OS\sX\s10_6_([3-7])/i)), // Safari 4 and 5 (excluding Kindle Fire, "Silk") occasionally fail to load/play HTML5 audio on Snow Leopard 10.6.3 through 10.6.7 due to bug(s) in QuickTime X and/or other underlying frameworks. :/ Confirmed bug. https://bugs.webkit.org/show_bug.cgi?id=32159 + hasConsole = (window.console !== _undefined && console.log !== _undefined), + isFocused = (doc.hasFocus !== _undefined ? doc.hasFocus() : null), + tryInitOnFocus = (isSafari && (doc.hasFocus === _undefined || !doc.hasFocus())), + okToDisable = !tryInitOnFocus, + flashMIME = /(mp3|mp4|mpa|m4a|m4b)/i, + emptyURL = 'about:blank', // safe URL to unload, or load nothing from (flash 8 + most HTML5 UAs) + emptyWAV = 'data:audio/wave;base64,/UklGRiYAAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YQIAAAD//w==', // tiny WAV for HTML5 unloading + overHTTP = (doc.location ? doc.location.protocol.match(/http/i) : null), + http = (!overHTTP ? '//' : ''), + // mp3, mp4, aac etc. + netStreamMimeTypes = /^\s*audio\/(?:x-)?(?:mpeg4|aac|flv|mov|mp4|m4v|m4a|m4b|mp4v|3gp|3g2)\s*(?:$|;)/i, + // Flash v9.0r115+ "moviestar" formats + netStreamTypes = ['mpeg4', 'aac', 'flv', 'mov', 'mp4', 'm4v', 'f4v', 'm4a', 'm4b', 'mp4v', '3gp', '3g2'], + netStreamPattern = new RegExp('\\.(' + netStreamTypes.join('|') + ')(\\?.*)?$', 'i'); + + this.mimePattern = /^\s*audio\/(?:x-)?(?:mp(?:eg|3))\s*(?:$|;)/i; // default mp3 set + + // use altURL if not "online" + this.useAltURL = !overHTTP; + + swfCSS = { + swfBox: 'sm2-object-box', + swfDefault: 'movieContainer', + swfError: 'swf_error', // SWF loaded, but SM2 couldn't start (other error) + swfTimedout: 'swf_timedout', + swfLoaded: 'swf_loaded', + swfUnblocked: 'swf_unblocked', // or loaded OK + sm2Debug: 'sm2_debug', + highPerf: 'high_performance', + flashDebug: 'flash_debug' + }; + + /** + * HTML5 error codes, per W3C + * Error code 1, MEDIA_ERR_ABORTED: Client aborted download at user's request. + * Error code 2, MEDIA_ERR_NETWORK: A network error of some description caused the user agent to stop fetching the media resource, after the resource was established to be usable. + * Error code 3, MEDIA_ERR_DECODE: An error of some description occurred while decoding the media resource, after the resource was established to be usable. + * Error code 4, MEDIA_ERR_SRC_NOT_SUPPORTED: Media (audio file) not supported ("not usable.") + * Reference: https://html.spec.whatwg.org/multipage/embedded-content.html#error-codes + */ + html5ErrorCodes = [ + null, + 'MEDIA_ERR_ABORTED', + 'MEDIA_ERR_NETWORK', + 'MEDIA_ERR_DECODE', + 'MEDIA_ERR_SRC_NOT_SUPPORTED' + ]; + + /** + * basic HTML5 Audio() support test + * try...catch because of IE 9 "not implemented" nonsense + * https://github.com/Modernizr/Modernizr/issues/224 + */ + + this.hasHTML5 = (function() { + try { + // new Audio(null) for stupid Opera 9.64 case, which throws not_enough_arguments exception otherwise. + return (Audio !== _undefined && (isOpera && opera !== _undefined && opera.version() < 10 ? new Audio(null) : new Audio()).canPlayType !== _undefined); + } catch(e) { + return false; + } + }()); + + /** + * Public SoundManager API + * ----------------------- + */ + + /** + * Configures top-level soundManager properties. + * + * @param {object} options Option parameters, eg. { flashVersion: 9, url: '/path/to/swfs/' } + * onready and ontimeout are also accepted parameters. call soundManager.setup() to see the full list. + */ + + this.setup = function(options) { + + var noURL = (!sm2.url); + + // warn if flash options have already been applied + + if (options !== _undefined && didInit && needsFlash && sm2.ok() && (options.flashVersion !== _undefined || options.url !== _undefined || options.html5Test !== _undefined)) { + complain(str('setupLate')); + } + + // TODO: defer: true? + + assign(options); + + if (!useGlobalHTML5Audio) { + + if (mobileHTML5) { + + // force the singleton HTML5 pattern on mobile, by default. + if (!sm2.setupOptions.ignoreMobileRestrictions || sm2.setupOptions.forceUseGlobalHTML5Audio) { + messages.push(strings.globalHTML5); + useGlobalHTML5Audio = true; + } + + } else if (sm2.setupOptions.forceUseGlobalHTML5Audio) { + + // only apply singleton HTML5 on desktop if forced. + messages.push(strings.globalHTML5); + useGlobalHTML5Audio = true; + + } + + } + + if (!didSetup && mobileHTML5) { + + if (sm2.setupOptions.ignoreMobileRestrictions) { + + messages.push(strings.ignoreMobile); + + } else { + + // prefer HTML5 for mobile + tablet-like devices, probably more reliable vs. flash at this point. + + // + if (!sm2.setupOptions.useHTML5Audio || sm2.setupOptions.preferFlash) { + // notify that defaults are being changed. + sm2._wD(strings.mobileUA); + } + // + + sm2.setupOptions.useHTML5Audio = true; + sm2.setupOptions.preferFlash = false; + + if (is_iDevice) { + + // no flash here. + sm2.ignoreFlash = true; + + } else if ((isAndroid && !ua.match(/android\s2\.3/i)) || !isAndroid) { + + /** + * Android devices tend to work better with a single audio instance, specifically for chained playback of sounds in sequence. + * Common use case: exiting sound onfinish() -> createSound() -> play() + * Presuming similar restrictions for other mobile, non-Android, non-iOS devices. + */ + + // + sm2._wD(strings.globalHTML5); + // + + useGlobalHTML5Audio = true; + + } + + } + + } + + // special case 1: "Late setup". SM2 loaded normally, but user didn't assign flash URL eg., setup({url:...}) before SM2 init. Treat as delayed init. + + if (options) { + + if (noURL && didDCLoaded && options.url !== _undefined) { + sm2.beginDelayedInit(); + } + + // special case 2: If lazy-loading SM2 (DOMContentLoaded has already happened) and user calls setup() with url: parameter, try to init ASAP. + + if (!didDCLoaded && options.url !== _undefined && doc.readyState === 'complete') { + setTimeout(domContentLoaded, 1); + } + + } + + didSetup = true; + + return sm2; + + }; + + this.ok = function() { + + return (needsFlash ? (didInit && !disabled) : (sm2.useHTML5Audio && sm2.hasHTML5)); + + }; + + this.supported = this.ok; // legacy + + this.getMovie = function(movie_id) { + + // safety net: some old browsers differ on SWF references, possibly related to ExternalInterface / flash version + return id(movie_id) || doc[movie_id] || window[movie_id]; + + }; + + /** + * Creates a SMSound sound object instance. Can also be overloaded, e.g., createSound('mySound', '/some.mp3'); + * + * @param {object} oOptions Sound options (at minimum, url parameter is required.) + * @return {object} SMSound The new SMSound object. + */ + + this.createSound = function(oOptions, _url) { + + var cs, cs_string, options, oSound = null; + + // + cs = sm + '.createSound(): '; + cs_string = cs + str(!didInit ? 'notReady' : 'notOK'); + // + + if (!didInit || !sm2.ok()) { + complain(cs_string); + return false; + } + + if (_url !== _undefined) { + // function overloading in JS! :) ... assume simple createSound(id, url) use case. + oOptions = { + id: oOptions, + url: _url + }; + } + + // inherit from defaultOptions + options = mixin(oOptions); + + options.url = parseURL(options.url); + + // generate an id, if needed. + if (options.id === _undefined) { + options.id = sm2.setupOptions.idPrefix + (idCounter++); + } + + // + if (options.id.toString().charAt(0).match(/^[0-9]$/)) { + sm2._wD(cs + str('badID', options.id), 2); + } + + sm2._wD(cs + options.id + (options.url ? ' (' + options.url + ')' : ''), 1); + // + + if (idCheck(options.id, true)) { + sm2._wD(cs + options.id + ' exists', 1); + return sm2.sounds[options.id]; + } + + function make() { + + options = loopFix(options); + sm2.sounds[options.id] = new SMSound(options); + sm2.soundIDs.push(options.id); + return sm2.sounds[options.id]; + + } + + if (html5OK(options)) { + + oSound = make(); + // + if (!sm2.html5Only) { + sm2._wD(options.id + ': Using HTML5'); + } + // + oSound._setup_html5(options); + + } else { + + if (sm2.html5Only) { + sm2._wD(options.id + ': No HTML5 support for this sound, and no Flash. Exiting.'); + return make(); + } + + // TODO: Move HTML5/flash checks into generic URL parsing/handling function. + + if (sm2.html5.usingFlash && options.url && options.url.match(/data:/i)) { + // data: URIs not supported by Flash, either. + sm2._wD(options.id + ': data: URIs not supported via Flash. Exiting.'); + return make(); + } + + if (fV > 8) { + if (options.isMovieStar === null) { + // attempt to detect MPEG-4 formats + options.isMovieStar = !!(options.serverURL || (options.type ? options.type.match(netStreamMimeTypes) : false) || (options.url && options.url.match(netStreamPattern))); + } + // + if (options.isMovieStar) { + sm2._wD(cs + 'using MovieStar handling'); + if (options.loops > 1) { + _wDS('noNSLoop'); + } + } + // + } + + options = policyFix(options, cs); + oSound = make(); + + if (fV === 8) { + flash._createSound(options.id, options.loops || 1, options.usePolicyFile); + } else { + flash._createSound(options.id, options.url, options.usePeakData, options.useWaveformData, options.useEQData, options.isMovieStar, (options.isMovieStar ? options.bufferTime : false), options.loops || 1, options.serverURL, options.duration || null, options.autoPlay, true, options.autoLoad, options.usePolicyFile); + if (!options.serverURL) { + // We are connected immediately + oSound.connected = true; + if (options.onconnect) { + options.onconnect.apply(oSound); + } + } + } + + if (!options.serverURL && (options.autoLoad || options.autoPlay)) { + // call load for non-rtmp streams + oSound.load(options); + } + + } + + // rtmp will play in onconnect + if (!options.serverURL && options.autoPlay) { + oSound.play(); + } + + return oSound; + + }; + + /** + * Destroys a SMSound sound object instance. + * + * @param {string} sID The ID of the sound to destroy + */ + + this.destroySound = function(sID, _bFromSound) { + + // explicitly destroy a sound before normal page unload, etc. + + if (!idCheck(sID)) return false; + + var oS = sm2.sounds[sID], i; + + oS.stop(); + + // Disable all callbacks after stop(), when the sound is being destroyed + oS._iO = {}; + + oS.unload(); + + for (i = 0; i < sm2.soundIDs.length; i++) { + if (sm2.soundIDs[i] === sID) { + sm2.soundIDs.splice(i, 1); + break; + } + } + + if (!_bFromSound) { + // ignore if being called from SMSound instance + oS.destruct(true); + } + + oS = null; + delete sm2.sounds[sID]; + + return true; + + }; + + /** + * Calls the load() method of a SMSound object by ID. + * + * @param {string} sID The ID of the sound + * @param {object} oOptions Optional: Sound options + */ + + this.load = function(sID, oOptions) { + + if (!idCheck(sID)) return false; + + return sm2.sounds[sID].load(oOptions); + + }; + + /** + * Calls the unload() method of a SMSound object by ID. + * + * @param {string} sID The ID of the sound + */ + + this.unload = function(sID) { + + if (!idCheck(sID)) return false; + + return sm2.sounds[sID].unload(); + + }; + + /** + * Calls the onPosition() method of a SMSound object by ID. + * + * @param {string} sID The ID of the sound + * @param {number} nPosition The position to watch for + * @param {function} oMethod The relevant callback to fire + * @param {object} oScope Optional: The scope to apply the callback to + * @return {SMSound} The SMSound object + */ + + this.onPosition = function(sID, nPosition, oMethod, oScope) { + + if (!idCheck(sID)) return false; + + return sm2.sounds[sID].onposition(nPosition, oMethod, oScope); + + }; + + // legacy/backwards-compability: lower-case method name + this.onposition = this.onPosition; + + /** + * Calls the clearOnPosition() method of a SMSound object by ID. + * + * @param {string} sID The ID of the sound + * @param {number} nPosition The position to watch for + * @param {function} oMethod Optional: The relevant callback to fire + * @return {SMSound} The SMSound object + */ + + this.clearOnPosition = function(sID, nPosition, oMethod) { + + if (!idCheck(sID)) return false; + + return sm2.sounds[sID].clearOnPosition(nPosition, oMethod); + + }; + + /** + * Calls the play() method of a SMSound object by ID. + * + * @param {string} sID The ID of the sound + * @param {object} oOptions Optional: Sound options + * @return {SMSound} The SMSound object + */ + + this.play = function(sID, oOptions) { + + var result = null, + // legacy function-overloading use case: play('mySound', '/path/to/some.mp3'); + overloaded = (oOptions && !(oOptions instanceof Object)); + + if (!didInit || !sm2.ok()) { + complain(sm + '.play(): ' + str(!didInit ? 'notReady' : 'notOK')); + return false; + } + + if (!idCheck(sID, overloaded)) { + + // no sound found for the given ID. Bail. + if (!overloaded) return false; + + if (overloaded) { + oOptions = { + url: oOptions + }; + } + + if (oOptions && oOptions.url) { + // overloading use case, create+play: .play('someID', {url:'/path/to.mp3'}); + sm2._wD(sm + '.play(): Attempting to create "' + sID + '"', 1); + oOptions.id = sID; + result = sm2.createSound(oOptions).play(); + } + + } else if (overloaded) { + + // existing sound object case + oOptions = { + url: oOptions + }; + + } + + if (result === null) { + // default case + result = sm2.sounds[sID].play(oOptions); + } + + return result; + + }; + + // just for convenience + this.start = this.play; + + /** + * Calls the setPlaybackRate() method of a SMSound object by ID. + * + * @param {string} sID The ID of the sound + * @return {SMSound} The SMSound object + */ + + this.setPlaybackRate = function(sID, rate, allowOverride) { + + if (!idCheck(sID)) return false; + + return sm2.sounds[sID].setPlaybackRate(rate, allowOverride); + + }; + + /** + * Calls the setPosition() method of a SMSound object by ID. + * + * @param {string} sID The ID of the sound + * @param {number} nMsecOffset Position (milliseconds) + * @return {SMSound} The SMSound object + */ + + this.setPosition = function(sID, nMsecOffset) { + + if (!idCheck(sID)) return false; + + return sm2.sounds[sID].setPosition(nMsecOffset); + + }; + + /** + * Calls the stop() method of a SMSound object by ID. + * + * @param {string} sID The ID of the sound + * @return {SMSound} The SMSound object + */ + + this.stop = function(sID) { + + if (!idCheck(sID)) return false; + + sm2._wD(sm + '.stop(' + sID + ')', 1); + + return sm2.sounds[sID].stop(); + + }; + + /** + * Stops all currently-playing sounds. + */ + + this.stopAll = function() { + + var oSound; + sm2._wD(sm + '.stopAll()', 1); + + for (oSound in sm2.sounds) { + if (sm2.sounds.hasOwnProperty(oSound)) { + // apply only to sound objects + sm2.sounds[oSound].stop(); + } + } + + }; + + /** + * Calls the pause() method of a SMSound object by ID. + * + * @param {string} sID The ID of the sound + * @return {SMSound} The SMSound object + */ + + this.pause = function(sID) { + + if (!idCheck(sID)) return false; + + return sm2.sounds[sID].pause(); + + }; + + /** + * Pauses all currently-playing sounds. + */ + + this.pauseAll = function() { + + var i; + for (i = sm2.soundIDs.length - 1; i >= 0; i--) { + sm2.sounds[sm2.soundIDs[i]].pause(); + } + + }; + + /** + * Calls the resume() method of a SMSound object by ID. + * + * @param {string} sID The ID of the sound + * @return {SMSound} The SMSound object + */ + + this.resume = function(sID) { + + if (!idCheck(sID)) return false; + + return sm2.sounds[sID].resume(); + + }; + + /** + * Resumes all currently-paused sounds. + */ + + this.resumeAll = function() { + + var i; + for (i = sm2.soundIDs.length - 1; i >= 0; i--) { + sm2.sounds[sm2.soundIDs[i]].resume(); + } + + }; + + /** + * Calls the togglePause() method of a SMSound object by ID. + * + * @param {string} sID The ID of the sound + * @return {SMSound} The SMSound object + */ + + this.togglePause = function(sID) { + + if (!idCheck(sID)) return false; + + return sm2.sounds[sID].togglePause(); + + }; + + /** + * Calls the setPan() method of a SMSound object by ID. + * + * @param {string} sID The ID of the sound + * @param {number} nPan The pan value (-100 to 100) + * @return {SMSound} The SMSound object + */ + + this.setPan = function(sID, nPan) { + + if (!idCheck(sID)) return false; + + return sm2.sounds[sID].setPan(nPan); + + }; + + /** + * Calls the setVolume() method of a SMSound object by ID + * Overloaded case: pass only volume argument eg., setVolume(50) to apply to all sounds. + * + * @param {string} sID The ID of the sound + * @param {number} nVol The volume value (0 to 100) + * @return {SMSound} The SMSound object + */ + + this.setVolume = function(sID, nVol) { + + // setVolume(50) function overloading case - apply to all sounds + + var i, j; + + if (sID !== _undefined && !isNaN(sID) && nVol === _undefined) { + for (i = 0, j = sm2.soundIDs.length; i < j; i++) { + sm2.sounds[sm2.soundIDs[i]].setVolume(sID); + } + return false; + } + + // setVolume('mySound', 50) case + + if (!idCheck(sID)) return false; + + return sm2.sounds[sID].setVolume(nVol); + + }; + + /** + * Calls the mute() method of either a single SMSound object by ID, or all sound objects. + * + * @param {string} sID Optional: The ID of the sound (if omitted, all sounds will be used.) + */ + + this.mute = function(sID) { + + var i = 0; + + if (sID instanceof String) { + sID = null; + } + + if (!sID) { + + sm2._wD(sm + '.mute(): Muting all sounds'); + for (i = sm2.soundIDs.length - 1; i >= 0; i--) { + sm2.sounds[sm2.soundIDs[i]].mute(); + } + sm2.muted = true; + + } else { + + if (!idCheck(sID)) return false; + + sm2._wD(sm + '.mute(): Muting "' + sID + '"'); + return sm2.sounds[sID].mute(); + + } + + return true; + + }; + + /** + * Mutes all sounds. + */ + + this.muteAll = function() { + + sm2.mute(); + + }; + + /** + * Calls the unmute() method of either a single SMSound object by ID, or all sound objects. + * + * @param {string} sID Optional: The ID of the sound (if omitted, all sounds will be used.) + */ + + this.unmute = function(sID) { + + var i; + + if (sID instanceof String) { + sID = null; + } + + if (!sID) { + + sm2._wD(sm + '.unmute(): Unmuting all sounds'); + for (i = sm2.soundIDs.length - 1; i >= 0; i--) { + sm2.sounds[sm2.soundIDs[i]].unmute(); + } + sm2.muted = false; + + } else { + + if (!idCheck(sID)) return false; + + sm2._wD(sm + '.unmute(): Unmuting "' + sID + '"'); + + return sm2.sounds[sID].unmute(); + + } + + return true; + + }; + + /** + * Unmutes all sounds. + */ + + this.unmuteAll = function() { + + sm2.unmute(); + + }; + + /** + * Calls the toggleMute() method of a SMSound object by ID. + * + * @param {string} sID The ID of the sound + * @return {SMSound} The SMSound object + */ + + this.toggleMute = function(sID) { + + if (!idCheck(sID)) return false; + + return sm2.sounds[sID].toggleMute(); + + }; + + /** + * Retrieves the memory used by the flash plugin. + * + * @return {number} The amount of memory in use + */ + + this.getMemoryUse = function() { + + // flash-only + var ram = 0; + + if (flash && fV !== 8) { + ram = parseInt(flash._getMemoryUse(), 10); + } + + return ram; + + }; + + /** + * Undocumented: NOPs soundManager and all SMSound objects. + */ + + this.disable = function(bNoDisable) { + + // destroy all functions + var i; + + if (bNoDisable === _undefined) { + bNoDisable = false; + } + + // already disabled? + if (disabled) return false; + + disabled = true; + + _wDS('shutdown', 1); + + for (i = sm2.soundIDs.length - 1; i >= 0; i--) { + disableObject(sm2.sounds[sm2.soundIDs[i]]); + } + + disableObject(sm2); + + // fire "complete", despite fail + initComplete(bNoDisable); + + event.remove(window, 'load', initUserOnload); + + return true; + + }; + + /** + * Determines playability of a MIME type, eg. 'audio/mp3'. + */ + + this.canPlayMIME = function(sMIME) { + + var result; + + if (sm2.hasHTML5) { + result = html5CanPlay({ + type: sMIME + }); + } + + if (!result && needsFlash) { + // if flash 9, test netStream (movieStar) types as well. + result = (sMIME && sm2.ok() ? !!((fV > 8 ? sMIME.match(netStreamMimeTypes) : null) || sMIME.match(sm2.mimePattern)) : null); // TODO: make less "weird" (per JSLint) + } + + return result; + + }; + + /** + * Determines playability of a URL based on audio support. + * + * @param {string} sURL The URL to test + * @return {boolean} URL playability + */ + + this.canPlayURL = function(sURL) { + + var result; + + if (sm2.hasHTML5) { + result = html5CanPlay({ + url: sURL + }); + } + + if (!result && needsFlash) { + result = (sURL && sm2.ok() ? !!(sURL.match(sm2.filePattern)) : null); + } + + return result; + + }; + + /** + * Determines playability of an HTML DOM <a> object (or similar object literal) based on audio support. + * + * @param {object} oLink an HTML DOM <a> object or object literal including href and/or type attributes + * @return {boolean} URL playability + */ + + this.canPlayLink = function(oLink) { + + if (oLink.type !== _undefined && oLink.type && sm2.canPlayMIME(oLink.type)) return true; + + return sm2.canPlayURL(oLink.href); + + }; + + /** + * Retrieves a SMSound object by ID. + * + * @param {string} sID The ID of the sound + * @return {SMSound} The SMSound object + */ + + this.getSoundById = function(sID, _suppressDebug) { + + if (!sID) return null; + + var result = sm2.sounds[sID]; + + // + if (!result && !_suppressDebug) { + sm2._wD(sm + '.getSoundById(): Sound "' + sID + '" not found.', 2); + } + // + + return result; + + }; + + /** + * Queues a callback for execution when SoundManager has successfully initialized. + * + * @param {function} oMethod The callback method to fire + * @param {object} oScope Optional: The scope to apply to the callback + */ + + this.onready = function(oMethod, oScope) { + + var sType = 'onready', + result = false; + + if (typeof oMethod === 'function') { + + // + if (didInit) { + sm2._wD(str('queue', sType)); + } + // + + if (!oScope) { + oScope = window; + } + + addOnEvent(sType, oMethod, oScope); + processOnEvents(); + + result = true; + + } else { + + throw str('needFunction', sType); + + } + + return result; + + }; + + /** + * Queues a callback for execution when SoundManager has failed to initialize. + * + * @param {function} oMethod The callback method to fire + * @param {object} oScope Optional: The scope to apply to the callback + */ + + this.ontimeout = function(oMethod, oScope) { + + var sType = 'ontimeout', + result = false; + + if (typeof oMethod === 'function') { + + // + if (didInit) { + sm2._wD(str('queue', sType)); + } + // + + if (!oScope) { + oScope = window; + } + + addOnEvent(sType, oMethod, oScope); + processOnEvents({ type: sType }); + + result = true; + + } else { + + throw str('needFunction', sType); + + } + + return result; + + }; + + /** + * Writes console.log()-style debug output to a console or in-browser element. + * Applies when debugMode = true + * + * @param {string} sText The console message + * @param {object} nType Optional log level (number), or object. Number case: Log type/style where 0 = 'info', 1 = 'warn', 2 = 'error'. Object case: Object to be dumped. + */ + + this._writeDebug = function(sText, sTypeOrObject) { + + // pseudo-private console.log()-style output + // + + var sDID = 'soundmanager-debug', o, oItem; + + if (!sm2.setupOptions.debugMode) return false; + + if (hasConsole && sm2.useConsole) { + if (sTypeOrObject && typeof sTypeOrObject === 'object') { + // object passed; dump to console. + console.log(sText, sTypeOrObject); + } else if (debugLevels[sTypeOrObject] !== _undefined) { + console[debugLevels[sTypeOrObject]](sText); + } else { + console.log(sText); + } + if (sm2.consoleOnly) return true; + } + + o = id(sDID); + + if (!o) return false; + + oItem = doc.createElement('div'); + + if (++wdCount % 2 === 0) { + oItem.className = 'sm2-alt'; + } + + if (sTypeOrObject === _undefined) { + sTypeOrObject = 0; + } else { + sTypeOrObject = parseInt(sTypeOrObject, 10); + } + + oItem.appendChild(doc.createTextNode(sText)); + + if (sTypeOrObject) { + if (sTypeOrObject >= 2) { + oItem.style.fontWeight = 'bold'; + } + if (sTypeOrObject === 3) { + oItem.style.color = '#ff3333'; + } + } + + // top-to-bottom + // o.appendChild(oItem); + + // bottom-to-top + o.insertBefore(oItem, o.firstChild); + + o = null; + // + + return true; + + }; + + // + // last-resort debugging option + if (wl.indexOf('sm2-debug=alert') !== -1) { + this._writeDebug = function(sText) { + window.alert(sText); + }; + } + // + + // alias + this._wD = this._writeDebug; + + /** + * Provides debug / state information on all SMSound objects. + */ + + this._debug = function() { + + // + var i, j; + _wDS('currentObj', 1); + + for (i = 0, j = sm2.soundIDs.length; i < j; i++) { + sm2.sounds[sm2.soundIDs[i]]._debug(); + } + // + + }; + + /** + * Restarts and re-initializes the SoundManager instance. + * + * @param {boolean} resetEvents Optional: When true, removes all registered onready and ontimeout event callbacks. + * @param {boolean} excludeInit Options: When true, does not call beginDelayedInit() (which would restart SM2). + * @return {object} soundManager The soundManager instance. + */ + + this.reboot = function(resetEvents, excludeInit) { + + // reset some (or all) state, and re-init unless otherwise specified. + + // + if (sm2.soundIDs.length) { + sm2._wD('Destroying ' + sm2.soundIDs.length + ' SMSound object' + (sm2.soundIDs.length !== 1 ? 's' : '') + '...'); + } + // + + var i, j, k; + + for (i = sm2.soundIDs.length - 1; i >= 0; i--) { + sm2.sounds[sm2.soundIDs[i]].destruct(); + } + + // trash ze flash (remove from the DOM) + + if (flash) { + + try { + + if (isIE) { + oRemovedHTML = flash.innerHTML; + } + + oRemoved = flash.parentNode.removeChild(flash); + + } catch(e) { + + // Remove failed? May be due to flash blockers silently removing the SWF object/embed node from the DOM. Warn and continue. + + _wDS('badRemove', 2); + + } + + } + + // actually, force recreate of movie. + + oRemovedHTML = oRemoved = needsFlash = flash = null; + + sm2.enabled = didDCLoaded = didInit = waitingForEI = initPending = didAppend = appendSuccess = disabled = useGlobalHTML5Audio = sm2.swfLoaded = false; + + sm2.soundIDs = []; + sm2.sounds = {}; + + idCounter = 0; + didSetup = false; + + if (!resetEvents) { + // reset callbacks for onready, ontimeout etc. so that they will fire again on re-init + for (i in on_queue) { + if (on_queue.hasOwnProperty(i)) { + for (j = 0, k = on_queue[i].length; j < k; j++) { + on_queue[i][j].fired = false; + } + } + } + } else { + // remove all callbacks entirely + on_queue = []; + } + + // + if (!excludeInit) { + sm2._wD(sm + ': Rebooting...'); + } + // + + // reset HTML5 and flash canPlay test results + + sm2.html5 = { + usingFlash: null + }; + + sm2.flash = {}; + + // reset device-specific HTML/flash mode switches + + sm2.html5Only = false; + sm2.ignoreFlash = false; + + window.setTimeout(function() { + + // by default, re-init + + if (!excludeInit) { + sm2.beginDelayedInit(); + } + + }, 20); + + return sm2; + + }; + + this.reset = function() { + + /** + * Shuts down and restores the SoundManager instance to its original loaded state, without an explicit reboot. All onready/ontimeout handlers are removed. + * After this call, SM2 may be re-initialized via soundManager.beginDelayedInit(). + * @return {object} soundManager The soundManager instance. + */ + + _wDS('reset'); + + return sm2.reboot(true, true); + + }; + + /** + * Undocumented: Determines the SM2 flash movie's load progress. + * + * @return {number or null} Percent loaded, or if invalid/unsupported, null. + */ + + this.getMoviePercent = function() { + + /** + * Interesting syntax notes... + * Flash/ExternalInterface (ActiveX/NPAPI) bridge methods are not typeof "function" nor instanceof Function, but are still valid. + * Furthermore, using (flash && flash.PercentLoaded) causes IE to throw "object doesn't support this property or method". + * Thus, 'in' syntax must be used. + */ + + return (flash && 'PercentLoaded' in flash ? flash.PercentLoaded() : null); + + }; + + /** + * Additional helper for manually invoking SM2's init process after DOM Ready / window.onload(). + */ + + this.beginDelayedInit = function() { + + windowLoaded = true; + domContentLoaded(); + + setTimeout(function() { + + if (initPending) return false; + + createMovie(); + initMovie(); + initPending = true; + + return true; + + }, 20); + + delayWaitForEI(); + + }; + + /** + * Destroys the SoundManager instance and all SMSound instances. + */ + + this.destruct = function() { + + sm2._wD(sm + '.destruct()'); + sm2.disable(true); + + }; + + /** + * SMSound() (sound object) constructor + * ------------------------------------ + * + * @param {object} oOptions Sound options (id and url are required attributes) + * @return {SMSound} The new SMSound object + */ + + SMSound = function(oOptions) { + + var s = this, resetProperties, add_html5_events, remove_html5_events, stop_html5_timer, start_html5_timer, attachOnPosition, onplay_called = false, onPositionItems = [], onPositionFired = 0, detachOnPosition, applyFromTo, lastURL = null, lastHTML5State, urlOmitted; + + lastHTML5State = { + // tracks duration + position (time) + duration: null, + time: null + }; + + this.id = oOptions.id; + + // legacy + this.sID = this.id; + + this.url = oOptions.url; + this.options = mixin(oOptions); + + // per-play-instance-specific options + this.instanceOptions = this.options; + + // short alias + this._iO = this.instanceOptions; + + // assign property defaults + this.pan = this.options.pan; + this.volume = this.options.volume; + + // whether or not this object is using HTML5 + this.isHTML5 = false; + + // internal HTML5 Audio() object reference + this._a = null; + + // for flash 8 special-case createSound() without url, followed by load/play with url case + urlOmitted = (!this.url); + + /** + * SMSound() public methods + * ------------------------ + */ + + this.id3 = {}; + + /** + * Writes SMSound object parameters to debug console + */ + + this._debug = function() { + + // + sm2._wD(s.id + ': Merged options:', s.options); + // + + }; + + /** + * Begins loading a sound per its *url*. + * + * @param {object} options Optional: Sound options + * @return {SMSound} The SMSound object + */ + + this.load = function(options) { + + var oSound = null, instanceOptions; + + if (options !== _undefined) { + s._iO = mixin(options, s.options); + } else { + options = s.options; + s._iO = options; + if (lastURL && lastURL !== s.url) { + _wDS('manURL'); + s._iO.url = s.url; + s.url = null; + } + } + + if (!s._iO.url) { + s._iO.url = s.url; + } + + s._iO.url = parseURL(s._iO.url); + + // ensure we're in sync + s.instanceOptions = s._iO; + + // local shortcut + instanceOptions = s._iO; + + sm2._wD(s.id + ': load (' + instanceOptions.url + ')'); + + if (!instanceOptions.url && !s.url) { + sm2._wD(s.id + ': load(): url is unassigned. Exiting.', 2); + return s; + } + + // + if (!s.isHTML5 && fV === 8 && !s.url && !instanceOptions.autoPlay) { + // flash 8 load() -> play() won't work before onload has fired. + sm2._wD(s.id + ': Flash 8 load() limitation: Wait for onload() before calling play().', 1); + } + // + + if (instanceOptions.url === s.url && s.readyState !== 0 && s.readyState !== 2) { + _wDS('onURL', 1); + // if loaded and an onload() exists, fire immediately. + if (s.readyState === 3 && instanceOptions.onload) { + // assume success based on truthy duration. + wrapCallback(s, function() { + instanceOptions.onload.apply(s, [(!!s.duration)]); + }); + } + return s; + } + + // reset a few state properties + + s.loaded = false; + s.readyState = 1; + s.playState = 0; + s.id3 = {}; + + // TODO: If switching from HTML5 -> flash (or vice versa), stop currently-playing audio. + + if (html5OK(instanceOptions)) { + + oSound = s._setup_html5(instanceOptions); + + if (!oSound._called_load) { + + s._html5_canplay = false; + + // TODO: review called_load / html5_canplay logic + + // if url provided directly to load(), assign it here. + + if (s.url !== instanceOptions.url) { + + sm2._wD(_wDS('manURL') + ': ' + instanceOptions.url); + + s._a.src = instanceOptions.url; + + // TODO: review / re-apply all relevant options (volume, loop, onposition etc.) + + // reset position for new URL + s.setPosition(0); + + } + + // given explicit load call, try to preload. + + // early HTML5 implementation (non-standard) + s._a.autobuffer = 'auto'; + + // standard property, values: none / metadata / auto + // reference: http://msdn.microsoft.com/en-us/library/ie/ff974759%28v=vs.85%29.aspx + s._a.preload = 'auto'; + + s._a._called_load = true; + + } else { + + sm2._wD(s.id + ': Ignoring request to load again'); + + } + + } else { + + if (sm2.html5Only) { + sm2._wD(s.id + ': No flash support. Exiting.'); + return s; + } + + if (s._iO.url && s._iO.url.match(/data:/i)) { + // data: URIs not supported by Flash, either. + sm2._wD(s.id + ': data: URIs not supported via Flash. Exiting.'); + return s; + } + + try { + s.isHTML5 = false; + s._iO = policyFix(loopFix(instanceOptions)); + // if we have "position", disable auto-play as we'll be seeking to that position at onload(). + if (s._iO.autoPlay && (s._iO.position || s._iO.from)) { + sm2._wD(s.id + ': Disabling autoPlay because of non-zero offset case'); + s._iO.autoPlay = false; + } + // re-assign local shortcut + instanceOptions = s._iO; + if (fV === 8) { + flash._load(s.id, instanceOptions.url, instanceOptions.stream, instanceOptions.autoPlay, instanceOptions.usePolicyFile); + } else { + flash._load(s.id, instanceOptions.url, !!(instanceOptions.stream), !!(instanceOptions.autoPlay), instanceOptions.loops || 1, !!(instanceOptions.autoLoad), instanceOptions.usePolicyFile); + } + } catch(e) { + _wDS('smError', 2); + debugTS('onload', false); + catchError({ + type: 'SMSOUND_LOAD_JS_EXCEPTION', + fatal: true + }); + } + + } + + // after all of this, ensure sound url is up to date. + s.url = instanceOptions.url; + + return s; + + }; + + /** + * Unloads a sound, canceling any open HTTP requests. + * + * @return {SMSound} The SMSound object + */ + + this.unload = function() { + + // Flash 8/AS2 can't "close" a stream - fake it by loading an empty URL + // Flash 9/AS3: Close stream, preventing further load + // HTML5: Most UAs will use empty URL + + if (s.readyState !== 0) { + + sm2._wD(s.id + ': unload()'); + + if (!s.isHTML5) { + + if (fV === 8) { + flash._unload(s.id, emptyURL); + } else { + flash._unload(s.id); + } + + } else { + + stop_html5_timer(); + + if (s._a) { + + s._a.pause(); + + // update empty URL, too + lastURL = html5Unload(s._a); + + } + + } + + // reset load/status flags + resetProperties(); + + } + + return s; + + }; + + /** + * Unloads and destroys a sound. + */ + + this.destruct = function(_bFromSM) { + + sm2._wD(s.id + ': Destruct'); + + if (!s.isHTML5) { + + // kill sound within Flash + // Disable the onfailure handler + s._iO.onfailure = null; + flash._destroySound(s.id); + + } else { + + stop_html5_timer(); + + if (s._a) { + s._a.pause(); + html5Unload(s._a); + if (!useGlobalHTML5Audio) { + remove_html5_events(); + } + // break obvious circular reference + s._a._s = null; + s._a = null; + } + + } + + if (!_bFromSM) { + // ensure deletion from controller + sm2.destroySound(s.id, true); + } + + }; + + /** + * Begins playing a sound. + * + * @param {object} options Optional: Sound options + * @return {SMSound} The SMSound object + */ + + this.play = function(options, _updatePlayState) { + + var fN, allowMulti, a, onready, + audioClone, onended, oncanplay, + startOK = true; + + // + fN = s.id + ': play(): '; + // + + // default to true + _updatePlayState = (_updatePlayState === _undefined ? true : _updatePlayState); + + if (!options) { + options = {}; + } + + // first, use local URL (if specified) + if (s.url) { + s._iO.url = s.url; + } + + // mix in any options defined at createSound() + s._iO = mixin(s._iO, s.options); + + // mix in any options specific to this method + s._iO = mixin(options, s._iO); + + s._iO.url = parseURL(s._iO.url); + + s.instanceOptions = s._iO; + + // RTMP-only + if (!s.isHTML5 && s._iO.serverURL && !s.connected) { + if (!s.getAutoPlay()) { + sm2._wD(fN + ' Netstream not connected yet - setting autoPlay'); + s.setAutoPlay(true); + } + // play will be called in onconnect() + return s; + } + + if (html5OK(s._iO)) { + s._setup_html5(s._iO); + start_html5_timer(); + } + + if (s.playState === 1 && !s.paused) { + + allowMulti = s._iO.multiShot; + + if (!allowMulti) { + + sm2._wD(fN + 'Already playing (one-shot)', 1); + + if (s.isHTML5) { + // go back to original position. + s.setPosition(s._iO.position); + } + + return s; + + } + + sm2._wD(fN + 'Already playing (multi-shot)', 1); + + } + + // edge case: play() with explicit URL parameter + if (options.url && options.url !== s.url) { + + // special case for createSound() followed by load() / play() with url; avoid double-load case. + if (!s.readyState && !s.isHTML5 && fV === 8 && urlOmitted) { + + urlOmitted = false; + + } else { + + // load using merged options + s.load(s._iO); + + } + + } + + if (!s.loaded) { + + if (s.readyState === 0) { + + sm2._wD(fN + 'Attempting to load'); + + // try to get this sound playing ASAP + if (!s.isHTML5 && !sm2.html5Only) { + + // flash: assign directly because setAutoPlay() increments the instanceCount + s._iO.autoPlay = true; + s.load(s._iO); + + } else if (s.isHTML5) { + + // iOS needs this when recycling sounds, loading a new URL on an existing object. + s.load(s._iO); + + } else { + + sm2._wD(fN + 'Unsupported type. Exiting.'); + + return s; + + } + + // HTML5 hack - re-set instanceOptions? + s.instanceOptions = s._iO; + + } else if (s.readyState === 2) { + + sm2._wD(fN + 'Could not load - exiting', 2); + + return s; + + } else { + + sm2._wD(fN + 'Loading - attempting to play...'); + + } + + } else { + + // "play()" + sm2._wD(fN.substr(0, fN.lastIndexOf(':'))); + + } + + if (!s.isHTML5 && fV === 9 && s.position > 0 && s.position === s.duration) { + // flash 9 needs a position reset if play() is called while at the end of a sound. + sm2._wD(fN + 'Sound at end, resetting to position: 0'); + options.position = 0; + } + + /** + * Streams will pause when their buffer is full if they are being loaded. + * In this case paused is true, but the song hasn't started playing yet. + * If we just call resume() the onplay() callback will never be called. + * So only call resume() if the position is > 0. + * Another reason is because options like volume won't have been applied yet. + * For normal sounds, just resume. + */ + + if (s.paused && s.position >= 0 && (!s._iO.serverURL || s.position > 0)) { + + // https://gist.github.com/37b17df75cc4d7a90bf6 + sm2._wD(fN + 'Resuming from paused state', 1); + s.resume(); + + } else { + + s._iO = mixin(options, s._iO); + + /** + * Preload in the event of play() with position under Flash, + * or from/to parameters and non-RTMP case + */ + if (((!s.isHTML5 && s._iO.position !== null && s._iO.position > 0) || (s._iO.from !== null && s._iO.from > 0) || s._iO.to !== null) && s.instanceCount === 0 && s.playState === 0 && !s._iO.serverURL) { + + onready = function() { + // sound "canplay" or onload() + // re-apply position/from/to to instance options, and start playback + s._iO = mixin(options, s._iO); + s.play(s._iO); + }; + + // HTML5 needs to at least have "canplay" fired before seeking. + if (s.isHTML5 && !s._html5_canplay) { + + // this hasn't been loaded yet. load it first, and then do this again. + sm2._wD(fN + 'Beginning load for non-zero offset case'); + + s.load({ + // note: custom HTML5-only event added for from/to implementation. + _oncanplay: onready + }); + + } else if (!s.isHTML5 && !s.loaded && (!s.readyState || s.readyState !== 2)) { + + // to be safe, preload the whole thing in Flash. + + sm2._wD(fN + 'Preloading for non-zero offset case'); + + s.load({ + onload: onready + }); + + } + + // otherwise, we're ready to go. re-apply local options, and continue + + s._iO = applyFromTo(); + + } + + // sm2._wD(fN + 'Starting to play'); + + // increment instance counter, where enabled + supported + if (!s.instanceCount || s._iO.multiShotEvents || (s.isHTML5 && s._iO.multiShot && !useGlobalHTML5Audio) || (!s.isHTML5 && fV > 8 && !s.getAutoPlay())) { + s.instanceCount++; + } + + // if first play and onposition parameters exist, apply them now + if (s._iO.onposition && s.playState === 0) { + attachOnPosition(s); + } + + s.playState = 1; + s.paused = false; + + s.position = (s._iO.position !== _undefined && !isNaN(s._iO.position) ? s._iO.position : 0); + + if (!s.isHTML5) { + s._iO = policyFix(loopFix(s._iO)); + } + + if (s._iO.onplay && _updatePlayState) { + s._iO.onplay.apply(s); + onplay_called = true; + } + + s.setVolume(s._iO.volume, true); + s.setPan(s._iO.pan, true); + + if (s._iO.playbackRate !== 1) { + s.setPlaybackRate(s._iO.playbackRate); + } + + if (!s.isHTML5) { + + startOK = flash._start(s.id, s._iO.loops || 1, (fV === 9 ? s.position : s.position / msecScale), s._iO.multiShot || false); + + if (fV === 9 && !startOK) { + // edge case: no sound hardware, or 32-channel flash ceiling hit. + // applies only to Flash 9, non-NetStream/MovieStar sounds. + // http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/media/Sound.html#play%28%29 + sm2._wD(fN + 'No sound hardware, or 32-sound ceiling hit', 2); + if (s._iO.onplayerror) { + s._iO.onplayerror.apply(s); + } + + } + + } else if (s.instanceCount < 2) { + + // HTML5 single-instance case + + start_html5_timer(); + + a = s._setup_html5(); + + s.setPosition(s._iO.position); + + a.play(); + + } else { + + // HTML5 multi-shot case + + sm2._wD(s.id + ': Cloning Audio() for instance #' + s.instanceCount + '...'); + + audioClone = new Audio(s._iO.url); + + onended = function() { + event.remove(audioClone, 'ended', onended); + s._onfinish(s); + // cleanup + html5Unload(audioClone); + audioClone = null; + }; + + oncanplay = function() { + event.remove(audioClone, 'canplay', oncanplay); + try { + audioClone.currentTime = s._iO.position / msecScale; + } catch(err) { + complain(s.id + ': multiShot play() failed to apply position of ' + (s._iO.position / msecScale)); + } + audioClone.play(); + }; + + event.add(audioClone, 'ended', onended); + + // apply volume to clones, too + if (s._iO.volume !== _undefined) { + audioClone.volume = Math.max(0, Math.min(1, s._iO.volume / 100)); + } + + // playing multiple muted sounds? if you do this, you're weird ;) - but let's cover it. + if (s.muted) { + audioClone.muted = true; + } + + if (s._iO.position) { + // HTML5 audio can't seek before onplay() event has fired. + // wait for canplay, then seek to position and start playback. + event.add(audioClone, 'canplay', oncanplay); + } else { + // begin playback at currentTime: 0 + audioClone.play(); + } + + } + + } + + return s; + + }; + + // just for convenience + this.start = this.play; + + /** + * Stops playing a sound (and optionally, all sounds) + * + * @param {boolean} bAll Optional: Whether to stop all sounds + * @return {SMSound} The SMSound object + */ + + this.stop = function(bAll) { + + var instanceOptions = s._iO, + originalPosition; + + if (s.playState === 1) { + + sm2._wD(s.id + ': stop()'); + + s._onbufferchange(0); + s._resetOnPosition(0); + s.paused = false; + + if (!s.isHTML5) { + s.playState = 0; + } + + // remove onPosition listeners, if any + detachOnPosition(); + + // and "to" position, if set + if (instanceOptions.to) { + s.clearOnPosition(instanceOptions.to); + } + + if (!s.isHTML5) { + + flash._stop(s.id, bAll); + + // hack for netStream: just unload + if (instanceOptions.serverURL) { + s.unload(); + } + + } else if (s._a) { + + originalPosition = s.position; + + // act like Flash, though + s.setPosition(0); + + // hack: reflect old position for onstop() (also like Flash) + s.position = originalPosition; + + // html5 has no stop() + // NOTE: pausing means iOS requires interaction to resume. + s._a.pause(); + + s.playState = 0; + + // and update UI + s._onTimer(); + + stop_html5_timer(); + + } + + s.instanceCount = 0; + s._iO = {}; + + if (instanceOptions.onstop) { + instanceOptions.onstop.apply(s); + } + + } + + return s; + + }; + + /** + * Undocumented/internal: Sets autoPlay for RTMP. + * + * @param {boolean} autoPlay state + */ + + this.setAutoPlay = function(autoPlay) { + + sm2._wD(s.id + ': Autoplay turned ' + (autoPlay ? 'on' : 'off')); + s._iO.autoPlay = autoPlay; + + if (!s.isHTML5) { + flash._setAutoPlay(s.id, autoPlay); + if (autoPlay) { + // only increment the instanceCount if the sound isn't loaded (TODO: verify RTMP) + if (!s.instanceCount && s.readyState === 1) { + s.instanceCount++; + sm2._wD(s.id + ': Incremented instance count to ' + s.instanceCount); + } + } + } + + }; + + /** + * Undocumented/internal: Returns the autoPlay boolean. + * + * @return {boolean} The current autoPlay value + */ + + this.getAutoPlay = function() { + + return s._iO.autoPlay; + + }; + + /** + * Sets the playback rate of a sound (HTML5-only.) + * + * @param {number} playbackRate (+/-) + * @return {SMSound} The SMSound object + */ + + this.setPlaybackRate = function(playbackRate) { + + // Per Mozilla, limit acceptable values to prevent playback from stopping (unless allowOverride is truthy.) + // https://developer.mozilla.org/en-US/Apps/Build/Audio_and_video_delivery/WebAudio_playbackRate_explained + var normalizedRate = Math.max(0.5, Math.min(4, playbackRate)); + + // + if (normalizedRate !== playbackRate) { + sm2._wD(s.id + ': setPlaybackRate(' + playbackRate + '): limiting rate to ' + normalizedRate, 2); + } + // + + if (s.isHTML5) { + try { + s._iO.playbackRate = normalizedRate; + s._a.playbackRate = normalizedRate; + } catch(e) { + sm2._wD(s.id + ': setPlaybackRate(' + normalizedRate + ') failed: ' + e.message, 2); + } + } + + return s; + + }; + + /** + * Sets the position of a sound. + * + * @param {number} nMsecOffset Position (milliseconds) + * @return {SMSound} The SMSound object + */ + + this.setPosition = function(nMsecOffset) { + + if (nMsecOffset === _undefined) { + nMsecOffset = 0; + } + + var position, position1K, + // Use the duration from the instance options, if we don't have a track duration yet. + // position >= 0 and <= current available (loaded) duration + offset = (s.isHTML5 ? Math.max(nMsecOffset, 0) : Math.min(s.duration || s._iO.duration, Math.max(nMsecOffset, 0))); + + s.position = offset; + position1K = s.position / msecScale; + s._resetOnPosition(s.position); + s._iO.position = offset; + + if (!s.isHTML5) { + + position = (fV === 9 ? s.position : position1K); + + if (s.readyState && s.readyState !== 2) { + // if paused or not playing, will not resume (by playing) + flash._setPosition(s.id, position, (s.paused || !s.playState), s._iO.multiShot); + } + + } else if (s._a) { + + // Set the position in the canplay handler if the sound is not ready yet + if (s._html5_canplay) { + + if (s._a.currentTime.toFixed(3) !== position1K.toFixed(3)) { + + /** + * DOM/JS errors/exceptions to watch out for: + * if seek is beyond (loaded?) position, "DOM exception 11" + * "INDEX_SIZE_ERR": DOM exception 1 + */ + sm2._wD(s.id + ': setPosition(' + position1K + ')'); + + try { + s._a.currentTime = position1K; + if (s.playState === 0 || s.paused) { + // allow seek without auto-play/resume + s._a.pause(); + } + } catch(e) { + sm2._wD(s.id + ': setPosition(' + position1K + ') failed: ' + e.message, 2); + } + + } + + } else if (position1K) { + + // warn on non-zero seek attempts + sm2._wD(s.id + ': setPosition(' + position1K + '): Cannot seek yet, sound not ready', 2); + return s; + + } + + if (s.paused) { + + // if paused, refresh UI right away by forcing update + s._onTimer(true); + + } + + } + + return s; + + }; + + /** + * Pauses sound playback. + * + * @return {SMSound} The SMSound object + */ + + this.pause = function(_bCallFlash) { + + if (s.paused || (s.playState === 0 && s.readyState !== 1)) return s; + + sm2._wD(s.id + ': pause()'); + s.paused = true; + + if (!s.isHTML5) { + if (_bCallFlash || _bCallFlash === _undefined) { + flash._pause(s.id, s._iO.multiShot); + } + } else { + s._setup_html5().pause(); + stop_html5_timer(); + } + + if (s._iO.onpause) { + s._iO.onpause.apply(s); + } + + return s; + + }; + + /** + * Resumes sound playback. + * + * @return {SMSound} The SMSound object + */ + + /** + * When auto-loaded streams pause on buffer full they have a playState of 0. + * We need to make sure that the playState is set to 1 when these streams "resume". + * When a paused stream is resumed, we need to trigger the onplay() callback if it + * hasn't been called already. In this case since the sound is being played for the + * first time, I think it's more appropriate to call onplay() rather than onresume(). + */ + + this.resume = function() { + + var instanceOptions = s._iO; + + if (!s.paused) return s; + + sm2._wD(s.id + ': resume()'); + s.paused = false; + s.playState = 1; + + if (!s.isHTML5) { + + if (instanceOptions.isMovieStar && !instanceOptions.serverURL) { + // Bizarre Webkit bug (Chrome reported via 8tracks.com dudes): AAC content paused for 30+ seconds(?) will not resume without a reposition. + s.setPosition(s.position); + } + + // flash method is toggle-based (pause/resume) + flash._pause(s.id, instanceOptions.multiShot); + + } else { + + s._setup_html5().play(); + start_html5_timer(); + + } + + if (!onplay_called && instanceOptions.onplay) { + + instanceOptions.onplay.apply(s); + onplay_called = true; + + } else if (instanceOptions.onresume) { + + instanceOptions.onresume.apply(s); + + } + + return s; + + }; + + /** + * Toggles sound playback. + * + * @return {SMSound} The SMSound object + */ + + this.togglePause = function() { + + sm2._wD(s.id + ': togglePause()'); + + if (s.playState === 0) { + s.play({ + position: (fV === 9 && !s.isHTML5 ? s.position : s.position / msecScale) + }); + return s; + } + + if (s.paused) { + s.resume(); + } else { + s.pause(); + } + + return s; + + }; + + /** + * Sets the panning (L-R) effect. + * + * @param {number} nPan The pan value (-100 to 100) + * @return {SMSound} The SMSound object + */ + + this.setPan = function(nPan, bInstanceOnly) { + + if (nPan === _undefined) { + nPan = 0; + } + + if (bInstanceOnly === _undefined) { + bInstanceOnly = false; + } + + if (!s.isHTML5) { + flash._setPan(s.id, nPan); + } // else { no HTML5 pan? } + + s._iO.pan = nPan; + + if (!bInstanceOnly) { + s.pan = nPan; + s.options.pan = nPan; + } + + return s; + + }; + + /** + * Sets the volume. + * + * @param {number} nVol The volume value (0 to 100) + * @return {SMSound} The SMSound object + */ + + this.setVolume = function(nVol, _bInstanceOnly) { + + /** + * Note: Setting volume has no effect on iOS "special snowflake" devices. + * Hardware volume control overrides software, and volume + * will always return 1 per Apple docs. (iOS 4 + 5.) + * http://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/HTML-canvas-guide/AddingSoundtoCanvasAnimations/AddingSoundtoCanvasAnimations.html + */ + + if (nVol === _undefined) { + nVol = 100; + } + + if (_bInstanceOnly === _undefined) { + _bInstanceOnly = false; + } + + if (!s.isHTML5) { + + flash._setVolume(s.id, (sm2.muted && !s.muted) || s.muted ? 0 : nVol); + + } else if (s._a) { + + if (sm2.muted && !s.muted) { + s.muted = true; + s._a.muted = true; + } + + // valid range for native HTML5 Audio(): 0-1 + s._a.volume = Math.max(0, Math.min(1, nVol / 100)); + + } + + s._iO.volume = nVol; + + if (!_bInstanceOnly) { + s.volume = nVol; + s.options.volume = nVol; + } + + return s; + + }; + + /** + * Mutes the sound. + * + * @return {SMSound} The SMSound object + */ + + this.mute = function() { + + s.muted = true; + + if (!s.isHTML5) { + flash._setVolume(s.id, 0); + } else if (s._a) { + s._a.muted = true; + } + + return s; + + }; + + /** + * Unmutes the sound. + * + * @return {SMSound} The SMSound object + */ + + this.unmute = function() { + + s.muted = false; + var hasIO = (s._iO.volume !== _undefined); + + if (!s.isHTML5) { + flash._setVolume(s.id, hasIO ? s._iO.volume : s.options.volume); + } else if (s._a) { + s._a.muted = false; + } + + return s; + + }; + + /** + * Toggles the muted state of a sound. + * + * @return {SMSound} The SMSound object + */ + + this.toggleMute = function() { + + return (s.muted ? s.unmute() : s.mute()); + + }; + + /** + * Registers a callback to be fired when a sound reaches a given position during playback. + * + * @param {number} nPosition The position to watch for + * @param {function} oMethod The relevant callback to fire + * @param {object} oScope Optional: The scope to apply the callback to + * @return {SMSound} The SMSound object + */ + + this.onPosition = function(nPosition, oMethod, oScope) { + + // TODO: basic dupe checking? + + onPositionItems.push({ + position: parseInt(nPosition, 10), + method: oMethod, + scope: (oScope !== _undefined ? oScope : s), + fired: false + }); + + return s; + + }; + + // legacy/backwards-compability: lower-case method name + this.onposition = this.onPosition; + + /** + * Removes registered callback(s) from a sound, by position and/or callback. + * + * @param {number} nPosition The position to clear callback(s) for + * @param {function} oMethod Optional: Identify one callback to be removed when multiple listeners exist for one position + * @return {SMSound} The SMSound object + */ + + this.clearOnPosition = function(nPosition, oMethod) { + + var i; + + nPosition = parseInt(nPosition, 10); + + if (isNaN(nPosition)) { + // safety check + return; + } + + for (i = 0; i < onPositionItems.length; i++) { + + if (nPosition === onPositionItems[i].position) { + // remove this item if no method was specified, or, if the method matches + + if (!oMethod || (oMethod === onPositionItems[i].method)) { + + if (onPositionItems[i].fired) { + // decrement "fired" counter, too + onPositionFired--; + } + + onPositionItems.splice(i, 1); + + } + + } + + } + + }; + + this._processOnPosition = function() { + + var i, item, j = onPositionItems.length; + + if (!j || !s.playState || onPositionFired >= j) return false; + + for (i = j - 1; i >= 0; i--) { + + item = onPositionItems[i]; + + if (!item.fired && s.position >= item.position) { + + item.fired = true; + onPositionFired++; + item.method.apply(item.scope, [item.position]); + + // reset j -- onPositionItems.length can be changed in the item callback above... occasionally breaking the loop. + j = onPositionItems.length; + + } + + } + + return true; + + }; + + this._resetOnPosition = function(nPosition) { + + // reset "fired" for items interested in this position + var i, item, j = onPositionItems.length; + + if (!j) return false; + + for (i = j - 1; i >= 0; i--) { + + item = onPositionItems[i]; + + if (item.fired && nPosition <= item.position) { + item.fired = false; + onPositionFired--; + } + + } + + return true; + + }; + + /** + * SMSound() private internals + * -------------------------------- + */ + + applyFromTo = function() { + + var instanceOptions = s._iO, + f = instanceOptions.from, + t = instanceOptions.to, + start, end; + + end = function() { + + // end has been reached. + sm2._wD(s.id + ': "To" time of ' + t + ' reached.'); + + // detach listener + s.clearOnPosition(t, end); + + // stop should clear this, too + s.stop(); + + }; + + start = function() { + + sm2._wD(s.id + ': Playing "from" ' + f); + + // add listener for end + if (t !== null && !isNaN(t)) { + s.onPosition(t, end); + } + + }; + + if (f !== null && !isNaN(f)) { + + // apply to instance options, guaranteeing correct start position. + instanceOptions.position = f; + + // multiShot timing can't be tracked, so prevent that. + instanceOptions.multiShot = false; + + start(); + + } + + // return updated instanceOptions including starting position + return instanceOptions; + + }; + + attachOnPosition = function() { + + var item, + op = s._iO.onposition; + + // attach onposition things, if any, now. + + if (op) { + + for (item in op) { + if (op.hasOwnProperty(item)) { + s.onPosition(parseInt(item, 10), op[item]); + } + } + + } + + }; + + detachOnPosition = function() { + + var item, + op = s._iO.onposition; + + // detach any onposition()-style listeners. + + if (op) { + + for (item in op) { + if (op.hasOwnProperty(item)) { + s.clearOnPosition(parseInt(item, 10)); + } + } + + } + + }; + + start_html5_timer = function() { + + if (s.isHTML5) { + startTimer(s); + } + + }; + + stop_html5_timer = function() { + + if (s.isHTML5) { + stopTimer(s); + } + + }; + + resetProperties = function(retainPosition) { + + if (!retainPosition) { + onPositionItems = []; + onPositionFired = 0; + } + + onplay_called = false; + + s._hasTimer = null; + s._a = null; + s._html5_canplay = false; + s.bytesLoaded = null; + s.bytesTotal = null; + s.duration = (s._iO && s._iO.duration ? s._iO.duration : null); + s.durationEstimate = null; + s.buffered = []; + + // legacy: 1D array + s.eqData = []; + + s.eqData.left = []; + s.eqData.right = []; + + s.failures = 0; + s.isBuffering = false; + s.instanceOptions = {}; + s.instanceCount = 0; + s.loaded = false; + s.metadata = {}; + + // 0 = uninitialised, 1 = loading, 2 = failed/error, 3 = loaded/success + s.readyState = 0; + + s.muted = false; + s.paused = false; + + s.peakData = { + left: 0, + right: 0 + }; + + s.waveformData = { + left: [], + right: [] + }; + + s.playState = 0; + s.position = null; + + s.id3 = {}; + + }; + + resetProperties(); + + /** + * Pseudo-private SMSound internals + * -------------------------------- + */ + + this._onTimer = function(bForce) { + + /** + * HTML5-only _whileplaying() etc. + * called from both HTML5 native events, and polling/interval-based timers + * mimics flash and fires only when time/duration change, so as to be polling-friendly + */ + + var duration, isNew = false, time, x = {}; + + if (s._hasTimer || bForce) { + + // TODO: May not need to track readyState (1 = loading) + + if (s._a && (bForce || ((s.playState > 0 || s.readyState === 1) && !s.paused))) { + + duration = s._get_html5_duration(); + + if (duration !== lastHTML5State.duration) { + + lastHTML5State.duration = duration; + s.duration = duration; + isNew = true; + + } + + // TODO: investigate why this goes wack if not set/re-set each time. + s.durationEstimate = s.duration; + + time = (s._a.currentTime * msecScale || 0); + + if (time !== lastHTML5State.time) { + + lastHTML5State.time = time; + isNew = true; + + } + + if (isNew || bForce) { + + s._whileplaying(time, x, x, x, x); + + } + + }/* else { + + // sm2._wD('_onTimer: Warn for "'+s.id+'": '+(!s._a?'Could not find element. ':'')+(s.playState === 0?'playState bad, 0?':'playState = '+s.playState+', OK')); + + return false; + + }*/ + + } + + return isNew; + + }; + + this._get_html5_duration = function() { + + var instanceOptions = s._iO, + // if audio object exists, use its duration - else, instance option duration (if provided - it's a hack, really, and should be retired) OR null + d = (s._a && s._a.duration ? s._a.duration * msecScale : (instanceOptions && instanceOptions.duration ? instanceOptions.duration : null)), + result = (d && !isNaN(d) && d !== Infinity ? d : null); + + return result; + + }; + + this._apply_loop = function(a, nLoops) { + + /** + * boolean instead of "loop", for webkit? - spec says string. http://www.w3.org/TR/html-markup/audio.html#audio.attrs.loop + * note that loop is either off or infinite under HTML5, unlike Flash which allows arbitrary loop counts to be specified. + */ + + // + if (!a.loop && nLoops > 1) { + sm2._wD('Note: Native HTML5 looping is infinite.', 1); + } + // + + a.loop = (nLoops > 1 ? 'loop' : ''); + + }; + + this._setup_html5 = function(options) { + + var instanceOptions = mixin(s._iO, options), + a = useGlobalHTML5Audio ? globalHTML5Audio : s._a, + dURL = decodeURI(instanceOptions.url), + sameURL; + + /** + * "First things first, I, Poppa..." (reset the previous state of the old sound, if playing) + * Fixes case with devices that can only play one sound at a time + * Otherwise, other sounds in mid-play will be terminated without warning and in a stuck state + */ + + if (useGlobalHTML5Audio) { + + if (dURL === decodeURI(lastGlobalHTML5URL)) { + // global HTML5 audio: re-use of URL + sameURL = true; + } + + } else if (dURL === decodeURI(lastURL)) { + + // options URL is the same as the "last" URL, and we used (loaded) it + sameURL = true; + + } + + if (a) { + + if (a._s) { + + if (useGlobalHTML5Audio) { + + if (a._s && a._s.playState && !sameURL) { + + // global HTML5 audio case, and loading a new URL. stop the currently-playing one. + a._s.stop(); + + } + + } else if (!useGlobalHTML5Audio && dURL === decodeURI(lastURL)) { + + // non-global HTML5 reuse case: same url, ignore request + s._apply_loop(a, instanceOptions.loops); + + return a; + + } + + } + + if (!sameURL) { + + // don't retain onPosition() stuff with new URLs. + + if (lastURL) { + resetProperties(false); + } + + // assign new HTML5 URL + + a.src = instanceOptions.url; + + s.url = instanceOptions.url; + + lastURL = instanceOptions.url; + + lastGlobalHTML5URL = instanceOptions.url; + + a._called_load = false; + + } + + } else { + + if (instanceOptions.autoLoad || instanceOptions.autoPlay) { + + s._a = new Audio(instanceOptions.url); + s._a.load(); + + } else { + + // null for stupid Opera 9.64 case + s._a = (isOpera && opera.version() < 10 ? new Audio(null) : new Audio()); + + } + + // assign local reference + a = s._a; + + a._called_load = false; + + if (useGlobalHTML5Audio) { + + globalHTML5Audio = a; + + } + + } + + s.isHTML5 = true; + + // store a ref on the track + s._a = a; + + // store a ref on the audio + a._s = s; + + add_html5_events(); + + s._apply_loop(a, instanceOptions.loops); + + if (instanceOptions.autoLoad || instanceOptions.autoPlay) { + + s.load(); + + } else { + + // early HTML5 implementation (non-standard) + a.autobuffer = false; + + // standard ('none' is also an option.) + a.preload = 'auto'; + + } + + return a; + + }; + + add_html5_events = function() { + + if (s._a._added_events) return false; + + var f; + + function add(oEvt, oFn, bCapture) { + return s._a ? s._a.addEventListener(oEvt, oFn, bCapture || false) : null; + } + + s._a._added_events = true; + + for (f in html5_events) { + if (html5_events.hasOwnProperty(f)) { + add(f, html5_events[f]); + } + } + + return true; + + }; + + remove_html5_events = function() { + + // Remove event listeners + + var f; + + function remove(oEvt, oFn, bCapture) { + return (s._a ? s._a.removeEventListener(oEvt, oFn, bCapture || false) : null); + } + + sm2._wD(s.id + ': Removing event listeners'); + s._a._added_events = false; + + for (f in html5_events) { + if (html5_events.hasOwnProperty(f)) { + remove(f, html5_events[f]); + } + } + + }; + + /** + * Pseudo-private event internals + * ------------------------------ + */ + + this._onload = function(nSuccess) { + + var fN, + // check for duration to prevent false positives from flash 8 when loading from cache. + loadOK = !!nSuccess || (!s.isHTML5 && fV === 8 && s.duration); + + // + fN = s.id + ': '; + sm2._wD(fN + (loadOK ? 'onload()' : 'Failed to load / invalid sound?' + (!s.duration ? ' Zero-length duration reported.' : ' -') + ' (' + s.url + ')'), (loadOK ? 1 : 2)); + + if (!loadOK && !s.isHTML5) { + if (sm2.sandbox.noRemote === true) { + sm2._wD(fN + str('noNet'), 1); + } + if (sm2.sandbox.noLocal === true) { + sm2._wD(fN + str('noLocal'), 1); + } + } + // + + s.loaded = loadOK; + s.readyState = (loadOK ? 3 : 2); + s._onbufferchange(0); + + if (!loadOK && !s.isHTML5) { + // note: no error code from Flash. + s._onerror(); + } + + if (s._iO.onload) { + wrapCallback(s, function() { + s._iO.onload.apply(s, [loadOK]); + }); + } + + return true; + + }; + + this._onerror = function(errorCode, description) { + + // https://html.spec.whatwg.org/multipage/embedded-content.html#error-codes + if (s._iO.onerror) { + wrapCallback(s, function() { + s._iO.onerror.apply(s, [errorCode, description]); + }); + } + + }; + + this._onbufferchange = function(nIsBuffering) { + + // ignore if not playing + if (s.playState === 0) return false; + + if ((nIsBuffering && s.isBuffering) || (!nIsBuffering && !s.isBuffering)) return false; + + s.isBuffering = (nIsBuffering === 1); + + if (s._iO.onbufferchange) { + sm2._wD(s.id + ': Buffer state change: ' + nIsBuffering); + s._iO.onbufferchange.apply(s, [nIsBuffering]); + } + + return true; + + }; + + /** + * Playback may have stopped due to buffering, or related reason. + * This state can be encountered on iOS < 6 when auto-play is blocked. + */ + + this._onsuspend = function() { + + if (s._iO.onsuspend) { + sm2._wD(s.id + ': Playback suspended'); + s._iO.onsuspend.apply(s); + } + + return true; + + }; + + /** + * flash 9/movieStar + RTMP-only method, should fire only once at most + * at this point we just recreate failed sounds rather than trying to reconnect + */ + + this._onfailure = function(msg, level, code) { + + s.failures++; + sm2._wD(s.id + ': Failure (' + s.failures + '): ' + msg); + + if (s._iO.onfailure && s.failures === 1) { + s._iO.onfailure(msg, level, code); + } else { + sm2._wD(s.id + ': Ignoring failure'); + } + + }; + + /** + * flash 9/movieStar + RTMP-only method for unhandled warnings/exceptions from Flash + * e.g., RTMP "method missing" warning (non-fatal) for getStreamLength on server + */ + + this._onwarning = function(msg, level, code) { + + if (s._iO.onwarning) { + s._iO.onwarning(msg, level, code); + } + + }; + + this._onfinish = function() { + + // store local copy before it gets trashed... + var io_onfinish = s._iO.onfinish; + + s._onbufferchange(0); + s._resetOnPosition(0); + + // reset some state items + if (s.instanceCount) { + + s.instanceCount--; + + if (!s.instanceCount) { + + // remove onPosition listeners, if any + detachOnPosition(); + + // reset instance options + s.playState = 0; + s.paused = false; + s.instanceCount = 0; + s.instanceOptions = {}; + s._iO = {}; + stop_html5_timer(); + + // reset position, too + if (s.isHTML5) { + s.position = 0; + } + + } + + if (!s.instanceCount || s._iO.multiShotEvents) { + // fire onfinish for last, or every instance + if (io_onfinish) { + sm2._wD(s.id + ': onfinish()'); + wrapCallback(s, function() { + io_onfinish.apply(s); + }); + } + } + + } + + }; + + this._whileloading = function(nBytesLoaded, nBytesTotal, nDuration, nBufferLength) { + + var instanceOptions = s._iO; + + s.bytesLoaded = nBytesLoaded; + s.bytesTotal = nBytesTotal; + s.duration = Math.floor(nDuration); + s.bufferLength = nBufferLength; + + if (!s.isHTML5 && !instanceOptions.isMovieStar) { + + if (instanceOptions.duration) { + // use duration from options, if specified and larger. nobody should be specifying duration in options, actually, and it should be retired. + s.durationEstimate = (s.duration > instanceOptions.duration) ? s.duration : instanceOptions.duration; + } else { + s.durationEstimate = parseInt((s.bytesTotal / s.bytesLoaded) * s.duration, 10); + } + + } else { + + s.durationEstimate = s.duration; + + } + + // for flash, reflect sequential-load-style buffering + if (!s.isHTML5) { + s.buffered = [{ + start: 0, + end: s.duration + }]; + } + + // allow whileloading to fire even if "load" fired under HTML5, due to HTTP range/partials + if ((s.readyState !== 3 || s.isHTML5) && instanceOptions.whileloading) { + instanceOptions.whileloading.apply(s); + } + + }; + + this._whileplaying = function(nPosition, oPeakData, oWaveformDataLeft, oWaveformDataRight, oEQData) { + + var instanceOptions = s._iO, + eqLeft; + + // flash safety net + if (isNaN(nPosition) || nPosition === null) return false; + + // Safari HTML5 play() may return small -ve values when starting from position: 0, eg. -50.120396875. Unexpected/invalid per W3, I think. Normalize to 0. + s.position = Math.max(0, nPosition); + + s._processOnPosition(); + + if (!s.isHTML5 && fV > 8) { + + if (instanceOptions.usePeakData && oPeakData !== _undefined && oPeakData) { + s.peakData = { + left: oPeakData.leftPeak, + right: oPeakData.rightPeak + }; + } + + if (instanceOptions.useWaveformData && oWaveformDataLeft !== _undefined && oWaveformDataLeft) { + s.waveformData = { + left: oWaveformDataLeft.split(','), + right: oWaveformDataRight.split(',') + }; + } + + if (instanceOptions.useEQData) { + if (oEQData !== _undefined && oEQData && oEQData.leftEQ) { + eqLeft = oEQData.leftEQ.split(','); + s.eqData = eqLeft; + s.eqData.left = eqLeft; + if (oEQData.rightEQ !== _undefined && oEQData.rightEQ) { + s.eqData.right = oEQData.rightEQ.split(','); + } + } + } + + } + + if (s.playState === 1) { + + // special case/hack: ensure buffering is false if loading from cache (and not yet started) + if (!s.isHTML5 && fV === 8 && !s.position && s.isBuffering) { + s._onbufferchange(0); + } + + if (instanceOptions.whileplaying) { + // flash may call after actual finish + instanceOptions.whileplaying.apply(s); + } + + } + + return true; + + }; + + this._oncaptiondata = function(oData) { + + /** + * internal: flash 9 + NetStream (MovieStar/RTMP-only) feature + * + * @param {object} oData + */ + + sm2._wD(s.id + ': Caption data received.'); + + s.captiondata = oData; + + if (s._iO.oncaptiondata) { + s._iO.oncaptiondata.apply(s, [oData]); + } + + }; + + this._onmetadata = function(oMDProps, oMDData) { + + /** + * internal: flash 9 + NetStream (MovieStar/RTMP-only) feature + * RTMP may include song title, MovieStar content may include encoding info + * + * @param {array} oMDProps (names) + * @param {array} oMDData (values) + */ + + sm2._wD(s.id + ': Metadata received.'); + + var oData = {}, i, j; + + for (i = 0, j = oMDProps.length; i < j; i++) { + oData[oMDProps[i]] = oMDData[i]; + } + + s.metadata = oData; + + if (s._iO.onmetadata) { + s._iO.onmetadata.call(s, s.metadata); + } + + }; + + this._onid3 = function(oID3Props, oID3Data) { + + /** + * internal: flash 8 + flash 9 ID3 feature + * may include artist, song title etc. + * + * @param {array} oID3Props (names) + * @param {array} oID3Data (values) + */ + + sm2._wD(s.id + ': ID3 data received.'); + + var oData = [], i, j; + + for (i = 0, j = oID3Props.length; i < j; i++) { + oData[oID3Props[i]] = oID3Data[i]; + } + + s.id3 = mixin(s.id3, oData); + + if (s._iO.onid3) { + s._iO.onid3.apply(s); + } + + }; + + // flash/RTMP-only + + this._onconnect = function(bSuccess) { + + bSuccess = (bSuccess === 1); + sm2._wD(s.id + ': ' + (bSuccess ? 'Connected.' : 'Failed to connect? - ' + s.url), (bSuccess ? 1 : 2)); + s.connected = bSuccess; + + if (bSuccess) { + + s.failures = 0; + + if (idCheck(s.id)) { + if (s.getAutoPlay()) { + // only update the play state if auto playing + s.play(_undefined, s.getAutoPlay()); + } else if (s._iO.autoLoad) { + s.load(); + } + } + + if (s._iO.onconnect) { + s._iO.onconnect.apply(s, [bSuccess]); + } + + } + + }; + + this._ondataerror = function(sError) { + + // flash 9 wave/eq data handler + // hack: called at start, and end from flash at/after onfinish() + if (s.playState > 0) { + sm2._wD(s.id + ': Data error: ' + sError); + if (s._iO.ondataerror) { + s._iO.ondataerror.apply(s); + } + } + + }; + + // + this._debug(); + // + + }; // SMSound() + + /** + * Private SoundManager internals + * ------------------------------ + */ + + getDocument = function() { + + return (doc.body || doc.getElementsByTagName('div')[0]); + + }; + + id = function(sID) { + + return doc.getElementById(sID); + + }; + + mixin = function(oMain, oAdd) { + + // non-destructive merge + var o1 = (oMain || {}), o2, o; + + // if unspecified, o2 is the default options object + o2 = (oAdd === _undefined ? sm2.defaultOptions : oAdd); + + for (o in o2) { + + if (o2.hasOwnProperty(o) && o1[o] === _undefined) { + + if (typeof o2[o] !== 'object' || o2[o] === null) { + + // assign directly + o1[o] = o2[o]; + + } else { + + // recurse through o2 + o1[o] = mixin(o1[o], o2[o]); + + } + + } + + } + + return o1; + + }; + + wrapCallback = function(oSound, callback) { + + /** + * 03/03/2013: Fix for Flash Player 11.6.602.171 + Flash 8 (flashVersion = 8) SWF issue + * setTimeout() fix for certain SMSound callbacks like onload() and onfinish(), where subsequent calls like play() and load() fail when Flash Player 11.6.602.171 is installed, and using soundManager with flashVersion = 8 (which is the default). + * Not sure of exact cause. Suspect race condition and/or invalid (NaN-style) position argument trickling down to the next JS -> Flash _start() call, in the play() case. + * Fix: setTimeout() to yield, plus safer null / NaN checking on position argument provided to Flash. + * https://getsatisfaction.com/schillmania/topics/recent_chrome_update_seems_to_have_broken_my_sm2_audio_player + */ + if (!oSound.isHTML5 && fV === 8) { + window.setTimeout(callback, 0); + } else { + callback(); + } + + }; + + // additional soundManager properties that soundManager.setup() will accept + + extraOptions = { + onready: 1, + ontimeout: 1, + defaultOptions: 1, + flash9Options: 1, + movieStarOptions: 1 + }; + + assign = function(o, oParent) { + + /** + * recursive assignment of properties, soundManager.setup() helper + * allows property assignment based on whitelist + */ + + var i, + result = true, + hasParent = (oParent !== _undefined), + setupOptions = sm2.setupOptions, + bonusOptions = extraOptions; + + // + + // if soundManager.setup() called, show accepted parameters. + + if (o === _undefined) { + + result = []; + + for (i in setupOptions) { + + if (setupOptions.hasOwnProperty(i)) { + result.push(i); + } + + } + + for (i in bonusOptions) { + + if (bonusOptions.hasOwnProperty(i)) { + + if (typeof sm2[i] === 'object') { + result.push(i + ': {...}'); + } else if (sm2[i] instanceof Function) { + result.push(i + ': function() {...}'); + } else { + result.push(i); + } + + } + + } + + sm2._wD(str('setup', result.join(', '))); + + return false; + + } + + // + + for (i in o) { + + if (o.hasOwnProperty(i)) { + + // if not an {object} we want to recurse through... + + if (typeof o[i] !== 'object' || o[i] === null || o[i] instanceof Array || o[i] instanceof RegExp) { + + // check "allowed" options + + if (hasParent && bonusOptions[oParent] !== _undefined) { + + // valid recursive / nested object option, eg., { defaultOptions: { volume: 50 } } + sm2[oParent][i] = o[i]; + + } else if (setupOptions[i] !== _undefined) { + + // special case: assign to setupOptions object, which soundManager property references + sm2.setupOptions[i] = o[i]; + + // assign directly to soundManager, too + sm2[i] = o[i]; + + } else if (bonusOptions[i] === _undefined) { + + // invalid or disallowed parameter. complain. + complain(str((sm2[i] === _undefined ? 'setupUndef' : 'setupError'), i), 2); + + result = false; + + } else if (sm2[i] instanceof Function) { + + /** + * valid extraOptions (bonusOptions) parameter. + * is it a method, like onready/ontimeout? call it. + * multiple parameters should be in an array, eg. soundManager.setup({onready: [myHandler, myScope]}); + */ + sm2[i].apply(sm2, (o[i] instanceof Array ? o[i] : [o[i]])); + + } else { + + // good old-fashioned direct assignment + sm2[i] = o[i]; + + } + + } else if (bonusOptions[i] === _undefined) { + + // recursion case, eg., { defaultOptions: { ... } } + + // invalid or disallowed parameter. complain. + complain(str((sm2[i] === _undefined ? 'setupUndef' : 'setupError'), i), 2); + + result = false; + + } else { + + // recurse through object + return assign(o[i], i); + + } + + } + + } + + return result; + + }; + + function preferFlashCheck(kind) { + + // whether flash should play a given type + return (sm2.preferFlash && hasFlash && !sm2.ignoreFlash && (sm2.flash[kind] !== _undefined && sm2.flash[kind])); + + } + + /** + * Internal DOM2-level event helpers + * --------------------------------- + */ + + event = (function() { + + // normalize event methods + var old = (window.attachEvent), + evt = { + add: (old ? 'attachEvent' : 'addEventListener'), + remove: (old ? 'detachEvent' : 'removeEventListener') + }; + + // normalize "on" event prefix, optional capture argument + function getArgs(oArgs) { + + var args = slice.call(oArgs), + len = args.length; + + if (old) { + // prefix + args[1] = 'on' + args[1]; + if (len > 3) { + // no capture + args.pop(); + } + } else if (len === 3) { + args.push(false); + } + + return args; + + } + + function apply(args, sType) { + + // normalize and call the event method, with the proper arguments + var element = args.shift(), + method = [evt[sType]]; + + if (old) { + // old IE can't do apply(). + element[method](args[0], args[1]); + } else { + element[method].apply(element, args); + } + + } + + function add() { + apply(getArgs(arguments), 'add'); + } + + function remove() { + apply(getArgs(arguments), 'remove'); + } + + return { + add: add, + remove: remove + }; + + }()); + + /** + * Internal HTML5 event handling + * ----------------------------- + */ + + function html5_event(oFn) { + + // wrap html5 event handlers so we don't call them on destroyed and/or unloaded sounds + + return function(e) { + + var s = this._s, + result; + + if (!s || !s._a) { + // + if (s && s.id) { + sm2._wD(s.id + ': Ignoring ' + e.type); + } else { + sm2._wD(h5 + 'Ignoring ' + e.type); + } + // + result = null; + } else { + result = oFn.call(this, e); + } + + return result; + + }; + + } + + html5_events = { + + // HTML5 event-name-to-handler map + + abort: html5_event(function() { + + sm2._wD(this._s.id + ': abort'); + + }), + + // enough has loaded to play + + canplay: html5_event(function() { + + var s = this._s, + position1K; + + if (s._html5_canplay) { + // this event has already fired. ignore. + return; + } + + s._html5_canplay = true; + sm2._wD(s.id + ': canplay'); + s._onbufferchange(0); + + // position according to instance options + position1K = (s._iO.position !== _undefined && !isNaN(s._iO.position) ? s._iO.position / msecScale : null); + + // set the position if position was provided before the sound loaded + if (this.currentTime !== position1K) { + sm2._wD(s.id + ': canplay: Setting position to ' + position1K); + try { + this.currentTime = position1K; + } catch(ee) { + sm2._wD(s.id + ': canplay: Setting position of ' + position1K + ' failed: ' + ee.message, 2); + } + } + + // hack for HTML5 from/to case + if (s._iO._oncanplay) { + s._iO._oncanplay(); + } + + }), + + canplaythrough: html5_event(function() { + + var s = this._s; + + if (!s.loaded) { + s._onbufferchange(0); + s._whileloading(s.bytesLoaded, s.bytesTotal, s._get_html5_duration()); + s._onload(true); + } + + }), + + durationchange: html5_event(function() { + + // durationchange may fire at various times, probably the safest way to capture accurate/final duration. + + var s = this._s, + duration; + + duration = s._get_html5_duration(); + + if (!isNaN(duration) && duration !== s.duration) { + + sm2._wD(this._s.id + ': durationchange (' + duration + ')' + (s.duration ? ', previously ' + s.duration : '')); + + s.durationEstimate = s.duration = duration; + + } + + }), + + // TODO: Reserved for potential use + /* + emptied: html5_event(function() { + + sm2._wD(this._s.id + ': emptied'); + + }), + */ + + ended: html5_event(function() { + + var s = this._s; + + sm2._wD(s.id + ': ended'); + + s._onfinish(); + + }), + + error: html5_event(function() { + + var description = (html5ErrorCodes[this.error.code] || null); + sm2._wD(this._s.id + ': HTML5 error, code ' + this.error.code + (description ? ' (' + description + ')' : '')); + this._s._onload(false); + this._s._onerror(this.error.code, description); + + }), + + loadeddata: html5_event(function() { + + var s = this._s; + + sm2._wD(s.id + ': loadeddata'); + + // safari seems to nicely report progress events, eventually totalling 100% + if (!s._loaded && !isSafari) { + s.duration = s._get_html5_duration(); + } + + }), + + loadedmetadata: html5_event(function() { + + sm2._wD(this._s.id + ': loadedmetadata'); + + }), + + loadstart: html5_event(function() { + + sm2._wD(this._s.id + ': loadstart'); + // assume buffering at first + this._s._onbufferchange(1); + + }), + + play: html5_event(function() { + + // sm2._wD(this._s.id + ': play()'); + // once play starts, no buffering + this._s._onbufferchange(0); + + }), + + playing: html5_event(function() { + + sm2._wD(this._s.id + ': playing ' + String.fromCharCode(9835)); + // once play starts, no buffering + this._s._onbufferchange(0); + + }), + + progress: html5_event(function(e) { + + // note: can fire repeatedly after "loaded" event, due to use of HTTP range/partials + + var s = this._s, + i, j, progStr, buffered = 0, + isProgress = (e.type === 'progress'), + ranges = e.target.buffered, + // firefox 3.6 implements e.loaded/total (bytes) + loaded = (e.loaded || 0), + total = (e.total || 1); + + // reset the "buffered" (loaded byte ranges) array + s.buffered = []; + + if (ranges && ranges.length) { + + // if loaded is 0, try TimeRanges implementation as % of load + // https://developer.mozilla.org/en/DOM/TimeRanges + + // re-build "buffered" array + // HTML5 returns seconds. SM2 API uses msec for setPosition() etc., whether Flash or HTML5. + for (i = 0, j = ranges.length; i < j; i++) { + s.buffered.push({ + start: ranges.start(i) * msecScale, + end: ranges.end(i) * msecScale + }); + } + + // use the last value locally + buffered = (ranges.end(0) - ranges.start(0)) * msecScale; + + // linear case, buffer sum; does not account for seeking and HTTP partials / byte ranges + loaded = Math.min(1, buffered / (e.target.duration * msecScale)); + + // + if (isProgress && ranges.length > 1) { + progStr = []; + j = ranges.length; + for (i = 0; i < j; i++) { + progStr.push((e.target.buffered.start(i) * msecScale) + '-' + (e.target.buffered.end(i) * msecScale)); + } + sm2._wD(this._s.id + ': progress, timeRanges: ' + progStr.join(', ')); + } + + if (isProgress && !isNaN(loaded)) { + sm2._wD(this._s.id + ': progress, ' + Math.floor(loaded * 100) + '% loaded'); + } + // + + } + + if (!isNaN(loaded)) { + + // TODO: prevent calls with duplicate values. + s._whileloading(loaded, total, s._get_html5_duration()); + if (loaded && total && loaded === total) { + // in case "onload" doesn't fire (eg. gecko 1.9.2) + html5_events.canplaythrough.call(this, e); + } + + } + + }), + + ratechange: html5_event(function() { + + sm2._wD(this._s.id + ': ratechange'); + + }), + + suspend: html5_event(function(e) { + + // download paused/stopped, may have finished (eg. onload) + var s = this._s; + + sm2._wD(this._s.id + ': suspend'); + html5_events.progress.call(this, e); + s._onsuspend(); + + }), + + stalled: html5_event(function() { + + sm2._wD(this._s.id + ': stalled'); + + }), + + timeupdate: html5_event(function() { + + this._s._onTimer(); + + }), + + waiting: html5_event(function() { + + var s = this._s; + + // see also: seeking + sm2._wD(this._s.id + ': waiting'); + + // playback faster than download rate, etc. + s._onbufferchange(1); + + }) + + }; + + html5OK = function(iO) { + + // playability test based on URL or MIME type + + var result; + + if (!iO || (!iO.type && !iO.url && !iO.serverURL)) { + + // nothing to check + result = false; + + } else if (iO.serverURL || (iO.type && preferFlashCheck(iO.type))) { + + // RTMP, or preferring flash + result = false; + + } else { + + // Use type, if specified. Pass data: URIs to HTML5. If HTML5-only mode, no other options, so just give 'er + result = ((iO.type ? html5CanPlay({ type: iO.type }) : html5CanPlay({ url: iO.url }) || sm2.html5Only || iO.url.match(/data:/i))); + + } + + return result; + + }; + + html5Unload = function(oAudio) { + + /** + * Internal method: Unload media, and cancel any current/pending network requests. + * Firefox can load an empty URL, which allegedly destroys the decoder and stops the download. + * https://developer.mozilla.org/En/Using_audio_and_video_in_Firefox#Stopping_the_download_of_media + * However, Firefox has been seen loading a relative URL from '' and thus requesting the hosting page on unload. + * Other UA behaviour is unclear, so everyone else gets an about:blank-style URL. + */ + + var url; + + if (oAudio) { + + // Firefox and Chrome accept short WAVe data: URIs. Chome dislikes audio/wav, but accepts audio/wav for data: MIME. + // Desktop Safari complains / fails on data: URI, so it gets about:blank. + url = (isSafari ? emptyURL : (sm2.html5.canPlayType('audio/wav') ? emptyWAV : emptyURL)); + + oAudio.src = url; + + // reset some state, too + if (oAudio._called_unload !== _undefined) { + oAudio._called_load = false; + } + + } + + if (useGlobalHTML5Audio) { + + // ensure URL state is trashed, also + lastGlobalHTML5URL = null; + + } + + return url; + + }; + + html5CanPlay = function(o) { + + /** + * Try to find MIME, test and return truthiness + * o = { + * url: '/path/to/an.mp3', + * type: 'audio/mp3' + * } + */ + + if (!sm2.useHTML5Audio || !sm2.hasHTML5) return false; + + var url = (o.url || null), + mime = (o.type || null), + aF = sm2.audioFormats, + result, + offset, + fileExt, + item; + + // account for known cases like audio/mp3 + + if (mime && sm2.html5[mime] !== _undefined) return (sm2.html5[mime] && !preferFlashCheck(mime)); + + if (!html5Ext) { + + html5Ext = []; + + for (item in aF) { + + if (aF.hasOwnProperty(item)) { + + html5Ext.push(item); + + if (aF[item].related) { + html5Ext = html5Ext.concat(aF[item].related); + } + + } + + } + + html5Ext = new RegExp('\\.(' + html5Ext.join('|') + ')(\\?.*)?$', 'i'); + + } + + // TODO: Strip URL queries, etc. + fileExt = (url ? url.toLowerCase().match(html5Ext) : null); + + if (!fileExt || !fileExt.length) { + + if (!mime) { + + result = false; + + } else { + + // audio/mp3 -> mp3, result should be known + offset = mime.indexOf(';'); + + // strip "audio/X; codecs..." + fileExt = (offset !== -1 ? mime.substr(0, offset) : mime).substr(6); + + } + + } else { + + // match the raw extension name - "mp3", for example + fileExt = fileExt[1]; + + } + + if (fileExt && sm2.html5[fileExt] !== _undefined) { + + // result known + result = (sm2.html5[fileExt] && !preferFlashCheck(fileExt)); + + } else { + + mime = 'audio/' + fileExt; + result = sm2.html5.canPlayType({ type: mime }); + + sm2.html5[fileExt] = result; + + // sm2._wD('canPlayType, found result: ' + result); + result = (result && sm2.html5[mime] && !preferFlashCheck(mime)); + } + + return result; + + }; + + testHTML5 = function() { + + /** + * Internal: Iterates over audioFormats, determining support eg. audio/mp3, audio/mpeg and so on + * assigns results to html5[] and flash[]. + */ + + if (!sm2.useHTML5Audio || !sm2.hasHTML5) { + + // without HTML5, we need Flash. + sm2.html5.usingFlash = true; + needsFlash = true; + + return false; + + } + + // double-whammy: Opera 9.64 throws WRONG_ARGUMENTS_ERR if no parameter passed to Audio(), and Webkit + iOS happily tries to load "null" as a URL. :/ + var a = (Audio !== _undefined ? (isOpera && opera.version() < 10 ? new Audio(null) : new Audio()) : null), + item, lookup, support = {}, aF, i; + + function cp(m) { + + var canPlay, j, + result = false, + isOK = false; + + if (!a || typeof a.canPlayType !== 'function') return result; + + if (m instanceof Array) { + + // iterate through all mime types, return any successes + + for (i = 0, j = m.length; i < j; i++) { + + if (sm2.html5[m[i]] || a.canPlayType(m[i]).match(sm2.html5Test)) { + + isOK = true; + sm2.html5[m[i]] = true; + + // note flash support, too + sm2.flash[m[i]] = !!(m[i].match(flashMIME)); + + } + + } + + result = isOK; + + } else { + + canPlay = (a && typeof a.canPlayType === 'function' ? a.canPlayType(m) : false); + result = !!(canPlay && (canPlay.match(sm2.html5Test))); + + } + + return result; + + } + + // test all registered formats + codecs + + aF = sm2.audioFormats; + + for (item in aF) { + + if (aF.hasOwnProperty(item)) { + + lookup = 'audio/' + item; + + support[item] = cp(aF[item].type); + + // write back generic type too, eg. audio/mp3 + support[lookup] = support[item]; + + // assign flash + if (item.match(flashMIME)) { + + sm2.flash[item] = true; + sm2.flash[lookup] = true; + + } else { + + sm2.flash[item] = false; + sm2.flash[lookup] = false; + + } + + // assign result to related formats, too + + if (aF[item] && aF[item].related) { + + for (i = aF[item].related.length - 1; i >= 0; i--) { + + // eg. audio/m4a + support['audio/' + aF[item].related[i]] = support[item]; + sm2.html5[aF[item].related[i]] = support[item]; + sm2.flash[aF[item].related[i]] = support[item]; + + } + + } + + } + + } + + support.canPlayType = (a ? cp : null); + sm2.html5 = mixin(sm2.html5, support); + + sm2.html5.usingFlash = featureCheck(); + needsFlash = sm2.html5.usingFlash; + + return true; + + }; + + strings = { + + // + notReady: 'Unavailable - wait until onready() has fired.', + notOK: 'Audio support is not available.', + domError: sm + 'exception caught while appending SWF to DOM.', + spcWmode: 'Removing wmode, preventing known SWF loading issue(s)', + swf404: smc + 'Verify that %s is a valid path.', + tryDebug: 'Try ' + sm + '.debugFlash = true for more security details (output goes to SWF.)', + checkSWF: 'See SWF output for more debug info.', + localFail: smc + 'Non-HTTP page (' + doc.location.protocol + ' URL?) Review Flash player security settings for this special case:\nhttp://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html\nMay need to add/allow path, eg. c:/sm2/ or /users/me/sm2/', + waitFocus: smc + 'Special case: Waiting for SWF to load with window focus...', + waitForever: smc + 'Waiting indefinitely for Flash (will recover if unblocked)...', + waitSWF: smc + 'Waiting for 100% SWF load...', + needFunction: smc + 'Function object expected for %s', + badID: 'Sound ID "%s" should be a string, starting with a non-numeric character', + currentObj: smc + '_debug(): Current sound objects', + waitOnload: smc + 'Waiting for window.onload()', + docLoaded: smc + 'Document already loaded', + onload: smc + 'initComplete(): calling soundManager.onload()', + onloadOK: sm + '.onload() complete', + didInit: smc + 'init(): Already called?', + secNote: 'Flash security note: Network/internet URLs will not load due to security restrictions. Access can be configured via Flash Player Global Security Settings Page: http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html', + badRemove: smc + 'Failed to remove Flash node.', + shutdown: sm + '.disable(): Shutting down', + queue: smc + 'Queueing %s handler', + smError: 'SMSound.load(): Exception: JS-Flash communication failed, or JS error.', + fbTimeout: 'No flash response, applying .' + swfCSS.swfTimedout + ' CSS...', + fbLoaded: 'Flash loaded', + fbHandler: smc + 'flashBlockHandler()', + manURL: 'SMSound.load(): Using manually-assigned URL', + onURL: sm + '.load(): current URL already assigned.', + badFV: sm + '.flashVersion must be 8 or 9. "%s" is invalid. Reverting to %s.', + as2loop: 'Note: Setting stream:false so looping can work (flash 8 limitation)', + noNSLoop: 'Note: Looping not implemented for MovieStar formats', + needfl9: 'Note: Switching to flash 9, required for MP4 formats.', + mfTimeout: 'Setting flashLoadTimeout = 0 (infinite) for off-screen, mobile flash case', + needFlash: smc + 'Fatal error: Flash is needed to play some required formats, but is not available.', + gotFocus: smc + 'Got window focus.', + policy: 'Enabling usePolicyFile for data access', + setup: sm + '.setup(): allowed parameters: %s', + setupError: sm + '.setup(): "%s" cannot be assigned with this method.', + setupUndef: sm + '.setup(): Could not find option "%s"', + setupLate: sm + '.setup(): url, flashVersion and html5Test property changes will not take effect until reboot().', + noURL: smc + 'Flash URL required. Call soundManager.setup({url:...}) to get started.', + sm2Loaded: 'SoundManager 2: Ready. ' + String.fromCharCode(10003), + reset: sm + '.reset(): Removing event callbacks', + mobileUA: 'Mobile UA detected, preferring HTML5 by default.', + globalHTML5: 'Using singleton HTML5 Audio() pattern for this device.', + ignoreMobile: 'Ignoring mobile restrictions for this device.' + // + + }; + + str = function() { + + // internal string replace helper. + // arguments: o [,items to replace] + // + + var args, + i, j, o, + sstr; + + // real array, please + args = slice.call(arguments); + + // first argument + o = args.shift(); + + sstr = (strings && strings[o] ? strings[o] : ''); + + if (sstr && args && args.length) { + for (i = 0, j = args.length; i < j; i++) { + sstr = sstr.replace('%s', args[i]); + } + } + + return sstr; + // + + }; + + loopFix = function(sOpt) { + + // flash 8 requires stream = false for looping to work + if (fV === 8 && sOpt.loops > 1 && sOpt.stream) { + _wDS('as2loop'); + sOpt.stream = false; + } + + return sOpt; + + }; + + policyFix = function(sOpt, sPre) { + + if (sOpt && !sOpt.usePolicyFile && (sOpt.onid3 || sOpt.usePeakData || sOpt.useWaveformData || sOpt.useEQData)) { + sm2._wD((sPre || '') + str('policy')); + sOpt.usePolicyFile = true; + } + + return sOpt; + + }; + + complain = function(sMsg) { + + // + if (hasConsole && console.warn !== _undefined) { + console.warn(sMsg); + } else { + sm2._wD(sMsg); + } + // + + }; + + doNothing = function() { + + return false; + + }; + + disableObject = function(o) { + + var oProp; + + for (oProp in o) { + if (o.hasOwnProperty(oProp) && typeof o[oProp] === 'function') { + o[oProp] = doNothing; + } + } + + oProp = null; + + }; + + failSafely = function(bNoDisable) { + + // general failure exception handler + + if (bNoDisable === _undefined) { + bNoDisable = false; + } + + if (disabled || bNoDisable) { + sm2.disable(bNoDisable); + } + + }; + + normalizeMovieURL = function(movieURL) { + + var urlParams = null, url; + + if (movieURL) { + + if (movieURL.match(/\.swf(\?.*)?$/i)) { + + urlParams = movieURL.substr(movieURL.toLowerCase().lastIndexOf('.swf?') + 4); + + // assume user knows what they're doing + if (urlParams) return movieURL; + + } else if (movieURL.lastIndexOf('/') !== movieURL.length - 1) { + + // append trailing slash, if needed + movieURL += '/'; + + } + + } + + url = (movieURL && movieURL.lastIndexOf('/') !== -1 ? movieURL.substr(0, movieURL.lastIndexOf('/') + 1) : './') + sm2.movieURL; + + if (sm2.noSWFCache) { + url += ('?ts=' + new Date().getTime()); + } + + return url; + + }; + + setVersionInfo = function() { + + // short-hand for internal use + + fV = parseInt(sm2.flashVersion, 10); + + if (fV !== 8 && fV !== 9) { + sm2._wD(str('badFV', fV, defaultFlashVersion)); + sm2.flashVersion = fV = defaultFlashVersion; + } + + // debug flash movie, if applicable + + var isDebug = (sm2.debugMode || sm2.debugFlash ? '_debug.swf' : '.swf'); + + if (sm2.useHTML5Audio && !sm2.html5Only && sm2.audioFormats.mp4.required && fV < 9) { + sm2._wD(str('needfl9')); + sm2.flashVersion = fV = 9; + } + + sm2.version = sm2.versionNumber + (sm2.html5Only ? ' (HTML5-only mode)' : (fV === 9 ? ' (AS3/Flash 9)' : ' (AS2/Flash 8)')); + + // set up default options + if (fV > 8) { + + // +flash 9 base options + sm2.defaultOptions = mixin(sm2.defaultOptions, sm2.flash9Options); + sm2.features.buffering = true; + + // +moviestar support + sm2.defaultOptions = mixin(sm2.defaultOptions, sm2.movieStarOptions); + sm2.filePatterns.flash9 = new RegExp('\\.(mp3|' + netStreamTypes.join('|') + ')(\\?.*)?$', 'i'); + sm2.features.movieStar = true; + + } else { + + sm2.features.movieStar = false; + + } + + // regExp for flash canPlay(), etc. + sm2.filePattern = sm2.filePatterns[(fV !== 8 ? 'flash9' : 'flash8')]; + + // if applicable, use _debug versions of SWFs + sm2.movieURL = (fV === 8 ? 'soundmanager2.swf' : 'soundmanager2_flash9.swf').replace('.swf', isDebug); + + sm2.features.peakData = sm2.features.waveformData = sm2.features.eqData = (fV > 8); + + }; + + setPolling = function(bPolling, bHighPerformance) { + + if (!flash) { + return; + } + + flash._setPolling(bPolling, bHighPerformance); + + }; + + initDebug = function() { + + // starts debug mode, creating output
    for UAs without console object + + // allow force of debug mode via URL + // + if (sm2.debugURLParam.test(wl)) { + sm2.setupOptions.debugMode = sm2.debugMode = true; + } + + if (id(sm2.debugID)) { + return; + } + + var oD, oDebug, oTarget, oToggle, tmp; + + if (sm2.debugMode && !id(sm2.debugID) && (!hasConsole || !sm2.useConsole || !sm2.consoleOnly)) { + + oD = doc.createElement('div'); + oD.id = sm2.debugID + '-toggle'; + + oToggle = { + position: 'fixed', + bottom: '0px', + right: '0px', + width: '1.2em', + height: '1.2em', + lineHeight: '1.2em', + margin: '2px', + textAlign: 'center', + border: '1px solid #999', + cursor: 'pointer', + background: '#fff', + color: '#333', + zIndex: 10001 + }; + + oD.appendChild(doc.createTextNode('-')); + oD.onclick = toggleDebug; + oD.title = 'Toggle SM2 debug console'; + + if (ua.match(/msie 6/i)) { + oD.style.position = 'absolute'; + oD.style.cursor = 'hand'; + } + + for (tmp in oToggle) { + if (oToggle.hasOwnProperty(tmp)) { + oD.style[tmp] = oToggle[tmp]; + } + } + + oDebug = doc.createElement('div'); + oDebug.id = sm2.debugID; + oDebug.style.display = (sm2.debugMode ? 'block' : 'none'); + + if (sm2.debugMode && !id(oD.id)) { + try { + oTarget = getDocument(); + oTarget.appendChild(oD); + } catch(e2) { + throw new Error(str('domError') + ' \n' + e2.toString()); + } + oTarget.appendChild(oDebug); + } + + } + + oTarget = null; + // + + }; + + idCheck = this.getSoundById; + + // + _wDS = function(o, errorLevel) { + + return (!o ? '' : sm2._wD(str(o), errorLevel)); + + }; + + toggleDebug = function() { + + var o = id(sm2.debugID), + oT = id(sm2.debugID + '-toggle'); + + if (!o) { + return; + } + + if (debugOpen) { + // minimize + oT.innerHTML = '+'; + o.style.display = 'none'; + } else { + oT.innerHTML = '-'; + o.style.display = 'block'; + } + + debugOpen = !debugOpen; + + }; + + debugTS = function(sEventType, bSuccess, sMessage) { + + // troubleshooter debug hooks + + if (window.sm2Debugger !== _undefined) { + try { + sm2Debugger.handleEvent(sEventType, bSuccess, sMessage); + } catch(e) { + // oh well + return false; + } + } + + return true; + + }; + // + + getSWFCSS = function() { + + var css = []; + + if (sm2.debugMode) { + css.push(swfCSS.sm2Debug); + } + + if (sm2.debugFlash) { + css.push(swfCSS.flashDebug); + } + + if (sm2.useHighPerformance) { + css.push(swfCSS.highPerf); + } + + return css.join(' '); + + }; + + flashBlockHandler = function() { + + // *possible* flash block situation. + + var name = str('fbHandler'), + p = sm2.getMoviePercent(), + css = swfCSS, + error = { + type: 'FLASHBLOCK' + }; + + if (sm2.html5Only) { + // no flash, or unused + return; + } + + if (!sm2.ok()) { + + if (needsFlash) { + // make the movie more visible, so user can fix + sm2.oMC.className = getSWFCSS() + ' ' + css.swfDefault + ' ' + (p === null ? css.swfTimedout : css.swfError); + sm2._wD(name + ': ' + str('fbTimeout') + (p ? ' (' + str('fbLoaded') + ')' : '')); + } + + sm2.didFlashBlock = true; + + // fire onready(), complain lightly + processOnEvents({ + type: 'ontimeout', + ignoreInit: true, + error: error + }); + + catchError(error); + + } else { + + // SM2 loaded OK (or recovered) + + // + if (sm2.didFlashBlock) { + sm2._wD(name + ': Unblocked'); + } + // + + if (sm2.oMC) { + sm2.oMC.className = [getSWFCSS(), css.swfDefault, css.swfLoaded + (sm2.didFlashBlock ? ' ' + css.swfUnblocked : '')].join(' '); + } + + } + + }; + + addOnEvent = function(sType, oMethod, oScope) { + + if (on_queue[sType] === _undefined) { + on_queue[sType] = []; + } + + on_queue[sType].push({ + method: oMethod, + scope: (oScope || null), + fired: false + }); + + }; + + processOnEvents = function(oOptions) { + + // if unspecified, assume OK/error + + if (!oOptions) { + oOptions = { + type: (sm2.ok() ? 'onready' : 'ontimeout') + }; + } + + // not ready yet. + if (!didInit && oOptions && !oOptions.ignoreInit) return false; + + // invalid case + if (oOptions.type === 'ontimeout' && (sm2.ok() || (disabled && !oOptions.ignoreInit))) return false; + + var status = { + success: (oOptions && oOptions.ignoreInit ? sm2.ok() : !disabled) + }, + + // queue specified by type, or none + srcQueue = (oOptions && oOptions.type ? on_queue[oOptions.type] || [] : []), + + queue = [], i, j, + args = [status], + canRetry = (needsFlash && !sm2.ok()); + + if (oOptions.error) { + args[0].error = oOptions.error; + } + + for (i = 0, j = srcQueue.length; i < j; i++) { + if (srcQueue[i].fired !== true) { + queue.push(srcQueue[i]); + } + } + + if (queue.length) { + + // sm2._wD(sm + ': Firing ' + queue.length + ' ' + oOptions.type + '() item' + (queue.length === 1 ? '' : 's')); + for (i = 0, j = queue.length; i < j; i++) { + + if (queue[i].scope) { + queue[i].method.apply(queue[i].scope, args); + } else { + queue[i].method.apply(this, args); + } + + if (!canRetry) { + // useFlashBlock and SWF timeout case doesn't count here. + queue[i].fired = true; + + } + + } + + } + + return true; + + }; + + initUserOnload = function() { + + window.setTimeout(function() { + + if (sm2.useFlashBlock) { + flashBlockHandler(); + } + + processOnEvents(); + + // call user-defined "onload", scoped to window + + if (typeof sm2.onload === 'function') { + _wDS('onload', 1); + sm2.onload.apply(window); + _wDS('onloadOK', 1); + } + + if (sm2.waitForWindowLoad) { + event.add(window, 'load', initUserOnload); + } + + }, 1); + + }; + + detectFlash = function() { + + /** + * Hat tip: Flash Detect library (BSD, (C) 2007) by Carl "DocYes" S. Yestrau + * http://featureblend.com/javascript-flash-detection-library.html / http://featureblend.com/license.txt + */ + + // this work has already been done. + if (hasFlash !== _undefined) return hasFlash; + + var hasPlugin = false, n = navigator, obj, type, types, AX = window.ActiveXObject; + + // MS Edge 14 throws an "Unspecified Error" because n.plugins is inaccessible due to permissions + var nP; + + try { + nP = n.plugins; + } catch(e) { + nP = undefined; + } + + if (nP && nP.length) { + + type = 'application/x-shockwave-flash'; + types = n.mimeTypes; + + if (types && types[type] && types[type].enabledPlugin && types[type].enabledPlugin.description) { + hasPlugin = true; + } + + } else if (AX !== _undefined && !ua.match(/MSAppHost/i)) { + + // Windows 8 Store Apps (MSAppHost) are weird (compatibility?) and won't complain here, but will barf if Flash/ActiveX object is appended to the DOM. + try { + obj = new AX('ShockwaveFlash.ShockwaveFlash'); + } catch(e) { + // oh well + obj = null; + } + + hasPlugin = (!!obj); + + // cleanup, because it is ActiveX after all + obj = null; + + } + + hasFlash = hasPlugin; + + return hasPlugin; + + }; + + featureCheck = function() { + + var flashNeeded, + item, + formats = sm2.audioFormats, + // iPhone <= 3.1 has broken HTML5 audio(), but firmware 3.2 (original iPad) + iOS4 works. + isSpecial = (is_iDevice && !!(ua.match(/os (1|2|3_0|3_1)\s/i))); + + if (isSpecial) { + + // has Audio(), but is broken; let it load links directly. + sm2.hasHTML5 = false; + + // ignore flash case, however + sm2.html5Only = true; + + // hide the SWF, if present + if (sm2.oMC) { + sm2.oMC.style.display = 'none'; + } + + } else if (sm2.useHTML5Audio) { + + if (!sm2.html5 || !sm2.html5.canPlayType) { + sm2._wD('SoundManager: No HTML5 Audio() support detected.'); + sm2.hasHTML5 = false; + } + + // + if (isBadSafari) { + sm2._wD(smc + 'Note: Buggy HTML5 Audio in Safari on this OS X release, see https://bugs.webkit.org/show_bug.cgi?id=32159 - ' + (!hasFlash ? ' would use flash fallback for MP3/MP4, but none detected.' : 'will use flash fallback for MP3/MP4, if available'), 1); + } + // + + } + + if (sm2.useHTML5Audio && sm2.hasHTML5) { + + // sort out whether flash is optional, required or can be ignored. + + // innocent until proven guilty. + canIgnoreFlash = true; + + for (item in formats) { + + if (formats.hasOwnProperty(item)) { + + if (formats[item].required) { + + if (!sm2.html5.canPlayType(formats[item].type)) { + + // 100% HTML5 mode is not possible. + canIgnoreFlash = false; + flashNeeded = true; + + } else if (sm2.preferFlash && (sm2.flash[item] || sm2.flash[formats[item].type])) { + + // flash may be required, or preferred for this format. + flashNeeded = true; + + } + + } + + } + + } + + } + + // sanity check... + if (sm2.ignoreFlash) { + flashNeeded = false; + canIgnoreFlash = true; + } + + sm2.html5Only = (sm2.hasHTML5 && sm2.useHTML5Audio && !flashNeeded); + + return (!sm2.html5Only); + + }; + + parseURL = function(url) { + + /** + * Internal: Finds and returns the first playable URL (or failing that, the first URL.) + * @param {string or array} url A single URL string, OR, an array of URL strings or {url:'/path/to/resource', type:'audio/mp3'} objects. + */ + + var i, j, urlResult = 0, result; + + if (url instanceof Array) { + + // find the first good one + for (i = 0, j = url.length; i < j; i++) { + + if (url[i] instanceof Object) { + + // MIME check + if (sm2.canPlayMIME(url[i].type)) { + urlResult = i; + break; + } + + } else if (sm2.canPlayURL(url[i])) { + + // URL string check + urlResult = i; + break; + + } + + } + + // normalize to string + if (url[urlResult].url) { + url[urlResult] = url[urlResult].url; + } + + result = url[urlResult]; + + } else { + + // single URL case + result = url; + + } + + return result; + + }; + + + startTimer = function(oSound) { + + /** + * attach a timer to this sound, and start an interval if needed + */ + + if (!oSound._hasTimer) { + + oSound._hasTimer = true; + + if (!mobileHTML5 && sm2.html5PollingInterval) { + + if (h5IntervalTimer === null && h5TimerCount === 0) { + + h5IntervalTimer = setInterval(timerExecute, sm2.html5PollingInterval); + + } + + h5TimerCount++; + + } + + } + + }; + + stopTimer = function(oSound) { + + /** + * detach a timer + */ + + if (oSound._hasTimer) { + + oSound._hasTimer = false; + + if (!mobileHTML5 && sm2.html5PollingInterval) { + + // interval will stop itself at next execution. + + h5TimerCount--; + + } + + } + + }; + + timerExecute = function() { + + /** + * manual polling for HTML5 progress events, ie., whileplaying() + * (can achieve greater precision than conservative default HTML5 interval) + */ + + var i; + + if (h5IntervalTimer !== null && !h5TimerCount) { + + // no active timers, stop polling interval. + + clearInterval(h5IntervalTimer); + + h5IntervalTimer = null; + + return; + + } + + // check all HTML5 sounds with timers + + for (i = sm2.soundIDs.length - 1; i >= 0; i--) { + + if (sm2.sounds[sm2.soundIDs[i]].isHTML5 && sm2.sounds[sm2.soundIDs[i]]._hasTimer) { + sm2.sounds[sm2.soundIDs[i]]._onTimer(); + } + + } + + }; + + catchError = function(options) { + + options = (options !== _undefined ? options : {}); + + if (typeof sm2.onerror === 'function') { + sm2.onerror.apply(window, [{ + type: (options.type !== _undefined ? options.type : null) + }]); + } + + if (options.fatal !== _undefined && options.fatal) { + sm2.disable(); + } + + }; + + badSafariFix = function() { + + // special case: "bad" Safari (OS X 10.3 - 10.7) must fall back to flash for MP3/MP4 + if (!isBadSafari || !detectFlash()) { + // doesn't apply + return; + } + + var aF = sm2.audioFormats, i, item; + + for (item in aF) { + + if (aF.hasOwnProperty(item)) { + + if (item === 'mp3' || item === 'mp4') { + + sm2._wD(sm + ': Using flash fallback for ' + item + ' format'); + sm2.html5[item] = false; + + // assign result to related formats, too + if (aF[item] && aF[item].related) { + for (i = aF[item].related.length - 1; i >= 0; i--) { + sm2.html5[aF[item].related[i]] = false; + } + } + + } + + } + + } + + }; + + /** + * Pseudo-private flash/ExternalInterface methods + * ---------------------------------------------- + */ + + this._setSandboxType = function(sandboxType) { + + // + // Security sandbox according to Flash plugin + var sb = sm2.sandbox; + + sb.type = sandboxType; + sb.description = sb.types[(sb.types[sandboxType] !== _undefined ? sandboxType : 'unknown')]; + + if (sb.type === 'localWithFile') { + + sb.noRemote = true; + sb.noLocal = false; + _wDS('secNote', 2); + + } else if (sb.type === 'localWithNetwork') { + + sb.noRemote = false; + sb.noLocal = true; + + } else if (sb.type === 'localTrusted') { + + sb.noRemote = false; + sb.noLocal = false; + + } + // + + }; + + this._externalInterfaceOK = function(swfVersion) { + + // flash callback confirming flash loaded, EI working etc. + // swfVersion: SWF build string + + if (sm2.swfLoaded) { + return; + } + + var e; + + debugTS('swf', true); + debugTS('flashtojs', true); + sm2.swfLoaded = true; + tryInitOnFocus = false; + + if (isBadSafari) { + badSafariFix(); + } + + // complain if JS + SWF build/version strings don't match, excluding +DEV builds + // + if (!swfVersion || swfVersion.replace(/\+dev/i, '') !== sm2.versionNumber.replace(/\+dev/i, '')) { + + e = sm + ': Fatal: JavaScript file build "' + sm2.versionNumber + '" does not match Flash SWF build "' + swfVersion + '" at ' + sm2.url + '. Ensure both are up-to-date.'; + + // escape flash -> JS stack so this error fires in window. + setTimeout(function() { + throw new Error(e); + }, 0); + + // exit, init will fail with timeout + return; + + } + // + + // IE needs a larger timeout + setTimeout(init, isIE ? 100 : 1); + + }; + + /** + * Private initialization helpers + * ------------------------------ + */ + + createMovie = function(movieID, movieURL) { + + // ignore if already connected + if (didAppend && appendSuccess) return false; + + function initMsg() { + + // + + var options = [], + title, + msg = [], + delimiter = ' + '; + + title = 'SoundManager ' + sm2.version + (!sm2.html5Only && sm2.useHTML5Audio ? (sm2.hasHTML5 ? ' + HTML5 audio' : ', no HTML5 audio support') : ''); + + if (!sm2.html5Only) { + + if (sm2.preferFlash) { + options.push('preferFlash'); + } + + if (sm2.useHighPerformance) { + options.push('useHighPerformance'); + } + + if (sm2.flashPollingInterval) { + options.push('flashPollingInterval (' + sm2.flashPollingInterval + 'ms)'); + } + + if (sm2.html5PollingInterval) { + options.push('html5PollingInterval (' + sm2.html5PollingInterval + 'ms)'); + } + + if (sm2.wmode) { + options.push('wmode (' + sm2.wmode + ')'); + } + + if (sm2.debugFlash) { + options.push('debugFlash'); + } + + if (sm2.useFlashBlock) { + options.push('flashBlock'); + } + + } else if (sm2.html5PollingInterval) { + options.push('html5PollingInterval (' + sm2.html5PollingInterval + 'ms)'); + } + + if (options.length) { + msg = msg.concat([options.join(delimiter)]); + } + + sm2._wD(title + (msg.length ? delimiter + msg.join(', ') : ''), 1); + + showSupport(); + + // + + } + + if (sm2.html5Only) { + + // 100% HTML5 mode + setVersionInfo(); + + initMsg(); + sm2.oMC = id(sm2.movieID); + init(); + + // prevent multiple init attempts + didAppend = true; + + appendSuccess = true; + + return false; + + } + + // flash path + var remoteURL = (movieURL || sm2.url), + localURL = (sm2.altURL || remoteURL), + swfTitle = 'JS/Flash audio component (SoundManager 2)', + oTarget = getDocument(), + extraClass = getSWFCSS(), + isRTL = null, + html = doc.getElementsByTagName('html')[0], + oEmbed, oMovie, tmp, movieHTML, oEl, s, x, sClass; + + isRTL = (html && html.dir && html.dir.match(/rtl/i)); + movieID = (movieID === _undefined ? sm2.id : movieID); + + function param(name, value) { + return ''; + } + + // safety check for legacy (change to Flash 9 URL) + setVersionInfo(); + sm2.url = normalizeMovieURL(overHTTP ? remoteURL : localURL); + movieURL = sm2.url; + + sm2.wmode = (!sm2.wmode && sm2.useHighPerformance ? 'transparent' : sm2.wmode); + + if (sm2.wmode !== null && (ua.match(/msie 8/i) || (!isIE && !sm2.useHighPerformance)) && navigator.platform.match(/win32|win64/i)) { + /** + * extra-special case: movie doesn't load until scrolled into view when using wmode = anything but 'window' here + * does not apply when using high performance (position:fixed means on-screen), OR infinite flash load timeout + * wmode breaks IE 8 on Vista + Win7 too in some cases, as of January 2011 (?) + */ + messages.push(strings.spcWmode); + sm2.wmode = null; + } + + oEmbed = { + name: movieID, + id: movieID, + src: movieURL, + quality: 'high', + allowScriptAccess: sm2.allowScriptAccess, + bgcolor: sm2.bgColor, + pluginspage: http + 'www.macromedia.com/go/getflashplayer', + title: swfTitle, + type: 'application/x-shockwave-flash', + wmode: sm2.wmode, + // http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html + hasPriority: 'true' + }; + + if (sm2.debugFlash) { + oEmbed.FlashVars = 'debug=1'; + } + + if (!sm2.wmode) { + // don't write empty attribute + delete oEmbed.wmode; + } + + if (isIE) { + + // IE is "special". + oMovie = doc.createElement('div'); + movieHTML = [ + '', + param('movie', movieURL), + param('AllowScriptAccess', sm2.allowScriptAccess), + param('quality', oEmbed.quality), + (sm2.wmode ? param('wmode', sm2.wmode) : ''), + param('bgcolor', sm2.bgColor), + param('hasPriority', 'true'), + (sm2.debugFlash ? param('FlashVars', oEmbed.FlashVars) : ''), + '' + ].join(''); + + } else { + + oMovie = doc.createElement('embed'); + for (tmp in oEmbed) { + if (oEmbed.hasOwnProperty(tmp)) { + oMovie.setAttribute(tmp, oEmbed[tmp]); + } + } + + } + + initDebug(); + extraClass = getSWFCSS(); + oTarget = getDocument(); + + if (oTarget) { + + sm2.oMC = (id(sm2.movieID) || doc.createElement('div')); + + if (!sm2.oMC.id) { + + sm2.oMC.id = sm2.movieID; + sm2.oMC.className = swfCSS.swfDefault + ' ' + extraClass; + s = null; + oEl = null; + + if (!sm2.useFlashBlock) { + if (sm2.useHighPerformance) { + // on-screen at all times + s = { + position: 'fixed', + width: '8px', + height: '8px', + // >= 6px for flash to run fast, >= 8px to start up under Firefox/win32 in some cases. odd? yes. + bottom: '0px', + left: '0px', + overflow: 'hidden' + }; + } else { + // hide off-screen, lower priority + s = { + position: 'absolute', + width: '6px', + height: '6px', + top: '-9999px', + left: '-9999px' + }; + if (isRTL) { + s.left = Math.abs(parseInt(s.left, 10)) + 'px'; + } + } + } + + if (isWebkit) { + // soundcloud-reported render/crash fix, safari 5 + sm2.oMC.style.zIndex = 10000; + } + + if (!sm2.debugFlash) { + for (x in s) { + if (s.hasOwnProperty(x)) { + sm2.oMC.style[x] = s[x]; + } + } + } + + try { + + if (!isIE) { + sm2.oMC.appendChild(oMovie); + } + + oTarget.appendChild(sm2.oMC); + + if (isIE) { + oEl = sm2.oMC.appendChild(doc.createElement('div')); + oEl.className = swfCSS.swfBox; + oEl.innerHTML = movieHTML; + } + + appendSuccess = true; + + } catch(e) { + + throw new Error(str('domError') + ' \n' + e.toString()); + + } + + } else { + + // SM2 container is already in the document (eg. flashblock use case) + sClass = sm2.oMC.className; + sm2.oMC.className = (sClass ? sClass + ' ' : swfCSS.swfDefault) + (extraClass ? ' ' + extraClass : ''); + sm2.oMC.appendChild(oMovie); + + if (isIE) { + oEl = sm2.oMC.appendChild(doc.createElement('div')); + oEl.className = swfCSS.swfBox; + oEl.innerHTML = movieHTML; + } + + appendSuccess = true; + + } + + } + + didAppend = true; + + initMsg(); + + // sm2._wD(sm + ': Trying to load ' + movieURL + (!overHTTP && sm2.altURL ? ' (alternate URL)' : ''), 1); + + return true; + + }; + + initMovie = function() { + + if (sm2.html5Only) { + createMovie(); + return false; + } + + // attempt to get, or create, movie (may already exist) + if (flash) return false; + + if (!sm2.url) { + + /** + * Something isn't right - we've reached init, but the soundManager url property has not been set. + * User has not called setup({url: ...}), or has not set soundManager.url (legacy use case) directly before init time. + * Notify and exit. If user calls setup() with a url: property, init will be restarted as in the deferred loading case. + */ + + _wDS('noURL'); + return false; + + } + + // inline markup case + flash = sm2.getMovie(sm2.id); + + if (!flash) { + + if (!oRemoved) { + + // try to create + createMovie(sm2.id, sm2.url); + + } else { + + // try to re-append removed movie after reboot() + if (!isIE) { + sm2.oMC.appendChild(oRemoved); + } else { + sm2.oMC.innerHTML = oRemovedHTML; + } + + oRemoved = null; + didAppend = true; + + } + + flash = sm2.getMovie(sm2.id); + + } + + if (typeof sm2.oninitmovie === 'function') { + setTimeout(sm2.oninitmovie, 1); + } + + // + flushMessages(); + // + + return true; + + }; + + delayWaitForEI = function() { + + setTimeout(waitForEI, 1000); + + }; + + rebootIntoHTML5 = function() { + + // special case: try for a reboot with preferFlash: false, if 100% HTML5 mode is possible and useFlashBlock is not enabled. + + window.setTimeout(function() { + + complain(smc + 'useFlashBlock is false, 100% HTML5 mode is possible. Rebooting with preferFlash: false...'); + + sm2.setup({ + preferFlash: false + }).reboot(); + + // if for some reason you want to detect this case, use an ontimeout() callback and look for html5Only and didFlashBlock == true. + sm2.didFlashBlock = true; + + sm2.beginDelayedInit(); + + }, 1); + + }; + + waitForEI = function() { + + var p, + loadIncomplete = false; + + if (!sm2.url) { + // No SWF url to load (noURL case) - exit for now. Will be retried when url is set. + return; + } + + if (waitingForEI) { + return; + } + + waitingForEI = true; + event.remove(window, 'load', delayWaitForEI); + + if (hasFlash && tryInitOnFocus && !isFocused) { + // Safari won't load flash in background tabs, only when focused. + _wDS('waitFocus'); + return; + } + + if (!didInit) { + p = sm2.getMoviePercent(); + if (p > 0 && p < 100) { + loadIncomplete = true; + } + } + + setTimeout(function() { + + p = sm2.getMoviePercent(); + + if (loadIncomplete) { + // special case: if movie *partially* loaded, retry until it's 100% before assuming failure. + waitingForEI = false; + sm2._wD(str('waitSWF')); + window.setTimeout(delayWaitForEI, 1); + return; + } + + // + if (!didInit) { + + sm2._wD(sm + ': No Flash response within expected time. Likely causes: ' + (p === 0 ? 'SWF load failed, ' : '') + 'Flash blocked or JS-Flash security error.' + (sm2.debugFlash ? ' ' + str('checkSWF') : ''), 2); + + if (!overHTTP && p) { + + _wDS('localFail', 2); + + if (!sm2.debugFlash) { + _wDS('tryDebug', 2); + } + + } + + if (p === 0) { + + // if 0 (not null), probably a 404. + sm2._wD(str('swf404', sm2.url), 1); + + } + + debugTS('flashtojs', false, ': Timed out' + (overHTTP ? ' (Check flash security or flash blockers)' : ' (No plugin/missing SWF?)')); + + } + // + + // give up / time-out, depending + + if (!didInit && okToDisable) { + + if (p === null) { + + // SWF failed to report load progress. Possibly blocked. + + if (sm2.useFlashBlock || sm2.flashLoadTimeout === 0) { + + if (sm2.useFlashBlock) { + + flashBlockHandler(); + + } + + _wDS('waitForever'); + + } else if (!sm2.useFlashBlock && canIgnoreFlash) { + + // no custom flash block handling, but SWF has timed out. Will recover if user unblocks / allows SWF load. + rebootIntoHTML5(); + + } else { + + _wDS('waitForever'); + + // fire any regular registered ontimeout() listeners. + processOnEvents({ + type: 'ontimeout', + ignoreInit: true, + error: { + type: 'INIT_FLASHBLOCK' + } + }); + + } + + } else if (sm2.flashLoadTimeout === 0) { + + // SWF loaded? Shouldn't be a blocking issue, then. + + _wDS('waitForever'); + + } else if (!sm2.useFlashBlock && canIgnoreFlash) { + + rebootIntoHTML5(); + + } else { + + failSafely(true); + + } + + } + + }, sm2.flashLoadTimeout); + + }; + + handleFocus = function() { + + function cleanup() { + event.remove(window, 'focus', handleFocus); + } + + if (isFocused || !tryInitOnFocus) { + // already focused, or not special Safari background tab case + cleanup(); + return true; + } + + okToDisable = true; + isFocused = true; + _wDS('gotFocus'); + + // allow init to restart + waitingForEI = false; + + // kick off ExternalInterface timeout, now that the SWF has started + delayWaitForEI(); + + cleanup(); + return true; + + }; + + flushMessages = function() { + + // + + // SM2 pre-init debug messages + if (messages.length) { + sm2._wD('SoundManager 2: ' + messages.join(' '), 1); + messages = []; + } + + // + + }; + + showSupport = function() { + + // + + flushMessages(); + + var item, tests = []; + + if (sm2.useHTML5Audio && sm2.hasHTML5) { + for (item in sm2.audioFormats) { + if (sm2.audioFormats.hasOwnProperty(item)) { + tests.push(item + ' = ' + sm2.html5[item] + (!sm2.html5[item] && needsFlash && sm2.flash[item] ? ' (using flash)' : (sm2.preferFlash && sm2.flash[item] && needsFlash ? ' (preferring flash)' : (!sm2.html5[item] ? ' (' + (sm2.audioFormats[item].required ? 'required, ' : '') + 'and no flash support)' : '')))); + } + } + sm2._wD('SoundManager 2 HTML5 support: ' + tests.join(', '), 1); + } + + // + + }; + + initComplete = function(bNoDisable) { + + if (didInit) return false; + + if (sm2.html5Only) { + // all good. + _wDS('sm2Loaded', 1); + didInit = true; + initUserOnload(); + debugTS('onload', true); + return true; + } + + var wasTimeout = (sm2.useFlashBlock && sm2.flashLoadTimeout && !sm2.getMoviePercent()), + result = true, + error; + + if (!wasTimeout) { + didInit = true; + } + + error = { + type: (!hasFlash && needsFlash ? 'NO_FLASH' : 'INIT_TIMEOUT') + }; + + sm2._wD('SoundManager 2 ' + (disabled ? 'failed to load' : 'loaded') + ' (' + (disabled ? 'Flash security/load error' : 'OK') + ') ' + String.fromCharCode(disabled ? 10006 : 10003), disabled ? 2 : 1); + + if (disabled || bNoDisable) { + + if (sm2.useFlashBlock && sm2.oMC) { + sm2.oMC.className = getSWFCSS() + ' ' + (sm2.getMoviePercent() === null ? swfCSS.swfTimedout : swfCSS.swfError); + } + + processOnEvents({ + type: 'ontimeout', + error: error, + ignoreInit: true + }); + + debugTS('onload', false); + catchError(error); + + result = false; + + } else { + + debugTS('onload', true); + + } + + if (!disabled) { + + if (sm2.waitForWindowLoad && !windowLoaded) { + + _wDS('waitOnload'); + event.add(window, 'load', initUserOnload); + + } else { + + // + if (sm2.waitForWindowLoad && windowLoaded) { + _wDS('docLoaded'); + } + // + + initUserOnload(); + + } + + } + + return result; + + }; + + /** + * apply top-level setupOptions object as local properties, eg., this.setupOptions.flashVersion -> this.flashVersion (soundManager.flashVersion) + * this maintains backward compatibility, and allows properties to be defined separately for use by soundManager.setup(). + */ + + setProperties = function() { + + var i, + o = sm2.setupOptions; + + for (i in o) { + + if (o.hasOwnProperty(i)) { + + // assign local property if not already defined + + if (sm2[i] === _undefined) { + + sm2[i] = o[i]; + + } else if (sm2[i] !== o[i]) { + + // legacy support: write manually-assigned property (eg., soundManager.url) back to setupOptions to keep things in sync + sm2.setupOptions[i] = sm2[i]; + + } + + } + + } + + }; + + + init = function() { + + // called after onload() + + if (didInit) { + _wDS('didInit'); + return false; + } + + function cleanup() { + event.remove(window, 'load', sm2.beginDelayedInit); + } + + if (sm2.html5Only) { + + if (!didInit) { + // we don't need no steenking flash! + cleanup(); + sm2.enabled = true; + initComplete(); + } + + return true; + + } + + // flash path + initMovie(); + + try { + + // attempt to talk to Flash + flash._externalInterfaceTest(false); + + /** + * Apply user-specified polling interval, OR, if "high performance" set, faster vs. default polling + * (determines frequency of whileloading/whileplaying callbacks, effectively driving UI framerates) + */ + setPolling(true, (sm2.flashPollingInterval || (sm2.useHighPerformance ? 10 : 50))); + + if (!sm2.debugMode) { + // stop the SWF from making debug output calls to JS + flash._disableDebug(); + } + + sm2.enabled = true; + debugTS('jstoflash', true); + + if (!sm2.html5Only) { + // prevent browser from showing cached page state (or rather, restoring "suspended" page state) via back button, because flash may be dead + // http://www.webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/ + event.add(window, 'unload', doNothing); + } + + } catch(e) { + + sm2._wD('js/flash exception: ' + e.toString()); + + debugTS('jstoflash', false); + + catchError({ + type: 'JS_TO_FLASH_EXCEPTION', + fatal: true + }); + + // don't disable, for reboot() + failSafely(true); + + initComplete(); + + return false; + + } + + initComplete(); + + // disconnect events + cleanup(); + + return true; + + }; + + domContentLoaded = function() { + + if (didDCLoaded) return false; + + didDCLoaded = true; + + // assign top-level soundManager properties eg. soundManager.url + setProperties(); + + initDebug(); + + if (!hasFlash && sm2.hasHTML5) { + + sm2._wD('SoundManager 2: No Flash detected' + (!sm2.useHTML5Audio ? ', enabling HTML5.' : '. Trying HTML5-only mode.'), 1); + + sm2.setup({ + useHTML5Audio: true, + // make sure we aren't preferring flash, either + // TODO: preferFlash should not matter if flash is not installed. Currently, stuff breaks without the below tweak. + preferFlash: false + }); + + } + + testHTML5(); + + if (!hasFlash && needsFlash) { + + messages.push(strings.needFlash); + + // TODO: Fatal here vs. timeout approach, etc. + // hack: fail sooner. + sm2.setup({ + flashLoadTimeout: 1 + }); + + } + + if (doc.removeEventListener) { + doc.removeEventListener('DOMContentLoaded', domContentLoaded, false); + } + + initMovie(); + + return true; + + }; + + domContentLoadedIE = function() { + + if (doc.readyState === 'complete') { + domContentLoaded(); + doc.detachEvent('onreadystatechange', domContentLoadedIE); + } + + return true; + + }; + + winOnLoad = function() { + + // catch edge case of initComplete() firing after window.load() + windowLoaded = true; + + // catch case where DOMContentLoaded has been sent, but we're still in doc.readyState = 'interactive' + domContentLoaded(); + + event.remove(window, 'load', winOnLoad); + + }; + + // sniff up-front + detectFlash(); + + // focus and window load, init (primarily flash-driven) + event.add(window, 'focus', handleFocus); + event.add(window, 'load', delayWaitForEI); + event.add(window, 'load', winOnLoad); + + if (doc.addEventListener) { + + doc.addEventListener('DOMContentLoaded', domContentLoaded, false); + + } else if (doc.attachEvent) { + + doc.attachEvent('onreadystatechange', domContentLoadedIE); + + } else { + + // no add/attachevent support - safe to assume no JS -> Flash either + debugTS('onload', false); + catchError({ + type: 'NO_DOM2_EVENTS', + fatal: true + }); + + } + +} // SoundManager() + +// SM2_DEFER details: http://www.schillmania.com/projects/soundmanager2/doc/getstarted/#lazy-loading + +if (window.SM2_DEFER === _undefined || !SM2_DEFER) { + soundManager = new SoundManager(); +} + +/** + * SoundManager public interfaces + * ------------------------------ + */ + +if (typeof module === 'object' && module && typeof module.exports === 'object') { + + /** + * commonJS module + */ + + module.exports.SoundManager = SoundManager; + module.exports.soundManager = soundManager; + +} else if (typeof define === 'function' && define.amd) { + + /** + * AMD - requireJS + * basic usage: + * require(["/path/to/soundmanager2.js"], function(SoundManager) { + * SoundManager.getInstance().setup({ + * url: '/swf/', + * onready: function() { ... } + * }) + * }); + * + * SM2_DEFER usage: + * window.SM2_DEFER = true; + * require(["/path/to/soundmanager2.js"], function(SoundManager) { + * SoundManager.getInstance(function() { + * var soundManager = new SoundManager.constructor(); + * soundManager.setup({ + * url: '/swf/', + * ... + * }); + * ... + * soundManager.beginDelayedInit(); + * return soundManager; + * }) + * }); + */ + + define(function() { + /** + * Retrieve the global instance of SoundManager. + * If a global instance does not exist it can be created using a callback. + * + * @param {Function} smBuilder Optional: Callback used to create a new SoundManager instance + * @return {SoundManager} The global SoundManager instance + */ + function getInstance(smBuilder) { + if (!window.soundManager && smBuilder instanceof Function) { + var instance = smBuilder(SoundManager); + if (instance instanceof SoundManager) { + window.soundManager = instance; + } + } + return window.soundManager; + } + return { + constructor: SoundManager, + getInstance: getInstance + }; + }); + +} + +// standard browser case + +// constructor +window.SoundManager = SoundManager; + +/** + * note: SM2 requires a window global due to Flash, which makes calls to window.soundManager. + * Flash may not always be needed, but this is not known until async init and SM2 may even "reboot" into Flash mode. + */ + +// public API, flash callbacks etc. +window.soundManager = soundManager; + +}(window)); diff --git a/cps/static/js/logviewer.js b/cps/static/js/logviewer.js new file mode 100644 index 00000000..fd5b79e9 --- /dev/null +++ b/cps/static/js/logviewer.js @@ -0,0 +1,74 @@ +/* This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web) + * Copyright (C) 2018 OzzieIsaacs + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +// Upon loading load the logfile for the first option (event log) +$(function() { + init(0); +}); + +// After change the radio option load the corresponding log file +$("#log_group input").on("change", function() { + var element = $("#log_group input[type='radio']:checked").val(); + init(element); +}); + + +// Handle reloading of the log file and display the content +function init(logType) { + var d = document.getElementById("renderer"); + d.innerHTML = "loading ..."; + + /*var r = new XMLHttpRequest(); + r.open("GET", "/ajax/log/" + logType, true); + r.responseType = "text"; + r.onload = function() { + var text; + text = (r.responseText).split("\n"); + $("#renderer").text(""); + console.log(text.length); + for (var i = 0; i < text.length; i++) { + $("#renderer").append( "
    " + _sanitize(text[i]) + "
    " ); + } + }; + r.send();*/ + $.ajax({ + url: "/ajax/log/" + logType, + datatype: "text", + cache: false + }) + .done( function(data) { + var text; + $("#renderer").text(""); + text = (data).split("\n"); + // console.log(text.length); + for (var i = 0; i < text.length; i++) { + $("#renderer").append( "
    " + _sanitize(text[i]) + "
    " ); + } + }); +} + + +function _sanitize(t) { + t = t + .replace(/&/g, "&") + .replace(/ /g, " ") + .replace(//g, ">"); + + return t; +} + diff --git a/cps/static/js/main.js b/cps/static/js/main.js index 9a51df5b..6a59c6b7 100644 --- a/cps/static/js/main.js +++ b/cps/static/js/main.js @@ -29,6 +29,23 @@ $(document).on("change", "input[type=\"checkbox\"][data-control]", function () { }); }); + +// Generic control/related handler to show/hide fields based on a select' value +$(document).on("change", "select[data-control]", function() { + var $this = $(this); + var name = $this.data("control"); + var showOrHide = parseInt($this.val()); + // var showOrHideLast = $("#" + name + " option:last").val() + for (var i = 0; i < $(this)[0].length; i++) { + if (parseInt($(this)[0][i].value) === showOrHide) { + $("[data-related=\"" + name + "-" + i + "\"]").show(); + } else { + $("[data-related=\"" + name + "-" + i + "\"]").hide(); + } + } +}); + + $(function() { var updateTimerID; var updateText; @@ -77,6 +94,13 @@ $(function() { layoutMode : "fitRows" }); + $(".grid").isotope({ + // options + itemSelector : ".grid-item", + layoutMode : "fitColumns" + }); + + var $loadMore = $(".load-more .row").infiniteScroll({ debug: false, // selector for the paged navigation (it will be hidden) @@ -181,6 +205,7 @@ $(function() { // Init all data control handlers to default $("input[data-control]").trigger("change"); + $("select[data-control]").trigger("change"); $("#bookDetailsModal") .on("show.bs.modal", function(e) { @@ -205,12 +230,12 @@ $(function() { $(window).resize(function() { $(".discover .row").isotope("layout"); }); - + $(".author-expand").click(function() { $(this).parent().find("a.author-name").slice($(this).data("authors-max")).toggle(); $(this).parent().find("span.author-hidden-divider").toggle(); $(this).html() === $(this).data("collapse-caption") ? $(this).html("(...)") : $(this).html($(this).data("collapse-caption")); $(".discover .row").isotope("layout"); }); - + }); diff --git a/cps/static/js/table.js b/cps/static/js/table.js index 420478dc..47daa6da 100644 --- a/cps/static/js/table.js +++ b/cps/static/js/table.js @@ -15,18 +15,20 @@ * along with this program. If not, see . */ +/* exported TableActions */ + $(function() { $("#domain_submit").click(function(event) { event.preventDefault(); $("#domain_add").ajaxForm(); $(this).closest("form").submit(); - $.ajax({ + $.ajax ({ method:"get", url: window.location.pathname + "/../../ajax/domainlist", async: true, timeout: 900, - success:function(data){ + success:function(data) { $("#domain-table").bootstrapTable("load", data); } }); diff --git a/cps/static/js/uploadprogress.js b/cps/static/js/uploadprogress.js index 8f70d2d0..be987437 100644 --- a/cps/static/js/uploadprogress.js +++ b/cps/static/js/uploadprogress.js @@ -57,7 +57,7 @@ this.$modalBar = this.$modal.find(".progress-bar"); // Translate texts - this.$modalTitle.text(this.options.modalTitle) + this.$modalTitle.text(this.options.modalTitle); this.$modalFooter.children("button").text(this.options.modalFooter); this.$modal.on("hidden.bs.modal", $.proxy(this.reset, this)); @@ -113,8 +113,7 @@ if (contentType.indexOf("application/json") !== -1) { var response = $.parseJSON(xhr.responseText); url = response.location; - } - else{ + } else { url = this.options.redirect_url; } window.location.href = url; @@ -136,12 +135,10 @@ if (contentType.indexOf("text/plain") !== -1) { responseText = "
    " + responseText + "
    "; document.write(responseText); - } - else { + } else { this.$modalBar.text(responseText); } - } - else { + } else { this.$modalBar.text(this.options.modalTitleFailed); } }, diff --git a/cps/subproc_wrapper.py b/cps/subproc_wrapper.py new file mode 100644 index 00000000..088cb3d5 --- /dev/null +++ b/cps/subproc_wrapper.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# This file is part of the Calibre-Web (https://github.com/janeczku/calibre-web) +# Copyright (C) 2018-2019 OzzieIsaacs +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + +from __future__ import division, print_function, unicode_literals +import sys +import os +import subprocess + + +def process_open(command, quotes=(), env=None, sout=subprocess.PIPE, serr=subprocess.PIPE): + # Linux py2.7 encode as list without quotes no empty element for parameters + # linux py3.x no encode and as list without quotes no empty element for parameters + # windows py2.7 encode as string with quotes empty element for parameters is okay + # windows py 3.x no encode and as string with quotes empty element for parameters is okay + # separate handling for windows and linux + if os.name == 'nt': + for key, element in enumerate(command): + if key in quotes: + command[key] = '"' + element + '"' + exc_command = " ".join(command) + if sys.version_info < (3, 0): + exc_command = exc_command.encode(sys.getfilesystemencoding()) + else: + if sys.version_info < (3, 0): + exc_command = [x.encode(sys.getfilesystemencoding()) for x in command] + else: + exc_command = [x for x in command] + + return subprocess.Popen(exc_command, shell=False, stdout=sout, stderr=serr, universal_newlines=True, env=env) + + +def process_wait(command, serr=subprocess.PIPE): + '''Run command, wait for process to terminate, and return an iterator over lines of its output.''' + p = process_open(command, serr=serr) + p.wait() + for l in p.stdout.readlines(): + if isinstance(l, bytes): + l = l.decode('utf-8') + yield l diff --git a/cps/templates/admin.html b/cps/templates/admin.html index a1c6adaa..17b84f34 100644 --- a/cps/templates/admin.html +++ b/cps/templates/admin.html @@ -12,25 +12,27 @@ {{_('DLS')}} {{_('Admin')}} {{_('Download')}} + {{_('View Ebooks')}} {{_('Upload')}} {{_('Edit')}} - {% for user in content %} + {% for user in allUser %} {% if not user.role_anonymous() or config.config_anonbrowse %} -
    {{user.nickname}} + {{user.nickname}} {{user.email}} {{user.kindle_mail}} {{user.downloads.count()}} {% if user.role_admin() %}{% else %}{% endif %} {% if user.role_download() %}{% else %}{% endif %} + {% if user.role_viewer() %}{% else %}{% endif %} {% if user.role_upload() %}{% else %}{% endif %} {% if user.role_edit() %}{% else %}{% endif %} {% endif %} {% endfor %} - +
    @@ -53,7 +55,7 @@ {{email.mail_from}} - + @@ -67,7 +69,7 @@
    {{_('Log level')}}
    -
    {{config.get_Log_Level()}}
    +
    {{config.get_log_level()}}
    {{_('Port')}}
    @@ -96,14 +98,15 @@
    {% if config.config_remote_login %}{% else %}{% endif %}
    - - + +

    {{_('Administration')}}

    +
    {{_('Reconnect to Calibre DB')}}
    {{_('Restart Calibre-Web')}}
    {{_('Stop Calibre-Web')}}
    diff --git a/cps/templates/author.html b/cps/templates/author.html index 672ea5ce..27a16fbc 100644 --- a/cps/templates/author.html +++ b/cps/templates/author.html @@ -22,21 +22,29 @@ {% if author is not none %}

    {{_("In Library")}}

    {% endif %} +
    {% if entries[0] %} {% for entry in entries %}
    - +

    {{entry.title|shortentitle}}

    @@ -45,7 +53,7 @@ {% if not loop.first %} & {% endif %} - {{author.name.replace('|',',')|shortentitle(30)}} + {{author.name.replace('|',',')|shortentitle(30)}} {% if loop.last %} (...) {% endif %} @@ -53,7 +61,12 @@ {% if not loop.first %} & {% endif %} - {{author.name.replace('|',',')|shortentitle(30)}} + {{author.name.replace('|',',')|shortentitle(30)}} + {% endif %} + {% endfor %} + {% for format in entry.data %} + {% if format.format|lower == 'mp3' %} + {% endif %} {% endfor %}

    diff --git a/cps/templates/book_edit.html b/cps/templates/book_edit.html index 90eb20c0..9305e204 100644 --- a/cps/templates/book_edit.html +++ b/cps/templates/book_edit.html @@ -5,11 +5,7 @@
    - {% if book.has_cover %} - {{ book.title }} - {% else %} - {{ book.title }} - {% endif %} + {{ book.title }}
    {% if g.user.role_delete_books() %}
    @@ -19,7 +15,7 @@

    {{_('Delete formats:')}}

    {% for file in book.data %} {% endfor %}
    @@ -28,7 +24,7 @@ {% if source_formats|length > 0 and conversion_formats|length > 0 %}

    {{_('Convert book format:')}}

    -
    +
    @@ -53,7 +49,7 @@ {% endif %}
    - +
    @@ -175,7 +171,7 @@
    {{_('Get metadata')}} - {{_('Back')}} + {{_('Back')}}
    @@ -196,7 +192,7 @@
    diff --git a/cps/templates/config_edit.html b/cps/templates/config_edit.html index cef969d3..de4063c9 100644 --- a/cps/templates/config_edit.html +++ b/cps/templates/config_edit.html @@ -17,10 +17,10 @@
    - +
    - +
    @@ -31,12 +31,12 @@
    {% else %} - {% if show_authenticate_google_drive and g.user.is_authenticated and content.config_use_google_drive %} + {% if show_authenticate_google_drive and g.user.is_authenticated and config.config_use_google_drive %} {% else %} - {% if show_authenticate_google_drive and g.user.is_authenticated and not content.config_use_google_drive %} + {% if show_authenticate_google_drive and g.user.is_authenticated and not config.config_use_google_drive %}
    {{_('Please hit submit to continue with setup')}}
    {% endif %} {% if not g.user.is_authenticated %} @@ -48,18 +48,18 @@
    - {% if content.config_google_drive_watch_changes_response %} + {% if config.config_google_drive_watch_changes_response %} {% else %} - Enable watch of metadata.db + Enable watch of metadata.db {% endif %} {% endif %} {% endif %} @@ -83,23 +83,23 @@
    - +
    - +
    - +
    - - + + + +
    @@ -119,15 +119,23 @@
    - + +
    +
    + + +
    +
    + +
    @@ -144,37 +152,134 @@
    - +
    - +
    - +
    - +
    - {% if goodreads %} + {% if feature_support['goodreads'] %}
    - + {{_('Obtain an API Key')}}
    - +
    - +
    + {% endif %} + {% if feature_support['ldap'] or feature_support['oauth'] %} +
    + + +
    + {% if feature_support['ldap'] %} +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    +
    + + +
    +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + {% endif %} + {% if feature_support['oauth'] %} +
    + +
    + + +
    +
    + + +
    +
    +
    + +
    + + +
    +
    + + +
    +
    + {% endif %} {% endif %}
    @@ -191,27 +296,27 @@
    -
    +
    -
    +
    -
    +
    - +
    - +
    {% if rarfile_support %}
    - +
    {% endif %}
    @@ -222,11 +327,11 @@
    - {% if not origin %} - {{_('Back')}} + {% if show_back_button %} + {{_('Back')}} {% endif %} - {% if success %} - {{_('Login')}} + {% if show_login_button %} + {{_('Login')}} {% endif %}
    diff --git a/cps/templates/config_view_edit.html b/cps/templates/config_view_edit.html index 83c20834..bc6defa4 100644 --- a/cps/templates/config_view_edit.html +++ b/cps/templates/config_view_edit.html @@ -17,48 +17,48 @@
    - +
    - +
    - +
    - +
    - +
    - +
    @@ -77,31 +77,35 @@
    - +
    - +
    - + + +
    +
    +
    - +
    - +
    - +
    - +
    @@ -118,65 +122,29 @@
    -
    - - -
    -
    - - -
    -
    - - -
    -
    - - -
    -
    - - -
    -
    - - -
    -
    - - -
    -
    - - -
    -
    - - -
    -
    - - -
    -
    - - -
    -
    - - -
    -
    - - -
    + {% for element in sidebar %} + {% if element['config_show'] %} +
    + + +
    + {% endif %} + {% endfor %} +
    + + +
    +
    + + +
    - {{_('Back')}} + {{_('Back')}}
    diff --git a/cps/templates/detail.html b/cps/templates/detail.html index 9d87e231..b76a8afa 100644 --- a/cps/templates/detail.html +++ b/cps/templates/detail.html @@ -4,11 +4,7 @@
    - {% if entry.has_cover %} - {{ entry.title }} - {% else %} - {{ entry.title }} - {% endif %} + {{ entry.title }}
    @@ -22,7 +18,7 @@ {{_('Download')}} : {% for format in entry.data %} - + {{format.format}} ({{ format.uncompressed_size|filesizeformat }}) {% endfor %} @@ -33,7 +29,7 @@ {% endif %} @@ -42,7 +38,7 @@ {% endif %} {% if g.user.kindle_mail and kindle_list %} {% if kindle_list.__len__() == 1 %} - {{kindle_list[0]['text']}} + {{kindle_list[0]['text']}} {% else %}
    {% endif %} {% endif %} - {% if reader_list %} + {% if reader_list and g.user.role_viewer() %}
    - {% endif %} + {% endif %} + {% if audioentries|length > 0 %} +
    + + + +
    + {% endif %}

    {{entry.title|shortentitle(40)}}

    {% for author in entry.authors %} - {{author.name.replace('|',',')}} + {{author.name.replace('|',',')}} {% if not loop.last %} & {% endif %} @@ -97,7 +114,7 @@ {% endif %} {% if entry.series|length > 0 %} -

    {{_('Book')}} {{entry.series_index}} {{_('of')}} {{entry.series[0].name}}

    +

    {{_('Book')}} {{entry.series_index}} {{_('of')}} {{entry.series[0].name}}

    {% endif %} {% if entry.languages.__len__() > 0 %} @@ -126,7 +143,7 @@ {% for tag in entry.tags %} - {{tag.name}} + {{tag.name}} {%endfor%}

    @@ -137,7 +154,7 @@ @@ -178,7 +195,7 @@

    -

    +