Repo cleaning

This commit is contained in:
cttynul
2019-04-23 14:34:44 +02:00
parent 8e7ee78a87
commit 824854bc7b
1251 changed files with 0 additions and 275995 deletions

View File

@@ -1,24 +0,0 @@
Esta versión de Alfa no necesita de ningún programa para instalar (tampoco kodi), es una versión independiente que solo necesita un navegador web y un equipo (en el cual será instalado) para ver el contenido desde cualquier dispositivo que cuente con un navegador web.
REQUISITOS:
Se necesita que esté instalado python 2.x desde aqui: https://www.python.org/
COMO INSTALAR LA VERSION MEDIASERVER:
-Descargar Alfa desde el reposotorio de Github: https://github.com/alfa-addon/addon (opcion Clone or download - Download zip
-El archivo descargado (addon-master.zip) abrirlo e ingresar a la carpeta: addon-master
-Descomprimir la carpeta plugin.video.alfa en alguna carpeta
-Luego descomprimir la carpeta mediaserver encima de la carpeta plugi.video.alfa reemplazando los archivos existentes.
COMO INICIAR LA VERSION MEDIASERVER
Para iniciar: python alfa.py
Y mostrará en pantalla la url a la cual se puede conectar desde cualquier dispositivo que contenga un navegador web.
Ejemplo:
http://192.168.1.10:8080

View File

@@ -1,169 +0,0 @@
# -*- coding: utf-8 -*-
import os
import random
import re
import threading
import time
import traceback
from platformcode import platformtools
from BaseHTTPServer import HTTPServer
from HTTPWebSocketsHandler import HTTPWebSocketsHandler
from platformcode import config, logger
from core import jsontools as json
class MyHTTPServer(HTTPServer):
daemon_threads = True
def process_request_thread(self, request, client_address):
try:
self.finish_request(request, client_address)
self.shutdown_request(request)
except:
self.handle_error(request, client_address)
self.shutdown_request(request)
def process_request(self, request, client_address):
ID = "%032x" % (random.getrandbits(128))
t = threading.Thread(target=self.process_request_thread,
args=(request, client_address), name=ID)
t.daemon = self.daemon_threads
t.start()
def handle_error(self, request, client_address):
import traceback
if not "socket.py" in traceback.format_exc():
logger.error(traceback.format_exc())
class Handler(HTTPWebSocketsHandler):
def log_message(self, format, *args):
# sys.stderr.write("%s - - [%s] %s\n" %(self.client_address[0], self.log_date_time_string(), format%args))
pass
def sendMessage(self, message):
self.send_message(message)
def do_GET_HTTP(self):
from platformcode import platformtools
from platformcode import controllers
# Control de accesos
Usuario = "user"
Password = "password"
ControlAcceso = False
import base64
# Comprueba la clave
if ControlAcceso and self.headers.getheader('Authorization') <> "Basic " + base64.b64encode(
Usuario + ":" + Password):
self.send_response(401)
self.send_header('WWW-Authenticate',
'Basic realm=\"' + config.get_localized_string(70264) + '\"')
self.send_header('Content-type', 'text/html; charset=utf-8')
self.end_headers()
self.wfile.write('¡Los datos introducidos no son correctos!')
return
data = re.compile('/data/([^/]+)/([^/]+)/([^/]+)', re.DOTALL).findall(self.path)
if data:
data = data[0]
if data[0] in platformtools.requests:
c = platformtools.requests[data[0]]
response = {"id": data[1], "result": data[2]}
print response
c.handler = self
c.set_data(response)
while data[0] in platformtools.requests and not self.wfile.closed:
time.sleep(1)
else:
if self.path == "": self.path = "/"
# Busca el controller para la url
controller = controllers.find_controller(self.path)
if controller:
try:
c = controller(self)
c.run(self.path)
except:
if not "socket.py" in traceback.format_exc():
logger.error(traceback.format_exc())
finally:
c.__del__()
del c
return
def on_ws_message(self, message):
try:
if message:
json_message = json.load(message)
if "request" in json_message:
t = threading.Thread(target=run, args=[self.controller, json_message["request"].encode("utf8")], name=self.ID)
t.setDaemon(True)
t.start()
elif "data" in json_message:
if type(json_message["data"]["result"]) == unicode:
json_message["data"]["result"] = json_message["data"]["result"].encode("utf8")
self.controller.data = json_message["data"]
except:
logger.error(traceback.format_exc())
show_error_message(traceback.format_exc())
def on_ws_connected(self):
try:
self.ID = "%032x" % (random.getrandbits(128))
from platformcode.controllers.html import html
self.controller = html(self, self.ID)
self.server.fnc_info()
except:
logger.error(traceback.format_exc())
def on_ws_closed(self):
self.controller.__del__()
del self.controller
self.server.fnc_info()
def address_string(self):
# Disable reverse name lookups
return self.client_address[:2][0]
PORT = config.get_setting("server.port")
server = MyHTTPServer(('', int(PORT)), Handler)
def run(controller, path):
try:
controller.run(path)
except:
logger.error(traceback.format_exc())
show_error_message(traceback.format_exc())
def show_error_message(err_info):
from core import scrapertools
patron = 'File "' + os.path.join(config.get_runtime_path(), "channels", "").replace("\\", "\\\\") + '([^.]+)\.py"'
canal = scrapertools.find_single_match(err_info, patron)
if canal:
platformtools.dialog_ok(
"Se ha producido un error en el canal " + canal,
"Esto puede ser devido a varias razones: \n \
- El servidor no está disponible, o no esta respondiendo.\n \
- Cambios en el diseño de la web.\n \
- Etc...\n \
Comprueba el log para ver mas detalles del error.")
else:
platformtools.dialog_ok(
"Se ha producido un error en Alfa",
"Comprueba el log para ver mas detalles del error.")
def start(fnc_info):
server.fnc_info = fnc_info
threading.Thread(target=server.serve_forever).start()
def stop():
server.socket.close()
server.shutdown()

View File

@@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@@ -1 +0,0 @@
# -*- coding: utf-8 -*-

View File

@@ -1,98 +0,0 @@
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# Launcher
# ------------------------------------------------------------
import os
import sys
import threading
import time
from functools import wraps
# Requerido para el ejecutable en windows
import SimpleHTTPServer
sys.dont_write_bytecode = True
from platformcode import config
sys.path.append(os.path.join(config.get_runtime_path(), 'lib'))
from platformcode import platformtools, logger
import HTTPAndWSServer
http_port = config.get_setting("server.port")
myip = config.get_local_ip()
version = config.get_addon_version()
def thread_name_wrap(func):
@wraps(func)
def bar(*args, **kw):
if "name" not in kw:
kw['name'] = threading.current_thread().name
return func(*args, **kw)
return bar
threading.Thread.__init__ = thread_name_wrap(threading.Thread.__init__)
if sys.version_info < (2, 7, 11):
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
def show_info():
os.system('cls' if os.name == 'nt' else 'clear')
print ("--------------------------------------------------------------------")
print ("Alfa %s Iniciado" %version)
print ("La URL para acceder es http://%s:%s" % (myip, http_port))
print ("--------------------------------------------------------------------")
print ("Runtime Path : " + config.get_runtime_path())
print ("Data Path : " + config.get_data_path())
print ("Download Path : " + config.get_setting("downloadpath"))
print ("DownloadList Path : " + config.get_setting("downloadlistpath"))
print ("Bookmark Path : " + config.get_setting("bookmarkpath"))
print ("Videolibrary Path : " + config.get_setting("videolibrarypath"))
print ("--------------------------------------------------------------------")
controllers = platformtools.controllers
for a in controllers:
try:
print platformtools.controllers[a].controller.client_ip + " - (" + platformtools.controllers[
a].controller.name + ")"
except:
pass
def start():
logger.info("server init...")
config.verify_directories_created()
try:
HTTPAndWSServer.start(show_info)
# Da por levantado el servicio
logger.info("--------------------------------------------------------------------")
logger.info("Alfa %s Iniciado" %version)
logger.info("La URL para acceder es http://%s:%s" % (myip, http_port))
logger.info("--------------------------------------------------------------------")
logger.info("Runtime Path : " + config.get_runtime_path())
logger.info("Data Path : " + config.get_data_path())
logger.info("Download Path : " + config.get_setting("downloadpath"))
logger.info("DownloadList Path : " + config.get_setting("downloadlistpath"))
logger.info("Bookmark Path : " + config.get_setting("bookmarkpath"))
logger.info("VideoLibrary Path : " + config.get_setting("videolibrarypath"))
logger.info("--------------------------------------------------------------------")
show_info()
flag = True
while flag:
time.sleep(1)
except KeyboardInterrupt:
print 'Deteniendo el servidor HTTP...'
HTTPAndWSServer.stop()
print 'Alfa Detenido'
flag = False
# Inicia el programa
start()

View File

@@ -1,3 +0,0 @@
TempMode
Silent=1
setup=alfa.exe

View File

@@ -1,9 +0,0 @@
REM Genera los archivos para el ejecutable en windows de Alfa Mediaserver
REM Y tambien genera el zip para Mediaserver
REM Los 2 los genera en la raiz del disco
winrar a -r \Alfa-Mediaserver-.zip \plugin.video.alfa\
python setup.py py2exe -p channels,servers,lib,platformcode
xcopy lib dist\lib /y /s /i
xcopy platformcode dist\platformcode /y /s /i
xcopy resources dist\resources /y /s /i
winrar a -ep1 -r -iiconplatformcode\template\favicon.ico -sfx -zdatos.txt \Alfa-Mediaserver--win dist\

View File

@@ -1,229 +0,0 @@
'''
The MIT License (MIT)
Copyright (C) 2014, 2015 Seven Watt <info@sevenwatt.com>
<http://www.sevenwatt.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'''
# HTTPWebSocketHandler from SevenW: https://github.com/SevenW/httpwebsockethandler
from SimpleHTTPServer import SimpleHTTPRequestHandler
import struct
from base64 import b64encode
from hashlib import sha1
from mimetools import Message
from StringIO import StringIO
import errno, socket #for socket exceptions
import threading
class WebSocketError(Exception):
pass
class HTTPWebSocketsHandler(SimpleHTTPRequestHandler):
_ws_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
_opcode_continu = 0x0
_opcode_text = 0x1
_opcode_binary = 0x2
_opcode_close = 0x8
_opcode_ping = 0x9
_opcode_pong = 0xa
mutex = threading.Lock()
def on_ws_message(self, message):
"""Override this handler to process incoming websocket messages."""
pass
def on_ws_connected(self):
"""Override this handler."""
pass
def on_ws_closed(self):
"""Override this handler."""
pass
def do_GET_HTTP(self):
"""Override this handler."""
SimpleHTTPRequestHandler.do_GET(self)
pass
def send_message(self, message):
self._send_message(self._opcode_text, message)
def setup(self):
SimpleHTTPRequestHandler.setup(self)
self.connected = False
# def finish(self):
# #needed when wfile is used, or when self.close_connection is not used
# #
# #catch errors in SimpleHTTPRequestHandler.finish() after socket disappeared
# #due to loss of network connection
# try:
# SimpleHTTPRequestHandler.finish(self)
# except (socket.error, TypeError) as err:
# self.log_message("finish(): Exception: in SimpleHTTPRequestHandler.finish(): %s" % str(err.args))
# def handle(self):
# #needed when wfile is used, or when self.close_connection is not used
# #
# #catch errors in SimpleHTTPRequestHandler.handle() after socket disappeared
# #due to loss of network connection
# try:
# SimpleHTTPRequestHandler.handle(self)
# except (socket.error, TypeError) as err:
# self.log_message("handle(): Exception: in SimpleHTTPRequestHandler.handle(): %s" % str(err.args))
def checkAuthentication(self):
auth = self.headers.get('Authorization')
if auth != "Basic %s" % self.server.auth:
self.send_response(401)
self.send_header("WWW-Authenticate", 'Basic realm="Plugwise"')
self.end_headers();
return False
return True
def do_GET(self):
# if self.server.auth and not self.checkAuthentication():
# return
if self.headers.get("Upgrade", None) == "websocket":
self._handshake()
#This handler is in websocket mode now.
#do_GET only returns after client close or socket error.
self._read_messages()
else:
self.do_GET_HTTP()
def _read_messages(self):
while self.connected == True:
try:
self._read_next_message()
except (socket.error, WebSocketError), e:
#websocket content error, time-out or disconnect.
self.log_message("RCV: Close connection: Socket Error %s" % str(e.args))
self._ws_close()
except Exception as err:
#unexpected error in websocket connection.
self.log_error("RCV: Exception: in _read_messages: %s" % str(err.args))
self._ws_close()
def _read_next_message(self):
#self.rfile.read(n) is blocking.
#it returns however immediately when the socket is closed.
try:
self.opcode = ord(self.rfile.read(1)) & 0x0F
length = ord(self.rfile.read(1)) & 0x7F
if length == 126:
length = struct.unpack(">H", self.rfile.read(2))[0]
elif length == 127:
length = struct.unpack(">Q", self.rfile.read(8))[0]
masks = [ord(byte) for byte in self.rfile.read(4)]
decoded = ""
for char in self.rfile.read(length):
decoded += chr(ord(char) ^ masks[len(decoded) % 4])
self._on_message(decoded)
except (struct.error, TypeError) as e:
#catch exceptions from ord() and struct.unpack()
if self.connected:
raise WebSocketError("Websocket read aborted while listening")
else:
#the socket was closed while waiting for input
self.log_error("RCV: _read_next_message aborted after closed connection")
pass
def _send_message(self, opcode, message):
try:
#use of self.wfile.write gives socket exception after socket is closed. Avoid.
self.request.send(chr(0x80 + opcode))
length = len(message)
if length <= 125:
self.request.send(chr(length))
elif length >= 126 and length <= 65535:
self.request.send(chr(126))
self.request.send(struct.pack(">H", length))
else:
self.request.send(chr(127))
self.request.send(struct.pack(">Q", length))
if length > 0:
self.request.send(message)
except socket.error, e:
#websocket content error, time-out or disconnect.
self.log_message("SND: Close connection: Socket Error %s" % str(e.args))
self._ws_close()
except Exception as err:
#unexpected error in websocket connection.
self.log_error("SND: Exception: in _send_message: %s" % str(err.args))
self._ws_close()
def _handshake(self):
headers=self.headers
if headers.get("Upgrade", None) != "websocket":
return
key = headers['Sec-WebSocket-Key']
digest = b64encode(sha1(key + self._ws_GUID).hexdigest().decode('hex'))
self.send_response(101, 'Switching Protocols')
self.send_header('Upgrade', 'websocket')
self.send_header('Connection', 'Upgrade')
self.send_header('Sec-WebSocket-Accept', str(digest))
self.end_headers()
self.connected = True
#self.close_connection = 0
self.on_ws_connected()
def _ws_close(self):
#avoid closing a single socket two time for send and receive.
self.mutex.acquire()
try:
if self.connected:
self.connected = False
#Terminate BaseHTTPRequestHandler.handle() loop:
self.close_connection = 1
#send close and ignore exceptions. An error may already have occurred.
try:
self._send_close()
except:
pass
self.on_ws_closed()
else:
self.log_message("_ws_close websocket in closed state. Ignore.")
pass
finally:
self.mutex.release()
def _on_message(self, message):
#self.log_message("_on_message: opcode: %02X msg: %s" % (self.opcode, message))
# close
if self.opcode == self._opcode_close:
self.connected = False
#Terminate BaseHTTPRequestHandler.handle() loop:
self.close_connection = 1
try:
self._send_close()
except:
pass
self.on_ws_closed()
# ping
elif self.opcode == self._opcode_ping:
_send_message(self._opcode_pong, message)
# pong
elif self.opcode == self._opcode_pong:
pass
# data
elif (self.opcode == self._opcode_continu or
self.opcode == self._opcode_text or
self.opcode == self._opcode_binary):
self.on_ws_message(message)
def _send_close(self):
#Dedicated _send_close allows for catch all exception handling
msg = bytearray()
msg.append(0x80 + self._opcode_close)
msg.append(0x00)
self.request.send(msg)

View File

@@ -1,11 +0,0 @@
# -*- coding: utf-8 -*-
# librería que simula xbmc para evitar errores en módulos que lo usen en mediaserver
# y no tener que poner excepciones en el código del addon
def getInfoLabel(parm):
if parm == 'Container.PluginName': return 'plugin.video.alfa'
elif parm == 'Container.FolderName': return 'Alfa'
return ''

View File

@@ -1,12 +0,0 @@
# -*- coding: utf-8 -*-
import os
import sys
# Appends the main plugin dir to the PYTHONPATH if an internal package cannot be imported.
# Examples: In Plex Media Server all modules are under "Code.*" package, and in Enigma2 under "Plugins.Extensions.*"
try:
# from core import logger
import core
except:
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))

View File

@@ -1,424 +0,0 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# Parámetros de configuración (mediaserver)
# ------------------------------------------------------------
import os
import re
import sys
PLATFORM_NAME = "mediaserver"
PLUGIN_NAME = "alfa"
settings_dic = {}
adult_setting = {}
def get_addon_version(linea_inicio=0, total_lineas=2, with_fix=False):
'''
Devuelve el número de de versión del addon, obtenido desde el archivo addon.xml
'''
path = os.path.join(get_runtime_path(), "addon.xml")
f = open(path, "rb")
data = []
for x, line in enumerate(f):
if x < linea_inicio: continue
if len(data) == total_lineas: break
data.append(line)
f.close()
data1 = "".join(data)
# <addon id="plugin.video.alfa" name="Alfa" version="2.5.21" provider-name="Alfa Addon">
aux = re.findall('<addon id="plugin.video.alfa" name="Alfa" version="([^"]+)"', data1, re.MULTILINE | re.DOTALL)
version = "???"
if len(aux) > 0:
version = aux[0]
return version
def get_platform(full_version=False):
# full_version solo es util en xbmc/kodi
ret = {
'num_version': 1.0,
'name_version': PLATFORM_NAME,
'video_db': "",
'plaform': PLATFORM_NAME
}
if full_version:
return ret
else:
return PLATFORM_NAME
def is_xbmc():
return False
def get_videolibrary_support():
return True
def get_system_platform():
""" fonction: pour recuperer la platform que xbmc tourne """
platform = "unknown"
if sys.platform == "linux" or sys.platform == "linux2":
platform = "linux"
elif sys.platform == "darwin":
platform = "osx"
elif sys.platform == "win32":
platform = "windows"
return platform
def open_settings():
options = []
from xml.dom import minidom
settings = open(menufilepath, 'rb').read()
xmldoc = minidom.parseString(settings)
for category in xmldoc.getElementsByTagName("category"):
for setting in category.getElementsByTagName("setting"):
options.append(dict(setting.attributes.items() + [(u"category", category.getAttribute("label")),
(u"value", get_setting(setting.getAttribute("id")))]))
from platformcode import platformtools
global adult_setting
adult_password = get_setting('adult_password')
if not adult_password:
adult_password = set_setting('adult_password', '0000')
adult_mode = get_setting('adult_mode')
adult_request_password = get_setting('adult_request_password')
platformtools.open_settings(options)
# Hemos accedido a la seccion de Canales para adultos
if get_setting('adult_aux_intro_password'):
# La contraseña de acceso es correcta
if get_setting('adult_aux_intro_password') == adult_password:
# Cambio de contraseña
if get_setting('adult_aux_new_password1'):
if get_setting('adult_aux_new_password1') == get_setting('adult_aux_new_password2'):
set_setting('adult_password', get_setting('adult_aux_new_password1'))
else:
platformtools.dialog_ok("Canales para adultos",
"Los campos 'Nueva contraseña' y 'Confirmar nueva contraseña' no coinciden."
, "Entre de nuevo en 'Preferencias' para cambiar la contraseña")
else:
platformtools.dialog_ok("Canales para adultos", "La contraseña no es correcta.",
"Los cambios realizados en esta sección no se guardaran.")
# Deshacer cambios
set_setting("adult_mode", adult_mode)
set_setting("adult_request_password", adult_request_password)
# Borramos settings auxiliares
set_setting('adult_aux_intro_password', '')
set_setting('adult_aux_new_password1', '')
set_setting('adult_aux_new_password2', '')
def get_setting(name, channel="", server="", default=None):
"""
Retorna el valor de configuracion del parametro solicitado.
Devuelve el valor del parametro 'name' en la configuracion global, en la configuracion propia del canal 'channel'
o en la del servidor 'server'.
Los parametros channel y server no deben usarse simultaneamente. Si se especifica el nombre del canal se devolvera
el resultado de llamar a channeltools.get_channel_setting(name, channel, default). Si se especifica el nombre del
servidor se devolvera el resultado de llamar a servertools.get_channel_setting(name, server, default). Si no se
especifica ninguno de los anteriores se devolvera el valor del parametro en la configuracion global si existe o
el valor default en caso contrario.
@param name: nombre del parametro
@type name: str
@param channel: nombre del canal
@type channel: str
@param server: nombre del servidor
@type server: str
@param default: valor devuelto en caso de que no exista el parametro name
@type default: any
@return: El valor del parametro 'name'
@rtype: any
"""
# Specific channel setting
if channel:
# logger.info("config.get_setting reading channel setting '"+name+"' from channel json")
from core import channeltools
value = channeltools.get_channel_setting(name, channel, default)
# logger.info("config.get_setting -> '"+repr(value)+"'")
return value
elif server:
# logger.info("config.get_setting reading server setting '"+name+"' from server json")
from core import servertools
value = servertools.get_server_setting(name, server, default)
# logger.info("config.get_setting -> '"+repr(value)+"'")
return value
# Global setting
else:
# logger.info("config.get_setting reading main setting '"+name+"'")
global settings_dic
value = settings_dic.get(name, default)
if value == default:
return value
# logger.info("config.get_setting -> '"+value+"'")
# hack para devolver el tipo correspondiente
if value == "true":
return True
elif value == "false":
return False
else:
# special case return as str
if name in ["adult_password", "adult_aux_intro_password", "adult_aux_new_password1",
"adult_aux_new_password2"]:
return value
else:
try:
value = int(value)
except ValueError:
pass
return value
def set_setting(name, value, channel="", server=""):
"""
Fija el valor de configuracion del parametro indicado.
Establece 'value' como el valor del parametro 'name' en la configuracion global o en la configuracion propia del
canal 'channel'.
Devuelve el valor cambiado o None si la asignacion no se ha podido completar.
Si se especifica el nombre del canal busca en la ruta \addon_data\plugin.video.alfa\settings_channels el
archivo channel_data.json y establece el parametro 'name' al valor indicado por 'value'. Si el archivo
channel_data.json no existe busca en la carpeta channels el archivo channel.xml y crea un archivo channel_data.json
antes de modificar el parametro 'name'.
Si el parametro 'name' no existe lo añade, con su valor, al archivo correspondiente.
Parametros:
name -- nombre del parametro
value -- valor del parametro
channel [opcional] -- nombre del canal
Retorna:
'value' en caso de que se haya podido fijar el valor y None en caso contrario
"""
if channel:
from core import channeltools
return channeltools.set_channel_setting(name, value, channel)
elif server:
from core import servertools
return servertools.set_server_setting(name, value, server)
else:
global settings_dic
if isinstance(value, bool):
if value:
value = "true"
else:
value = "false"
elif isinstance(value, (int, long)):
value = str(value)
settings_dic[name] = value
from xml.dom import minidom
# Crea un Nuevo XML vacio
new_settings = minidom.getDOMImplementation().createDocument(None, "settings", None)
new_settings_root = new_settings.documentElement
for key in settings_dic:
nodo = new_settings.createElement("setting")
nodo.setAttribute("value", settings_dic[key])
nodo.setAttribute("id", key)
new_settings_root.appendChild(nodo)
fichero = open(configfilepath, "w")
fichero.write(new_settings.toprettyxml(encoding='utf-8'))
fichero.close()
return value
def get_localized_string(code):
translationsfile = open(TRANSLATION_FILE_PATH, "r")
translations = translationsfile.read()
translationsfile.close()
cadenas = re.findall('msgctxt\s*"#%s"\nmsgid\s*"(.*?)"\nmsgstr\s*"(.*?)"' % code, translations)
if len(cadenas) > 0:
dev = cadenas[0][1]
if not dev:
dev = cadenas[0][0]
else:
dev = "%d" % code
try:
dev = dev.encode("utf-8")
except:
pass
return dev
def get_localized_category(categ):
categories = {'movie': get_localized_string(30122), 'tvshow': get_localized_string(30123),
'anime': get_localized_string(30124), 'documentary': get_localized_string(30125),
'vos': get_localized_string(30136), 'adult': get_localized_string(30126),
'direct': get_localized_string(30137), 'torrent': get_localized_string(70015)}
return categories[categ] if categ in categories else categ
def get_videolibrary_path():
value = get_setting("videolibrarypath")
if value == "":
verify_directories_created()
value = get_setting("videolibrarypath")
return value
def get_temp_file(filename):
import tempfile
return os.path.join(tempfile.gettempdir(), filename)
def get_runtime_path():
return os.getcwd()
def get_data_path():
dev = os.path.join(os.path.expanduser("~"), ".alfa")
# Crea el directorio si no existe
if not os.path.exists(dev):
os.makedirs(dev)
return dev
def get_cookie_data():
import os
ficherocookies = os.path.join(get_data_path(), 'cookies.dat')
cookiedatafile = open(ficherocookies, 'r')
cookiedata = cookiedatafile.read()
cookiedatafile.close()
return cookiedata
# Test if all the required directories are created
def verify_directories_created():
from platformcode import logger
from core import filetools
config_paths = [["videolibrarypath", "library"],
["downloadpath", "downloads"],
["downloadlistpath", "downloads/list"],
["bookmarkpath", "favorites"],
["settings_path", "settings_channels"]]
for path, default in config_paths:
saved_path = get_setting(path)
if not saved_path:
saved_path = filetools.join(get_data_path(), *default.split("/"))
set_setting(path, saved_path)
if not filetools.exists(saved_path):
logger.debug("Creating %s: %s" % (path, saved_path))
filetools.mkdir(saved_path)
config_paths = [["folder_movies", "CINE"],
["folder_tvshows", "SERIES"]]
for path, default in config_paths:
saved_path = get_setting(path)
if not saved_path:
saved_path = default
set_setting(path, saved_path)
content_path = filetools.join(get_videolibrary_path(), saved_path)
if not filetools.exists(content_path):
logger.debug("Creating %s: %s" % (path, content_path))
# si se crea el directorio
filetools.mkdir(content_path)
def get_local_ip():
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 53)) # connecting to a UDP address doesn't send packets
myip = s.getsockname()[0]
return myip
def load_settings():
global settings_dic
defaults = {}
from xml.etree import ElementTree
# Lee el archivo XML (si existe)
if os.path.exists(configfilepath):
settings = open(configfilepath, 'rb').read()
root = ElementTree.fromstring(settings)
for target in root.findall("setting"):
settings_dic[target.get("id")] = target.get("value")
defaultsettings = open(menufilepath, 'rb').read()
root = ElementTree.fromstring(defaultsettings)
for category in root.findall("category"):
for target in category.findall("setting"):
if target.get("id"):
defaults[target.get("id")] = target.get("default")
for key in defaults:
if key not in settings_dic:
settings_dic[key] = defaults[key]
set_settings(settings_dic)
def set_settings(JsonRespuesta):
for Ajuste in JsonRespuesta:
settings_dic[Ajuste] = JsonRespuesta[Ajuste].encode("utf8")
from xml.dom import minidom
# Crea un Nuevo XML vacio
new_settings = minidom.getDOMImplementation().createDocument(None, "settings", None)
new_settings_root = new_settings.documentElement
for key in settings_dic:
nodo = new_settings.createElement("setting")
nodo.setAttribute("value", settings_dic[key])
nodo.setAttribute("id", key)
new_settings_root.appendChild(nodo)
fichero = open(configfilepath, "w")
fichero.write(new_settings.toprettyxml(encoding='utf-8'))
fichero.close()
# Fichero de configuración
menufilepath = os.path.join(get_runtime_path(), "resources", "settings.xml")
configfilepath = os.path.join(get_data_path(), "settings.xml")
if not os.path.exists(get_data_path()):
os.mkdir(get_data_path())
load_settings()
TRANSLATION_FILE_PATH = os.path.join(get_runtime_path(), "resources", "language", settings_dic["mediaserver_language"], "strings.po")
# modo adulto:
# sistema actual 0: Nunca, 1:Siempre, 2:Solo hasta que se reinicie sesión
# si es == 2 lo desactivamos.
if get_setting("adult_mode") == 2:
set_setting("adult_mode", 0)

View File

@@ -1,41 +0,0 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# Módulo para acciones en el cliente HTML
# ------------------------------------------------------------
import os
from inspect import isclass
from controller import Controller
from platformcode import config, logger
def load_controllers():
controllers = []
path = os.path.join(config.get_runtime_path(),"platformcode", "controllers")
for fname in os.listdir(path):
mod, ext = os.path.splitext(fname)
fname = os.path.join(path, fname)
if os.path.isfile(fname) and ext == '.py' and not mod.startswith('_'):
try:
exec "import " + mod + " as controller"
except:
import traceback
logger.error(traceback.format_exc())
for c in dir(controller):
cls = getattr(controller, c)
if not c.startswith('_') and isclass(cls) and issubclass(cls, Controller) and Controller != cls:
controllers.append(cls)
return controllers
controllers = load_controllers()
def find_controller(url):
result = []
for c in controllers:
if c().match(url):
return c

View File

@@ -1,129 +0,0 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# Mediaserver Base controller
# ------------------------------------------------------------
import threading
from platformcode import config, platformtools
class Controller(object):
pattern = ""
name = None
def __init__(self, handler=None, ID=None):
self.handler = handler
self.id = ID
if not self.id:
self.id = threading.current_thread().name
if self.handler:
self.platformtools = Platformtools()
self.host = "http://%s:%s" % (config.get_local_ip(), config.get_setting("server.port"))
def __setattr__(self, name, value):
super(Controller, self).__setattr__(name, value)
if name == "platformtools":
platformtools.controllers[self.id] = self.platformtools
def __del__(self):
from platformcode import platformtools
if self.id in platformtools.controllers:
del platformtools.controllers[self.id]
def run(self, path):
pass
def match(self, path):
if self.pattern.findall(path):
return True
else:
return False
class Platformtools(object):
def dialog_ok(self, heading, line1, line2="", line3=""):
pass
def dialog_notification(self, heading, message, icon=0, time=5000, sound=True):
pass
def dialog_yesno(self, heading, line1, line2="", line3="", nolabel="No", yeslabel="Si", autoclose=""):
return True
def dialog_select(self, heading, list):
pass
def dialog_progress(self, heading, line1, line2="", line3=""):
class Dialog(object):
def __init__(self, heading, line1, line2, line3, PObject):
self.PObject = PObject
self.closed = False
self.heading = heading
text = line1
if line2: text += "\n" + line2
if line3: text += "\n" + line3
def iscanceled(self):
return self.closed
def update(self, percent, line1, line2="", line3=""):
pass
def close(self):
self.closed = True
return Dialog(heading, line1, line2, line3, None)
def dialog_progress_bg(self, heading, message=""):
class Dialog(object):
def __init__(self, heading, message, PObject):
self.PObject = PObject
self.closed = False
self.heading = heading
def isFinished(self):
return not self.closed
def update(self, percent=0, heading="", message=""):
pass
def close(self):
self.closed = True
return Dialog(heading, message, None)
def dialog_input(self, default="", heading="", hidden=False):
return default
def dialog_numeric(self, type, heading, default=""):
return None
def itemlist_refresh(self):
pass
def itemlist_update(self, item):
pass
def render_items(self, itemlist, parentitem):
pass
def is_playing(self):
return False
def play_video(self, item):
pass
def show_channel_settings(self, list_controls=None, dict_values=None, caption="", callback=None, item=None,
custom_button=None, channelpath=None):
pass
def show_video_info(self, data, caption="Información del vídeo", callback=None, item=None):
pass
def show_recaptcha(self, key, url):
pass

View File

@@ -1,103 +0,0 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# Controlador para acceso a archivos locales
# ------------------------------------------------------------
import os
import re
import time
from controller import Controller
from platformcode import config, logger
class fileserver(Controller):
pattern = re.compile("^/(?:media/.*?)?(?:local/.*?)?$")
def run(self, path):
if path == "/":
f = open(os.path.join(config.get_runtime_path(), "platformcode", "template", "page.html"), "rb")
self.handler.send_response(200)
self.handler.send_header('Content-type', 'text/html')
self.handler.end_headers()
respuesta = f.read()
self.handler.wfile.write(respuesta)
f.close()
elif path.startswith("/local/"):
import base64
import urllib
Path = path.replace("/local/", "").split("/")[0]
Path = base64.b64decode(urllib.unquote_plus(Path))
Size = int(os.path.getsize(Path.decode("utf8")))
f = open(Path.decode("utf8"), "rb")
if not self.handler.headers.get("range") == None:
if "=" in str(self.handler.headers.get("range")) and "-" in str(self.handler.headers.get("range")):
Inicio = int(self.handler.headers.get("range").split("=")[1].split("-")[0])
if self.handler.headers.get("range").split("=")[1].split("-")[1] <> "":
Fin = int(self.handler.headers.get("range").split("=")[1].split("-")[1])
else:
Fin = Size - 1
else:
Inicio = 0
Fin = Size - 1
if not Fin > Inicio: Fin = Size - 1
if self.handler.headers.get("range") == None:
logger.info("-------------------------------------------------------")
logger.info("Solicitando archivo local: " + Path)
logger.info("-------------------------------------------------------")
self.handler.send_response(200)
self.handler.send_header("Content-Disposition", "attachment; filename=video.mp4")
self.handler.send_header('Accept-Ranges', 'bytes')
self.handler.send_header('Content-Length', str(Size))
self.handler.send_header("Connection", "close")
self.handler.end_headers()
while True:
time.sleep(0.2)
buffer = f.read(1024 * 250)
if not buffer:
break
self.handler.wfile.write(buffer)
self.handler.wfile.close()
f.close()
else:
logger.info("-------------------------------------------------------")
logger.info("Solicitando archivo local: " + Path)
logger.info("Rango: " + str(Inicio) + "-" + str(Fin) + "/" + str(Size))
logger.info("-------------------------------------------------------")
f.seek(Inicio)
self.handler.send_response(206)
self.handler.send_header("Content-Disposition", "attachment; filename=video.mp4")
self.handler.send_header('Accept-Ranges', 'bytes')
self.handler.send_header('Content-Length', str(Fin - Inicio))
self.handler.send_header('Content-Range', str(Inicio) + "-" + str(Fin) + "/" + str(Size))
self.handler.send_header("Connection", "close")
self.handler.end_headers()
while True:
time.sleep(0.2)
buffer = f.read(1024 * 250)
if not buffer:
break
self.handler.wfile.write(buffer)
self.handler.wfile.close()
f.close()
elif path.startswith("/media/"):
file = os.path.join(config.get_runtime_path(), "platformcode", "template", path[7:])
from mimetypes import MimeTypes
mime = MimeTypes()
mime_type = mime.guess_type(file)
try:
mim = mime_type[0]
except:
mim = ""
f = open(file, "rb")
self.handler.send_response(200)
self.handler.send_header('Content-type', mim)
self.handler.end_headers()
self.handler.wfile.write(f.read())
f.close()

View File

@@ -1,786 +0,0 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# Controlador para HTML
# ------------------------------------------------------------
import json
import os
import re
import threading
import time
import channelselector
from controller import Controller
from controller import Platformtools
from platformcode import config
from core.item import Item
from core.tmdb import Tmdb
from platformcode import launcher, logger
## Obtiene la versión del addon
version = config.get_addon_version()
class html(Controller):
pattern = re.compile("##")
name = "HTML"
def __init__(self, handler=None, ID=None):
super(html, self).__init__(handler, ID)
self.platformtools = platform(self)
self.data = {}
if self.handler:
if hasattr(handler, "client"):
self.client_ip = handler.client.getpeername()[0]
else:
self.client_ip = handler.client_address[0]
self.send_message({"action": "connect",
"data": {"version": "Alfa %s" % version,
"date": "--/--/----"}})
t = threading.Thread(target=launcher.start, name=ID)
t.setDaemon(True)
t.start()
def run(self, path):
if path:
item = Item().fromurl(path)
else:
item = Item(channel="channelselector", action="mainlist", viewmode="banner")
launcher.run(item)
def get_data(self, id):
while not "id" in self.data or not self.data["id"] == id:
time.sleep(0.1)
data = self.data["result"]
self.data = {}
return data
def send_message(self, data):
import random
ID = "%032x" % (random.getrandbits(128))
data["id"] = ID
self.handler.sendMessage(json.dumps(data))
return ID
class platform(Platformtools):
def __init__(self, controller):
self.controller = controller
self.handler = controller.handler
self.get_data = controller.get_data
self.send_message = controller.send_message
def render_items(self, itemlist, parent_item):
"""
Función encargada de mostrar el itemlist, se pasa como parametros el itemlist y el item del que procede
@type itemlist: list
@param itemlist: lista de elementos a mostrar
@type parent_item: item
@param parent_item: elemento padre
"""
# Si el itemlist no es un list salimos
if not type(itemlist) == list:
JsonData = {}
JsonData["action"] = "HideLoading"
JsonData["data"] = {}
self.send_message(JsonData)
return
# Si no hay ningun item, mostramos un aviso
if not len(itemlist):
itemlist.append(Item(title="No hay elementos que mostrar"))
if parent_item.channel == "channelselector" and not parent_item.action == "filterchannels":
parent_item.viewmode = "banner"
elif parent_item.channel == "channelselector" and parent_item.action == "filterchannels":
parent_item.viewmode = "channel"
if not parent_item.viewmode:
parent_item.viewmode = "list"
# Item Atrás
if not (parent_item.channel == "channelselector" and parent_item.action == "mainlist") and not \
itemlist[0].action == "go_back":
if parent_item.viewmode in ["banner", "channel"]:
itemlist.insert(0, Item(title="Atrás", action="go_back",
thumbnail=channelselector.get_thumb("back.png", "banner_")))
else:
itemlist.insert(0, Item(title="Atrás", action="go_back",
thumbnail=channelselector.get_thumb("back.png", "banner_")))
JsonData = {}
JsonData["action"] = "EndItems"
JsonData["data"] = {}
JsonData["data"]["itemlist"] = []
JsonData["data"]["viewmode"] = parent_item.viewmode
JsonData["data"]["category"] = parent_item.category.capitalize()
JsonData["data"]["host"] = self.controller.host
if parent_item.url: JsonData["data"]["url"] = parent_item.url
# Recorremos el itemlist
for item in itemlist:
if not item.thumbnail and item.action == "search": item.thumbnail = channelselector.get_thumb("search.png", "banner_")
#if not item.thumbnail and item.folder == True: item.thumbnail = channelselector.get_thumb("folder.png", "banner_")
if not item.thumbnail and item.folder == False: item.thumbnail = channelselector.get_thumb("nofolder.png", "banner_")
# Estas imagenes no estan en banner, asi que si queremos banner, para que no se vean mal las quitamos
elif parent_item.viewmode in ["banner", "channel"] and item.thumbnail.startswith(
"http://media.xxxxx/thumb_"):
item.thumbnail = ""
# Si el item no contiene categoria,le ponemos la del item padre
if item.category == "":
item.category = parent_item.category
# Si el item no contiene fanart,le ponemos la del item padre
if item.fanart == "":
item.fanart = parent_item.fanart
title = item.title.replace(item.title.lstrip(), "").replace(" ", "&nbsp;") + item.title.lstrip()
# Formatear titulo
if item.text_color:
title = '[COLOR %s]%s[/COLOR]' % (item.text_color, title)
if item.text_bold:
title = '[B]%s[/B]' % title
if item.text_italic:
title = '[I]%s[/I]' % title
title = self.kodi_labels_to_html(title)
# Añade headers a las imagenes si estan en un servidor con cloudflare
from core import httptools
item.thumbnail = httptools.get_url_headers(item.thumbnail)
item.fanart = httptools.get_url_headers(item.fanart)
JsonItem = {}
JsonItem["title"] = title
JsonItem["thumbnail"] = item.thumbnail
JsonItem["fanart"] = item.fanart
JsonItem["plot"] = item.plot
JsonItem["action"] = item.action
JsonItem["url"] = item.tourl()
JsonItem["context"] = []
if not item.action == "go_back":
for Comando in self.set_context_commands(item, parent_item):
JsonItem["context"].append({"title": Comando[0], "url": Comando[1]})
JsonData["data"]["itemlist"].append(JsonItem)
ID = self.send_message(JsonData)
self.get_data(ID)
def set_context_commands(self, item, parent_item):
"""
Función para generar los menus contextuales.
1. Partiendo de los datos de item.context
a. Metodo antiguo item.context tipo str separando las opciones por "|" (ejemplo: item.context = "1|2|3")
(solo predefinidos)
b. Metodo list: item.context es un list con las diferentes opciones del menu:
- Predefinidos: Se cargara una opcion predefinida con un nombre.
item.context = ["1","2","3"]
- dict(): Se cargara el item actual modificando los campos que se incluyan en el dict() en caso de
modificar los campos channel y action estos serán guardados en from_channel y from_action.
item.context = [{"title":"Nombre del menu", "action": "action del menu", "channel",
"channel del menu"}, {...}]
2. Añadiendo opciones segun criterios
Se pueden añadir opciones al menu contextual a items que cumplan ciertas condiciones
3. Añadiendo opciones a todos los items
Se pueden añadir opciones al menu contextual para todos los items
@param item: elemento que contiene los menu contextuales
@type item: item
@param parent_item:
@type parent_item: item
"""
context_commands = []
# Creamos un list con las diferentes opciones incluidas en item.context
if type(item.context) == str:
context = item.context.split("|")
elif type(item.context) == list:
context = item.context
else:
context = []
# Opciones segun item.context
for command in context:
# Predefinidos
if type(command) == str:
if command == "buscar_trailer":
context_commands.append(("Buscar Trailer",
item.clone(channel="trailertools", action="buscartrailer",
contextual=True).tourl()))
# Formato dict
if type(command) == dict:
# Los parametros del dict, se sobreescriben al nuevo context_item en caso de sobreescribir "action" y
# "channel", los datos originales se guardan en "from_action" y "from_channel"
if "action" in command:
command["from_action"] = item.action
if "channel" in command:
command["from_channel"] = item.channel
context_commands.append(
(command["title"], item.clone(**command).tourl()))
# Opciones segun criterios
# Ir al Menu Principal (channel.mainlist)
if parent_item.channel not in ["news",
"channelselector"] and item.action != "mainlist" and parent_item.action != "mainlist":
context_commands.append(("Ir al Menu Principal", Item(channel=item.channel, action="mainlist").tourl()))
# Añadir a Favoritos
if item.channel not in ["favorites", "videolibrary", "help", "setting",
""] and not parent_item.channel == "favorites":
context_commands.append((config.get_localized_string(30155),
item.clone(channel="favorites", action="addFavourite", from_channel=item.channel,
from_action=item.action).tourl()))
# Añadimos opción contextual para Añadir la serie completa a la videoteca
if item.channel != "videolibrary" and item.action in ["episodios", "get_episodios"] \
and (item.contentSerieName or item.show):
context_commands.append(("Añadir Serie a Videoteca",
item.clone(action="add_serie_to_library", from_action=item.action).tourl()))
# Añadir Pelicula a videoteca
if item.channel != "videolibrary" and item.action in ["detail", "findvideos"] \
and item.contentType == 'movie':
context_commands.append(("Añadir Pelicula a Videoteca",
item.clone(action="add_pelicula_to_library", from_action=item.action).tourl()))
# Descargar pelicula
if item.contentType == "movie" and not item.channel == "downloads":
context_commands.append(("Descargar Pelicula",
item.clone(channel="downloads", action="save_download", from_channel=item.channel,
from_action=item.action).tourl()))
# Descargar serie
if item.contentType == "tvshow" and not item.channel == "downloads":
context_commands.append(("Descargar Serie",
item.clone(channel="downloads", action="save_download", from_channel=item.channel,
from_action=item.action).tourl()))
# Descargar episodio
if item.contentType == "episode" and not item.channel == "downloads":
context_commands.append(("Descargar Episodio",
item.clone(channel="downloads", action="save_download", from_channel=item.channel,
from_action=item.action).tourl()))
# Descargar temporada
if item.contentType == "season" and not item.channel == "downloads":
context_commands.append(("Descargar Temporada",
item.clone(channel="downloads", action="save_download", from_channel=item.channel,
from_action=item.action).tourl()))
# Abrir configuración
if parent_item.channel not in ["setting", "news", "search"]:
context_commands.append(("Abrir Configuración", Item(channel="setting", action="mainlist").tourl()))
return sorted(context_commands, key=lambda comand: comand[0])
def dialog_ok(self, heading, line1, line2="", line3=""):
text = line1
if line2: text += "\n" + line2
if line3: text += "\n" + line3
text = self.kodi_labels_to_html(text)
JsonData = {}
JsonData["action"] = "Alert"
JsonData["data"] = {}
JsonData["data"]["title"] = heading
JsonData["data"]["text"] = unicode(text, "utf8", "ignore").encode("utf8")
ID = self.send_message(JsonData)
self.get_data(ID)
def dialog_notification(self, heading, message, icon=0, time=5000, sound=True):
JsonData = {}
JsonData["action"] = "notification"
JsonData["data"] = {}
JsonData["data"]["title"] = self.kodi_labels_to_html(heading)
JsonData["data"]["text"] = self.kodi_labels_to_html(message)
JsonData["data"]["icon"] = icon
JsonData["data"]["sound"] = sound
JsonData["data"]["time"] = time
self.send_message(JsonData)
return
def dialog_yesno(self, heading, line1, line2="", line3="", nolabel="No", yeslabel="Si", autoclose=""):
text = line1
if line2: text += "\n" + line2
if line3: text += "\n" + line3
text = self.kodi_labels_to_html(text)
heading = self.kodi_labels_to_html(heading)
JsonData = {}
JsonData["action"] = "AlertYesNo"
JsonData["data"] = {}
JsonData["data"]["title"] = heading
JsonData["data"]["text"] = text
ID = self.send_message(JsonData)
response = self.get_data(ID)
return response
def dialog_select(self, heading, list):
JsonData = {}
heading = self.kodi_labels_to_html(heading)
JsonData["action"] = "List"
JsonData["data"] = {}
JsonData["data"]["title"] = heading
JsonData["data"]["list"] = []
for Elemento in list:
JsonData["data"]["list"].append(self.kodi_labels_to_html(Elemento))
ID = self.send_message(JsonData)
response = self.get_data(ID)
return response
def dialog_progress(self, heading, line1, line2="", line3=""):
class Dialog(object):
def __init__(self, heading, line1, line2, line3, platformtools):
self.platformtools = platformtools
self.closed = False
self.heading = self.platformtools.kodi_labels_to_html(heading)
text = line1
if line2: text += "\n" + line2
if line3: text += "\n" + line3
text = self.platformtools.kodi_labels_to_html(text)
JsonData = {}
JsonData["action"] = "Progress"
JsonData["data"] = {}
JsonData["data"]["title"] = heading
JsonData["data"]["text"] = text
JsonData["data"]["percent"] = 0
ID = self.platformtools.send_message(JsonData)
self.platformtools.get_data(ID)
def iscanceled(self):
JsonData = {}
JsonData["action"] = "ProgressIsCanceled"
JsonData["data"] = {}
ID = self.platformtools.send_message(JsonData)
response = self.platformtools.get_data(ID)
return response
def update(self, percent, line1, line2="", line3=""):
text = line1
if line2: text += "\n" + line2
if line3: text += "\n" + line3
text = self.platformtools.kodi_labels_to_html(text)
JsonData = {}
JsonData["action"] = "ProgressUpdate"
JsonData["data"] = {}
JsonData["data"]["title"] = self.heading
JsonData["data"]["text"] = text
JsonData["data"]["percent"] = percent
self.platformtools.send_message(JsonData)
def close(self):
JsonData = {}
JsonData["action"] = "ProgressClose"
JsonData["data"] = {}
ID = self.platformtools.send_message(JsonData)
self.platformtools.get_data(ID)
self.closed = True
return Dialog(heading, line1, line2, line3, self)
def dialog_progress_bg(self, heading, message=""):
class Dialog(object):
def __init__(self, heading, message, platformtools):
self.platformtools = platformtools
self.closed = False
self.heading = self.platformtools.kodi_labels_to_html(heading)
message = self.platformtools.kodi_labels_to_html(message)
JsonData = {}
JsonData["action"] = "ProgressBG"
JsonData["data"] = {}
JsonData["data"]["title"] = heading
JsonData["data"]["text"] = message
JsonData["data"]["percent"] = 0
ID = self.platformtools.send_message(JsonData)
self.platformtools.get_data(ID)
def isFinished(self):
return not self.closed
def update(self, percent=0, heading="", message=""):
JsonData = {}
JsonData["action"] = "ProgressBGUpdate"
JsonData["data"] = {}
JsonData["data"]["title"] = self.platformtools.kodi_labels_to_html(heading)
JsonData["data"]["text"] = self.platformtools.kodi_labels_to_html(message)
JsonData["data"]["percent"] = percent
self.platformtools.send_message(JsonData)
def close(self):
JsonData = {}
JsonData["action"] = "ProgressBGClose"
JsonData["data"] = {}
ID = self.platformtools.send_message(JsonData)
self.platformtools.get_data(ID)
self.closed = True
return Dialog(heading, message, self)
def dialog_input(self, default="", heading="", hidden=False):
JsonData = {}
JsonData["action"] = "Keyboard"
JsonData["data"] = {}
JsonData["data"]["title"] = self.kodi_labels_to_html(heading)
JsonData["data"]["text"] = default
JsonData["data"]["password"] = hidden
ID = self.send_message(JsonData)
response = self.get_data(ID)
return response
def dialog_numeric(self, type, heading, default=""):
return self.dialog_input("", heading, False)
def itemlist_refresh(self):
JsonData = {}
JsonData["action"] = "Refresh"
JsonData["data"] = {}
ID = self.send_message(JsonData)
self.get_data(ID)
def itemlist_update(self, item):
JsonData = {}
JsonData["action"] = "Update"
JsonData["data"] = {}
JsonData["data"]["url"] = item.tourl()
ID = self.send_message(JsonData)
self.get_data(ID)
def is_playing(self):
JsonData = {}
JsonData["action"] = "isPlaying"
JsonData["data"] = {}
ID = self.send_message(JsonData)
response = self.get_data(ID)
return response
def play_video(self, item):
if item.contentTitle:
title = item.contentTitle
elif item.fulltitle:
title = item.fulltitle
else:
title = item.title
if item.contentPlot:
plot = item.contentPlot
else:
plot = item.plot
if item.server == "torrent":
self.play_torrent(item)
else:
JsonData = {}
JsonData["action"] = "Play"
JsonData["data"] = {}
JsonData["data"]["title"] = title
JsonData["data"]["plot"] = plot
JsonData["data"]["video_url"] = item.video_url
JsonData["data"]["url"] = item.url
JsonData["data"]["host"] = self.controller.host
ID = self.send_message(JsonData)
self.get_data(ID)
def play_torrent(self, item):
import time
import os
played = False
# Importamos el cliente
from btserver import Client
# Iniciamos el cliente:
c = Client(url=item.url, is_playing_fnc=self.is_playing, wait_time=None, timeout=5,
temp_path=os.path.join(config.get_data_path(), "torrent"))
# Mostramos el progreso
progreso = self.dialog_progress("Alfa - Torrent", "Iniciando...")
# Mientras el progreso no sea cancelado ni el cliente cerrado
while not progreso.iscanceled() and not c.closed:
try:
# Obtenemos el estado del torrent
s = c.status
# Montamos las tres lineas con la info del torrent
txt = '%.2f%% de %.1fMB %s | %.1f kB/s' % \
(s.progress_file, s.file_size, s.str_state, s._download_rate)
txt2 = 'S: %d(%d) P: %d(%d) | DHT:%s (%d) | Trakers: %d' % \
(
s.num_seeds, s.num_complete, s.num_peers, s.num_incomplete, s.dht_state, s.dht_nodes,
s.trackers)
txt3 = 'Origen Peers TRK: %d DHT: %d PEX: %d LSD %d ' % \
(s.trk_peers, s.dht_peers, s.pex_peers, s.lsd_peers)
progreso.update(s.buffer, txt, txt2, txt3)
time.sleep(1)
# Si el buffer se ha llenado y la reproduccion no ha sido iniciada, se inicia
if s.buffer == 100 and not played:
# Cerramos el progreso
progreso.close()
# Obtenemos el playlist del torrent
item.video_url = c.get_play_list()
item.server = "directo"
self.play_video(item)
# Marcamos como reproducido para que no se vuelva a iniciar
played = True
# Y esperamos a que el reproductor se cierre
while self.is_playing():
time.sleep(1)
# Cuando este cerrado, Volvemos a mostrar el dialogo
progreso = self.dialog_progress("Alfa - Torrent", "Iniciando...")
except:
import traceback
logger.info(traceback.format_exc())
break
progreso.update(100, "Terminando y eliminando datos", " ", " ")
# Detenemos el cliente
if not c.closed:
c.stop()
# Y cerramos el progreso
progreso.close()
return
def open_settings(self, items):
from platformcode import config
JsonData = {}
JsonData["action"] = "OpenConfig"
JsonData["data"] = {}
JsonData["data"]["title"] = "Opciones"
JsonData["data"]["items"] = []
for item in items:
if item.get('option') == 'hidden':
item['hidden'] = True
for key in item:
if key in ["lvalues", "label", "category"]:
try:
ops = item[key].split("|")
for x, op in enumerate(ops):
ops[x] = config.get_localized_string(int(ops[x]))
item[key] = "|".join(ops)
except:
pass
JsonData["data"]["items"].append(item)
ID = self.send_message(JsonData)
response = self.get_data(ID)
if response:
from platformcode import config
config.set_settings(response)
JsonData = {}
JsonData["action"] = "HideLoading"
JsonData["data"] = {}
self.send_message(JsonData)
def show_channel_settings(self, list_controls=None, dict_values=None, caption="", callback=None, item=None,
custom_button=None, channelpath=None):
from platformcode import config
from core import channeltools
from core import servertools
import inspect
if not os.path.isdir(os.path.join(config.get_data_path(), "settings_channels")):
os.mkdir(os.path.join(config.get_data_path(), "settings_channels"))
title = caption
if type(custom_button) == dict:
custom_button = {"label": custom_button.get("label", ""),
"function": custom_button.get("function", ""),
"visible": bool(custom_button.get("visible", True)),
"close": bool(custom_button.get("close", False))}
else:
custom_button = None
# Obtenemos el canal desde donde se ha echo la llamada y cargamos los settings disponibles para ese canal
if not channelpath:
channelpath = inspect.currentframe().f_back.f_back.f_code.co_filename
channelname = os.path.basename(channelpath).split(".")[0]
ch_type = os.path.basename(os.path.dirname(channelpath))
# Si no tenemos list_controls, hay que sacarlos del json del canal
if not list_controls:
# Si la ruta del canal esta en la carpeta "channels", obtenemos los controles y valores mediante chaneltools
if os.path.join(config.get_runtime_path(), "channels") in channelpath:
# La llamada se hace desde un canal
list_controls, default_values = channeltools.get_channel_controls_settings(channelname)
kwargs = {"channel": channelname}
# Si la ruta del canal esta en la carpeta "servers", obtenemos los controles y valores mediante servertools
elif os.path.join(config.get_runtime_path(), "servers") in channelpath:
# La llamada se hace desde un server
list_controls, default_values = servertools.get_server_controls_settings(channelname)
kwargs = {"server": channelname}
# En caso contrario salimos
else:
return None
# Si no se pasan dict_values, creamos un dict en blanco
if dict_values == None:
dict_values = {}
# Ponemos el titulo
if caption == "":
caption = str(config.get_localized_string(30100)) + " -- " + channelname.capitalize()
elif caption.startswith('@') and unicode(caption[1:]).isnumeric():
caption = config.get_localized_string(int(caption[1:]))
JsonData = {}
JsonData["action"] = "OpenConfig"
JsonData["data"] = {}
JsonData["data"]["title"] = self.kodi_labels_to_html(caption)
JsonData["data"]["custom_button"] = custom_button
JsonData["data"]["items"] = []
# Añadir controles
for c in list_controls:
if not "default" in c: c["default"] = ""
if not "color" in c: c["color"] = "auto"
if not "label" in c: continue
# Obtenemos el valor
if "id" in c:
if not c["id"] in dict_values:
if not callback:
c["value"] = config.get_setting(c["id"], **kwargs)
else:
c["value"] = c["default"]
dict_values[c["id"]] = c["value"]
else:
c["value"] = dict_values[c["id"]]
# Translation
if c['label'].startswith('@') and unicode(c['label'][1:]).isnumeric():
c['label'] = str(config.get_localized_string(c['label'][1:]))
if c["label"].endswith(":"): c["label"] = c["label"][:-1]
if c['type'] == 'list':
lvalues = []
for li in c['lvalues']:
if li.startswith('@') and unicode(li[1:]).isnumeric():
lvalues.append(str(config.get_localized_string(li[1:])))
else:
lvalues.append(li)
c['lvalues'] = lvalues
c["label"] = self.kodi_labels_to_html(c["label"])
JsonData["data"]["items"].append(c)
ID = self.send_message(JsonData)
close = False
while True:
data = self.get_data(ID)
if type(data) == dict:
JsonData["action"] = "HideLoading"
JsonData["data"] = {}
self.send_message(JsonData)
for v in data:
if data[v] == "true": data[v] = True
if data[v] == "false": data[v] = False
if unicode(data[v]).isnumeric(): data[v] = int(data[v])
if callback and '.' in callback:
package, callback = callback.rsplit('.', 1)
else:
package = '%s.%s' % (ch_type, channelname)
cb_channel = None
try:
cb_channel = __import__(package, None, None, [package])
except ImportError:
logger.error('Imposible importar %s' % package)
if callback:
# Si existe una funcion callback la invocamos ...
return getattr(cb_channel, callback)(item, data)
else:
# si no, probamos si en el canal existe una funcion 'cb_validate_config' ...
try:
return getattr(cb_channel, 'cb_validate_config')(item, data)
except AttributeError:
# ... si tampoco existe 'cb_validate_config'...
for v in data:
config.set_setting(v, data[v], **kwargs)
elif data == "custom_button":
if '.' in callback:
package, callback = callback.rsplit('.', 1)
else:
package = '%s.%s' % (ch_type, channelname)
try:
cb_channel = __import__(package, None, None, [package])
except ImportError:
logger.error('Imposible importar %s' % package)
else:
return_value = getattr(cb_channel, custom_button['function'])(item, dict_values)
if custom_button["close"] == True:
return return_value
else:
JsonData["action"] = "custom_button"
JsonData["data"] = {}
JsonData["data"]["values"] = dict_values
JsonData["data"]["return_value"] = return_value
ID = self.send_message(JsonData)
elif data == False:
return None
def show_video_info(self, data, caption="", item=None, scraper=Tmdb):
from platformcode import html_info_window
return html_info_window.InfoWindow().start(self, data, caption, item, scraper)
def show_recaptcha(self, key, url):
from platformcode import html_recaptcha
return html_recaptcha.recaptcha().start(self, key, url)
def kodi_labels_to_html(self, text):
text = re.sub(r"(?:\[I\])(.*?)(?:\[/I\])", r"<i>\1</i>", text)
text = re.sub(r"(?:\[B\])(.*?)(?:\[/B\])", r"<b>\1</b>", text)
text = re.sub(r"(?:\[COLOR (?:0x)?([0-f]{2})([0-f]{2})([0-f]{2})([0-f]{2})\])(.*?)(?:\[/COLOR\])",
lambda m: "<span style='color: rgba(%s,%s,%s,%s)'>%s</span>" % (
int(m.group(2), 16), int(m.group(3), 16), int(m.group(4), 16), int(m.group(1), 16) / 255.0,
m.group(5)), text)
text = re.sub(r"(?:\[COLOR (?:0x)?([0-f]{2})([0-f]{2})([0-f]{2})\])(.*?)(?:\[/COLOR\])",
r"<span style='color: #\1\2\3'>\4</span>", text)
text = re.sub(r"(?:\[COLOR (?:0x)?([a-z|A-Z]+)\])(.*?)(?:\[/COLOR\])", r"<span style='color: \1'>\2</span>",
text)
return text

View File

@@ -1,188 +0,0 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# Controlador para RSS
# ------------------------------------------------------------
import json
import random
import re
import threading
import time
from controller import Controller
from controller import Platformtools
from core.item import Item
class jsonserver(Controller):
pattern = re.compile("^/json")
data = {}
def __init__(self, handler=None):
super(jsonserver, self).__init__(handler)
self.platformtools = platformtools(self)
def extract_item(self, path):
if path == "/json" or path == "/json/":
item = Item(channel="channelselector", action="mainlist")
else:
item = Item().fromurl(path.replace("/json/", ""))
return item
def run(self, path):
item = self.extract_item(path)
from platformcode import launcher
launcher.run(item)
def set_data(self, data):
self.data = data
def get_data(self, id):
if "id" in self.data and self.data["id"] == id:
data = self.data["result"]
else:
data = None
return data
def send_data(self, data, headers={}, response=200):
headers.setdefault("content-type", "application/json")
headers.setdefault("connection", "close")
self.handler.send_response(response)
for header in headers:
self.handler.send_header(header, headers[header])
self.handler.end_headers()
self.handler.wfile.write(data)
class platformtools(Platformtools):
def __init__(self, controller):
self.controller = controller
self.handler = controller.handler
def render_items(self, itemlist, parentitem):
JSONResponse = {}
JSONResponse["title"] = parentitem.title
JSONResponse["date"] = time.strftime("%x")
JSONResponse["time"] = time.strftime("%X")
JSONResponse["count"] = len(itemlist)
JSONResponse["list"] = []
for item in itemlist:
JSONItem = {}
JSONItem["title"] = item.title
JSONItem["url"] = "http://" + self.controller.host + "/json/" + item.tourl()
if item.thumbnail: JSONItem["thumbnail"] = item.thumbnail
if item.plot: JSONItem["plot"] = item.plot
JSONResponse["list"].append(JSONItem)
self.controller.send_data(json.dumps(JSONResponse, indent=4, sort_keys=True))
def dialog_select(self, heading, list):
ID = "%032x" % (random.getrandbits(128))
response = '<?xml version="1.0" encoding="UTF-8" ?>\n'
response += '<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">\n'
response += '<channel>\n'
response += '<link>/rss</link>\n'
response += '<title>' + heading + '</title>\n'
for option in list:
response += '<item>\n'
response += '<title>' + option + '</title>\n'
response += '<image>%s</image>\n'
response += '<link>http://' + self.controller.host + '/data/' + threading.current_thread().name + '/' + ID + '/' + str(
list.index(option)) + '</link>\n'
response += '</item>\n\n'
response += '</channel>\n'
response += '</rss>\n'
self.controller.send_data(response)
self.handler.server.shutdown_request(self.handler.request)
while not self.controller.get_data(ID):
continue
return int(self.controller.get_data(ID))
def dialog_ok(self, heading, line1, line2="", line3=""):
text = line1
if line2: text += "\n" + line2
if line3: text += "\n" + line3
ID = "%032x" % (random.getrandbits(128))
response = '<?xml version="1.0" encoding="UTF-8" ?>\n'
response += '<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">\n'
response += '<channel>\n'
response += '<link>/rss</link>\n'
response += '<title>' + heading + '</title>\n'
response += '<item>\n'
response += '<title>' + text + '</title>\n'
response += '<image>%s</image>\n'
response += '<link></link>\n'
response += '</item>\n\n'
response += '<item>\n'
response += '<title>Si</title>\n'
response += '<image>%s</image>\n'
response += '<link>http://' + self.controller.host + '/data/' + threading.current_thread().name + '/' + ID + '/1</link>\n'
response += '</item>\n\n'
response += '<item>\n'
response += '</channel>\n'
response += '</rss>\n'
self.controller.send_data(response)
self.handler.server.shutdown_request(self.handler.request)
while not self.controller.get_data(ID):
continue
def dialog_yesno(self, heading, line1, line2="", line3=""):
text = line1
if line2: text += "\n" + line2
if line3: text += "\n" + line3
ID = "%032x" % (random.getrandbits(128))
response = '<?xml version="1.0" encoding="UTF-8" ?>\n'
response += '<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">\n'
response += '<channel>\n'
response += '<link>/rss</link>\n'
response += '<title>' + heading + '</title>\n'
response += '<item>\n'
response += '<title>' + text + '</title>\n'
response += '<image>%s</image>\n'
response += '<link></link>\n'
response += '</item>\n\n'
response += '<item>\n'
response += '<title>Si</title>\n'
response += '<image>%s</image>\n'
response += '<link>http://' + self.controller.host + '/data/' + threading.current_thread().name + '/' + ID + '/1</link>\n'
response += '</item>\n\n'
response += '<item>\n'
response += '<title>No</title>\n'
response += '<image>%s</image>\n'
response += '<link>http://' + self.controller.host + '/data/' + threading.current_thread().name + '/' + ID + '/0</link>\n'
response += '</item>\n\n'
response += '</channel>\n'
response += '</rss>\n'
self.controller.send_data(response)
self.handler.server.shutdown_request(self.handler.request)
while not self.controller.get_data(ID):
continue
return bool(int(self.controller.get_data(ID)))
def dialog_notification(self, heading, message, icon=0, time=5000, sound=True):
# No disponible por ahora, muestra un dialog_ok
self.dialog_ok(heading, message)
def play_video(self, item):
response = '<?xml version="1.0" encoding="UTF-8" ?>\n'
response += '<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">\n'
response += '<channel>\n'
response += '<link>/rss</link>\n'
response += '<title>' + item.title + '</title>\n'
response += '<item>\n'
response += '<title>' + item.title + '</title>\n'
response += '<image>%s</image>\n'
response += '<link>' + item.video_url + '</link>\n'
response += '</item>\n\n'
response += '</channel>\n'
response += '</rss>\n'
self.controller.send_data(response)

View File

@@ -1,58 +0,0 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# Controlador para acceso indirecto a ficheros remotos
# ------------------------------------------------------------
import base64
import re
import urllib
import urllib2
from controller import Controller
class proxy(Controller):
pattern = re.compile("^/proxy/")
def run(self, path):
url = path.replace("/proxy/", "").split("/")[0]
url = base64.b64decode(urllib.unquote_plus(url))
request_headers = self.handler.headers.dict
if "host" in request_headers: request_headers.pop("host")
if "referer" in request_headers: request_headers.pop("referer")
if "cookie" in request_headers: request_headers.pop("cookie")
if "|" in url:
url_headers = dict(
[[header.split("=")[0].lower(), urllib.unquote_plus("=".join(header.split("=")[1:]))] for header in
url.split("|")[1].split("&")])
url = url.split("|")[0]
request_headers.update(url_headers)
req = urllib2.Request(url, headers=request_headers)
opener = urllib2.build_opener(urllib2.HTTPHandler(debuglevel=0))
try:
h = opener.open(req)
except urllib2.HTTPError, e:
h = e
except:
self.handler.send_response("503")
self.handler.wfile.close()
h.close()
self.handler.send_response(h.getcode())
for header in h.info():
self.handler.send_header(header, h.info()[header])
self.handler.end_headers()
blocksize = 1024
bloqueleido = h.read(blocksize)
while len(bloqueleido) > 0:
self.handler.wfile.write(bloqueleido)
bloqueleido = h.read(blocksize)
self.handler.wfile.close()
h.close()

View File

@@ -1,199 +0,0 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# Controlador para RSS
# ------------------------------------------------------------
import random
import re
import threading
from controller import Controller
from controller import Platformtools
from core.item import Item
class rss(Controller):
pattern = re.compile("^/rss")
data = {}
def __init__(self, handler=None, ):
super(rss, self).__init__(handler)
self.platformtools = platformtools(self)
def extract_item(self, path):
if path == "/rss" or path == "/rss/":
item = Item(channel="channelselector", action="mainlist")
else:
item = Item().fromurl(path.replace("/rss/", ""))
return item
def run(self, path):
item = self.extract_item(path)
from platformcode import launcher
launcher.run(item)
def set_data(self, data):
self.data = data
def get_data(self, id):
if "id" in self.data and self.data["id"] == id:
data = self.data["result"]
else:
data = None
return data
def send_data(self, data, headers={}, response=200):
headers.setdefault("content-type", "application/rss+xml")
headers.setdefault("connection", "close")
self.handler.send_response(response)
for header in headers:
self.handler.send_header(header, headers[header])
self.handler.end_headers()
self.handler.wfile.write(data)
class platformtools(Platformtools):
def __init__(self, controller):
self.controller = controller
self.handler = controller.handler
def create_rss(self, itemlist):
resp = '<?xml version="1.0" encoding="UTF-8" ?>\n'
resp += '<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">\n'
resp += '<channel>\n'
resp += '<link>http://' + self.controller.host + '/rss</link>\n'
resp += '<title>Menú Principal</title>\n'
for item in itemlist:
resp += '<item>\n'
resp += '<title>' + item.title + '</title>\n'
resp += '<image>' + item.thumbnail + '</image>\n'
resp += '<link>' + self.controller.host + '/rss/' + item.tourl() + '</link>\n'
resp += '</item>\n\n'
resp += '</channel>\n'
resp += '</rss>\n'
return resp
def render_items(self, itemlist, parentitem):
new_itemlist = []
for item in itemlist:
# if item.action == "search": continue
# if item.channel=="search": continue
# if item.channel=="setting": continue
# if item.channel=="help": continue
new_itemlist.append(item)
response = self.create_rss(new_itemlist)
self.controller.send_data(response)
def dialog_select(self, heading, list):
ID = "%032x" % (random.getrandbits(128))
response = '<?xml version="1.0" encoding="UTF-8" ?>\n'
response += '<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">\n'
response += '<channel>\n'
response += '<link>/rss</link>\n'
response += '<title>' + heading + '</title>\n'
for option in list:
response += '<item>\n'
response += '<title>' + option + '</title>\n'
response += '<image>%s</image>\n'
response += '<link>http://' + self.controller.host + '/data/' + threading.current_thread().name + '/' + ID + '/' + str(
list.index(option)) + '</link>\n'
response += '</item>\n\n'
response += '</channel>\n'
response += '</rss>\n'
self.controller.send_data(response)
self.handler.server.shutdown_request(self.handler.request)
while not self.controller.get_data(ID):
continue
return int(self.controller.get_data(ID))
def dialog_ok(self, heading, line1, line2="", line3=""):
text = line1
if line2: text += "\n" + line2
if line3: text += "\n" + line3
ID = "%032x" % (random.getrandbits(128))
response = '<?xml version="1.0" encoding="UTF-8" ?>\n'
response += '<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">\n'
response += '<channel>\n'
response += '<link>/rss</link>\n'
response += '<title>' + heading + '</title>\n'
response += '<item>\n'
response += '<title>' + text + '</title>\n'
response += '<image>%s</image>\n'
response += '<link></link>\n'
response += '</item>\n\n'
response += '<item>\n'
response += '<title>Si</title>\n'
response += '<image>%s</image>\n'
response += '<link>http://' + self.controller.host + '/data/' + threading.current_thread().name + '/' + ID + '/1</link>\n'
response += '</item>\n\n'
response += '<item>\n'
response += '</channel>\n'
response += '</rss>\n'
self.controller.send_data(response)
self.handler.server.shutdown_request(self.handler.request)
while not self.controller.get_data(ID):
continue
def dialog_yesno(self, heading, line1, line2="", line3=""):
text = line1
if line2: text += "\n" + line2
if line3: text += "\n" + line3
ID = "%032x" % (random.getrandbits(128))
response = '<?xml version="1.0" encoding="UTF-8" ?>\n'
response += '<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">\n'
response += '<channel>\n'
response += '<link>/rss</link>\n'
response += '<title>' + heading + '</title>\n'
response += '<item>\n'
response += '<title>' + text + '</title>\n'
response += '<image>%s</image>\n'
response += '<link></link>\n'
response += '</item>\n\n'
response += '<item>\n'
response += '<title>Si</title>\n'
response += '<image>%s</image>\n'
response += '<link>http://' + self.controller.host + '/data/' + threading.current_thread().name + '/' + ID + '/1</link>\n'
response += '</item>\n\n'
response += '<item>\n'
response += '<title>No</title>\n'
response += '<image>%s</image>\n'
response += '<link>http://' + self.controller.host + '/data/' + threading.current_thread().name + '/' + ID + '/0</link>\n'
response += '</item>\n\n'
response += '</channel>\n'
response += '</rss>\n'
self.controller.send_data(response)
self.handler.server.shutdown_request(self.handler.request)
while not self.controller.get_data(ID):
continue
return bool(int(self.controller.get_data(ID)))
def dialog_notification(self, heading, message, icon=0, time=5000, sound=True):
# No disponible por ahora, muestra un dialog_ok
self.dialog_ok(heading, message)
def play_video(self, item):
response = '<?xml version="1.0" encoding="UTF-8" ?>\n'
response += '<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">\n'
response += '<channel>\n'
response += '<link>/rss</link>\n'
response += '<title>' + item.title + '</title>\n'
response += '<item>\n'
response += '<title>' + item.title + '</title>\n'
response += '<image>%s</image>\n'
response += '<link>' + item.video_url + '</link>\n'
response += '</item>\n\n'
response += '</channel>\n'
response += '</rss>\n'
self.controller.send_data(response)

View File

@@ -1,173 +0,0 @@
# -*- coding: utf-8 -*-
from core.tmdb import Tmdb
from platformcode import logger
class InfoWindow(object):
otmdb = None
item_title = ""
item_serie = ""
item_temporada = 0
item_episodio = 0
result = {}
@staticmethod
def get_language(lng):
# Cambiamos el formato del Idioma
languages = {
'aa': 'Afar', 'ab': 'Abkhazian', 'af': 'Afrikaans', 'ak': 'Akan', 'sq': 'Albanian', 'am': 'Amharic',
'ar': 'Arabic', 'an': 'Aragonese', 'as': 'Assamese', 'av': 'Avaric', 'ae': 'Avestan',
'ay': 'Aymara', 'az': 'Azerbaijani', 'ba': 'Bashkir', 'bm': 'Bambara', 'eu': 'Basque',
'be': 'Belarusian', 'bn': 'Bengali', 'bh': 'Bihari languages', 'bi': 'Bislama',
'bo': 'Tibetan', 'bs': 'Bosnian', 'br': 'Breton', 'bg': 'Bulgarian', 'my': 'Burmese',
'ca': 'Catalan; Valencian', 'cs': 'Czech', 'ch': 'Chamorro', 'ce': 'Chechen', 'zh': 'Chinese',
'cu': 'Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church Slavonic',
'cv': 'Chuvash', 'kw': 'Cornish', 'co': 'Corsican', 'cr': 'Cree', 'cy': 'Welsh',
'da': 'Danish', 'de': 'German', 'dv': 'Divehi; Dhivehi; Maldivian', 'nl': 'Dutch; Flemish',
'dz': 'Dzongkha', 'en': 'English', 'eo': 'Esperanto',
'et': 'Estonian', 'ee': 'Ewe', 'fo': 'Faroese', 'fa': 'Persian', 'fj': 'Fijian',
'fi': 'Finnish', 'fr': 'French', 'fy': 'Western Frisian', 'ff': 'Fulah',
'Ga': 'Georgian', 'gd': 'Gaelic; Scottish Gaelic', 'ga': 'Irish', 'gl': 'Galician',
'gv': 'Manx', 'el': 'Greek, Modern (1453-)', 'gn': 'Guarani', 'gu': 'Gujarati',
'ht': 'Haitian; Haitian Creole', 'ha': 'Hausa', 'he': 'Hebrew', 'hz': 'Herero', 'hi': 'Hindi',
'ho': 'Hiri Motu', 'hr': 'Croatian', 'hu': 'Hungarian', 'hy': 'Armenian', 'ig': 'Igbo',
'is': 'Icelandic', 'io': 'Ido', 'ii': 'Sichuan Yi; Nuosu', 'iu': 'Inuktitut',
'ie': 'Interlingue; Occidental', 'ia': 'Interlingua (International Auxiliary Language Association)',
'id': 'Indonesian', 'ik': 'Inupiaq', 'it': 'Italian', 'jv': 'Javanese',
'ja': 'Japanese', 'kl': 'Kalaallisut; Greenlandic', 'kn': 'Kannada', 'ks': 'Kashmiri',
'ka': 'Georgian', 'kr': 'Kanuri', 'kk': 'Kazakh', 'km': 'Central Khmer', 'ki': 'Kikuyu; Gikuyu',
'rw': 'Kinyarwanda', 'ky': 'Kirghiz; Kyrgyz', 'kv': 'Komi', 'kg': 'Kongo', 'ko': 'Korean',
'kj': 'Kuanyama; Kwanyama', 'ku': 'Kurdish', 'lo': 'Lao', 'la': 'Latin', 'lv': 'Latvian',
'li': 'Limburgan; Limburger; Limburgish', 'ln': 'Lingala', 'lt': 'Lithuanian',
'lb': 'Luxembourgish; Letzeburgesch', 'lu': 'Luba-Katanga', 'lg': 'Ganda', 'mk': 'Macedonian',
'mh': 'Marshallese', 'ml': 'Malayalam', 'mi': 'Maori', 'mr': 'Marathi', 'ms': 'Malay', 'Mi': 'Micmac',
'mg': 'Malagasy', 'mt': 'Maltese', 'mn': 'Mongolian', 'na': 'Nauru',
'nv': 'Navajo; Navaho', 'nr': 'Ndebele, South; South Ndebele', 'nd': 'Ndebele, North; North Ndebele',
'ng': 'Ndonga', 'ne': 'Nepali', 'nn': 'Norwegian Nynorsk; Nynorsk, Norwegian',
'nb': 'Bokmål, Norwegian; Norwegian Bokmål', 'no': 'Norwegian', 'oc': 'Occitan (post 1500)',
'oj': 'Ojibwa', 'or': 'Oriya', 'om': 'Oromo', 'os': 'Ossetian; Ossetic', 'pa': 'Panjabi; Punjabi',
'pi': 'Pali', 'pl': 'Polish', 'pt': 'Portuguese', 'ps': 'Pushto; Pashto', 'qu': 'Quechua',
'ro': 'Romanian; Moldavian; Moldovan', 'rn': 'Rundi', 'ru': 'Russian', 'sg': 'Sango', 'rm': 'Romansh',
'sa': 'Sanskrit', 'si': 'Sinhala; Sinhalese', 'sk': 'Slovak', 'sl': 'Slovenian', 'se': 'Northern Sami',
'sm': 'Samoan', 'sn': 'Shona', 'sd': 'Sindhi', 'so': 'Somali', 'st': 'Sotho, Southern', 'es': 'Spanish',
'sc': 'Sardinian', 'sr': 'Serbian', 'ss': 'Swati', 'su': 'Sundanese', 'sw': 'Swahili', 'sv': 'Swedish',
'ty': 'Tahitian', 'ta': 'Tamil', 'tt': 'Tatar', 'te': 'Telugu', 'tg': 'Tajik', 'tl': 'Tagalog',
'th': 'Thai', 'ti': 'Tigrinya', 'to': 'Tonga (Tonga Islands)', 'tn': 'Tswana', 'ts': 'Tsonga',
'tk': 'Turkmen', 'tr': 'Turkish', 'tw': 'Twi', 'ug': 'Uighur; Uyghur', 'uk': 'Ukrainian',
'ur': 'Urdu', 'uz': 'Uzbek', 've': 'Venda', 'vi': 'Vietnamese', 'vo': 'Volapük',
'wa': 'Walloon', 'wo': 'Wolof', 'xh': 'Xhosa', 'yi': 'Yiddish', 'yo': 'Yoruba', 'za': 'Zhuang; Chuang',
'zu': 'Zulu'}
return languages.get(lng, lng)
def get_scraper_data(self, data_in):
self.otmdb = None
# logger.debug(str(data_in))
if self.listData:
# Datos comunes a todos los listados
infoLabels = self.scraper().get_infoLabels(origen=data_in)
if "original_language" in infoLabels:
infoLabels["language"] = self.get_language(infoLabels["original_language"])
if "vote_average" in data_in and "vote_count" in data_in:
infoLabels["puntuacion"] = str(data_in["vote_average"]) + "/10 (" + str(data_in["vote_count"]) + ")"
self.result = infoLabels
def start(self, handler, data, caption="Información del vídeo", item=None, scraper=Tmdb):
# Capturamos los parametros
self.caption = caption
self.item = item
self.indexList = -1
self.listData = []
self.handler = handler
self.scraper = scraper
logger.debug(data)
if type(data) == list:
self.listData = data
self.indexList = 0
data = self.listData[self.indexList]
self.get_scraper_data(data)
ID = self.update_window()
return self.onClick(ID)
def update_window(self):
JsonData = {}
JsonData["action"] = "OpenInfo"
JsonData["data"] = {}
JsonData["data"]["buttons"] = len(self.listData) > 0
JsonData["data"]["previous"] = self.indexList > 0
JsonData["data"]["next"] = self.indexList + 1 < len(self.listData)
JsonData["data"]["count"] = "(%s/%s)" % (self.indexList + 1, len(self.listData))
JsonData["data"]["title"] = self.caption
JsonData["data"]["fanart"] = self.result.get("fanart", "")
JsonData["data"]["thumbnail"] = self.result.get("thumbnail", "")
JsonData["data"]["lines"] = []
if self.result.get("mediatype", "movie") == "movie":
JsonData["data"]["lines"].append({"title": "Título:", "text": self.result.get("title", "N/A")})
JsonData["data"]["lines"].append(
{"title": "Título Original:", "text": self.result.get("originaltitle", "N/A")})
JsonData["data"]["lines"].append({"title": "Idioma Original:", "text": self.result.get("language", "N/A")})
JsonData["data"]["lines"].append({"title": "Puntuación:", "text": self.result.get("puntuacion", "N/A")})
JsonData["data"]["lines"].append({"title": "Lanzamiento:", "text": self.result.get("release_date", "N/A")})
JsonData["data"]["lines"].append({"title": "Generos:", "text": self.result.get("genre", "N/A")})
JsonData["data"]["lines"].append({"title": "", "text": ""})
else:
JsonData["data"]["lines"].append({"title": "Serie:", "text": self.result.get("title", "N/A")})
JsonData["data"]["lines"].append({"title": "Idioma Original:", "text": self.result.get("language", "N/A")})
JsonData["data"]["lines"].append({"title": "Puntuación:", "text": self.result.get("puntuacion", "N/A")})
JsonData["data"]["lines"].append({"title": "Generos:", "text": self.result.get("genre", "N/A")})
if self.result.get("season"):
JsonData["data"]["lines"].append(
{"title": "Titulo temporada:", "text": self.result.get("temporada_nombre", "N/A")})
JsonData["data"]["lines"].append({"title": "Temporada:",
"text": self.result.get("season", "N/A") + " de " + self.result.get(
"seasons", "N/A")})
JsonData["data"]["lines"].append({"title": "", "text": ""})
if self.result.get("episode"):
JsonData["data"]["lines"].append({"title": "Titulo:", "text": self.result.get("episode_title", "N/A")})
JsonData["data"]["lines"].append({"title": "Episodio:",
"text": self.result.get("episode", "N/A") + " de " + self.result.get(
"episodes", "N/A")})
JsonData["data"]["lines"].append({"title": "Emisión:", "text": self.result.get("date", "N/A")})
if self.result.get("plot"):
JsonData["data"]["lines"].append({"title": "Sinopsis:", "text": self.result["plot"]})
else:
JsonData["data"]["lines"].append({"title": "", "text": ""})
ID = self.handler.send_message(JsonData)
return ID
def onClick(self, ID):
while True:
response = self.handler.get_data(ID)
if response == "ok":
return self.listData[self.indexList]
elif response == "close":
return None
elif response == "next" and self.indexList < len(self.listData) - 1:
self.indexList += 1
self.get_scraper_data(self.listData[self.indexList])
ID = self.update_window()
elif response == "previous" and self.indexList > 0:
self.indexList -= 1
self.get_scraper_data(self.listData[self.indexList])
ID = self.update_window()

View File

@@ -1,79 +0,0 @@
# -*- coding: utf-8 -*-
from core import httptools
from core import scrapertools
from platformcode import platformtools, logger
class recaptcha(object):
def start(self, handler, key, referer):
self.handler = handler
self.referer = referer
self.key = key
self.headers = {'Referer': self.referer}
api_js = httptools.downloadpage("http://www.google.com/recaptcha/api.js?hl=es").data
version = scrapertools.find_single_match(api_js, 'po.src = \'(.*?)\';').split("/")[5]
self.url = "https://www.google.com/recaptcha/api/fallback?k=%s&hl=es&v=%s&t=2&ff=true" % (self.key, version)
ID = self.update_window()
return self.onClick(ID)
def update_window(self):
data = httptools.downloadpage(self.url, headers=self.headers).data
self.message = scrapertools.find_single_match(data,
'<div class="rc-imageselect-desc-no-canonical">(.*?)(?:</label>|</div>)')
self.token = scrapertools.find_single_match(data, 'name="c" value="([^"]+)"')
self.image = "https://www.google.com/recaptcha/api2/payload?k=%s&c=%s" % (self.key, self.token)
self.result = {}
JsonData = {}
JsonData["action"] = "recaptcha"
JsonData["data"] = {}
JsonData["data"]["title"] = "reCaptcha"
JsonData["data"]["image"] = self.image
JsonData["data"]["message"] = self.message
JsonData["data"]["selected"] = [int(k) for k in range(9) if self.result.get(k, False) == True]
JsonData["data"]["unselected"] = [int(k) for k in range(9) if self.result.get(k, False) == False]
ID = self.handler.send_message(JsonData)
return ID
def onClick(self, ID):
while True:
response = self.handler.get_data(ID)
if type(response) == int:
self.result[response] = not self.result.get(response, False)
JsonData = {}
JsonData["action"] = "recaptcha_select"
JsonData["data"] = {}
JsonData["data"]["selected"] = [int(k) for k in range(9) if self.result.get(k, False) == True]
JsonData["data"]["unselected"] = [int(k) for k in range(9) if self.result.get(k, False) == False]
self.handler.send_message(JsonData)
elif response == "refresh":
ID = self.update_window()
continue
elif response == True:
post = "c=%s" % self.token
for r in sorted([k for k, v in self.result.items() if v == True]):
post += "&response=%s" % r
logger.info(post)
logger.info(self.result)
data = httptools.downloadpage(self.url, post, headers=self.headers).data
result = scrapertools.find_single_match(data, '<div class="fbc-verification-token">.*?>([^<]+)<')
if result:
platformtools.dialog_notification("Captcha Correcto", "La verificación ha concluido")
JsonData = {}
JsonData["action"] = "ShowLoading"
self.handler.send_message(JsonData)
return result
else:
ID = self.update_window()
else:
return

View File

@@ -1,508 +0,0 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# Mediaserver Launcher
# ------------------------------------------------------------
import os
import sys
from core import channeltools
from core import servertools
from core import videolibrarytools
from core.item import Item
from platformcode import config, platformtools, logger
def start():
""" Primera funcion que se ejecuta al entrar en el plugin.
Dentro de esta funcion deberian ir todas las llamadas a las
funciones que deseamos que se ejecuten nada mas abrir el plugin.
"""
logger.info()
# Test if all the required directories are created
config.verify_directories_created()
import videolibrary_service
videolibrary_service.start()
def run(item):
itemlist = []
# Muestra el item en el log:
print_items(item)
# Control Parental, comprueba si es adulto o no
if item.action == "mainlist":
# Parental control
if channeltools.is_adult(item.channel) and config.get_setting("adult_request_password"):
tecleado = platformtools.dialog_input("", config.get_localized_string(60334), True)
if tecleado is None or tecleado != config.get_setting("adult_password"):
platformtools.render_items(None, item)
return
channelmodule = None
# Importa el canal para el item, todo item debe tener un canal, sino sale de la función
if item.channel:
channelmodule = import_channel(item)
# If item has no action, stops here
if item.action == "":
logger.info("Item sin accion")
itemlist = None
# Action Play, para mostrar el menú con las opciones de reproduccion.
elif item.action == "play":
logger.info("play")
# Si el canal tiene una acción "play" tiene prioridad
if hasattr(channelmodule, 'play'):
logger.info("executing channel 'play' method")
itemlist = channelmodule.play(item)
b_favourite = item.isFavourite
if len(itemlist) > 0 and isinstance(itemlist[0], Item):
item = itemlist[0]
if b_favourite:
item.isFavourite = True
play_menu(item)
elif len(itemlist) > 0 and isinstance(itemlist[0], list):
item.video_urls = itemlist
play_menu(item)
else:
platformtools.dialog_ok("plugin", "No hay nada para reproducir")
else:
logger.info("no channel 'play' method, executing core method")
play_menu(item)
itemlist = None
# Action Search, para mostrar el teclado y lanzar la busqueda con el texto indicado.
elif item.action == "search":
logger.info("search")
tecleado = platformtools.dialog_input()
if tecleado:
itemlist = channelmodule.search(item, tecleado)
else:
itemlist = []
elif item.channel == "channelselector":
import channelselector
if item.action == "mainlist":
itemlist = channelselector.getmainlist("banner_")
if item.action == "getchanneltypes":
itemlist = channelselector.getchanneltypes("banner_")
if item.action == "filterchannels":
itemlist = channelselector.filterchannels(item.channel_type, "banner_")
elif item.action == "script":
from core import tmdb
if tmdb.drop_bd():
platformtools.dialog_notification("Alfa", "caché eliminada", time=2000, sound=False)
# Todas las demas las intenta ejecturaren el siguiente orden:
# 1. En el canal
# 2. En el launcher
# 3. Si no existe en el canal ni en el launcher guarda un error en el log
else:
# Si existe la funcion en el canal la ejecuta
if hasattr(channelmodule, item.action):
logger.info("Ejectuando accion: " + item.channel + "." + item.action + "(item)")
exec "itemlist = channelmodule." + item.action + "(item)"
# Si existe la funcion en el launcher la ejecuta
elif hasattr(sys.modules[__name__], item.action):
logger.info("Ejectuando accion: " + item.action + "(item)")
exec "itemlist =" + item.action + "(item)"
# Si no existe devuelve un error
else:
logger.info(
"No se ha encontrado la accion [" + item.action + "] en el canal [" + item.channel + "] ni en el launcher")
# Llegados a este punto ya tenemos que tener el itemlist con los resultados correspondientes
# Pueden darse 3 escenarios distintos:
# 1. la función ha generado resultados y estan en el itemlist
# 2. la función no ha generado resultados y por tanto el itemlist contiene 0 items, itemlist = []
# 3. la función realiza alguna accion con la cual no se generan nuevos items, en ese caso el resultado deve ser: itemlist = None para que no modifique el listado
# A partir de aquí ya se ha ejecutado la funcion en el lugar adecuado, si queremos realizar alguna acción sobre los resultados, este es el lugar.
# Filtrado de Servers
if item.action == "findvideos":
itemlist = servertools.filter_servers(itemlist)
# Si la accion no ha devuelto ningún resultado, añade un item con el texto "No hay elementos para mostrar"
if type(itemlist) == list:
if len(itemlist) == 0:
from channelselector import get_thumb
itemlist = [Item(title="No hay elementos para mostrar", thumbnail=get_thumb("error.png"))]
# Imprime en el log el resultado
print_items(itemlist)
# Muestra los resultados en pantalla
platformtools.render_items(itemlist, item)
def import_channel(item):
channel = item.channel
channelmodule = ""
if os.path.exists(os.path.join(config.get_runtime_path(), "channels", channel + ".py")):
exec "from channels import " + channel + " as channelmodule"
elif os.path.exists(os.path.join(config.get_runtime_path(), "core", channel + ".py")):
exec "from core import " + channel + " as channelmodule"
elif os.path.exists(os.path.join(config.get_runtime_path(), channel + ".py")):
exec "import " + channel + " as channelmodule"
return channelmodule
def print_items(itemlist):
if type(itemlist) == list:
if len(itemlist) > 0:
logger.info("Items devueltos")
logger.info("-----------------------------------------------------------------------")
for item in itemlist:
logger.info(item.tostring())
logger.info("-----------------------------------------------------------------------")
else:
item = itemlist
logger.info("-----------------------------------------------------------------------")
logger.info(item.tostring())
logger.info("-----------------------------------------------------------------------")
def findvideos(item):
logger.info()
itemlist = servertools.find_video_items(item)
return itemlist
def add_pelicula_to_library(item):
videolibrarytools.add_movie(item)
def add_serie_to_library(item):
channel = import_channel(item)
videolibrarytools.add_tvshow(item, channel)
def download_all_episodes(item, first_episode="", preferred_server="vidspot", filter_language=""):
logger.info("show=" + item.show)
channel = import_channel(item)
show_title = item.show
# Obtiene el listado desde el que se llamó
action = item.extra
# Esta marca es porque el item tiene algo más aparte en el atributo "extra"
if "###" in item.extra:
action = item.extra.split("###")[0]
item.extra = item.extra.split("###")[1]
exec "episode_itemlist = channel." + action + "(item)"
# Ordena los episodios para que funcione el filtro de first_episode
episode_itemlist = sorted(episode_itemlist, key=lambda Item: Item.title)
from core import downloadtools
from core import scrapertools
best_server = preferred_server
worst_server = "moevideos"
# Para cada episodio
if first_episode == "":
empezar = True
else:
empezar = False
for episode_item in episode_itemlist:
try:
logger.info("episode=" + episode_item.title)
episode_title = scrapertools.get_match(episode_item.title, "(\d+x\d+)")
logger.info("episode=" + episode_title)
except:
import traceback
logger.error(traceback.format_exc())
continue
if first_episode != "" and episode_title == first_episode:
empezar = True
if episodio_ya_descargado(show_title, episode_title):
continue
if not empezar:
continue
# Extrae los mirrors
try:
mirrors_itemlist = channel.findvideos(episode_item)
except:
mirrors_itemlist = servertools.find_video_items(episode_item)
print mirrors_itemlist
descargado = False
new_mirror_itemlist_1 = []
new_mirror_itemlist_2 = []
new_mirror_itemlist_3 = []
new_mirror_itemlist_4 = []
new_mirror_itemlist_5 = []
new_mirror_itemlist_6 = []
for mirror_item in mirrors_itemlist:
# Si está en español va al principio, si no va al final
if "(Español)" in mirror_item.title:
if best_server in mirror_item.title.lower():
new_mirror_itemlist_1.append(mirror_item)
else:
new_mirror_itemlist_2.append(mirror_item)
elif "(Latino)" in mirror_item.title:
if best_server in mirror_item.title.lower():
new_mirror_itemlist_3.append(mirror_item)
else:
new_mirror_itemlist_4.append(mirror_item)
elif "(VOS)" in mirror_item.title:
if best_server in mirror_item.title.lower():
new_mirror_itemlist_3.append(mirror_item)
else:
new_mirror_itemlist_4.append(mirror_item)
else:
if best_server in mirror_item.title.lower():
new_mirror_itemlist_5.append(mirror_item)
else:
new_mirror_itemlist_6.append(mirror_item)
mirrors_itemlist = new_mirror_itemlist_1 + new_mirror_itemlist_2 + new_mirror_itemlist_3 + new_mirror_itemlist_4 + new_mirror_itemlist_5 + new_mirror_itemlist_6
for mirror_item in mirrors_itemlist:
logger.info("mirror=" + mirror_item.title)
if "(Español)" in mirror_item.title:
idioma = "(Español)"
codigo_idioma = "es"
elif "(Latino)" in mirror_item.title:
idioma = "(Latino)"
codigo_idioma = "lat"
elif "(VOS)" in mirror_item.title:
idioma = "(VOS)"
codigo_idioma = "vos"
elif "(VO)" in mirror_item.title:
idioma = "(VO)"
codigo_idioma = "vo"
else:
idioma = "(Desconocido)"
codigo_idioma = "desconocido"
logger.info("filter_language=#" + filter_language + "#, codigo_idioma=#" + codigo_idioma + "#")
if filter_language == "" or (filter_language != "" and filter_language == codigo_idioma):
logger.info("downloading mirror")
else:
logger.info("language " + codigo_idioma + " filtered, skipping")
continue
if hasattr(channel, 'play'):
video_items = channel.play(mirror_item)
else:
video_items = [mirror_item]
if len(video_items) > 0:
video_item = video_items[0]
# Comprueba que esté disponible
video_urls, puedes, motivo = servertools.resolve_video_urls_for_playing(video_item.server,
video_item.url,
video_password="",
muestra_dialogo=False)
# Lo añade a la lista de descargas
if puedes:
logger.info("downloading mirror started...")
# El vídeo de más calidad es el último
mediaurl = video_urls[len(video_urls) - 1][1]
devuelve = downloadtools.downloadbest(video_urls,
show_title + " " + episode_title + " " + idioma + " [" + video_item.server + "]",
continuar=False)
if devuelve == 0:
logger.info("download ok")
descargado = True
break
elif devuelve == -1:
try:
platformtools.dialog_ok("plugin", "Descarga abortada")
except:
pass
return
else:
logger.info("download error, try another mirror")
continue
else:
logger.info("downloading mirror not available... trying next")
if not descargado:
logger.info("EPISODIO NO DESCARGADO " + episode_title)
def add_to_favorites(item):
# Proviene del menu contextual:
if "item_action" in item:
item.action = item.item_action
del item.item_action
item.context = []
from channels import favorites
from core import downloadtools
if not item.fulltitle: item.fulltitle = item.title
title = platformtools.dialog_input(
default=downloadtools.limpia_nombre_excepto_1(item.fulltitle) + " [" + item.channel + "]")
if title is not None:
item.title = title
favorites.addFavourite(item)
platformtools.dialog_ok("Alfa", config.get_localized_string(
30102) + "\n" + item.title + "\n" + config.get_localized_string(30108))
return
def remove_from_favorites(item):
from channels import favorites
# En "extra" está el nombre del fichero en favoritos
favorites.delFavourite(item.extra)
platformtools.dialog_ok("Alfa",
config.get_localized_string(30102) + "\n" + item.title + "\n" + config.get_localized_string(
30105))
platformtools.itemlist_refresh()
return
def download(item):
from channels import downloads
if item.contentType == "list" or item.contentType == "tvshow":
item.contentType = "video"
item.play_menu = True
downloads.save_download(item)
return
def add_to_library(item):
if "item_action" in item:
item.action = item.item_action
del item.item_action
if not item.fulltitle == "":
item.title = item.fulltitle
videolibrarytools.savelibrary(item)
platformtools.dialog_ok("Alfa",
config.get_localized_string(30101) + "\n" + item.title + "\n" + config.get_localized_string(
30135))
return
def delete_file(item):
os.remove(item.url)
platformtools.itemlist_refresh()
return
def search_trailer(item):
config.set_setting("subtitulo", False)
item.channel = "trailertools"
item.action = "buscartrailer"
item.contextual = True
run(item)
return
# Crea la lista de opciones para el menu de reproduccion
def check_video_options(item, video_urls):
itemlist = []
# Opciones Reproducir
playable = (len(video_urls) > 0)
for video_url in video_urls:
itemlist.append(
item.clone(option=config.get_localized_string(30151) + " " + video_url[0], video_url=video_url[1],
action="play_video"))
if item.server == "local":
itemlist.append(item.clone(option=config.get_localized_string(30164), action="delete_file"))
if not item.server == "local" and playable:
itemlist.append(item.clone(option=config.get_localized_string(30153), action="download", video_urls=video_urls))
if item.channel == "favorites":
itemlist.append(item.clone(option=config.get_localized_string(30154), action="remove_from_favorites"))
if not item.channel == "favorites" and playable:
itemlist.append(
item.clone(option=config.get_localized_string(30155), action="add_to_favorites", item_action=item.action))
if not item.strmfile and playable and item.contentType == "movie":
itemlist.append(
item.clone(option=config.get_localized_string(30161), action="add_to_library", item_action=item.action))
if not item.channel in ["Trailer", "ecarteleratrailers"] and playable:
itemlist.append(item.clone(option=config.get_localized_string(30162), action="search_trailer"))
return itemlist
# play_menu, abre el menu con las opciones para reproducir
def play_menu(item):
if item.server == "": item.server = "directo"
if item.video_urls:
video_urls, puedes, motivo = item.video_urls, True, ""
else:
video_urls, puedes, motivo = servertools.resolve_video_urls_for_playing(item.server, item.url, item.password,
True)
if not "strmfile" in item: item.strmfile = False
# TODO: unificar show y Serie ya que se usan indistintamente.
if not "Serie" in item: item.Serie = item.show
if item.server == "": item.server = "directo"
opciones = check_video_options(item, video_urls)
if not puedes:
if item.server != "directo":
motivo = motivo.replace("<br/>", "\n")
platformtools.dialog_ok("No puedes ver ese vídeo porque...", motivo + "\n" + item.url)
else:
platformtools.dialog_ok("No puedes ver ese vídeo porque...",
"El servidor donde está alojado no está\nsoportado en Alfa todavía\n" + item.url)
if len(opciones) == 0:
return
default_action = config.get_setting("default_action")
logger.info("default_action=%s" % (default_action))
# Si la accion por defecto es "Preguntar", pregunta
if default_action == 0:
seleccion = platformtools.dialog_select(config.get_localized_string(30163),
[opcion.option for opcion in opciones])
elif default_action == 1:
seleccion = 0
elif default_action == 2:
seleccion = len(video_urls) - 1
elif default_action == 3:
seleccion = seleccion
else:
seleccion = 0
if seleccion > -1:
logger.info("seleccion=%d" % seleccion)
logger.info("seleccion=%s" % opciones[seleccion].option)
selecteditem = opciones[seleccion]
del selecteditem.option
run(opciones[seleccion])
return
# play_video, Llama a la función especifica de la plataforma para reproducir
def play_video(item):
platformtools.play_video(item)

View File

@@ -1,53 +0,0 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# logger for mediaserver
# ------------------------------------------------------------
import logging
import logging.config
import os
import config
class ExtendedLogger(logging.Logger):
def findCaller(self):
f = logging.currentframe().f_back.f_back
rv = "(unknown file)", 0, "(unknown function)"
while hasattr(f, "f_code"):
co = f.f_code
filename = os.path.normcase(co.co_filename)
if "logger" in filename: # This line is modified.
f = f.f_back
continue
filename = filename + " " + co.co_name
rv = (filename, f.f_lineno, co.co_name)
break
return rv
logging.setLoggerClass(ExtendedLogger)
logging.basicConfig(level=logging.DEBUG,
format='%(levelname)-5s %(asctime)s [%(filename)-40s] %(message)s',
datefmt="%d/%m/%y-%H:%M:%S",
filename=os.path.join(config.get_data_path(), "alfa.log"),
filemode='w')
logger_object = logging.getLogger("mediaserver")
def info(texto=""):
if config.get_setting("debug"):
logger_object.info(unicode(str(texto), "utf-8", "ignore").replace("\n", "\n" + " " * 67))
def debug(texto=""):
if config.get_setting("debug"):
logger_object.debug(unicode(str(texto), "utf-8", "ignore").replace("\n", "\n" + " " * 67))
def error(texto=""):
logger_object.error(unicode(str(texto), "utf-8", "ignore").replace("\n", "\n" + " " * 67))
class WebErrorException(Exception):
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)

View File

@@ -1,107 +0,0 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# platformtools
# ------------------------------------------------------------
# Herramientas responsables de adaptar los diferentes
# cuadros de dialogo a una plataforma en concreto,
# en este caso Mediserver.
# version 1.3
# ------------------------------------------------------------
import threading
controllers = {}
def dialog_ok(*args, **kwargs):
id = threading.current_thread().name
return controllers[id].dialog_ok(*args, **kwargs)
def dialog_notification(*args, **kwargs):
id = threading.current_thread().name
return controllers[id].dialog_notification(*args, **kwargs)
def dialog_yesno(*args, **kwargs):
id = threading.current_thread().name
return controllers[id].dialog_yesno(*args, **kwargs)
def dialog_select(*args, **kwargs):
id = threading.current_thread().name
return controllers[id].dialog_select(*args, **kwargs)
def dialog_progress(*args, **kwargs):
id = threading.current_thread().name
return controllers[id].dialog_progress(*args, **kwargs)
def dialog_progress_bg(*args, **kwargs):
id = threading.current_thread().name
return controllers[id].dialog_progress_bg(*args, **kwargs)
def dialog_input(*args, **kwargs):
id = threading.current_thread().name
return controllers[id].dialog_input(*args, **kwargs)
def dialog_numeric(*args, **kwargs):
id = threading.current_thread().name
return controllers[id].dialog_numeric(*args, **kwargs)
def itemlist_refresh(*args, **kwargs):
id = threading.current_thread().name
return controllers[id].itemlist_refresh(*args, **kwargs)
def itemlist_update(*args, **kwargs):
id = threading.current_thread().name
return controllers[id].itemlist_update(*args, **kwargs)
def render_items(*args, **kwargs):
id = threading.current_thread().name
return controllers[id].render_items(*args, **kwargs)
def is_playing(*args, **kwargs):
id = threading.current_thread().name
return controllers[id].is_playing(*args, **kwargs)
def play_video(*args, **kwargs):
id = threading.current_thread().name
return controllers[id].play_video(*args, **kwargs)
def stop_video(*args, **kwargs):
# id = threading.current_thread().name
# return controllers[id].play_video(*args, **kwargs)
return False
def open_settings(*args, **kwargs):
id = threading.current_thread().name
return controllers[id].open_settings(*args, **kwargs)
def show_channel_settings(*args, **kwargs):
id = threading.current_thread().name
return controllers[id].show_channel_settings(*args, **kwargs)
def show_video_info(*args, **kwargs):
id = threading.current_thread().name
return controllers[id].show_video_info(*args, **kwargs)
def show_recaptcha(*args, **kwargs):
id = threading.current_thread().name
return controllers[id].show_recaptcha(*args, **kwargs)
def torrent_client_installed(show_tuple=False):
return []

File diff suppressed because one or more lines are too long

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

View File

@@ -1,7 +0,0 @@
<li onmousemove="focus_element(this.getElementsByTagName('input')[0])">
<div class="control">
<span class="name" style='color:%item_color'>%item_label</span>
<input class="checkbox" onchange="evaluate_controls(this)" onfocus="this.parentNode.className='control control_focused'" onblur="this.parentNode.className='control'" type="checkbox" id="%item_id" %item_value>
<label class="checkbox"><i></i></label>
</div>
</li>

View File

@@ -1 +0,0 @@
<a class="control_button" href="javascript:void(0)"onmouseover="focus_element(this)" onclick="change_category('%item_category')">%item_label</a>

View File

@@ -1 +0,0 @@
<ul class="settings_list" style="display:none" id="%item_id">%item_value</ul>

View File

@@ -1,5 +0,0 @@
<li>
<div>
<span class="name" style='color:%item_color'>%item_label</span>
</div>
</li>

View File

@@ -1,7 +0,0 @@
<li onmousemove="focus_element(this.getElementsByTagName('select')[0])">
<div class="control">
<span class="name" style='color:%item_color'>%item_label</span>
<select class="list" onchange="evaluate_controls(this)" name="%item_type" onfocus="this.parentNode.className='control control_focused'" onblur="this.parentNode.className='control'" id="%item_id">%item_values</select>
<label class="list"><i></i></label>
</div>
</li>

View File

@@ -1,4 +0,0 @@
<li>
<div class="separator">
</div>
</li>

View File

@@ -1,7 +0,0 @@
<li onmousemove="focus_element(this.getElementsByTagName('input')[0])">
<div class="control">
<span class="name" style='color:%item_color'>%item_label</span>
<input class="text" onchange="evaluate_controls(this)" onkeyup="evaluate_controls(this)" onfocus="this.parentNode.className='control control_focused'" onblur="this.parentNode.className='control'" onkeypress="%keypress" type="%item_type" id="%item_id" value="%item_value">
<label class="text"><i></i></label>
</div>
</li>

View File

@@ -1,10 +0,0 @@
<li class="item_banner">
<a class="item %item_class" onblur="unload_info(this)" oncontextmenu="dialog.menu('Menu','%menu_items');return false" onfocus="focused_item=this;load_info(this, 'banner')" onmouseover="focus_element(this)" href="javascript:void(0)" onclick="send_request('%item_url')">
<img class="thumbnail" onerror="this.style.visibility='hidden'">
<h3 class="label">%item_title</h3>
<label class="thumbnail">%item_thumbnail</label>
<label class="plot">%item_plot</label>
<label class="fanart">%item_fanart</label>
</a>
%item_menu
</li>

View File

@@ -1,10 +0,0 @@
<li class="item_channel">
<a class="item %item_class" onblur="unload_info(this)" oncontextmenu="dialog.menu('Menu','%menu_items');return false" onfocus="focused_item=this;load_info(this, 'channel')" onmouseover="focus_element(this)" href="javascript:void(0)" onclick="send_request('%item_url')">
<h3 class="label">%item_title</h3>
<img class="thumbnail" onerror="this.style.visibility='hidden'" onload="this.parentNode.children[0].style.visibility='hidden'">
<label class="thumbnail">%item_thumbnail</label>
<label class="plot">%item_plot</label>
<label class="fanart">%item_fanart</label>
</a>
%item_menu
</li>

View File

@@ -1,10 +0,0 @@
<li class="item_list">
<a class="item %item_class" onblur="unload_info(this)" oncontextmenu="dialog.menu('Menu','%menu_items');return false" onfocus="focused_item=this;load_info(this, 'list')" onmouseover="focus_element(this)" href="javascript:void(0)" onclick="send_request('%item_url')">
<h3 class="label">%item_title</h3>
<img class="thumbnail" onerror="image_error(this)">
<label class="thumbnail">%item_thumbnail</label>
<label class="plot">%item_plot</label>
<label class="fanart">%item_fanart</label>
</a>
%item_menu
</li>

View File

@@ -1 +0,0 @@
<a class="item_menu" href="javascript:void(0)" onmouseover="focus_element(this)" onclick="focused_item=this;dialog.menu('Menu','%menu_items')"></a>

View File

@@ -1,10 +0,0 @@
<li class="item_movie">
<a class="item %item_class" onblur="unload_info(this)" oncontextmenu="dialog.menu('Menu','%menu_items');return false" onfocus="focused_item=this;load_info(this, 'movie')" onmouseover="focus_element(this)" href="javascript:void(0)" onclick="send_request('%item_url')">
<h3 class="label">%item_title</h3>
<img class="thumbnail" onerror="image_error(this)">
<label class="thumbnail">%item_thumbnail</label>
<label class="plot">%item_plot</label>
<label class="fanart">%item_fanart</label>
</a>
%item_menu
</li>

View File

@@ -1,6 +0,0 @@
<object class="media_player" data="http://releases.flowplayer.org/swf/flowplayer-3.2.18.swf" type="application/x-shockwave-flash">
<param name="movie" value="http://releases.flowplayer.org/swf/flowplayer-3.2.18.swf" />
<param name="allowfullscreen" value="true" />
<param name="allowscriptaccess" value="always" />
<param name="flashvars" value='config={"clip":{"url":"%video_url"},"playlist":[{"url":"%video_url"}]}' />
</object>

View File

@@ -1 +0,0 @@
<video class="media_player" id="media_player" type="application/x-mplayer2" autoplay="true" controls="true" src="%video_url"/>

View File

@@ -1,7 +0,0 @@
<object class="media_player" classid="clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921" codebase="http://downloads.videolan.org/pub/videolan/vlc/latest/win32/axvlc.cab" id="vlc" events="False">
<param name="Src" value="%video_url"></param>
<param name="ShowDisplay" value="True"></param>
<param name="AutoLoop" value="no"></param>
<param name="AutoPlay" value="yes"></param>
<embed type="application/x-google-vlc-plugin" name="vlcfirefox" autoplay="yes" loop="no" width="100%" height="100%" target="%video_url"></embed>
</object>

View File

@@ -1,5 +0,0 @@
<li class="item">
<a href="javascript:void(0)" onmouseover="focus_element(this)" onclick="dialog.closeall(); %item_action">
<h3>%item_title</h3>
</a>
</li>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 85 KiB

View File

@@ -1,503 +0,0 @@
loading.close = function () {
var el = document.getElementById("window_loading");
if (el.style.display == "block") {
el.style.display = "none";
document.getElementById("window_overlay").style.display = "none";
if (focused_item) {
focused_item.focus();
}
else if (document.getElementById("itemlist").children.length) {
document.getElementById("itemlist").children[0].children[0].focus();
};
};
};
loading.show = function (message) {
if (!message) {
message = "Cargando...";
};
var el = document.getElementById("window_loading");
el.getElementById("loading_message").innerHTML = message;
document.getElementById("window_overlay").style.display = "block";
el.style.display = "block";
el.getElementById("loading_message").focus();
center_window(el);
};
dialog.closeall = function () {
document.getElementById('window_overlay').style.display = 'none';
document.getElementById("window_loading").style.display = "none";
document.getElementById("window_select").style.display = "none";
document.getElementById("window_settings").style.display = "none";
document.getElementById("window_settings").style.display = "none";
document.getElementById("window_player").style.display = "none";
document.getElementById("window_player").getElementById("media_content").innerHTML = '';
document.getElementById("window_ok").style.display = "none";
document.getElementById("window_yesno").style.display = "none";
document.getElementById("window_input").style.display = "none";
document.getElementById("window_recaptcha").style.display = "none";
document.getElementById("window_progress").style.display = "none";
document.getElementById("window_info").style.display = "none";
if (focused_item) {
focused_item.focus();
}
else if (document.getElementById("itemlist").children.length) {
document.getElementById("itemlist").children[0].children[0].focus();
};
};
dialog.menu = function (title, list) {
dialog.closeall();
if (list) {
var el = document.getElementById("window_select")
el.getElementById("window_heading").innerHTML = title;
el.getElementById("control_list").innerHTML = atob(list);
el.style.display = "block";
document.getElementById("window_overlay").style.display = "block";
el.getElementById("control_list").children[0].children[0].focus();
center_window(el);
};
};
dialog.select = function (id, data) {
dialog.closeall();
var el = document.getElementById("window_select");
el.getElementById("window_heading").innerHTML = data.title;
el.RequestID = id;
var lista = [];
for (var x in data.list) {
lista.push(replace_list(html.dialog.select.item, {
"item_title": data.list[x],
"item_action": "send_data({'id':'" + id + "', 'result':" + x + "})"
}));
};
el.getElementById("control_list").innerHTML = lista.join("");
el.style.display = "block";
document.getElementById("window_overlay").style.display = "block";
el.getElementById("control_list").children[0].children[0].focus();
center_window(el);
};
dialog.player = function (title, player) {
dialog.closeall();
var el = document.getElementById("window_player");
el.getElementById("window_heading").innerHTML = title;
el.getElementById("media_content").innerHTML = player;
el.style.display = "block";
document.getElementById("window_overlay").style.display = "block";
el.children[0].focus();
center_window(el);
};
dialog.ok = function (id, data) {
dialog.closeall();
var el = document.getElementById("window_ok");
document.getElementById("window_overlay").style.display = "block";
el.style.display = "block";
el.RequestID = id;
el.getElementById("window_message").innerHTML = data.text.replace(new RegExp("\n", 'g'), "<br/>");
el.getElementById("window_heading").innerHTML = data.title;
el.getElementById("window_footer").children[0].focus();
center_window(el);
};
dialog.yesno = function (id, data) {
dialog.closeall();
var el = document.getElementById("window_yesno");
document.getElementById("window_overlay").style.display = "block";
el.style.display = "block";
el.RequestID = id;
el.getElementById("window_message").innerHTML = data.text.replace(new RegExp("\n", 'g'), "<br/>");
el.getElementById("window_heading").innerHTML = data.title;
el.getElementById("window_footer").children[0].focus();
center_window(el);
};
dialog.notification = function (id, data) {
var el = document.getElementById("window_notification");
el.style.display = "block";
if (!data.icon){data.icon = 0}
el.getElementById("window_heading").innerHTML = data.title;
el.getElementById("window_message").innerHTML = data.text;
el.getElementById("window_icon").className = "window_icon" + data.icon;
auto_scroll(el.getElementById("window_message"))
setTimeout(function(){ el.style.display = "none"; }, data.time);
};
dialog.keyboard = function (id, data) {
dialog.closeall();
var el = document.getElementById("window_input");
if (data.title === "") {
data.title = "Teclado";
};
if (data.password == true) {
el.getElementById("window_value").type = "password";
}
else {
el.getElementById("window_value").type = "text";
};
el.RequestID = id;
document.getElementById("window_overlay").style.display = "block";
el.style.display = "block";
el.getElementById("window_value").value = data.text;
el.getElementById("window_heading").innerHTML = data.title;
el.getElementById("window_value").focus();
center_window(el);
};
dialog.recaptcha = function (id, data) {
dialog.closeall();
var el = document.getElementById("window_recaptcha");
if (data.title === "") {
data.title = "Introduce el texto de la imagen";
};
el.RequestID = id;
document.getElementById("window_overlay").style.display = "block";
el.style.display = "block";
el.getElementById("window_image").style.backgroundImage = "url(" + data.image + ")";
el.getElementById("window_heading").innerHTML = data.title;
el.getElementById("window_message").innerHTML = data.message;
for (var x in [0,1,2,3,4,5,6,7,8]) {
el.getElementById("window_image").children[x].className = "";
}
el.getElementById("window_footer").children[0].focus();
center_window(el);
};
dialog.recaptcha_select = function (id, data) {
var el = document.getElementById("window_recaptcha");
console.log(data.selected)
console.log(data.unselected)
for (var x in data.selected) {
el.getElementById("window_image").children[data.selected[x]].className = "selected";
}
for (var x in data.unselected) {
el.getElementById("window_image").children[data.unselected[x]].className = "";
}
};
dialog.progress_bg = function (id, data) {
var el = document.getElementById("window_background_progress");
el.style.display = "block";
el.RequestID = id;
el.getElementById("window_message").innerHTML = data.text.replace(new RegExp("\n", 'g'), "<br/>");
el.getElementById("window_heading").innerHTML = data.title;
el.getElementById("progressbar").style.width = data.percent + "%";
};
dialog.progress_bg_close = function () {
document.getElementById("window_background_progress").style.display = "none";
};
dialog.progress = function (id, data) {
var el = document.getElementById("window_progress");
if (id != el.RequestID) {
dialog.closeall();
};
el.RequestID = id;
document.getElementById("window_overlay").style.display = "block";
el.style.display = "block";
el.getElementById("window_message").innerHTML = data.text.replace(new RegExp("\n", 'g'), "<br/>");
el.getElementById("window_heading").innerHTML = data.title;
el.getElementById("canceled").checked = "";
el.getElementById("progress").style.width = data.percent + "%";
el.getElementById("window_footer").children[0].focus;
center_window(el);
};
dialog.progress_update = function (id, data) {
var el = document.getElementById("window_progress");
el.getElementById("window_message").innerHTML = data.text.replace(new RegExp("\n", 'g'), "<br/>");
if (el.getElementById("canceled").checked != "") {
el.getElementById("window_heading").innerHTML = data.title + " " + data.percent + "% - Cancelando...";
}
else {
el.getElementById("window_heading").innerHTML = data.title + " " + data.percent + "%";
};
el.getElementById("progress").style.width = data.percent + "%";
};
dialog.progress_close = function () {
dialog.closeall();
};
dialog.custom_button = function(id, data) {
var el = document.getElementById("window_settings");
el.RequestID = id;
if (data.return_value.label){
el.getElementById("custom_button").innerHTML = data.return_value.label
};
var controls = document.getElementById("window_settings").getControls();
for (var x in controls) {
switch (controls[x].type) {
case "text":
controls[x].value = data.values[controls[x].id];
break;
case "password":
controls[x].value = data.values[controls[x].id];
break;
case "checkbox":
value = data.values[controls[x].id];
if (value == true) {
value = "checked";
}
else {
value = "";
};
controls[x].checked = value;
break;
case "select-one":
if (controls[x].name == "enum") {
controls[x].selectedIndex = data.values[controls[x].id];
}
else if (controls[x].name == "labelenum") {
controls[x].value = data.values[controls[x].id];
};
break;
};
controls[x].onchange()
};
};
dialog.config = function (id, data, Secciones, Lista) {
dialog.closeall();
var el = document.getElementById("window_settings");
el.RequestID = id;
el.getElementById("controls_container").innerHTML = Lista;
el.getElementById("window_heading").innerHTML = data.title;
if (data.custom_button != null) {
if (!data.custom_button.visible) {
el.getElementById("custom_button").style.display = "none"
}
else {
el.getElementById("custom_button").style.display = "inline";
el.getElementById("custom_button").innerHTML = data.custom_button.label;
el.getElementById("custom_button").onclick = function () {
custom_button(data.custom_button);
};
};
}
else {
el.getElementById("custom_button").style.display = "inline";
el.getElementById("custom_button").innerHTML = "Por defecto";
el.getElementById("custom_button").onclick = function () {
custom_button(null);
};
};
if (Secciones != "") {
el.getElementById("category_container").innerHTML = Secciones;
el.getElementById("category_container").style.display = "block";
el.getElementById("category_General").style.display = "block";
}
else {
el.getElementById("category_container").style.display = "none";
el.getElementById("category_undefined").style.display = "block";
};
el.getElementById("window_footer").style.display = "block";
el.getElementById("window_footer_local").style.display = "none";
document.getElementById("window_overlay").style.display = "block";
el.style.display = "block";
if (Secciones != "") {
el.getElementById("category_container").children[0].focus();
el.getElementById("category_General").scrollTop = 0;
}
else {
el.getElementById("window_footer").children[0].focus();
el.getElementById("category_undefined").scrollTop = 0;
};
center_window(el);
};
dialog.settings = function () {
dialog.closeall();
var el = document.getElementById("window_settings");
el.getElementById("window_heading").innerHTML = "Ajustes";
var controls = [];
controls.push(replace_list(html.config.label, {
"item_color": "#FFFFFF",
"item_label": "Navegación:"
}));
if (settings.builtin_history) {
var value = "checked=checked";
}
else {
var value = "";
};
controls.push(replace_list(html.config.bool, {
"item_color": "#FFFFFF",
"item_label": "Usar navegación del explorador",
"item_id": "builtin_history",
"item_value": value
}));
controls.push(replace_list(html.config.label, {
"item_color": "#FFFFFF",
"item_label": "Visualización:"
}));
if (settings.show_fanart) {
var value = "checked=checked";
}
else {
var value = "";
};
controls.push(replace_list(html.config.bool, {
"item_color": "#FFFFFF",
"item_label": "Mostrar Fanarts",
"item_id": "show_fanart",
"item_value": value
}));
controls.push(replace_list(html.config.label, {
"item_color": "#FFFFFF",
"item_label": "Reproducción:"
}));
var options = ["<option>Preguntar</option>", "<option>Indirecto</option>", "<option>Directo</option>"];
options[settings.play_mode] = options[settings.play_mode].replace("<option>", "<option selected=selected>");
controls.push(replace_list(html.config.list, {
"item_type": "enum",
"item_color": "#FFFFFF",
"item_label": "Método de reproduccion:",
"item_id": "play_mode",
"item_values": options.join("")
}));
options = ["<option>Preguntar</option>"];
for (var player in players) {
options.push("<option>" + players[player] + "</option>");
};
options[settings.player_mode] = options[settings.player_mode].replace("<option>", "<option selected=selected>");
controls.push(replace_list(html.config.list, {
"item_type": "enum",
"item_color": "#FFFFFF",
"item_label": "Reproductor:",
"item_id": "player_mode",
"item_values": options.join("")
}));
el.getElementById("controls_container").innerHTML = replace_list(html.config.container, {
"item_id": "category_all",
"item_value": controls.join("").replace(/evaluate_controls\(this\)/g, '')
});
el.getElementById("category_container").style.display = "none";
el.getElementById("category_all").style.display = "block";
el.getElementById("window_footer").style.display = "none";
el.getElementById("window_footer_local").style.display = "block";
document.getElementById("window_overlay").style.display = "block";
el.style.display = "block";
el.children[0].focus();
center_window(el);
};
dialog.info = function (id, data) {
dialog.closeall();
var el = document.getElementById("window_info");
el.RequestID = id;
el.getElementById("window_heading").innerHTML = data.title;
el.getElementById("info_fanart").src = data.fanart;
el.getElementById("info_poster").src = data.thumbnail;
if (data.buttons) {
el.getElementById("window_footer").style.display = "block";
el.getElementById("page_info").innerHTML = data.count;
if (data.previous) {
el.getElementById("previous").onclick = function () {
info_window('previous');
};
el.getElementById("previous").className = "control_button";
el.getElementById("previous").disabled = false;
}
else {
el.getElementById("previous").onclick = "";
el.getElementById("previous").className = "control_button disabled";
el.getElementById("previous").disabled = true;
};
if (data.next) {
el.getElementById("next").onclick = function () {
info_window('next');
};
el.getElementById("next").className = "control_button";
el.getElementById("next").disabled = false;
}
else {
el.getElementById("next").onclick = "";
el.getElementById("next").className = "control_button disabled";
el.getElementById("next").disabled = true;
};
}
else {
el.getElementById("window_footer").style.display = "none";
};
el.getElementById("line1_head").innerHTML = data["lines"][0]["title"];
el.getElementById("line2_head").innerHTML = data["lines"][1]["title"];
el.getElementById("line3_head").innerHTML = data["lines"][2]["title"];
el.getElementById("line4_head").innerHTML = data["lines"][3]["title"];
el.getElementById("line5_head").innerHTML = data["lines"][4]["title"];
el.getElementById("line6_head").innerHTML = data["lines"][5]["title"];
el.getElementById("line7_head").innerHTML = data["lines"][6]["title"];
el.getElementById("line8_head").innerHTML = data["lines"][7]["title"];
el.getElementById("line1").innerHTML = data["lines"][0]["text"];
el.getElementById("line2").innerHTML = data["lines"][1]["text"];
el.getElementById("line3").innerHTML = data["lines"][2]["text"];
el.getElementById("line4").innerHTML = data["lines"][3]["text"];
el.getElementById("line5").innerHTML = data["lines"][4]["text"];
el.getElementById("line6").innerHTML = data["lines"][5]["text"];
el.getElementById("line7").innerHTML = data["lines"][6]["text"];
el.getElementById("line8").innerHTML = data["lines"][7]["text"];
if (el.style.display == "block") {
update = true;
}
else {
update = false;
};
document.getElementById("window_overlay").style.display = "block";
el.style.display = "block";
auto_scroll(el.getElementById("line1"));
auto_scroll(el.getElementById("line2"));
auto_scroll(el.getElementById("line3"));
auto_scroll(el.getElementById("line4"));
auto_scroll(el.getElementById("line5"));
auto_scroll(el.getElementById("line6"));
auto_scroll(el.getElementById("line7"));
auto_scroll(el.getElementById("line8"));
if (data["buttons"]) {
if (!update) {
el.getElementById("window_footer").children[3].focus();
};
}
else {
el.children[0].focus();
};
center_window(el);
};

View File

@@ -1,107 +0,0 @@
HTMLElement.prototype.getElementById = function(id) {
if (this.querySelector("#" + id)) {
return this.querySelector("#" + id);
};
for (var x = 0; x < this.children.length; x++) {
if (this.children[x].id == id) {
return this.children[x];
};
};
for (var x = 0; x < this.children.length; x++) {
result = this.children[x].getElementById(id);
if (result != null) {
return result;
};
};
return null;
};
HTMLElement.prototype.getControls = function() {
return [].concat(Array.prototype.slice.call(this.getElementsByTagName("input")), Array.prototype.slice.call(this.getElementsByTagName("select")));
};
window.onload = function() {
var url = (window.location.href.split("#")[1] ? window.location.href.split("#")[1] : "");
dispose();
loading.show("Cargando pagina...");
ajax_running.remove = function(val) {
if (this.indexOf(val) > -1) {
this.splice(this.indexOf(val), 1);
};
if (!this.length && !websocket) {
send_request(url);
};
};
load_settings();
dowload_files();
};
window.onpopstate = function(e) {
if (e.state) {
nav_history.go(e.state - nav_history.current);
};
};
window.onresize = function() {
dispose();
};
window.getCookie = function(name) {
var match = document.cookie.match(new RegExp(name + '=([^;]+)'));
if (match) return match[1];
};
function load_settings() {
settings["play_mode"] = (window.getCookie("play_mode") ? parseInt(window.getCookie("play_mode")) : 0);
settings["player_mode"] = (window.getCookie("player_mode") ? parseInt(window.getCookie("player_mode")) : 0);
settings["show_fanart"] = (window.getCookie("show_fanart") == "false" ? false : true);
settings["builtin_history"] = (window.getCookie("builtin_history") == "true" ? true : false);
};
function save_settings() {
var controls = document.getElementById("window_settings").getControls();
for (var x in controls) {
switch (controls[x].type) {
case "text":
case "password":
save_setting(controls[x].id, controls[x].value);
break;
case "checkbox":
save_setting(controls[x].id, controls[x].checked);
break;
case "select-one":
save_setting(controls[x].id, controls[x].selectedIndex);
break;
};
};
load_settings();
};
function save_setting(id, value) {
document.cookie = id + "=" + value + '; expires=Fri, 31 Dec 9999 23:59:59 GMT';
};
function dowload_files() {
ajax_to_dict("/media/html/player_vlc.html", html, "vlc_player");
ajax_to_dict("/media/html/player_html.html", html, "html_player");
ajax_to_dict("/media/html/player_flash.html", html, "flash_player");
ajax_to_dict("/media/html/itemlist_banner.html", html, "itemlist.banner");
ajax_to_dict("/media/html/itemlist_channel.html", html, "itemlist.channel");
ajax_to_dict("/media/html/itemlist_movie.html", html, "itemlist.movie");
ajax_to_dict("/media/html/itemlist_list.html", html, "itemlist.list");
ajax_to_dict("/media/html/itemlist_menu.html", html, "itemlist.menu");
ajax_to_dict("/media/html/select_item.html", html, "dialog.select.item");
ajax_to_dict("/media/html/config_label.html", html, "config.label");
ajax_to_dict("/media/html/config_sep.html", html, "config.sep");
ajax_to_dict("/media/html/config_text.html", html, "config.text");
ajax_to_dict("/media/html/config_bool.html", html, "config.bool");
ajax_to_dict("/media/html/config_list.html", html, "config.list");
ajax_to_dict("/media/html/config_category.html", html, "config.category");
ajax_to_dict("/media/html/config_container.html", html, "config.container");
};

View File

@@ -1,739 +0,0 @@
window.onkeydown = function (e) {
if (e.keyCode == 27) {
dialog.closeall()
}
if (e.target.tagName == "BODY") {
body_events(e);
};
if (document.getElementById("window_loading").contains(e.target)) {
window_loading_events(e);
};
if (document.getElementById("window_settings").contains(e.target)) {
window_settings_events(e);
};
if (document.getElementById("window_select").contains(e.target)) {
window_select_events(e);
};
if (document.getElementById("window_ok").contains(e.target)) {
window_generic_events(e);
};
if (document.getElementById("window_yesno").contains(e.target)) {
window_generic_events(e);
};
if (document.getElementById("window_recaptcha").contains(e.target)) {
window_recaptcha_events(e);
};
if (document.getElementById("window_progress").contains(e.target)) {
window_generic_events(e);
};
if (document.getElementById("window_info").contains(e.target)) {
window_generic_events(e);
}
if (document.getElementById("window_input").contains(e.target)) {
window_input_events(e);
};
if (document.getElementById("itemlist").contains(e.target)) {
itemlist_events(e);
};
};
function itemlist_events(e) {
var el = document.getElementById('itemlist');
switch (e.keyCode) {
case 96:
case 97:
case 98:
case 99:
case 100:
case 101:
case 102:
case 103:
case 104:
case 105:
numeric_search(e.keyCode);
break;
case 93: //Menu
e.preventDefault();
if (e.target.parentNode.children.length == 2) {
e.target.parentNode.children[1].onclick.apply(e.target.parentNode.children[1]);
focused_item = e.target.parentNode.children[1];
};
break;
case 8: //BACK
e.preventDefault();
if (nav_history.current > 0) {
send_request("go_back");
};
break;
case 37: //LEFT
e.preventDefault();
var index = Array.prototype.indexOf.call(e.target.parentNode.children, e.target);
if (index > 0){
e.target.parentNode.children[index - 1].focus();
};
break;
case 38: //UP
e.preventDefault();
var index = Array.prototype.indexOf.call(el.children, e.target.parentNode);
if (index == 0) {
index = el.children.length;
};
el.children[index - 1].children[0].focus();
break;
case 39: //RIGHT
e.preventDefault();
var index = Array.prototype.indexOf.call(e.target.parentNode.children, e.target);
if (index < e.target.parentNode.children.length - 1){
e.target.parentNode.children[index + 1].focus();
};
break;
case 40: //DOWN
e.preventDefault();
var index = Array.prototype.indexOf.call(el.children, e.target.parentNode);
if (index + 1 == el.children.length) {
index = -1;
};
el.children[index + 1].children[0].focus();
break;
};
};
function window_loading_events(e) {
switch (e.keyCode) {
case 8: //BACK
loading.close();
connection_retry = false;
e.preventDefault();
break;
};
};
function body_events(e) {
switch (e.keyCode) {
case 8: //BACK
e.preventDefault();
break;
case 37: //LEFT
case 38: //UP
case 39: //RIGHT
case 40: //DOWN
e.preventDefault();
document.getElementById("itemlist").children[0].children[0].focus();
break;
};
};
function window_generic_events(e) {
var el = (document.getElementById("window_ok").contains(e.target) ? document.getElementById("window_ok") : el);
var el = (document.getElementById("window_yesno").contains(e.target) ? document.getElementById("window_yesno") : el);
var el = (document.getElementById("window_progress").contains(e.target) ? document.getElementById("window_progress") : el);
var el = (document.getElementById("window_info").contains(e.target) ? document.getElementById("window_info") : el);
switch (e.keyCode) {
case 8: //BACK
e.preventDefault();
dialog.closeall();
break;
case 38: //UP
e.preventDefault();
if (el.getElementById("window_footer").contains(e.target)) {
el.children[0].focus();
};
break;
case 37: //LEFT
e.preventDefault();
if (el.getElementById("window_footer").contains(e.target)) {
var index = Array.prototype.indexOf.call(el.getElementById("window_footer").children, e.target) -1;
while (index >= 0 && el.getElementById("window_footer").children[index].disabled){
index --;
};
if (index >=0){
el.getElementById("window_footer").children[index].focus();
};
};
break;
case 39: //RIGHT
e.preventDefault();
if (el.getElementById("window_footer").contains(e.target)) {
var index = Array.prototype.indexOf.call(el.getElementById("window_footer").children, e.target) +1;
while (index < el.getElementById("window_footer").children.length && el.getElementById("window_footer").children[index].disabled){
index ++;
};
if (index < el.getElementById("window_footer").children.length){
el.getElementById("window_footer").children[index].focus();
};
};
break;
case 40: //DOWN
e.preventDefault();
if (e.target.parentNode == el) {
el.getElementById("window_footer").children[0].focus();
};
break;
};
};
function window_recaptcha_events(e) {
var el = document.getElementById("window_recaptcha");
switch (e.keyCode) {
case 8: //BACK
e.preventDefault();
dialog.closeall();
break;
case 38: //UP
e.preventDefault();
if (el.getElementById("window_footer").contains(e.target)) {
el.getElementById("window_image").children[el.getElementById("window_image").children.length -1].focus();
}
else {
var index = Array.prototype.indexOf.call(el.getElementById("window_image").children, e.target) -3;
if (index >-1) {
el.getElementById("window_image").children[index].focus();
}
else {
el.children[0].focus();
};
};
break;
case 37: //LEFT
e.preventDefault();
if (el.getElementById("window_footer").contains(e.target)) {
var index = Array.prototype.indexOf.call(el.getElementById("window_footer").children, e.target) -1;
while (index >= 0 && el.getElementById("window_footer").children[index].disabled){
index --;
};
if (index >=0){
el.getElementById("window_footer").children[index].focus();
};
} else if (e.target.parentNode == el.getElementById("window_image")) {
var index = Array.prototype.indexOf.call(el.getElementById("window_image").children, e.target) -1;
if ([-1,2,5].indexOf(index) == -1) {
el.getElementById("window_image").children[index].focus();
};
};
break;
case 39: //RIGHT
e.preventDefault();
if (el.getElementById("window_footer").contains(e.target)) {
var index = Array.prototype.indexOf.call(el.getElementById("window_footer").children, e.target) +1;
while (index < el.getElementById("window_footer").children.length && el.getElementById("window_footer").children[index].disabled){
index ++;
};
if (index < el.getElementById("window_footer").children.length){
el.getElementById("window_footer").children[index].focus();
};
} else if (e.target.parentNode == el.getElementById("window_image")) {
var index = Array.prototype.indexOf.call(el.getElementById("window_image").children, e.target) +1;
if ([3,6,9].indexOf(index) == -1) {
el.getElementById("window_image").children[index].focus();
};
};
break;
case 40: //DOWN
e.preventDefault();
if (e.target.parentNode == el) {
el.getElementById("window_image").children[0].focus();
}
else if (e.target.parentNode == el.getElementById("window_image")) {
var index = Array.prototype.indexOf.call(el.getElementById("window_image").children, e.target) +3;
if (index < el.getElementById("window_image").children.length) {
el.getElementById("window_image").children[index].focus();
}
else {
el.getElementById("window_footer").children[0].focus();
};
};
break;
};
};
function window_select_events(e) {
var el = document.getElementById('window_select');
switch (e.keyCode) {
case 8: //BACK
e.preventDefault();
dialog.closeall();
break;
case 38: //UP
e.preventDefault();
var index = Array.prototype.indexOf.call(el.getElementById("control_list").children, e.target.parentNode);
if (index != 0) {
el.getElementById("control_list").children[index - 1].children[0].focus();
}
else {
el.children[0].focus();
};
break;
case 40: //DOWN
e.preventDefault();
if (e.target.parentNode == el) {
el.getElementById("control_list").children[0].children[0].focus();
}
else {
var index = Array.prototype.indexOf.call(el.getElementById("control_list").children, e.target.parentNode);
el.getElementById("control_list").children[index + 1].children[0].focus();
};
break;
};
};
function window_settings_events(e) {
el = document.getElementById('window_settings');
switch (e.keyCode) {
case 8: //BACK
if ((e.target.tagName != "INPUT" || (e.target.type != "text" && e.target.type != "password")) && e.target.tagName != "SELECT") {
e.preventDefault();
dialog.closeall();
};
break;
case 38: //UP
e.preventDefault();
if (e.target.parentNode == el) {
return;
};
if (el.getElementById("category_container").contains(e.target)) {
el.children[0].focus();
return;
}
else if (el.getElementById("window_footer").contains(e.target) || el.getElementById("window_footer_local").contains(e.target)) {
var index = null;
var group = null;
}
else if (el.getElementById("controls_container").contains(e.target)) {
var group = Array.prototype.indexOf.call(el.getElementById("controls_container").children, e.target.parentNode.parentNode.parentNode);
var index = Array.prototype.indexOf.call(el.getElementById("controls_container").children[group].children, e.target.parentNode.parentNode) - 1;
};
if (group == null) {
for (group = 0; group < el.getElementById("category_container").children.length; group++) {
if (el.getElementById("category_container").children[group].style.display != "none") {
break;
};
};
};
if (index == null) {
index = el.getElementById("controls_container").children[group].children.length - 1;
};
while (index >= 0 &&
(el.getElementById("controls_container").children[group].children[index].children[0].className != "control" ||
el.getElementById("controls_container").children[group].children[index].children[0].children[1].disabled ||
el.getElementById("controls_container").children[group].children[index].style.display == "none")) {
index--;
};
if (index >= 0) {
el.getElementById("controls_container").children[group].children[index].children[0].children[1].focus();
}
else {
if (el.getElementById("category_container").style.display == "none") {
el.children[0].focus();
}
else {
el.getElementById("category_container").children[0].focus();
};
};
break;
case 37: //LEFT
if ((e.target.tagName != "INPUT" || (e.target.type != "text" && e.target.type != "password")) && e.target.tagName != "SELECT") {
e.preventDefault();
if (el.getElementById("category_container").contains(e.target)) {
var index = Array.prototype.indexOf.call(el.getElementById("category_container").children, e.target);
el.getElementById("category_container").children[index - 1].focus();
}
else if (el.getElementById("window_footer").contains(e.target)) {
var index = Array.prototype.indexOf.call(el.getElementById("window_footer").children, e.target);
el.getElementById("window_footer").children[index - 1].focus();
}
else if (el.getElementById("window_footer_local").contains(e.target)) {
var index = Array.prototype.indexOf.call(el.getElementById("window_footer_local").children, e.target);
el.getElementById("window_footer_local").children[index - 1].focus();
};
};
break;
case 39: //RIGHT
if ((e.target.tagName != "INPUT" || (e.target.type != "text" && e.target.type != "password")) && e.target.tagName != "SELECT") {
e.preventDefault();
if (el.getElementById("category_container").contains(e.target)) {
var index = Array.prototype.indexOf.call(el.getElementById("category_container").children, e.target);
el.getElementById("category_container").children[index + 1].focus();
}
else if (el.getElementById("window_footer").contains(e.target)) {
var index = Array.prototype.indexOf.call(el.getElementById("window_footer").children, e.target);
el.getElementById("window_footer").children[index + 1].focus();
}
else if (el.getElementById("window_footer_local").contains(e.target)) {
var index = Array.prototype.indexOf.call(el.getElementById("window_footer_local").children, e.target);
el.getElementById("window_footer_local").children[index + 1].focus();
};
};
break;
case 40: //DOWN
e.preventDefault();
if (e.target.parentNode == el) {
if (el.getElementById("category_container").style.display == "none") {
var index = 0;
var group = null;
}
else {
el.getElementById("category_container").children[0].focus();
};
}
else if (el.getElementById("category_container").contains(e.target)) {
var index = 0;
var group = null;
}
else if (el.getElementById("controls_container").contains(e.target)) {
var group = Array.prototype.indexOf.call(el.getElementById("controls_container").children, e.target.parentNode.parentNode.parentNode);
var index = Array.prototype.indexOf.call(el.getElementById("controls_container").children[group].children, e.target.parentNode.parentNode) + 1;
};
if (group == null) {
for (group = 0; group < el.getElementById("category_container").children.length; group++) {
if (el.getElementById("category_container").children[group].style.display != "none") {
break;
};
};
};
while (index < el.getElementById("controls_container").children[group].children.length &&
(el.getElementById("controls_container").children[group].children[index].children[0].className != "control" ||
el.getElementById("controls_container").children[group].children[index].children[0].children[1].disabled ||
el.getElementById("controls_container").children[group].children[index].style.display == "none")) {
index++;
};
if (index < el.getElementById("controls_container").children[group].children.length) {
el.getElementById("controls_container").children[group].children[index].children[0].children[1].focus();
}
else {
el.getElementById("window_footer").children[0].focus();
el.getElementById("window_footer_local").children[0].focus();
};
break;
};
};
function window_input_events(e) {
el = document.getElementById("window_input");
switch (e.keyCode) {
case 8: //BACK
if (e.target.tagName != "INPUT") {
e.preventDefault();
dialog.closeall();
};
break;
case 38: //UP
e.preventDefault();
if (el.getElementById("window_footer").contains(e.target)) {
el.getElementById("control_input").children[0].focus();
}
if (el.getElementById("control_input").contains(e.target)) {
el.children[0].focus();
};
break;
case 37: //LEFT
if (el.getElementById("window_footer").contains(e.target)) {
var index = Array.prototype.indexOf.call(el.getElementById("window_footer").children, e.target);
el.getElementById("window_footer").children[index - 1].focus();
e.preventDefault();
};
break;
case 39: //RIGHT
if (el.getElementById("window_footer").contains(e.target)) {
var index = Array.prototype.indexOf.call(el.getElementById("window_footer").children, e.target);
el.getElementById("window_footer").children[index + 1].focus();
e.preventDefault();
};
break;
case 40: //DOWN
e.preventDefault();
if (e.target.parentNode == el) {
el.getElementById("control_input").children[0].focus();
};
if (el.getElementById("control_input").contains(e.target)) {
el.getElementById("window_footer").children[0].focus();
};
break;
};
};
function numeric_search(keyCode) {
switch (keyCode) {
case 96:
keychar["keyCode"] = keyCode;
keychar["Char"] = "0";
break;
case 97:
keychar["keyCode"] = keyCode;
keychar["Char"] = "1";
break;
case 98:
if (keychar["keyCode"] == keyCode) {
switch (keychar["Char"]) {
case "a":
keychar["Char"] = "b";
break;
case "b":
keychar["Char"] = "c";
break;
case "c":
keychar["Char"] = "2";
break;
case "2":
keychar["Char"] = "a";
break;
};
}
else {
keychar["keyCode"] = keyCode;
keychar["Char"] = "a";
};
break;
case 99:
if (keychar["keyCode"] == keyCode) {
switch (keychar["Char"]) {
case "d":
keychar["Char"] = "e";
break;
case "e":
keychar["Char"] = "f";
break;
case "f":
keychar["Char"] = "3";
break;
case "3":
keychar["Char"] = "d";
break;
};
}
else {
keychar["keyCode"] = keyCode;
keychar["Char"] = "d";
};
break;
case 100:
if (keychar["keyCode"] == keyCode) {
switch (keychar["Char"]) {
case "g":
keychar["Char"] = "h";
break;
case "h":
keychar["Char"] = "i";
break;
case "i":
keychar["Char"] = "4";
break;
case "4":
keychar["Char"] = "g";
break;
};
}
else {
keychar["keyCode"] = keyCode;
keychar["Char"] = "g";
};
break;
case 101:
if (keychar["keyCode"] == keyCode) {
switch (keychar["Char"]) {
case "j":
keychar["Char"] = "k";
break;
case "k":
keychar["Char"] = "l";
break;
case "l":
keychar["Char"] = "5";
break;
case "5":
keychar["Char"] = "j";
break;
};
}
else {
keychar["keyCode"] = keyCode;
keychar["Char"] = "j";
};
break;
case 102:
if (keychar["keyCode"] == keyCode) {
switch (keychar["Char"]) {
case "m":
keychar["Char"] = "n";
break;
case "n":
keychar["Char"] = "o";
break;
case "o":
keychar["Char"] = "6";
break;
case "6":
keychar["Char"] = "m";
break;
};
}
else {
keychar["keyCode"] = keyCode;
keychar["Char"] = "m";
};
break;
case 103:
if (keychar["keyCode"] == keyCode) {
switch (keychar["Char"]) {
case "p":
keychar["Char"] = "q";
break;
case "q":
keychar["Char"] = "r";
break;
case "r":
keychar["Char"] = "s";
break;
case "s":
keychar["Char"] = "7";
break;
case "7":
keychar["Char"] = "p";
break;
};
}
else {
keychar["keyCode"] = keyCode;
keychar["Char"] = "p";
};
break;
case 104:
if (keychar["keyCode"] == keyCode) {
switch (keychar["Char"]) {
case "t":
keychar["Char"] = "u";
break;
case "u":
keychar["Char"] = "u";
break;
case "v":
keychar["Char"] = "8";
break;
case "8":
keychar["Char"] = "t";
break;
};
}
else {
keychar["keyCode"] = keyCode;
keychar["Char"] = "t";
};
break;
case 105:
if (keychar["keyCode"] == keyCode) {
switch (keychar["Char"]) {
case "x":
keychar["Char"] = "y";
break;
case "y":
keychar["Char"] = "z";
break;
case "z":
keychar["Char"] = "w";
break;
case "w":
keychar["Char"] = "9";
break;
case "9":
keychar["Char"] = "x";
break;
};
}
else {
keychar["keyCode"] = keyCode;
keychar["Char"] = "x";
};
break;
};
var el = document.getElementById('itemlist');
for (x = 0; x < el.children.length; x++) {
if (el.children[x].children[0].children[2].innerHTML.toLowerCase().indexOf(keychar["Char"]) === 0) {
el.children[x].children[0].focus();
break;
};
if (el.children[x].children[0].children[0].innerHTML.toLowerCase().indexOf(keychar["Char"]) === 0) {
el.children[x].children[0].focus();
break;
};
};
};
document.onkeypress = function (e) {
if ((e || window.event).keyCode === 32) {
if (media_player.paused) {
media_player.play();
}
else {
media_player.pause();
};
};
};
document.ondblclick = function () {
if (media_player.requestFullscreen) {
media_player.requestFullscreen();
}
else if (media_player.mozRequestFullScreen) {
media_player.mozRequestFullScreen();
}
else if (media_player.webkitRequestFullscreen) {
media_player.webkitRequestFullscreen();
};
};

View File

@@ -1,677 +0,0 @@
function get_response(data) {
var response = JSON.parse(data)
var data = response.data;
switch (response.action) {
case "connect":
document.getElementById("version").innerHTML = data.version;
document.getElementById("date").innerHTML = data.date;
session_id = response.id;
break;
case "EndItems":
var item_list = [];
for (var item in data.itemlist) {
context_items = [];
item = data.itemlist[item];
if (item.thumbnail && item.thumbnail.indexOf("http") != 0) {
item.thumbnail = domain + "/local/" + encodeURIComponent(btoa(item.thumbnail));
}
else if (item.thumbnail & false){
item.thumbnail = domain + "/proxy/" + encodeURIComponent(btoa(item.thumbnail));
};
if (item.fanart && item.fanart.indexOf("http") != 0) {
item.fanart = domain + "/local/" + encodeURIComponent(btoa(item.fanart));
}
else if (item.fanart & false){
item.fanart = domain + "/proxy/" + encodeURIComponent(btoa(item.fanart));
};
if (item.action == "go_back") {
item.url = "go_back";
};
if (item.context.length ) {
for (var x in item.context) {
html_item = replace_list(html.dialog.select.item, {
"item_action": "send_request('" + item.context[x].url + "')",
"item_title": item.context[x].title
});
context_items.push(html_item);
}
var menu_button = replace_list(html.itemlist.menu, {
"menu_items": btoa(context_items.join(""))
});
var menu_class = "item_with_menu";
}
else {
var menu_button = "";
var menu_class = "";
};
var replace_dict = {
"item_class": menu_class,
"item_url": item.url,
"item_thumbnail": item.thumbnail,
"item_fanart": item.fanart,
"item_title": item.title,
"item_plot": item.plot,
"item_menu": menu_button,
"menu_items": btoa(context_items.join(""))
};
if (html.itemlist[data.viewmode]) {
var html_item = replace_list(html.itemlist[data.viewmode], replace_dict);
}
else {
var html_item = replace_list(html.itemlist.movie, replace_dict);
}
item_list.push(html_item);
};
document.getElementById("itemlist").innerHTML = item_list.join("");
set_category(data.category);
document.getElementById("itemlist").children[0].children[0].focus();
document.getElementById("itemlist").scrollTop = 0;
show_images();
nav_history.newResponse(item_list, data.category, data.url);
set_original_url(data.url)
//console.debug(nav_history)
send_data({
"id": response.id,
"result": true
});
loading.close();
break;
case "Refresh":
nav_history.current -= 1
send_request(nav_history.states[nav_history.current].url);
send_data({
"id": response.id,
"result": true
});
break;
case "Alert":
loading.close();
dialog.ok(response.id, data);
break;
case "notification":
dialog.notification(response.id, data);
break;
case "AlertYesNo":
loading.close()
dialog.yesno(response.id, data)
break;
case "ProgressBG":
dialog.progress_bg(response.id, data);
send_data({
"id": response.id,
"result": true
});
break;
case "ProgressBGUpdate":
dialog.progress_bg(response.id, data);
break;
case "ProgressBGClose":
dialog.progress_bg_close();
send_data({
"id": response.id,
"result": true
});
break;
case "Progress":
loading.close();
dialog.progress(response.id, data);
send_data({
"id": response.id,
"result": true
});
break;
case "ProgressUpdate":
dialog.progress_update(response.id, data);
break;
case "ProgressClose":
dialog.progress_close();
send_data({
"id": response.id,
"result": true
});
loading.close();
break;
case "ProgressIsCanceled":
send_data({
"id": response.id,
"result": document.getElementById("window_progress").getElementById("canceled").checked != ""
});
break;
case "isPlaying":
send_data({
"id": response.id,
"result": document.getElementById("Player-popup").style.display == "block" || document.getElementById("Lista-popup").style.display == "block"
});
break;
case "Keyboard":
loading.close();
dialog.keyboard(response.id, data);
break;
case "recaptcha":
loading.close();
dialog.recaptcha(response.id, data);
break;
case "recaptcha_select":
loading.close();
dialog.recaptcha_select(response.id, data);
break
case "List":
loading.close();
dialog.select(response.id, data);
break;
case "Play":
send_data({
"id": response.id,
"result": true
});
loading.close();
if (settings.player_mode == 0) {
var lista = [];
for (var player in players) {
lista.push(replace_list(html.dialog.select.item, {
"item_title": players[player],
"item_action": "play_mode('" + data.video_url + "','" + data.title + "','" + player + "')"
}));
};
dialog.menu("Elige el Reproductor", btoa(lista.join("")));
}
else {
play_mode(data.video_url, data.title, Object.keys(players)[settings.player_mode - 1]);
};
break;
case "Update":
send_request(data.url);
loading.close();
break;
case "HideLoading":
loading.close();
break;
case "ShowLoading":
loading.show();
break;
case "OpenInfo":
loading.close();
dialog.info(response.id, data);
break;
case "custom_button":
dialog.custom_button(response.id, data);
break;
case "OpenConfig":
loading.close();
var itemlist = {};
default_settings = {};
settings_controls = [];
for (var x in data.items) {
if (!itemlist[data.items[x].category]) {
itemlist[data.items[x].category] = [];
};
if (data.items[x].id) {
default_settings[data.items[x].id] = data.items[x]["default"];
}
if (!data.items[x].color || data.items[x].color == "auto") {
data.items[x].color = "#FFFFFF";
};
if (!data.items[x].enabled && data.items[x].enable) {
data.items[x].enabled = data.items[x].enable;
};
settings_controls.push(data.items[x]);
switch (data.items[x].type) {
case "sep":
itemlist[data.items[x].category].push(replace_list(html.config.sep, {}));
break;
case "lsep":
case "label":
itemlist[data.items[x].category].push(replace_list(html.config.label, {
"item_color": data.items[x].color,
"item_label": data.items[x].label
}));
break;
case "number":
case "text":
if (data.items[x].hidden) {
var type = "password";
}
else {
var type = "text";
};
if (data.items[x].type == 'number') {
keypress = "if ('0123456789'.indexOf(event.key) == -1 && event.charCode){return false}"
}
else {
keypress = "";
};
if (!data.items[x].value) data.items[x].value = "";
itemlist[data.items[x].category].push(replace_list(html.config.text, {
"item_color": data.items[x].color,
"item_label": data.items[x].label,
"item_id": data.items[x].id,
"item_value": data.items[x].value,
"item_type": type,
"keypress": keypress
}));
break;
case "bool":
if (data.items[x].value == "true" || data.items[x].value == true) {
var value = "checked='checked'";
}
else {
var value = "";
};
itemlist[data.items[x].category].push(replace_list(html.config.bool, {
"item_color": data.items[x].color,
"item_label": data.items[x].label,
"item_id": data.items[x].id,
"item_value": value
}));
break;
case "labelenum":
if (!data.items[x].values) {
var values = data.items[x].lvalues.split("|");
}
else {
var values = data.items[x].values.split("|");
};
var options = [];
for (var y in values) {
if (data.items[x].value == values[y]) {
options.push("<option selected=selected>" + values[y] + "</option>");
}
else {
options.push("<option>" + values[y] + "</option>");
};
};
itemlist[data.items[x].category].push(replace_list(html.config.list, {
"item_type": "labelenum",
"item_color": data.items[x].color,
"item_label": data.items[x].label,
"item_id": data.items[x].id,
"item_values": options
}));
break;
case "list":
var options = [];
for (var y in data.items[x].lvalues) {
if (data.items[x].value == y) {
options.push("<option selected=selected>" + data.items[x].lvalues[y] + "</option>");
}
else {
options.push("<option>" + data.items[x].lvalues[y] + "</option>");
};
};
itemlist[data.items[x].category].push(replace_list(html.config.list, {
"item_type": "enum",
"item_color": data.items[x].color,
"item_label": data.items[x].label,
"item_id": data.items[x].id,
"item_values": options
}));
break;
case "enum":
if (!data.items[x].values) {
var values = data.items[x].lvalues.split("|");
}
else {
var values = data.items[x].values.split("|");
};
var options = [];
for (var y in values) {
if (data.items[x].value == y) {
options.push("<option selected=selected>" + values[y] + "</option>");
}
else {
options.push("<option>" + values[y] + "</option>");
};
};
itemlist[data.items[x].category].push(replace_list(html.config.list, {
"item_type": "enum",
"item_color": data.items[x].color,
"item_label": data.items[x].label,
"item_id": data.items[x].id,
"item_values": options
}));
break;
default:
break;
};
};
var categories = [];
var category_list = [];
for (var category in itemlist) {
if (Object.keys(itemlist).length > 1 || category != "undefined") {
categories.push(replace_list(html.config.category, {
"item_label": category,
"item_category": category
}));
};
category_list.push(replace_list(html.config.container, {
"item_id": "category_" + category,
"item_value": itemlist[category].join("")
}));
};
dialog.config(response.id, data, categories.join(""), category_list.join(""));
evaluate_controls();
break;
default:
break;
};
};
function custom_button(data) {
if (data == null) {
var controls = document.getElementById("window_settings").getControls();
for (var x in controls) {
switch (controls[x].type) {
case "text":
controls[x].value = default_settings[controls[x].id];
break;
case "password":
controls[x].value = default_settings[controls[x].id];
break;
case "checkbox":
value = default_settings[controls[x].id];
if (value == true) {
value = "checked";
}
else {
value = "";
};
controls[x].checked = value;
break;
case "select-one":
if (controls[x].name == "enum") {
controls[x].selectedIndex = default_settings[controls[x].id];
}
else if (controls[x].name == "labelenum") {
controls[x].value = default_settings[controls[x].id];
};
break;
};
controls[x].onchange()
};
}
else {
send_data({
"id": document.getElementById("window_settings").RequestID,
"result": "custom_button"
});
if (data["close"] == true) {
dialog.closeall();
};
};
};
function info_window(comando) {
send_data({
"id": document.getElementById("window_info").RequestID,
"result": comando
});
};
function save_config(Guardar) {
if (Guardar === true) {
var JsonAjustes = {};
var controls = document.getElementById("window_settings").getControls();
for (var x in controls) {
switch (controls[x].type) {
case "text":
JsonAjustes[controls[x].id] = controls[x].value;
break;
case "password":
JsonAjustes[controls[x].id] = controls[x].value;
break;
case "checkbox":
JsonAjustes[controls[x].id] = controls[x].checked.toString();
break;
case "select-one":
if (controls[x].name == "enum") {
JsonAjustes[controls[x].id] = controls[x].selectedIndex.toString();
}
else if (controls[x].name == "labelenum") {
JsonAjustes[controls[x].id] = controls[x].value;
}
break;
}
}
send_data({
"id": document.getElementById("window_settings").RequestID,
"result": JsonAjustes
});
}
else {
send_data({
"id": document.getElementById("window_settings").RequestID,
"result": false
});
};
loading.show();
};
function evaluate_controls(control_changed) {
if (typeof control_changed != "undefined") {
for (var x in settings_controls) {
if (settings_controls[x].id == control_changed.id) {
switch (control_changed.type) {
case "text":
settings_controls[x].value = control_changed.value;
break;
case "password":
settings_controls[x].value = control_changed.value;
break;
case "checkbox":
settings_controls[x].value = control_changed.checked;
break;
case "select-one":
if (control_changed.name == "enum") {
settings_controls[x].value = control_changed.selectedIndex;
}
else if (control_changed.name == "labelenum") {
settings_controls[x].value = control_changed.value;
};
break;
};
break;
};
};
};
for (var index in settings_controls) {
control = get_control_group(index);
set_visible(document.getElementById("window_settings").getElementById("controls_container").children[control[0]].children[control[1]], evaluate(index, settings_controls[index].visible));
set_enabled(document.getElementById("window_settings").getElementById("controls_container").children[control[0]].children[control[1]], evaluate(index, settings_controls[index].enabled));
};
};
function set_visible(element, visible) {
if (visible) {
element.style.display = "block";
}
else {
element.style.display = "none";
};
};
function set_enabled(element, enabled) {
if (element.children[0].className == "control") {
element.children[0].children[1].disabled = !enabled;
};
};
function get_control_group(index) {
var group = 0;
var pos = 0;
var children = document.getElementById("window_settings").getElementById("controls_container").children;
for (child in children) {
if (pos + children[child].children.length <= index) {
group ++;
pos += children[child].children.length;
}
else {
break;
};
};
return [group, index - pos];
};
function evaluate(index, condition) {
index = parseInt(index);
if (typeof condition == "undefined") {
return true;
};
if (typeof condition == "boolean") {
return condition;
};
if (condition.toLocaleLowerCase() == "true") {
return true;
}
else if (condition.toLocaleLowerCase() == "false") {
return false;
};
const regex = /(!?eq|!?gt|!?lt)?\(([^,]+),[\"|']?([^)|'|\"]*)['|\"]?\)[ ]*([+||])?/g;
while ((m = regex.exec(condition)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
};
var operator = m[1];
var id = parseInt(m[2]);
var value = m[3];
var next = m[4];
if (isNaN(id)) {
return false;
};
if (index + id < 0 || index + id >= settings_controls.length) {
return false;
}
else {
if (settings_controls[index + id].type == "list" || settings_controls[index + id].type == "enum") {
if (settings_controls[index + id].lvalues){
control_value = settings_controls[index + id].lvalues[settings_controls[index + id].value];
}
else {
control_value = settings_controls[index + id].values[settings_controls[index + id].value];
};
}
else {
control_value = settings_controls[index + id].value;
};
};
if (["lt", "!lt", "gt", "!gt"].indexOf(operator) > -1) {
value = parseInt(value);
if (isNaN(value)) {
return false;
};
};
if (["eq", "!eq"].indexOf(operator) > -1) {
if (typeof(value) == "string") {
if (!isNaN(parseInt(value))) {
value = parseInt(value);
}
else if (value.toLocaleLowerCase() == "true") {
value = true;
}
else if (value.toLocaleLowerCase() == "false") {
value = false;
};
};
};
if (operator == "eq") {
ok = (control_value == value);
};
if (operator == "!eq") {
ok = !(control_value == value);
};
if (operator == "gt") {
ok = (control_value > value);
};
if (operator == "!gt") {
ok = !(control_value > value);
};
if (operator == "lt") {
ok = (control_value < value);
};
if (operator == "!lt") {
ok = !(control_value < value);
};
if (next == "|" && ok == true) {
break;
};
if (next == "+" && ok == false) {
break;
};
};
return ok;
};

View File

@@ -1,79 +0,0 @@
function websocket_connect() {
if (websocket) {
websocket.close();
};
var status = document.getElementById("footer").getElementById("status");
status.innerHTML = "Conectando...";
loading.show("Estableciendo conexión...");
websocket = new WebSocket(websocket_host);
websocket.onopen = function (evt) {
loading.show();
status.innerHTML = "Conectado";
};
websocket.onclose = function (evt) {
status.innerHTML = "Desconectado";
};
websocket.onmessage = function (evt) {
get_response(evt.data);
};
websocket.onerror = function (evt) {
websocket.close();
};
};
function websocket_send(data, retry) {
if (!retry) {
connection_retry = true;
};
if (!websocket){
websocket_connect();
};
if (websocket.readyState != 1) {
if ((websocket.readyState == 2 || websocket.readyState == 3) && connection_retry) {
websocket_connect();
};
setTimeout(websocket_send, 500, data, true);
return;
}
else if (websocket.readyState == 1) {
data["id"] = session_id;
websocket.send(JSON.stringify(data));
};
};
function send_request(url) {
if (url == "go_back") {
nav_history.go(-1);
return;
};
nav_history.newRequest(url);
loading.show();
var send = {};
send["request"] = url;
websocket_send(send);
};
function send_data(dato) {
var send = {};
send["data"] = dato;
websocket_send(send);
};
function ajax_to_dict(url, obj, key) {
var xhttp = new XMLHttpRequest();
ajax_running.push(xhttp);
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
eval("obj." + key + " = xhttp.responseText");
ajax_running.remove(xhttp)
};
};
xhttp.open("GET", url, true);
xhttp.send();
};

View File

@@ -1,238 +0,0 @@
function dispose() {
var height = document.getElementById("window").offsetHeight;
var header = document.getElementById("header").offsetHeight;
var footer = document.getElementById("footer").offsetHeight;
var panelheight = height - header - footer;
document.getElementById('content').style.height = panelheight + "px";
if (document.getElementById("window").offsetWidth < 800) {
document.getElementById('panel_items').className = "panel_items_vertical";
document.getElementById('panel_info').className = "panel_info_vertical";
}
else {
document.getElementById('panel_items').className = "panel_items";
document.getElementById('panel_info').className = "panel_info";
}
};
function replace_list(data, list) {
for (var key in list) {
var re = new RegExp("%" + key, "g");
data = data.replace(re, list[key]);
};
return data;
};
function play_mode(url, title, player) {
if (!new RegExp("^(.+://)").test(url)) {
url = domain + "/local/" + encodeURIComponent(btoa(Utf8.encode(data.video_url))) + "/video.mp4";
}
else {
var indirect_url = domain + "/proxy/" + encodeURIComponent(btoa(Utf8.encode(url))) + "/video.mp4";
};
if (settings.play_mode == 0 && indirect_url) {
var lista = [];
lista.push(replace_list(html.dialog.select.item, {
"item_title": "Indirecto",
"item_action": player + "('" + indirect_url + "','" + title + "')"
}));
lista.push(replace_list(html.dialog.select.item, {
"item_title": "Directo",
"item_action": player + "('" + url + "','" + title + "')"
}));
dialog.menu("Metodo de reproducción", btoa(lista.join("")));
}
else if (settings.play_mode == 1 && indirect_url) {
eval(player)(indirect_url, title);
}
else {
eval(player)(url, title);
};
};
function play(url, title) {
window.open(url);
}
function vlc_play(url, title) {
var html_code = replace_list(html.vlc_player, {
"video_url": url
});
dialog.player(title, html_code);
}
function flash_play(url, title) {
var html_code = replace_list(html.flash_player, {
"video_url": url
});
dialog.player(title, html_code);
}
function html_play(url, title) {
var html_code = replace_list(html.html_player, {
"video_url": url
});
dialog.player(title, html_code);
}
function set_category(category) {
var el = document.getElementById("header");
if (category) {
el.getElementById("heading").innerHTML = "alfa / " + category;
document.title = "alfa / " + category;
}
else {
el.getElementById("heading").innerHTML = "alfa";
document.title = "alfa";
};
};
function focus_element(element) {
element.focus()
};
function image_error(thumbnail) {
var src = thumbnail.src;
if (thumbnail.src.indexOf(domain) == 0) {
thumbnail.src = "https://github.com/alfa-addon/addon/raw/master/plugin.video.alfa/resources/media/themes/default/thumb_folder.png"
}
else {
thumbnail.src = domain + "/proxy/" + encodeURIComponent(btoa(thumbnail.src));
}
if (thumbnail.parentNode == document.activeElement && document.activeElement.className != "item_menu"){
document.activeElement.onfocus();
};
};
function set_original_url(url){
currentWebLink = document.getElementById("current_web_link")
if (currentWebLink) {
if (url) {
currentWebLink.style.display = "block";
currentWebLink.href = url;
}
else {
currentWebLink.style.display = "none";
}
}
}
function show_images(){
var container = document.getElementById("itemlist");
var images = container.getElementsByTagName("img");
var item_height = images[0].parentNode.parentNode.offsetHeight;
var first = Math.floor(container.scrollTop / item_height);
var count = Math.ceil(container.offsetHeight / item_height + (container.scrollTop / item_height - first));
for (var x = first; x < first + count; x++){
var image = images[x]
if (image && !image.src){
image.src = image.parentNode.getElementsByClassName("thumbnail")[1].innerHTML;
if (image.parentNode == document.activeElement){
document.activeElement.onfocus();
};
};
};
};
function load_info(item, viewmode) {
var thumbnail = item.getElementsByClassName("thumbnail")[0];
var fanart = item.getElementsByClassName("fanart")[0];
var title = item.getElementsByClassName("label")[0];
var plot = item.getElementsByClassName("plot")[0];
var el = document.getElementById("media_info");
el.getElementById("media_poster").src = thumbnail.src;
el.getElementById("media_plot").innerHTML = plot.innerHTML.replace(/\n/g, "<br>");
el.getElementById("media_title").innerHTML = title.innerHTML;
if (fanart.innerHTML && settings.show_fanart) {
document.getElementById("content").style.backgroundImage = "linear-gradient(rgba(255,255,255,0.5),rgba(255,255,255,0.5)), url(" + fanart.innerHTML + ")";
document.getElementById("content").children[0].style.opacity = ".9";
document.getElementById("content").children[1].style.opacity = ".9";
}
else {
document.getElementById("content").style.backgroundImage = "";
document.getElementById("content").children[0].style.opacity = "";
document.getElementById("content").children[1].style.opacity = "";
};
if (viewmode == "list") {
el.getElementById("media_poster").style.display = "block";
el.getElementById("media_plot").style.display = "block";
el.getElementById("media_title").style.display = "none";
document.getElementById("version_info").style.display = "none";
}
else if (viewmode == "banner" || viewmode == "channel") {
el.getElementById("media_poster").style.display = "none";
el.getElementById("media_plot").style.display = "none";
el.getElementById("media_title").style.display = "none";
document.getElementById("version_info").style.display = "block";
}
else {
el.getElementById("media_poster").style.display = "block";
el.getElementById("media_plot").style.display = "block";
el.getElementById("media_title").style.display = "block";
document.getElementById("version_info").style.display = "none";
}
auto_scroll(el.getElementById("media_plot"));
};
function unload_info(obj) {
var el = document.getElementById('media_info');
document.getElementById("version_info").style.display = "block";
el.getElementById("media_poster").style.display = "none";
el.getElementById("media_plot").style.display = "none";
el.getElementById("media_title").style.display = "none";
el.getElementById("media_poster").src = "";
el.getElementById("media_plot").innerHTML = "";
el.getElementById("media_title").innerHTML = "";
document.getElementById("content").style.backgroundImage = ""
document.getElementById("content").children[0].style.opacity = "";
document.getElementById("content").children[1].style.opacity = "";
};
function change_category(category) {
var el = document.getElementById('window_settings');
el.getElementById("controls_container").scrollTop = 0;
categories = el.getElementById("controls_container").getElementsByTagName("ul");
for (var x in categories) {
if (categories[x].id == "category_" + category) {
categories[x].style.display = "block";
}
else if (categories[x].style) {
categories[x].style.display = "none";
};
};
};
function auto_scroll(element) {
clearInterval(element.interval);
element.scrollLeft = 0;
element.scrollTop = 0;
if (element.scrollWidth > element.offsetWidth) {
initialscrollWidth = element.scrollWidth;
element.innerHTML = element.innerHTML + " | " + element.innerHTML;
element.interval = setInterval(function () {
element.scrollLeft += 1;
if (element.scrollLeft - 1 >= element.scrollWidth - initialscrollWidth) {
element.scrollLeft = 0;
};
}, 80);
};
if (element.scrollHeight > element.offsetHeight) {
initialscrollHeight = element.scrollHeight;
element.innerHTML = element.innerHTML + "</br>" + element.innerHTML;
element.interval = setInterval(function () {
element.scrollTop += 1;
if (element.scrollTop >= element.scrollHeight - initialscrollHeight) {
element.scrollTop = 0;
};
}, 80);
};
};
function center_window(el) {
el.style.top = document.getElementById("window").offsetHeight / 2 - el.offsetHeight / 2 + "px";
};

View File

@@ -1,43 +0,0 @@
var Utf8 = { // public method for url encoding
encode: function(string) {
string = string.replace(/\r\n/g, "\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
} else if ((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
} else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
}, // public method for url decoding
decode: function(utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while (i < utftext.length) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
} else if ((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i + 1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
} else {
c2 = utftext.charCodeAt(i + 1);
c3 = utftext.charCodeAt(i + 2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
};

View File

@@ -1,142 +0,0 @@
var domain = window.location.href.split("/").slice(0, 3).join("/");
var focused_item = null;
var websocket = null;
var session_id = null;
var default_settings = {};
var settings_controls = [];
var connection_retry = true;
var settings = {};
var loading = {};
var dialog = {};
var ajax_running = [];
var keychar = {
"keyCode": 0,
"Time": 0,
"Char": ""
};
var html = {
"dialog": {
"select": {}
},
"config": {},
"itemlist": {}
};
var players = {
"play": "Abrir enlace",
"vlc_play": "Plugin VLC",
"flash_play": "Reproductor Flash",
"html_play": "Video HTML"
};
var nav_history = {
"newRequest": function (url) {
if (this.confirmed) {
if (this.states[this.current].url == url) {
this.states[this.current].url;
this.states[this.current].start;
}
else {
this.states[this.current].scroll = document.getElementById("itemlist").scrollTop;
this.states[this.current].focus = Array.prototype.indexOf.call(document.getElementById("itemlist").children, focused_item.parentNode);
this.current += 1;
this.states.splice(this.current, 0, {
"start": new Date().getTime(),
"url": url
});
this.confirmed = false;
}
}
else {
if (this.current == -1) {
this.current = 0;
this.states.push({
"start": new Date().getTime(),
"url": url
});
}
else {
this.states[this.current].start = new Date().getTime();
this.states[this.current].url = url;
}
}
},
"newResponse": function (data, category, url) {
if (!this.confirmed) {
if (this.states[this.current].focus >= 0) {
document.getElementById("itemlist").children[this.states[this.current].focus].children[0].focus();
document.getElementById("itemlist").scrollTop = this.states[this.current].scroll;
}
this.states[this.current].end = new Date().getTime();
this.states[this.current].data = data;
this.states[this.current].category = category;
this.states[this.current].source_url = url;
this.confirmed = true;
if (settings.builtin_history && !this.from_nav) {
if (this.current > 0) {
history.pushState(this.current.toString(), "", "#" + this.states[this.current].url);
}
else {
history.replaceState(this.current.toString(), "", "#" + this.states[this.current].url);
}
}
}
else {
if (this.states[this.current].focus >= 0) {
document.getElementById("itemlist").children[this.states[this.current].focus].children[0].focus();
document.getElementById("itemlist").scrollTop = this.states[this.current].scroll;
}
this.states[this.current].end = new Date().getTime();
this.states[this.current].data = data;
this.states[this.current].category = category;
this.states[this.current].source_url = url;
this.states = this.states.slice(0, this.current + 1);
}
this.from_nav = false;
},
"go": function (index) {
if (!this.confirmed) {
this.current -= 1;
this.confirmed = true;
}
this.states[this.current].scroll = document.getElementById("itemlist").scrollTop;
this.states[this.current].focus = Array.prototype.indexOf.call(document.getElementById("itemlist").children, focused_item.parentNode);
if (this.current + index < 0) {
this.current = -1;
this.confirmed = false;
send_request("");
return;
}
else if (this.current + index >= this.states.lenght) {
this.current = this.states.lenght - 1;
}
else {
this.current += index;
}
if (this.states[this.current].end - this.states[this.current].start > this.cache) {
document.getElementById("itemlist").innerHTML = this.states[this.current].data.join("");
set_category(this.states[this.current].category)
set_original_url(this.states[this.current].source_url)
if (this.states[this.current].focus >= 0) {
document.getElementById("itemlist").children[this.states[this.current].focus].children[0].focus();
}
if (this.states[this.current].scroll) {
document.getElementById("itemlist").scrollTop = this.states[this.current].scroll;
}
show_images();
this.confirmed = true;
}
else {
this.confirmed = false;
this.from_nav = true;
send_request(this.states[this.current].url);
}
},
"current": -1,
"confirmed": false,
"from_nav": false,
"states": [],
"cache": 2000 //Tiempo para determinar si se cargará la cache o se volvera a solicitar el item (el tiempo es el que tarda en responder el servidor)
};

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.4 KiB

View File

@@ -1,15 +0,0 @@
{
"name": "alfa",
"icons": [
{
"src": "/media/icon-512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"theme_color": "#00779F",
"background_color": "#00779F",
"start_url": "/",
"display": "standalone",
"orientation": "any"
}

View File

@@ -1,224 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="/media/favicon.ico" />
<!-- Web as app support -->
<link rel="manifest" href="/media/manifest.json">
<meta name="mobile-web-app-capable" content="yes">
<!-- Navigation bar color -->
<!-- Chrome, Firefox OS and Opera -->
<meta name="theme-color" content="#01455c">
<!-- Windows Phone -->
<meta name="msapplication-navbutton-color" content="#01455c">
<!-- iOS Safari -->
<meta name="apple-mobile-web-app-status-bar-style" content="#01455c">
<title>alfa</title>
<link rel="stylesheet" href="/media/css/alfa.css" />
<script type="text/javascript" src="/media/js/main.js"></script>
<script type="text/javascript" src="/media/js/vars.js"></script>
<script type="text/javascript" src="/media/js/ui.js"></script>
<script type="text/javascript" src="/media/js/navigation.js"></script>
<script type="text/javascript" src="/media/js/dialogs.js"></script>
<script type="text/javascript" src="/media/js/protocol.js"></script>
<script type="text/javascript" src="/media/js/socket.js"></script>
<script type="text/javascript" src="/media/js/utils.js"></script>
<script type="text/javascript">
websocket_host = 'ws://' + window.location.host
</script>
</head>
<body>
<!-- loading -->
<div class="window_loading" id="window_loading">
<span class="loading_animation"></span>
<a class="loading_message" id="loading_message" href="javascript:void(0)">Cargando...</a>
</div>
<!--/window_progress -->
<div class="window_background_progress" id="window_background_progress">
<div Class="window_heading" id="window_heading"></div>
<div Class="window_message" id="window_message"></div>
<div Class="progressbar_background" id="progressbar_background">
<div Class="progressbar" id="progressbar"></div>
</div>
</div>
<div class="window_overlay" id="window_overlay"></div>
<!-- window_select -->
<div class="window_select" id="window_select">
<a class="window_close" href="javascript:void(0)" onmouseover="this.focus()" onclick="send_data({'id':this.parentNode.RequestID, 'result':-1 });dialog.closeall();"></a>
<div class="window_heading" id="window_heading"></div>
<ul class="control_list" id="control_list"></ul>
</div>
<!-- window_ok -->
<div class="window_ok" id="window_ok">
<a class="window_close" href="javascript:void(0)" onmouseover="this.focus()" onclick="send_data({'id':this.parentNode.RequestID, 'result':true });dialog.closeall();"></a>
<div class="window_heading" id="window_heading"></div>
<div Class="window_message" id="window_message"></div>
<div class="window_footer" id="window_footer">
<a href="javascript:void(0)" class="control_button button_ok" onmouseover="this.focus()" onclick="send_data({'id':this.parentNode.parentNode.RequestID, 'result':true });dialog.closeall();">Aceptar</a>
</div>
</div>
<!-- window_yesno -->
<div class="window_yesno" id="window_yesno">
<a class="window_close" href="javascript:void(0)" onmouseover="this.focus()" onclick="send_data({'id':this.parentNode.RequestID, 'result':false });dialog.closeall();"></a>
<div class="window_heading" id="window_heading"></div>
<div Class="window_message" id="window_message"></div>
<div class="window_footer" id="window_footer">
<a href="javascript:void(0)" class="control_button button_ok" onmouseover="this.focus()" onclick="send_data({'id':this.parentNode.parentNode.RequestID, 'result':true });dialog.closeall();">Si</a>
<a href="javascript:void(0)" class="control_button button_close" onmouseover="this.focus()" onclick="send_data({'id':this.parentNode.parentNode.RequestID, 'result':false });dialog.closeall();">No</a>
</div>
</div>
<!-- window_notification -->
<div class="window_notification" id="window_notification">
<div class="window_icon" id="window_icon"></div>
<div Class="window_heading" id="window_heading"></div>
<div Class="window_message" id="window_message"></div>
</div>
<!--/window_progress -->
<div class="window_progress" id="window_progress">
<a class="window_close" href="javascript:void(0)" onmouseover="this.focus()" onclick="this.parentNode.querySelector('#canceled').checked='checked';this.parentNode.querySelector('#window_heading').innerHTML += ' Cancelando...';"></a>
<div class="window_heading" id="window_heading"></div>
<div Class="window_message" id="window_message"></div>
<div Class="progress_background" id="progress_background">
<div Class="progress" id="progress"></div>
</div>
<div class="window_footer" id="window_footer">
<a href="javascript:void(0)" class="control_button button_close" onmouseover="this.focus()" onclick="this.parentNode.querySelector('#canceled').checked='checked';this.parentNode.parentNode.querySelector('#window_heading').innerHTML += ' Cancelando...';">Cancelar</a>
<input type="checkbox" style="display:none" id="canceled">
</div>
</div>
<!-- window_input -->
<div class="window_input" id="window_input">
<a class="window_close" href="javascript:void(0)" onmouseover="this.focus()" onclick="send_data({'id':this.parentNode.RequestID, 'result':null });dialog.closeall();"></a>
<div class="window_heading" id="window_heading"></div>
<div class="control_input" id="control_input">
<input class="control_input" id="window_value" type="text" onkeypress="if(event.keyCode == 13){send_data({'id':this.parentNode.parentNode.RequestID, 'result':this.value });dialog.closeall();loading.show();}">
<label class="control_input"></label>
</div>
<div class="window_footer" id="window_footer">
<a href="javascript:void(0)" class="control_button button_ok" onmouseover="this.focus()" onclick="send_data({'id':this.parentNode.parentNode.RequestID, 'result':this.parentNode.parentNode.getElementById('window_value').value});dialog.closeall();loading.show();">Aceptar</a>
<a href="javascript:void(0)" class="control_button button_close" onmouseover="this.focus()" onclick="send_data({'id':this.parentNode.parentNode.RequestID, 'result':null });dialog.closeall();">Cancelar</a>
</div>
</div>
<!-- window_captcha -->
<div class="window_recaptcha" id="window_recaptcha">
<a class="window_close" href="javascript:void(0)" onmouseover="this.focus()" onclick="send_data({'id':this.parentNode.RequestID, 'result':null });dialog.closeall();"></a>
<div class="window_heading" id="window_heading"></div>
<div Class="window_message" id="window_message"></div>
<div class="window_image" id= "window_image">
<a href="javascript:void(0)" onmouseover="this.focus()" onmouseout="this.blur()" onclick="send_data({'id':this.parentNode.parentNode.RequestID, 'result': 0})"></a>
<a href="javascript:void(0)" onmouseover="this.focus()" onmouseout="this.blur()" onclick="send_data({'id':this.parentNode.parentNode.RequestID, 'result': 1})"></a>
<a href="javascript:void(0)" onmouseover="this.focus()" onmouseout="this.blur()" onclick="send_data({'id':this.parentNode.parentNode.RequestID, 'result': 2})"></a>
<a href="javascript:void(0)" onmouseover="this.focus()" onmouseout="this.blur()" onclick="send_data({'id':this.parentNode.parentNode.RequestID, 'result': 3})"></a>
<a href="javascript:void(0)" onmouseover="this.focus()" onmouseout="this.blur()" onclick="send_data({'id':this.parentNode.parentNode.RequestID, 'result': 4})"></a>
<a href="javascript:void(0)" onmouseover="this.focus()" onmouseout="this.blur()" onclick="send_data({'id':this.parentNode.parentNode.RequestID, 'result': 5})"></a>
<a href="javascript:void(0)" onmouseover="this.focus()" onmouseout="this.blur()" onclick="send_data({'id':this.parentNode.parentNode.RequestID, 'result': 6})"></a>
<a href="javascript:void(0)" onmouseover="this.focus()" onmouseout="this.blur()" onclick="send_data({'id':this.parentNode.parentNode.RequestID, 'result': 7})"></a>
<a href="javascript:void(0)" onmouseover="this.focus()" onmouseout="this.blur()" onclick="send_data({'id':this.parentNode.parentNode.RequestID, 'result': 8})"></a>
</div>
<div class="window_footer" id="window_footer">
<a href="javascript:void(0)" class="control_button button_ok" onmouseover="this.focus()" onclick="send_data({'id':this.parentNode.parentNode.RequestID, 'result':true});dialog.closeall();loading.show();">Aceptar</a>
<a href="javascript:void(0)" class="control_button button_close" onmouseover="this.focus()" onclick="send_data({'id':this.parentNode.parentNode.RequestID, 'result':null });dialog.closeall();">Cancelar</a>
<a href="javascript:void(0)" class="control_button button_ok" onmouseover="this.focus()" onclick="send_data({'id':this.parentNode.parentNode.RequestID, 'result':'refresh'});dialog.closeall();loading.show();">Recargar</a>
</div>
</div>
<!--/window_settings -->
<div id="window_settings" class="window_settings">
<a class="window_close" href="javascript:void(0)" onmouseover="this.focus()" onclick="dialog.closeall();if(this.parentNode.getElementById('window_footer').style.display != 'none'){save_config(false)}"></a>
<div class="window_heading" id="window_heading"></div>
<div class="category_container" id="category_container"></div>
<div class="controls_container" id="controls_container"></div>
<div class="window_footer" id="window_footer_local" style="display:none">
<a href="javascript:void(0)" class="control_button button_ok" onmouseover="this.focus()" onclick="save_settings();dialog.closeall()">Guardar</a>
<a href="javascript:void(0)" class="control_button button_close" onmouseover="this.focus()" onclick="dialog.closeall()">Cerrar</a>
</div>
<div class="window_footer" id="window_footer">
<a href="javascript:void(0)" class="control_button button_ok" onmouseover="this.focus()" onclick="dialog.closeall();save_config(true);">Guardar</a>
<a href="javascript:void(0)" class="control_button button_close" onmouseover="this.focus()" onclick="dialog.closeall();save_config(false);">Cerrar</a>
<a href="javascript:void(0)" class="control_button" onmouseover="this.focus()" onclick="custom_button();" id="custom_button"></a>
</div>
</div>
<!--/window_info -->
<div class="window_info" id="window_info">
<a class="window_close" href="javascript:void(0)" onmouseover="this.focus()" onclick="dialog.closeall();info_window('close')"></a>
<div class="window_heading" id="window_heading"></div>
<div class="window_content">
<img class="info_fanart" id="info_fanart">
<img class="info_poster" id="info_poster">
<span class="line1_head" id="line1_head"></span><span class="line1" id="line1"></span>
<span class="line2_head" id="line2_head"></span><span class="line2" id="line2"></span>
<span class="line3_head" id="line3_head"></span><span class="line3" id="line3"></span>
<span class="line4_head" id="line4_head"></span><span class="line4" id="line4"></span>
<span class="line5_head" id="line5_head"></span><span class="line5" id="line5"></span>
<span class="line6_head" id="line6_head"></span><span class="line6" id="line6"></span>
<span class="line7_head" id="line7_head"></span><span class="line7" id="line7"></span>
<span class="line8_head" id="line8_head"></span><span class="line8" id="line8"></span>
<span class="page_info" id="page_info"></span>
</div>
<div class="window_footer" id="window_footer">
<a href="javascript:void(0)" class="control_button" id="previous" onmouseover="this.focus()" onclick="info_window('previous')">Anterior</a>
<a href="javascript:void(0)" class="control_button" id="next" onmouseover="this.focus()" onclick="info_window('next')">Siguiente</a>
<a href="javascript:void(0)" class="control_button button_close" onmouseover="this.focus()" onclick="dialog.closeall();info_window('close')">Cancelar</a>
<a href="javascript:void(0)" class="control_button button_close" onmouseover="this.focus()" onclick="dialog.closeall();info_window('ok')">Aceptar</a>
</div>
</div>
<!-- window_player -->
<div class="window_player" id="window_player">
<a class="window_close" href="javascript:void(0)" onmouseover="this.focus()" onclick="dialog.closeall()"></a>
<div class="window_heading" id="window_heading"></div>
<div id="media_content" class="media_content"></div>
</div>
<div class="window" id="window">
<div class="header" id="header">
<div class="logo"></div>
<h1 class="heading" id="heading">alfa</h1>
<a class="settings" href="javascript:void(0)" onclick="dialog.settings()"></a>
</div>
<div class="content" id="content">
<div class="panel_info" id="panel_info">
<div class="media_info" id="media_info">
<img id="media_poster" src="" />
<h3 id="media_title"></h3>
<div id="media_plot"></div>
</div>
<div class="version_info" id="version_info">
<span class="Version" id="version"></span><br/>
<span class="Version" id="date"></span>
</div>
</div>
<div class="panel_items" id="panel_items">
<ul class="itemlist" id="itemlist" onscroll="show_images()">
</ul>
</div>
</div>
<div class="footer" id="footer">
<div class="left">
</div>
<div class="links">
<a href="#" id="current_web_link" target="_blank" hidden>Abrir web original</a>
</div>
<div class="status" id="status">Desconectado</div>
</div>
</div>
</body>
</html>

View File

@@ -1,54 +0,0 @@
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<settings>
<category label="General">
<setting label="Puertos" type="lsep" />
<setting default="8080" id="server.port" label="Puerto HTTP" type="number"/>
<setting type="sep"/>
<setting id="default_action" type="enum" lvalues="30006|30007|30008" label="30005" default="0"/>
<setting id="thumbnail_type" type="enum" lvalues="30011|30012|30200" label="30010" default="2"/>
<setting id="mediaserver_language" type="labelenum" values="English|Spanish|Spanish (Argentina)|Spanish (Mexico)|Italian" label="70277" default="Spanish" />
<setting id="channel_language" type="labelenum" values="all|cast|lat|it" label="30019" default="all"/>
<setting id="debug" type="bool" label="30003" default="false"/>
<setting label="Uso de servidores" type="lsep"/>
<setting id="resolve_priority" type="enum" label="Método prioritario" values="Free primero|Premium primero|Debriders primero" default="0"/>
<setting id="resolve_stop" type="bool" label="Dejar de buscar cuando encuentre una opción" default="true"/>
<setting id="hidepremium" type="bool" label="Ocultar servidores de pago sin cuenta" default="false"/>
<setting id="server_stats" type="bool" label="Enviar estadisticas sobre el uso de servidores" default="true"/>
<setting type="sep"/>
<setting label="Canales para adultos" type="lsep"/>
<setting id="adult_aux_intro_password" type="text" label="Contraseña (por defecto 0000):" option="hidden" default=""/>
<setting id="adult_mode" type="enum" values="Nunca|Siempre|Solo para esta sesión" label="30002" enable="!eq(-1,)" default="0"/>
<setting id="adult_request_password" type="bool" label="Solicitar contraseña para abrir canales de adultos" enable="!eq(-1,0)+!eq(-2,)" default="true"/>
<setting id="adult_aux_new_password1" type="text" label="Nueva contraseña:" option="hidden" enable="!eq(-3,)" default=""/>
<setting id="adult_aux_new_password2" type="text" label="Confirmar nueva contraseña:" option="hidden" enable="!eq(-1,)" default=""/>
</category>
<!-- Path downloads -->
<category label="30501">
<setting type="sep"/>
<setting id="downloadpath" type="text" label="30017" default=""/>
<setting id="downloadlistpath" type="text" label="30018" default=""/>
<setting id="videolibrarypath" type="text" label="30067" default=""/>
<setting type="sep"/>
<setting label="30131" type="lsep"/>
<setting id="folder_tvshows" type="text" label="Nombre de carpeta para 'Series'" default="SERIES"/>
<setting id="folder_movies" type="text" label="Nombre de carpeta para 'Peliculas'" default="CINE"/>
</category>
<category label="Otros">
<setting label="Info de películas/series en menú contextual" type="lsep"/>
<setting id="infoplus" type="bool" label="Mostrar opción Infoplus:" default="true"/>
<setting type="sep"/>
<setting label="TheMovieDB (obtiene datos de las películas o series)" type="lsep"/>
<setting id="tmdb_threads" type="labelenum" values="5|10|15|20|25|30" label="Búsquedas simultáneas (puede causar inestabilidad)" default="20"/>
<setting id="tmdb_plus_info" type="bool" label="Buscar información extendida (datos de actores) Aumenta el tiempo de búsqueda" default="false"/>
<setting id="tmdb_cache" type="bool" label="Usar caché (mejora las búsquedas recurrentes)" default="true"/>
<setting id="tmdb_cache_expire" type="enum" lvalues="cada 1 día|cada 7 días|cada 15 días|cada 30 días|No" label="¿Renovar caché?" enable="eq(-1,true)" default="4"/>
<!--<setting id="tmdb_clean_db_cache" type="action" label="Pulse para 'Borrar caché' guardada" action="RunPlugin(plugin://plugin.video.alfa/?ew0KICAgICJhY3Rpb24iOiAic2NyaXB0Ig0KfQ==)" />-->
</category>
</settings>

View File

@@ -1,18 +0,0 @@
# setup.py
# Para crear el ejecutable de Alfa mediaserver en windows
# Se usa py2exe
# Linea de comandos para la creacion: python setup.py py2exe -p channels,servers,lib,platformcode
from distutils.core import setup
import glob
import py2exe
setup(packages=['channels','servers','lib','platformcode','platformcode/controllers'],
data_files=[("channels",glob.glob("channels\\*.py")),
("channels",glob.glob("channels\\*.json")),
("servers",glob.glob("servers\\*.py")),
("servers",glob.glob("servers\\*.json")),
("",glob.glob("addon.xml")),
],
console=["alfa.py"]
)

View File

View File

@@ -1 +0,0 @@

View File

@@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@@ -1 +0,0 @@
# -*- coding: utf-8 -*-

View File

@@ -1,48 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<addon id="plugin.video.alfa" name="Alfa" version="2.8.3" provider-name="Alfa Addon">
<requires>
<import addon="xbmc.python" version="2.1.0"/>
<import addon="script.module.libtorrent" optional="true"/>
</requires>
<extension point="xbmc.python.pluginsource" library="default.py">
<provides>video</provides>
</extension>
<extension point="xbmc.addon.metadata">
<summary lang="es">Navega con Kodi por páginas web.</summary>
<assets>
<icon>logo-cumple.png</icon>
<fanart>fanart1.jpg</fanart>
<screenshot>resources/media/themes/ss/1.jpg</screenshot>
<screenshot>resources/media/themes/ss/2.jpg</screenshot>
<screenshot>resources/media/themes/ss/3.jpg</screenshot>
<screenshot>resources/media/themes/ss/4.jpg</screenshot>
</assets>
<news>[B]Estos son los cambios para esta versión:[/B]
[COLOR green][B]Arreglos[/B][/COLOR]
¤ animeshd ¤ gamovideo ¤ elitetorrent
¤ newpct1 ¤ cinetux ¤ asialiveaction
¤ gnula ¤ fembed ¤ hdfilmologia
¤ gvideo ¤ vidlox ¤ javtasty
¤ qwertyy
[COLOR green][B]Novedades[/B][/COLOR]
¤ watchseries ¤ xstreamcdn ¤ videobb
¤ animespace ¤ tvanime
Agradecimientos a @shlibidon por colaborar con esta versión
</news>
<description lang="es">Navega con Kodi por páginas web para ver sus videos de manera fácil.</description>
<summary lang="en">Browse web pages using Kodi</summary>
<description lang="en">Browse web pages using Kodi, you can easily watch their video content.</description>
<disclaimer>[COLOR red]The owners and submitters to this addon do not host or distribute any of the content displayed by these addons nor do they have any affiliation with the content providers.[/COLOR]</disclaimer>
<platform>all</platform>
<license>GNU GPL v3</license>
<forum>foro</forum>
<website>web</website>
<email>my@email.com</email>
<source>https://github.com/alfa-addon/addon</source>
</extension>
<extension point="xbmc.service" library="videolibrary_service.py" start="login|startup">
</extension>
</addon>

View File

@@ -1,16 +0,0 @@
{
"id": "LIKUOO",
"name": "LIKUOO",
"active": true,
"adult": true,
"language": ["*"],
"thumbnail": "https://likuoo.video/files_static/images/logo.jpg",
"banner": "",
"categories": [
"adult"
],
"settings": [
]
}

View File

@@ -1,93 +0,0 @@
# -*- coding: utf-8 -*-
#------------------------------------------------------------
import urlparse,urllib2,urllib,re
import os, sys
from platformcode import config, logger
from core import scrapertools
from core.item import Item
from core import servertools
from core import httptools
host = 'http://www.likuoo.video'
def mainlist(item):
logger.info()
itemlist = []
itemlist.append( Item(channel=item.channel, title="Ultimos" , action="lista", url=host))
itemlist.append( Item(channel=item.channel, title="Pornstar" , action="categorias", url=host + "/pornstars/"))
itemlist.append( Item(channel=item.channel, title="Categorias" , action="categorias", url=host + "/all-channels/"))
itemlist.append( Item(channel=item.channel, title="Buscar", action="search"))
return itemlist
def search(item, texto):
logger.info()
texto = texto.replace(" ", "+")
item.url = host + "/search/?s=%s" % texto
try:
return lista(item)
except:
import sys
for line in sys.exc_info():
logger.error("%s" % line)
return []
def categorias(item):
logger.info()
itemlist = []
data = httptools.downloadpage(item.url).data
data = re.sub(r"\n|\r|\t|&nbsp;|<br>", "", data)
patron = '<div class="item_p">.*?<a href="([^"]+)" title="([^"]+)"><img src="([^"]+)"'
matches = re.compile(patron,re.DOTALL).findall(data)
for scrapedurl,scrapedtitle,scrapedthumbnail in matches:
scrapedplot = ""
scrapedthumbnail = "https:" + scrapedthumbnail
scrapedurl = urlparse.urljoin(item.url,scrapedurl)
itemlist.append( Item(channel=item.channel, action="lista", title=scrapedtitle, url=scrapedurl,
fanart=scrapedthumbnail, thumbnail=scrapedthumbnail, plot=scrapedplot) )
next_page = scrapertools.find_single_match(data,'...<a href="([^"]+)" class="next">&#187;</a>')
if next_page!="":
next_page = urlparse.urljoin(item.url,next_page)
itemlist.append(item.clone(action="categorias", title="Página Siguiente >>", text_color="blue", url=next_page) )
return itemlist
def lista(item):
logger.info()
itemlist = []
data = httptools.downloadpage(item.url).data
data = re.sub(r"\n|\r|\t|&nbsp;|<br>", "", data)
patron = '<div class="item">.*?'
patron += '<a href="([^"]+)" title="(.*?)">.*?'
patron += 'src="(.*?)".*?'
patron += '<div class="runtime">(.*?)</div>'
matches = re.compile(patron,re.DOTALL).findall(data)
for scrapedurl,scrapedtitle,scrapedthumbnail,scrapedtime in matches:
url = urlparse.urljoin(item.url,scrapedurl)
scrapedtime = scrapedtime.replace("m", ":").replace("s", " ")
title = "[COLOR yellow]" + scrapedtime + "[/COLOR] " +scrapedtitle
contentTitle = title
thumbnail = "https:" + scrapedthumbnail
plot = ""
itemlist.append( Item(channel=item.channel, action="play", title=title, url=url, thumbnail=thumbnail,
fanart=thumbnail, plot=plot, contentTitle = contentTitle))
next_page = scrapertools.find_single_match(data,'...<a href="([^"]+)" class="next">&#187;</a>')
if next_page!="":
next_page = urlparse.urljoin(item.url,next_page)
itemlist.append(item.clone(action="lista", title="Página Siguiente >>", text_color="blue", url=next_page) )
return itemlist
def play(item):
logger.info()
data = httptools.downloadpage(item.url).data
itemlist = servertools.find_video_items(data=data)
for videoitem in itemlist:
videoitem.title = item.fulltitle
videoitem.fulltitle = item.fulltitle
videoitem.thumbnail = item.thumbnail
videochannel=item.channel
return itemlist

View File

@@ -1,16 +0,0 @@
{
"id": "TXXX",
"name": "TXXX",
"active": true,
"adult": true,
"language": ["*"],
"thumbnail": "http://www.txxx.com/images/desktop-logo.png",
"banner": "",
"categories": [
"adult"
],
"settings": [
]
}

View File

@@ -1,149 +0,0 @@
# -*- coding: utf-8 -*-
#------------------------------------------------------------
import urlparse,urllib2,urllib,re
import os, sys
from core import scrapertools
from core import servertools
from core.item import Item
from platformcode import config, logger
from core import httptools
host = 'http://www.txxx.com'
def mainlist(item):
logger.info()
itemlist = []
itemlist.append( Item(channel=item.channel, title="Ultimas" , action="lista", url=host + "/latest-updates/"))
itemlist.append( Item(channel=item.channel, title="Mejor valoradas" , action="lista", url=host + "/top-rated/"))
itemlist.append( Item(channel=item.channel, title="Mas popular" , action="lista", url=host + "/most-popular/"))
itemlist.append( Item(channel=item.channel, title="Canal" , action="catalogo", url=host + "/channels-list/most-popular/"))
itemlist.append( Item(channel=item.channel, title="Categorias" , action="categorias", url=host + "/categories/"))
itemlist.append( Item(channel=item.channel, title="Buscar", action="search"))
return itemlist
def search(item, texto):
logger.info()
texto = texto.replace(" ", "+")
item.url = host + "/search/s=%s" % texto
try:
return lista(item)
except:
import sys
for line in sys.exc_info():
logger.error("%s" % line)
return []
def catalogo(item):
logger.info()
itemlist = []
data = httptools.downloadpage(item.url).data
data = re.sub(r"\n|\r|\t|&nbsp;|<br>", "", data)
patron = '<div class="channel-thumb">.*?'
patron += '<a href="([^"]+)" title="([^"]+)".*?'
patron += '<img src="([^"]+)".*?'
patron += '<span>(.*?)</span>'
matches = re.compile(patron,re.DOTALL).findall(data)
for scrapedurl,scrapedtitle,scrapedthumbnail,num in matches:
scrapedplot = ""
scrapedurl = host + scrapedurl
title = scrapedtitle + "[COLOR yellow] " + num + "[/COLOR]"
itemlist.append( Item(channel=item.channel, action="lista", title=title , url=scrapedurl ,
thumbnail=scrapedthumbnail , plot=scrapedplot) )
next_page = scrapertools.find_single_match(data,'<a class=" btn btn--size--l btn--next" href="([^"]+)" title="Next Page"')
if next_page!="":
next_page = urlparse.urljoin(item.url,next_page)
itemlist.append( Item(channel=item.channel , action="catalogo" , title="Página Siguiente >>" ,
text_color="blue", url=next_page) )
return itemlist
def categorias(item):
logger.info()
itemlist = []
data = httptools.downloadpage(item.url).data
patron = '<a class="categories-list__link" href="([^"]+)">.*?'
patron += '<span class="categories-list__name cat-icon" data-title="([^"]+)">.*?'
patron += '<span class="categories-list__badge">(.*?)</span>'
matches = re.compile(patron,re.DOTALL).findall(data)
for scrapedurl,scrapedtitle,num in matches:
url = urlparse.urljoin(item.url,scrapedurl)
scrapedthumbnail = ""
scrapedplot = ""
title = scrapedtitle + "[COLOR yellow] " + num + "[/COLOR]"
itemlist.append( Item(channel=item.channel, action="lista", title=title , url=url ,
thumbnail=scrapedthumbnail, plot=scrapedplot) )
return itemlist
def lista(item):
logger.info()
itemlist = []
data = httptools.downloadpage(item.url).data
data = re.sub(r"\n|\r|\t|&nbsp;|<br>", "", data)
patron = 'data-video-id="\d+">.*?<a href="([^"]+)".*?'
patron += '<img src="([^"]+)" alt="([^"]+)".*?'
patron += '</div>(.*?)</div>'
matches = re.compile(patron,re.DOTALL).findall(data)
for scrapedurl,scrapedthumbnail,scrapedtitle,scrapedtime in matches:
contentTitle = scrapedtitle
scrapedhd = scrapertools.find_single_match(scrapedtime, '<span class="thumb__hd">(.*?)</span>')
duration = scrapertools.find_single_match(scrapedtime, '<span class="thumb__duration">(.*?)</span>')
if scrapedhd != '':
title = "[COLOR yellow]" +duration+ "[/COLOR] " + "[COLOR red]" +scrapedhd+ "[/COLOR] "+scrapedtitle
else:
title = "[COLOR yellow]" + duration + "[/COLOR] " + scrapedtitle
thumbnail = scrapedthumbnail
plot = ""
itemlist.append( Item(channel=item.channel, action="play" , title=title , url=scrapedurl, thumbnail=thumbnail,
plot=plot, contentTitle=title) )
next_page = scrapertools.find_single_match(data,'<a class=" btn btn--size--l btn--next.*?" href="([^"]+)" title="Next Page"')
if next_page!="":
next_page = urlparse.urljoin(item.url,next_page)
itemlist.append(item.clone(action="lista", title="Página Siguiente >>", text_color="blue", url=next_page) )
return itemlist
def play(item):
logger.info()
itemlist = []
data = httptools.downloadpage(item.url).data
video_url = scrapertools.find_single_match(data, 'var video_url = "([^"]*)"')
video_url += scrapertools.find_single_match(data, 'video_url \+= "([^"]*)"')
partes = video_url.split('||')
video_url = decode_url(partes[0])
video_url = re.sub('/get_file/\d+/[0-9a-z]{32}/', partes[1], video_url)
video_url += '&' if '?' in video_url else '?'
video_url += 'lip=' + partes[2] + '&lt=' + partes[3]
itemlist.append(item.clone(action="play", title=item.title, url=video_url))
return itemlist
def decode_url(txt):
_0x52f6x15 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,~'
reto = ''; n = 0
# En las dos siguientes líneas, ABCEM ocupan 2 bytes cada letra! El replace lo deja en 1 byte. !!!!: АВСЕМ (10 bytes) ABCEM (5 bytes)
txt = re.sub('[^АВСЕМA-Za-z0-9\.\,\~]', '', txt)
txt = txt.replace('А', 'A').replace('В', 'B').replace('С', 'C').replace('Е', 'E').replace('М', 'M')
while n < len(txt):
a = _0x52f6x15.index(txt[n])
n += 1
b = _0x52f6x15.index(txt[n])
n += 1
c = _0x52f6x15.index(txt[n])
n += 1
d = _0x52f6x15.index(txt[n])
n += 1
a = a << 2 | b >> 4
b = (b & 15) << 4 | c >> 2
e = (c & 3) << 6 | d
reto += chr(a)
if c != 64: reto += chr(b)
if d != 64: reto += chr(e)
return urllib.unquote(reto)

View File

@@ -1,12 +0,0 @@
# -*- coding: utf-8 -*-
import os
import sys
# Appends the main plugin dir to the PYTHONPATH if an internal package cannot be imported.
# Examples: In Plex Media Server all modules are under "Code.*" package, and in Enigma2 under "Plugins.Extensions.*"
try:
# from core import logger
import core
except:
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))

View File

@@ -1,15 +0,0 @@
{
"id": "absoluporn",
"name": "absoluporn",
"active": true,
"adult": true,
"language": ["*"],
"thumbnail": "http://www.absoluporn.es/image/deco/logo.gif",
"banner": "",
"categories": [
"adult"
],
"settings": [
]
}

View File

@@ -1,95 +0,0 @@
# -*- coding: utf-8 -*-
#------------------------------------------------------------
import urlparse,urllib2,urllib,re
import os, sys
from platformcode import config, logger
from core import scrapertools
from core.item import Item
from core import servertools
from core import httptools
host = 'http://www.absoluporn.es'
def mainlist(item):
logger.info()
itemlist = []
itemlist.append( Item(channel=item.channel, title="Nuevos" , action="lista", url=host + "/wall-date-1.html"))
itemlist.append( Item(channel=item.channel, title="Mas valorados" , action="lista", url=host + "/wall-note-1.html"))
itemlist.append( Item(channel=item.channel, title="Mas vistos" , action="lista", url=host + "/wall-main-1.html"))
itemlist.append( Item(channel=item.channel, title="Mas largos" , action="lista", url=host + "/wall-time-1.html"))
itemlist.append( Item(channel=item.channel, title="Categorias" , action="categorias", url=host))
itemlist.append( Item(channel=item.channel, title="Buscar", action="search"))
return itemlist
def search(item, texto):
logger.info()
texto = texto.replace(" ", "+")
item.url = host + "/search-%s-1.html" % texto
try:
return lista(item)
except:
import sys
for line in sys.exc_info():
logger.error("%s" % line)
return []
def categorias(item):
logger.info()
itemlist = []
data = httptools.downloadpage(item.url).data
patron = '&nbsp;<a href="([^"]+)" class="link1">([^"]+)</a>'
matches = re.compile(patron,re.DOTALL).findall(data)
for scrapedurl,scrapedtitle in matches:
scrapedplot = ""
scrapedthumbnail = ""
scrapedurl = scrapedurl.replace(".html", "_date.html")
scrapedurl = host +"/" + scrapedurl
itemlist.append( Item(channel=item.channel, action="lista", title=scrapedtitle, url=scrapedurl,
thumbnail=scrapedthumbnail , plot=scrapedplot) )
return itemlist
def lista(item):
logger.info()
itemlist = []
data = httptools.downloadpage(item.url).data
data = re.sub(r"\n|\r|\t|&nbsp;|<br>|<br/>", "", data)
patron = '<div class="thumb-main-titre"><a href="([^"]+)".*?'
patron += 'title="([^"]+)".*?'
patron += 'src="([^"]+)".*?'
patron += '<div class="time">(.*?)</div>'
matches = re.compile(patron,re.DOTALL).findall(data)
for scrapedurl,scrapedtitle,scrapedthumbnail,scrapedtime in matches:
url = urlparse.urljoin(item.url,scrapedurl)
title = "[COLOR yellow]" + scrapedtime + "[/COLOR] " + scrapedtitle
thumbnail = scrapedthumbnail
plot = ""
itemlist.append( Item(channel=item.channel, action="play", title=title, url=url, thumbnail=thumbnail, plot=plot,
fanart=thumbnail, contentTitle = scrapedtitle))
next_page = scrapertools.find_single_match(data, '<span class="text16">\d+</span> <a href="..([^"]+)"')
if next_page:
next_page = urlparse.urljoin(item.url,next_page)
itemlist.append( Item(channel=item.channel, action="lista", title="Página Siguiente >>", text_color="blue",
url=next_page) )
return itemlist
def play(item):
logger.info()
itemlist = []
data = httptools.downloadpage(item.url).data
patron = 'servervideo = \'([^\']+)\'.*?'
patron += 'path = \'([^\']+)\'.*?'
patron += 'filee = \'([^\']+)\'.*?'
matches = scrapertools.find_multiple_matches(data, patron)
for servervideo,path,filee in matches:
scrapedurl = servervideo + path + "56ea912c4df934c216c352fa8d623af3" + filee
itemlist.append(Item(channel=item.channel, action="play", title=item.title, fulltitle=item.fulltitle, url=scrapedurl,
thumbnail=item.thumbnail, plot=item.plot, show=item.title, server="directo", folder=False))
return itemlist

View File

@@ -1,921 +0,0 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# Alfa favoritos
# ==============
# - Lista de enlaces guardados como favoritos, solamente en Alfa, no Kodi.
# - Los enlaces se organizan en carpetas (virtuales) que puede definir el usuario.
# - Se utiliza un sólo fichero para guardar todas las carpetas y enlaces: alfavorites-default.json
# - Se puede copiar alfavorites-default.json a otros dispositivos ya que la única dependencia local es el thumbnail asociado a los enlaces,
# pero se detecta por código y se ajusta al dispositivo actual.
# - Se pueden tener distintos ficheros de alfavoritos y alternar entre ellos, pero solamente uno de ellos es la "lista activa".
# - Los ficheros deben estar en config.get_data_path() y empezar por alfavorites- y terminar en .json
# Requerimientos en otros módulos para ejecutar este canal:
# - Añadir un enlace a este canal en channelselector.py
# - Modificar platformtools.py para controlar el menú contextual y añadir "Guardar enlace" en set_context_commands
# ------------------------------------------------------------
import os, re
from datetime import datetime
from core.item import Item
from platformcode import config, logger, platformtools
from core import filetools, jsontools
def fechahora_actual():
return datetime.now().strftime('%Y-%m-%d %H:%M')
# Helpers para listas
# -------------------
PREFIJO_LISTA = 'alfavorites-'
# Devuelve el nombre de la lista activa (Ej: alfavorites-default.json)
def get_lista_activa():
return config.get_setting('lista_activa', default = PREFIJO_LISTA + 'default.json')
# Extrae nombre de la lista del fichero, quitando prefijo y sufijo (Ej: alfavorites-Prueba.json => Prueba)
def get_name_from_filename(filename):
return filename.replace(PREFIJO_LISTA, '').replace('.json', '')
# Componer el fichero de lista a partir de un nombre, añadiendo prefijo y sufijo (Ej: Prueba => alfavorites-Prueba.json)
def get_filename_from_name(name):
return PREFIJO_LISTA + name + '.json'
# Apuntar en un fichero de log los códigos de los ficheros que se hayan compartido
def save_log_lista_shared(msg):
msg = fechahora_actual() + ': ' + msg + os.linesep
fullfilename = os.path.join(config.get_data_path(), 'alfavorites_shared.log')
with open(fullfilename, 'a') as f: f.write(msg); f.close()
# Limpiar texto para usar como nombre de fichero
def text_clean(txt, disallowed_chars = '[^a-zA-Z0-9\-_()\[\]. ]+', blank_char = ' '):
import unicodedata
try:
txt = unicode(txt, 'utf-8')
except NameError: # unicode is a default on python 3
pass
txt = unicodedata.normalize('NFKD', txt).encode('ascii', 'ignore')
txt = txt.decode('utf-8').strip()
if blank_char != ' ': txt = txt.replace(' ', blank_char)
txt = re.sub(disallowed_chars, '', txt)
return str(txt)
# Clase para cargar y guardar en el fichero de Alfavoritos
# --------------------------------------------------------
class AlfavoritesData:
def __init__(self, filename = None):
# Si no se especifica ningún fichero se usa la lista_activa (si no la hay se crea)
if filename == None:
filename = get_lista_activa()
self.user_favorites_file = os.path.join(config.get_data_path(), filename)
if not os.path.exists(self.user_favorites_file):
fichero_anterior = os.path.join(config.get_data_path(), 'user_favorites.json')
if os.path.exists(fichero_anterior): # formato anterior, convertir (a eliminar después de algunas versiones)
jsondata = jsontools.load(filetools.read(fichero_anterior))
self.user_favorites = jsondata
self.info_lista = {}
self.save()
filetools.remove(fichero_anterior)
else:
self.user_favorites = []
else:
jsondata = jsontools.load(filetools.read(self.user_favorites_file))
if not 'user_favorites' in jsondata or not 'info_lista' in jsondata: # formato incorrecto
self.user_favorites = []
else:
self.user_favorites = jsondata['user_favorites']
self.info_lista = jsondata['info_lista']
if len(self.user_favorites) == 0:
self.info_lista = {}
# Crear algunas carpetas por defecto
self.user_favorites.append({ 'title': config.get_localized_string(30122), 'items': [] })
self.user_favorites.append({ 'title': config.get_localized_string(30123), 'items': [] })
self.user_favorites.append({ 'title': config.get_localized_string(70149), 'items': [] })
self.save()
def save(self):
if 'created' not in self.info_lista:
self.info_lista['created'] = fechahora_actual()
self.info_lista['updated'] = fechahora_actual()
jsondata = {}
jsondata['user_favorites'] = self.user_favorites
jsondata['info_lista'] = self.info_lista
if not filetools.write(self.user_favorites_file, jsontools.dump(jsondata)):
platformtools.dialog_ok('Alfa', config.get_localized_string(70614), os.path.basename(self.user_favorites_file))
# ============================
# Añadir desde menú contextual
# ============================
def addFavourite(item):
logger.info()
alfav = AlfavoritesData()
# Si se llega aquí mediante el menú contextual, hay que recuperar los parámetros action y channel
if item.from_action:
item.__dict__['action'] = item.__dict__.pop('from_action')
if item.from_channel:
item.__dict__['channel'] = item.__dict__.pop('from_channel')
# Limpiar título
item.title = re.sub(r'\[COLOR [^\]]*\]', '', item.title.replace('[/COLOR]', '')).strip()
if item.text_color:
item.__dict__.pop('text_color')
# Diálogo para escoger/crear carpeta
i_perfil = _selecciona_perfil(alfav, config.get_localized_string(70546))
if i_perfil == -1: return False
# Detectar que el mismo enlace no exista ya en la carpeta
campos = ['channel','action','url','extra','list_type'] # si todos estos campos coinciden se considera que el enlace ya existe
for enlace in alfav.user_favorites[i_perfil]['items']:
it = Item().fromurl(enlace)
repe = True
for prop in campos:
if prop in it.__dict__ and prop in item.__dict__ and it.__dict__[prop] != item.__dict__[prop]:
repe = False
break
if repe:
platformtools.dialog_notification(config.get_localized_string(70615), config.get_localized_string(70616))
return False
# Si es una película/serie, completar información de tmdb si no se tiene activado tmdb_plus_info (para season/episodio no hace falta pq ya se habrá hecho la "segunda pasada")
if (item.contentType == 'movie' or item.contentType == 'tvshow') and not config.get_setting('tmdb_plus_info', default=False):
from core import tmdb
tmdb.set_infoLabels(item, True) # obtener más datos en "segunda pasada" (actores, duración, ...)
# Añadir fecha en que se guarda
item.date_added = fechahora_actual()
# Guardar
alfav.user_favorites[i_perfil]['items'].append(item.tourl())
alfav.save()
platformtools.dialog_notification(config.get_localized_string(70531), config.get_localized_string(70532) % alfav.user_favorites[i_perfil]['title'])
return True
# ====================
# NAVEGACIÓN
# ====================
def mainlist(item):
logger.info()
alfav = AlfavoritesData()
item.category = get_name_from_filename(os.path.basename(alfav.user_favorites_file))
itemlist = []
last_i = len(alfav.user_favorites) - 1
for i_perfil, perfil in enumerate(alfav.user_favorites):
context = []
context.append({'title': config.get_localized_string(70533), 'channel': item.channel, 'action': 'editar_perfil_titulo',
'i_perfil': i_perfil})
context.append({'title': config.get_localized_string(70534), 'channel': item.channel, 'action': 'eliminar_perfil',
'i_perfil': i_perfil})
if i_perfil > 0:
context.append({'title': config.get_localized_string(70535), 'channel': item.channel, 'action': 'mover_perfil',
'i_perfil': i_perfil, 'direccion': 'top'})
context.append({'title': config.get_localized_string(70536), 'channel': item.channel, 'action': 'mover_perfil',
'i_perfil': i_perfil, 'direccion': 'arriba'})
if i_perfil < last_i:
context.append({'title': config.get_localized_string(70537), 'channel': item.channel, 'action': 'mover_perfil',
'i_perfil': i_perfil, 'direccion': 'abajo'})
context.append({'title': config.get_localized_string(70538), 'channel': item.channel, 'action': 'mover_perfil',
'i_perfil': i_perfil, 'direccion': 'bottom'})
plot = '%d enlaces en la carpeta' % len(perfil['items'])
itemlist.append(Item(channel=item.channel, action='mostrar_perfil', title=perfil['title'], plot=plot, i_perfil=i_perfil, context=context))
itemlist.append(item.clone(action='crear_perfil', title=config.get_localized_string(70542), folder=False))
itemlist.append(item.clone(action='mainlist_listas', title=config.get_localized_string(70603)))
return itemlist
def mostrar_perfil(item):
logger.info()
alfav = AlfavoritesData()
itemlist = []
i_perfil = item.i_perfil
if not alfav.user_favorites[i_perfil]: return itemlist
last_i = len(alfav.user_favorites[i_perfil]['items']) - 1
ruta_runtime = config.get_runtime_path()
for i_enlace, enlace in enumerate(alfav.user_favorites[i_perfil]['items']):
it = Item().fromurl(enlace)
it.context = [ {'title': '[COLOR blue]'+config.get_localized_string(70617)+'[/COLOR]', 'channel': item.channel, 'action': 'acciones_enlace',
'i_enlace': i_enlace, 'i_perfil': i_perfil} ]
it.plot += '[CR][CR][COLOR blue]Canal:[/COLOR] ' + it.channel + ' [COLOR blue]Action:[/COLOR] ' + it.action
if it.extra != '': it.plot += ' [COLOR blue]Extra:[/COLOR] ' + it.extra
it.plot += '[CR][COLOR blue]Url:[/COLOR] ' + it.url if isinstance(it.url, str) else '...'
if it.date_added != '': it.plot += '[CR][COLOR blue]Added:[/COLOR] ' + it.date_added
# Si no es una url, ni tiene la ruta del sistema, convertir el path ya que se habrá copiado de otro dispositivo.
# Sería más óptimo que la conversión se hiciera con un menú de importar, pero de momento se controla en run-time.
if it.thumbnail and '://' not in it.thumbnail and not it.thumbnail.startswith(ruta_runtime):
ruta, fichero = filetools.split(it.thumbnail)
if ruta == '' and fichero == it.thumbnail: # en linux el split con un path de windows no separa correctamente
ruta, fichero = filetools.split(it.thumbnail.replace('\\','/'))
if 'channels' in ruta and 'thumb' in ruta:
it.thumbnail = filetools.join(ruta_runtime, 'resources', 'media', 'channels', 'thumb', fichero)
elif 'themes' in ruta and 'default' in ruta:
it.thumbnail = filetools.join(ruta_runtime, 'resources', 'media', 'themes', 'default', fichero)
itemlist.append(it)
return itemlist
# Rutinas internas compartidas
# ----------------------------
# Diálogo para seleccionar/crear una carpeta. Devuelve índice de la carpeta en user_favorites (-1 si cancel)
def _selecciona_perfil(alfav, titulo='Seleccionar carpeta', i_actual=-1):
acciones = [(perfil['title'] if i_p != i_actual else '[I][COLOR pink]%s[/COLOR][/I]' % perfil['title']) for i_p, perfil in enumerate(alfav.user_favorites)]
acciones.append('Crear nueva carpeta')
i_perfil = -1
while i_perfil == -1: # repetir hasta seleccionar una carpeta o cancelar
ret = platformtools.dialog_select(titulo, acciones)
if ret == -1: return -1 # pedido cancel
if ret < len(alfav.user_favorites):
i_perfil = ret
else: # crear nueva carpeta
if _crea_perfil(alfav):
i_perfil = len(alfav.user_favorites) - 1
return i_perfil
# Diálogo para crear una carpeta
def _crea_perfil(alfav):
titulo = platformtools.dialog_input(default='', heading=config.get_localized_string(70551))
if titulo is None or titulo == '':
return False
alfav.user_favorites.append({'title': titulo, 'items': []})
alfav.save()
return True
# Gestión de perfiles y enlaces
# -----------------------------
def crear_perfil(item):
logger.info()
alfav = AlfavoritesData()
if not _crea_perfil(alfav): return False
platformtools.itemlist_refresh()
return True
def editar_perfil_titulo(item):
logger.info()
alfav = AlfavoritesData()
if not alfav.user_favorites[item.i_perfil]: return False
titulo = platformtools.dialog_input(default=alfav.user_favorites[item.i_perfil]['title'], heading=config.get_localized_string(70533))
if titulo is None or titulo == '' or titulo == alfav.user_favorites[item.i_perfil]['title']:
return False
alfav.user_favorites[item.i_perfil]['title'] = titulo
alfav.save()
platformtools.itemlist_refresh()
return True
def eliminar_perfil(item):
logger.info()
alfav = AlfavoritesData()
if not alfav.user_favorites[item.i_perfil]: return False
# Pedir confirmación
if not platformtools.dialog_yesno(config.get_localized_string(70618), config.get_localized_string(70619)): return False
del alfav.user_favorites[item.i_perfil]
alfav.save()
platformtools.itemlist_refresh()
return True
def acciones_enlace(item):
logger.info()
acciones = [config.get_localized_string(70620), config.get_localized_string(70621), config.get_localized_string(70622), config.get_localized_string(70623),
config.get_localized_string(70624), config.get_localized_string(70548), config.get_localized_string(70625),
config.get_localized_string(70626), config.get_localized_string(70627), config.get_localized_string(70628)]
ret = platformtools.dialog_select('Acción a ejecutar', acciones)
if ret == -1:
return False # pedido cancel
elif ret == 0:
return editar_enlace_titulo(item)
elif ret == 1:
return editar_enlace_color(item)
elif ret == 2:
return editar_enlace_thumbnail(item)
elif ret == 3:
return editar_enlace_carpeta(item)
elif ret == 4:
return editar_enlace_lista(item)
elif ret == 5:
return eliminar_enlace(item)
elif ret == 6:
return mover_enlace(item.clone(direccion='top'))
elif ret == 7:
return mover_enlace(item.clone(direccion='arriba'))
elif ret == 8:
return mover_enlace(item.clone(direccion='abajo'))
elif ret == 9:
return mover_enlace(item.clone(direccion='bottom'))
def editar_enlace_titulo(item):
logger.info()
alfav = AlfavoritesData()
if not alfav.user_favorites[item.i_perfil]: return False
if not alfav.user_favorites[item.i_perfil]['items'][item.i_enlace]: return False
it = Item().fromurl(alfav.user_favorites[item.i_perfil]['items'][item.i_enlace])
titulo = platformtools.dialog_input(default=it.title, heading='Cambiar título del enlace')
if titulo is None or titulo == '' or titulo == it.title:
return False
it.title = titulo
alfav.user_favorites[item.i_perfil]['items'][item.i_enlace] = it.tourl()
alfav.save()
platformtools.itemlist_refresh()
return True
def editar_enlace_color(item):
logger.info()
alfav = AlfavoritesData()
if not alfav.user_favorites[item.i_perfil]: return False
if not alfav.user_favorites[item.i_perfil]['items'][item.i_enlace]: return False
it = Item().fromurl(alfav.user_favorites[item.i_perfil]['items'][item.i_enlace])
colores = ['green','yellow','red','blue','white','orange','lime','aqua','pink','violet','purple','tomato','olive','antiquewhite','gold']
opciones = ['[COLOR %s]%s[/COLOR]' % (col, col) for col in colores]
ret = platformtools.dialog_select('Seleccionar color:', opciones)
if ret == -1: return False # pedido cancel
it.text_color = colores[ret]
alfav.user_favorites[item.i_perfil]['items'][item.i_enlace] = it.tourl()
alfav.save()
platformtools.itemlist_refresh()
return True
def editar_enlace_thumbnail(item):
logger.info()
alfav = AlfavoritesData()
if not alfav.user_favorites[item.i_perfil]: return False
if not alfav.user_favorites[item.i_perfil]['items'][item.i_enlace]: return False
it = Item().fromurl(alfav.user_favorites[item.i_perfil]['items'][item.i_enlace])
# A partir de Kodi 17 se puede usar xbmcgui.Dialog().select con thumbnails (ListItem & useDetails=True)
is_kodi17 = (config.get_platform(True)['num_version'] >= 17.0)
if is_kodi17:
import xbmcgui
# Diálogo para escoger thumbnail (el del canal o iconos predefinidos)
opciones = []
ids = []
try:
from core import channeltools
channel_parameters = channeltools.get_channel_parameters(it.channel)
if channel_parameters['thumbnail'] != '':
nombre = 'Canal %s' % it.channel
if is_kodi17:
it_thumb = xbmcgui.ListItem(nombre)
it_thumb.setArt({ 'thumb': channel_parameters['thumbnail'] })
opciones.append(it_thumb)
else:
opciones.append(nombre)
ids.append(channel_parameters['thumbnail'])
except:
pass
resource_path = os.path.join(config.get_runtime_path(), 'resources', 'media', 'themes', 'default')
for f in sorted(os.listdir(resource_path)):
if f.startswith('thumb_') and not f.startswith('thumb_intervenido') and f != 'thumb_back.png':
nombre = f.replace('thumb_', '').replace('_', ' ').replace('.png', '')
if is_kodi17:
it_thumb = xbmcgui.ListItem(nombre)
it_thumb.setArt({ 'thumb': os.path.join(resource_path, f) })
opciones.append(it_thumb)
else:
opciones.append(nombre)
ids.append(os.path.join(resource_path, f))
if is_kodi17:
ret = xbmcgui.Dialog().select('Seleccionar thumbnail:', opciones, useDetails=True)
else:
ret = platformtools.dialog_select('Seleccionar thumbnail:', opciones)
if ret == -1: return False # pedido cancel
it.thumbnail = ids[ret]
alfav.user_favorites[item.i_perfil]['items'][item.i_enlace] = it.tourl()
alfav.save()
platformtools.itemlist_refresh()
return True
def editar_enlace_carpeta(item):
logger.info()
alfav = AlfavoritesData()
if not alfav.user_favorites[item.i_perfil]: return False
if not alfav.user_favorites[item.i_perfil]['items'][item.i_enlace]: return False
# Diálogo para escoger/crear carpeta
i_perfil = _selecciona_perfil(alfav, 'Mover enlace a:', item.i_perfil)
if i_perfil == -1 or i_perfil == item.i_perfil: return False
alfav.user_favorites[i_perfil]['items'].append(alfav.user_favorites[item.i_perfil]['items'][item.i_enlace])
del alfav.user_favorites[item.i_perfil]['items'][item.i_enlace]
alfav.save()
platformtools.itemlist_refresh()
return True
def editar_enlace_lista(item):
logger.info()
alfav = AlfavoritesData()
if not alfav.user_favorites[item.i_perfil]: return False
if not alfav.user_favorites[item.i_perfil]['items'][item.i_enlace]: return False
# Diálogo para escoger lista
opciones = []
itemlist_listas = mainlist_listas(item)
for it in itemlist_listas:
if it.lista != '' and '[<---]' not in it.title: # descarta item crear y lista activa
opciones.append(it.lista)
if len(opciones) == 0:
platformtools.dialog_ok('Alfa', 'No hay otras listas dónde mover el enlace.', 'Puedes crearlas desde el menú Gestionar listas de enlaces')
return False
ret = platformtools.dialog_select('Seleccionar lista destino', opciones)
if ret == -1:
return False # pedido cancel
alfav_destino = AlfavoritesData(opciones[ret])
# Diálogo para escoger/crear carpeta en la lista de destino
i_perfil = _selecciona_perfil(alfav_destino, 'Seleccionar carpeta destino', -1)
if i_perfil == -1: return False
alfav_destino.user_favorites[i_perfil]['items'].append(alfav.user_favorites[item.i_perfil]['items'][item.i_enlace])
del alfav.user_favorites[item.i_perfil]['items'][item.i_enlace]
alfav_destino.save()
alfav.save()
platformtools.itemlist_refresh()
return True
def eliminar_enlace(item):
logger.info()
alfav = AlfavoritesData()
if not alfav.user_favorites[item.i_perfil]: return False
if not alfav.user_favorites[item.i_perfil]['items'][item.i_enlace]: return False
del alfav.user_favorites[item.i_perfil]['items'][item.i_enlace]
alfav.save()
platformtools.itemlist_refresh()
return True
# Mover perfiles y enlaces (arriba, abajo, top, bottom)
# ------------------------
def mover_perfil(item):
logger.info()
alfav = AlfavoritesData()
alfav.user_favorites = _mover_item(alfav.user_favorites, item.i_perfil, item.direccion)
alfav.save()
platformtools.itemlist_refresh()
return True
def mover_enlace(item):
logger.info()
alfav = AlfavoritesData()
if not alfav.user_favorites[item.i_perfil]: return False
alfav.user_favorites[item.i_perfil]['items'] = _mover_item(alfav.user_favorites[item.i_perfil]['items'], item.i_enlace, item.direccion)
alfav.save()
platformtools.itemlist_refresh()
return True
# Mueve un item determinado (numérico) de una lista (arriba, abajo, top, bottom) y devuelve la lista modificada
def _mover_item(lista, i_selected, direccion):
last_i = len(lista) - 1
if i_selected > last_i or i_selected < 0: return lista # índice inexistente en lista
if direccion == 'arriba':
if i_selected == 0: # Ya está arriba de todo
return lista
lista.insert(i_selected - 1, lista.pop(i_selected))
elif direccion == 'abajo':
if i_selected == last_i: # Ya está abajo de todo
return lista
lista.insert(i_selected + 1, lista.pop(i_selected))
elif direccion == 'top':
if i_selected == 0: # Ya está arriba de todo
return lista
lista.insert(0, lista.pop(i_selected))
elif direccion == 'bottom':
if i_selected == last_i: # Ya está abajo de todo
return lista
lista.insert(last_i, lista.pop(i_selected))
return lista
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Gestionar diferentes listas de alfavoritos
# ------------------------------------------
def mainlist_listas(item):
logger.info()
itemlist = []
item.category = 'Listas'
lista_activa = get_lista_activa()
import glob
path = os.path.join(config.get_data_path(), PREFIJO_LISTA+'*.json')
for fichero in glob.glob(path):
lista = os.path.basename(fichero)
nombre = get_name_from_filename(lista)
titulo = nombre if lista != lista_activa else '[COLOR gold]%s[/COLOR] [<---]' % nombre
itemlist.append(item.clone(action='acciones_lista', lista=lista, title=titulo, folder=False))
itemlist.append(item.clone(action='acciones_nueva_lista', title=config.get_localized_string(70642), folder=False))
return itemlist
def acciones_lista(item):
logger.info()
acciones = [config.get_localized_string(70604), config.get_localized_string(70629),
config.get_localized_string(70605), config.get_localized_string(70606), config.get_localized_string(70607)]
ret = platformtools.dialog_select(item.lista, acciones)
if ret == -1:
return False # pedido cancel
elif ret == 0:
return activar_lista(item)
elif ret == 1:
return renombrar_lista(item)
elif ret == 2:
return compartir_lista(item)
elif ret == 3:
return eliminar_lista(item)
elif ret == 4:
return informacion_lista(item)
def activar_lista(item):
logger.info()
fullfilename = os.path.join(config.get_data_path(), item.lista)
if not os.path.exists(fullfilename):
platformtools.dialog_ok('Alfa', config.get_localized_string(70630), item.lista)
return False
config.set_setting('lista_activa', item.lista)
from channelselector import get_thumb
item_inicio = Item(title=config.get_localized_string(70527), channel="alfavorites", action="mainlist",
thumbnail=get_thumb("mylink.png"),
category=config.get_localized_string(70527), viewmode="thumbnails")
platformtools.itemlist_update(item_inicio, replace=True)
return True
def renombrar_lista(item):
logger.info()
fullfilename_current = os.path.join(config.get_data_path(), item.lista)
if not os.path.exists(fullfilename_current):
platformtools.dialog_ok('Alfa', config.get_localized_string(70630), fullfilename_current)
return False
nombre = get_name_from_filename(item.lista)
titulo = platformtools.dialog_input(default=nombre, heading=config.get_localized_string(70612))
if titulo is None or titulo == '' or titulo == nombre:
return False
titulo = text_clean(titulo, blank_char='_')
filename = get_filename_from_name(titulo)
fullfilename = os.path.join(config.get_data_path(), filename)
# Comprobar que el nuevo nombre no exista
if os.path.exists(fullfilename):
platformtools.dialog_ok('Alfa', config.get_localized_string(70613), fullfilename)
return False
# Rename del fichero
if not filetools.rename(fullfilename_current, filename):
platformtools.dialog_ok('Alfa', config.get_localized_string(70631), fullfilename)
return False
# Update settings si es la lista activa
if item.lista == get_lista_activa():
config.set_setting('lista_activa', filename)
platformtools.itemlist_refresh()
return True
def eliminar_lista(item):
logger.info()
fullfilename = os.path.join(config.get_data_path(), item.lista)
if not os.path.exists(fullfilename):
platformtools.dialog_ok('Alfa', config.get_localized_string(70630), item.lista)
return False
if item.lista == get_lista_activa():
platformtools.dialog_ok('Alfa', config.get_localized_string(70632), item.lista)
return False
if not platformtools.dialog_yesno(config.get_localized_string(70606), config.get_localized_string(70633) + ' %s ?' % item.lista): return False
filetools.remove(fullfilename)
platformtools.itemlist_refresh()
return True
def informacion_lista(item):
logger.info()
fullfilename = os.path.join(config.get_data_path(), item.lista)
if not os.path.exists(fullfilename):
platformtools.dialog_ok('Alfa', config.get_localized_string(70630), item.lista)
return False
alfav = AlfavoritesData(item.lista)
txt = 'Lista: [COLOR gold]%s[/COLOR]' % item.lista
txt += '[CR]' + config.get_localized_string(70634) + ' ' + alfav.info_lista['created'] + ' ' + config.get_localized_string(70635) + ' ' + alfav.info_lista['updated']
if 'downloaded_date' in alfav.info_lista:
txt += '[CR]' + config.get_localized_string(70636) + ' ' + alfav.info_lista['downloaded_date'] + ' ' + alfav.info_lista['downloaded_from'] + ' ' + config.get_localized_string(70637)
if 'tinyupload_date' in alfav.info_lista:
txt += '[CR]' + config.get_localized_string(70638) + ' ' + alfav.info_lista['tinyupload_date'] + ' ' + config.get_localized_string(70639) + ' [COLOR blue]' + alfav.info_lista['tinyupload_code'] + '[/COLOR]'
txt += '[CR]' + config.get_localized_string(70640) + ' ' + len(alfav.user_favorites)
for perfil in alfav.user_favorites:
txt += '[CR]- %s (%d %s)' % (perfil['title'], len(perfil['items']), config.get_localized_string(70641))
platformtools.dialog_textviewer(config.get_localized_string(70607), txt)
return True
def compartir_lista(item):
logger.info()
fullfilename = os.path.join(config.get_data_path(), item.lista)
if not os.path.exists(fullfilename):
platformtools.dialog_ok('Alfa', config.get_localized_string(70630), fullfilename)
return False
try:
progreso = platformtools.dialog_progress_bg(config.get_localized_string(70643), config.get_localized_string(70644))
# Acceso a la página principal de tinyupload para obtener datos necesarios
from core import httptools, scrapertools
data = httptools.downloadpage('http://s000.tinyupload.com/index.php').data
upload_url = scrapertools.find_single_match(data, 'form action="([^"]+)')
sessionid = scrapertools.find_single_match(upload_url, 'sid=(.+)')
progreso.update(10, config.get_localized_string(70645), config.get_localized_string(70646))
# Envío del fichero a tinyupload mediante multipart/form-data
from lib import MultipartPostHandler
import urllib2
opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)
params = { 'MAX_FILE_SIZE' : '52428800', 'file_description' : '', 'sessionid' : sessionid, 'uploaded_file' : open(fullfilename, 'rb') }
handle = opener.open(upload_url, params)
data = handle.read()
progreso.close()
if not 'File was uploaded successfuly' in data:
logger.debug(data)
platformtools.dialog_ok('Alfa', config.get_localized_string(70647))
return False
codigo = scrapertools.find_single_match(data, 'href="index\.php\?file_id=([^"]+)')
except:
platformtools.dialog_ok('Alfa', config.get_localized_string(70647), item.lista)
return False
# Apuntar código en fichero de log y dentro de la lista
save_log_lista_shared(config.get_localized_string(70648) + ' ' + item.lista + ' ' + codigo + ' ' + config.get_localized_string(70649))
alfav = AlfavoritesData(item.lista)
alfav.info_lista['tinyupload_date'] = fechahora_actual()
alfav.info_lista['tinyupload_code'] = codigo
alfav.save()
platformtools.dialog_ok('Alfa', config.get_localized_string(70650), codigo)
return True
def acciones_nueva_lista(item):
logger.info()
acciones = [config.get_localized_string(70651),
config.get_localized_string(70652),
config.get_localized_string(70653),
config.get_localized_string(70654)]
ret = platformtools.dialog_select(config.get_localized_string(70608), acciones)
if ret == -1:
return False # pedido cancel
elif ret == 0:
return crear_lista(item)
elif ret == 1:
codigo = platformtools.dialog_input(default='', heading=config.get_localized_string(70609)) # 05370382084539519168
if codigo is None or codigo == '':
return False
return descargar_lista(item, 'http://s000.tinyupload.com/?file_id=' + codigo)
elif ret == 2:
url = platformtools.dialog_input(default='https://', heading=config.get_localized_string(70610))
if url is None or url == '':
return False
return descargar_lista(item, url)
elif ret == 3:
txt = config.get_localized_string(70611)
platformtools.dialog_textviewer(config.get_localized_string(70607), txt)
return False
def crear_lista(item):
logger.info()
titulo = platformtools.dialog_input(default='', heading=config.get_localized_string(70612))
if titulo is None or titulo == '':
return False
titulo = text_clean(titulo, blank_char='_')
filename = get_filename_from_name(titulo)
fullfilename = os.path.join(config.get_data_path(), filename)
# Comprobar que el fichero no exista ya
if os.path.exists(fullfilename):
platformtools.dialog_ok('Alfa', config.get_localized_string(70613), fullfilename)
return False
# Provocar que se guarde con las carpetas vacías por defecto
alfav = AlfavoritesData(filename)
platformtools.itemlist_refresh()
return True
def descargar_lista(item, url):
logger.info()
from core import httptools, scrapertools
if 'tinyupload.com/' in url:
try:
from urlparse import urlparse
data = httptools.downloadpage(url).data
logger.debug(data)
down_url, url_name = scrapertools.find_single_match(data, ' href="(download\.php[^"]*)"><b>([^<]*)')
url_json = '{uri.scheme}://{uri.netloc}/'.format(uri=urlparse(url)) + down_url
except:
platformtools.dialog_ok('Alfa', config.get_localized_string(70655), url)
return False
elif 'zippyshare.com/' in url:
from core import servertools
video_urls, puedes, motivo = servertools.resolve_video_urls_for_playing('zippyshare', url)
if not puedes:
platformtools.dialog_ok('Alfa', config.get_localized_string(70655), motivo)
return False
url_json = video_urls[0][1] # https://www58.zippyshare.com/d/qPzzQ0UM/25460/alfavorites-testeanding.json
url_name = url_json[url_json.rfind('/')+1:]
elif 'friendpaste.com/' in url:
url_json = url if url.endswith('/raw') else url + '/raw'
url_name = 'friendpaste'
else:
url_json = url
url_name = url[url.rfind('/')+1:]
# Download json
data = httptools.downloadpage(url_json).data
# Verificar formato json de alfavorites y añadir info de la descarga
jsondata = jsontools.load(data)
if 'user_favorites' not in jsondata or 'info_lista' not in jsondata:
logger.debug(data)
platformtools.dialog_ok('Alfa', config.get_localized_string(70656))
return False
jsondata['info_lista']['downloaded_date'] = fechahora_actual()
jsondata['info_lista']['downloaded_from'] = url
data = jsontools.dump(jsondata)
# Pedir nombre para la lista descargada
nombre = get_name_from_filename(url_name)
titulo = platformtools.dialog_input(default=nombre, heading=config.get_localized_string(70657))
if titulo is None or titulo == '':
return False
titulo = text_clean(titulo, blank_char='_')
filename = get_filename_from_name(titulo)
fullfilename = os.path.join(config.get_data_path(), filename)
# Si el nuevo nombre ya existe pedir confirmación para sobrescribir
if os.path.exists(fullfilename):
if not platformtools.dialog_yesno('Alfa', config.get_localized_string(70613), config.get_localized_string(70658), filename):
return False
if not filetools.write(fullfilename, data):
platformtools.dialog_ok('Alfa', config.get_localized_string(70659), filename)
platformtools.dialog_ok('Alfa', config.get_localized_string(70660), filename)
platformtools.itemlist_refresh()
return True

View File

@@ -1,14 +0,0 @@
{
"id": "alsoporn",
"name": "alsoporn",
"active": true,
"adult": true,
"language": ["*"],
"thumbnail": "http://alsoporn.com/images/alsoporn.png",
"banner": "",
"categories": [
"adult"
],
"settings": [
]
}

View File

@@ -1,90 +0,0 @@
# -*- coding: utf-8 -*-
#------------------------------------------------------------
import urlparse,urllib2,urllib,re
import os, sys
from platformcode import config, logger
from core import scrapertools
from core.item import Item
from core import servertools
from core import httptools
host = 'http://www.alsoporn.com'
def mainlist(item):
logger.info()
itemlist = []
# itemlist.append( Item(channel=item.channel, title="Nuevos" , action="lista", url=host + "/en/g/All/new/1"))
itemlist.append( Item(channel=item.channel, title="Top" , action="lista", url=host + "/g/All/top/1"))
itemlist.append( Item(channel=item.channel, title="Categorias" , action="categorias", url=host))
itemlist.append( Item(channel=item.channel, title="Buscar", action="search"))
return itemlist
def search(item, texto):
logger.info()
texto = texto.replace(" ", "+")
item.url = host + "/search/=%s/" % texto
try:
return lista(item)
except:
import sys
for line in sys.exc_info():
logger.error("%s" % line)
return []
def categorias(item):
logger.info()
itemlist = []
data = httptools.downloadpage(item.url).data
data = re.sub(r"\n|\r|\t|&nbsp;|<br>", "", data)
patron = '<a href="([^"]+)">.*?'
patron += '<img src="([^"]+)" alt="([^"]+)" />'
matches = re.compile(patron,re.DOTALL).findall(data)
for scrapedurl,scrapedthumbnail,scrapedtitle in matches:
scrapedplot = ""
scrapedurl = urlparse.urljoin(item.url,scrapedurl)
itemlist.append( Item(channel=item.channel, action="lista", title=scrapedtitle, url=scrapedurl,
fanart=scrapedthumbnail, thumbnail=scrapedthumbnail, plot=scrapedplot) )
return sorted(itemlist, key=lambda i: i.title)
def lista(item):
logger.info()
itemlist = []
data = httptools.downloadpage(item.url).data
data = re.sub(r"\n|\r|\t|&nbsp;|<br>", "", data)
patron = '<div class="alsoporn_prev">.*?'
patron += '<a href="([^"]+)">.*?'
patron += '<img src="([^"]+)" alt="([^"]+)">.*?'
patron += '<span>([^"]+)</span>'
matches = re.compile(patron,re.DOTALL).findall(data)
for scrapedurl,scrapedthumbnail,scrapedtitle,scrapedtime in matches:
url = urlparse.urljoin(item.url,scrapedurl)
title = "[COLOR yellow]" + scrapedtime + "[/COLOR] " + scrapedtitle
thumbnail = scrapedthumbnail
plot = ""
itemlist.append( Item(channel=item.channel, action="play", title=title, url=url, thumbnail=thumbnail,
fanart=thumbnail, plot=plot, contentTitle = scrapedtitle))
next_page = scrapertools.find_single_match(data,'<li><a href="([^"]+)" target="_self"><span class="alsoporn_page">NEXT</span></a>')
if next_page!="":
next_page = urlparse.urljoin(item.url,next_page)
itemlist.append(item.clone(action="lista", title="Página Siguiente >>", text_color="blue", url=next_page) )
return itemlist
def play(item):
logger.info()
itemlist = []
data = httptools.downloadpage(item.url).data
scrapedurl = scrapertools.find_single_match(data,'<iframe frameborder=0 scrolling="no" src=\'([^\']+)\'')
data = httptools.downloadpage(item.url).data
scrapedurl1 = scrapertools.find_single_match(data,'<iframe src="(.*?)"')
scrapedurl1 = scrapedurl1.replace("//www.playercdn.com/ec/i2.php?", "https://www.trinitytube.xyz/ec/i2.php?")
data = httptools.downloadpage(item.url).data
scrapedurl2 = scrapertools.find_single_match(data,'<source src="(.*?)"')
itemlist.append(item.clone(action="play", title=item.title, fulltitle = item.title, url=scrapedurl2))
return itemlist

View File

@@ -1,62 +0,0 @@
{
"id": "altadefinizione01",
"name": "Altadefinizione01",
"language": ["ita"],
"active": true,
"adult": false,
"thumbnail": "https://raw.githubusercontent.com/Zanzibar82/images/master/posters/altadefinizione01.png",
"banner": "https://raw.githubusercontent.com/Zanzibar82/images/master/posters/altadefinizione01.png",
"categories": ["movie"],
"settings": [
{
"id": "include_in_global_search",
"type": "bool",
"label": "Includi in Ricerca Globale",
"default": false,
"enabled": false,
"visible": false
},
{
"id": "include_in_newest_peliculas",
"type": "bool",
"label": "Includi in Novità - Film",
"default": true,
"enabled": true,
"visible": true
},
{
"id": "include_in_newest_italiano",
"type": "bool",
"label": "Includi in Novità - Italiano",
"default": true,
"enabled": true,
"visible": true
},
{
"id": "comprueba_enlaces",
"type": "bool",
"label": "Verifica se i link esistono",
"default": false,
"enabled": true,
"visible": true
},
{
"id": "comprueba_enlaces_num",
"type": "list",
"label": "Numero di link da verificare",
"default": 1,
"enabled": true,
"visible": "eq(-1,true)",
"lvalues": [ "5", "10", "15", "20" ]
},
{
"id": "filter_languages",
"type": "list",
"label": "Mostra link in lingua...",
"default": 0,
"enabled": true,
"visible": true,
"lvalues": ["Non filtrare","IT"]
}
]
}

View File

@@ -1,163 +0,0 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# Canale per altadefinizione01
# ------------------------------------------------------------
import re
import urlparse
from channels import filtertools, autoplay, support
from core import servertools, httptools, tmdb, scrapertoolsV2
from core.item import Item
from platformcode import logger, config
#URL che reindirizza sempre al dominio corrente
host = "https://altadefinizione01.team"
IDIOMAS = {'Italiano': 'IT'}
list_language = IDIOMAS.values()
list_servers = ['openload', 'streamango', 'rapidvideo', 'streamcherry', 'megadrive']
list_quality = ['default']
__comprueba_enlaces__ = config.get_setting('comprueba_enlaces', 'altadefinizione01')
__comprueba_enlaces_num__ = config.get_setting('comprueba_enlaces_num', 'altadefinizione01')
headers = [['Referer', host]]
blacklist_categorie = ['Altadefinizione01', 'Altadefinizione.to']
def mainlist(item):
support.log()
itemlist =[]
support.menu(itemlist, 'Al Cinema','peliculas',host+'/cinema/')
support.menu(itemlist, 'Ultimi Film Inseriti','peliculas',host)
support.menu(itemlist, 'Film Sub-ITA','peliculas',host+'/sub-ita/')
support.menu(itemlist, 'Film Ordine Alfabetico ','AZlist',host+'/catalog/')
support.menu(itemlist, 'Categorie Film','categories',host)
support.menu(itemlist, 'Cerca...','search')
autoplay.init(item.channel, list_servers, list_quality)
autoplay.show_option(item.channel, itemlist)
return itemlist
def categories(item):
support.log(item)
itemlist = support.scrape(item,'<li><a href="([^"]+)">(.*?)</a></li>',['url','title'],headers,'Altadefinizione01',patron_block='<ul class="kategori_list">(.*?)</ul>',action='peliculas',url_host=host)
return support.thumb(itemlist)
def AZlist(item):
support.log()
return support.scrape(item,r'<a title="([^"]+)" href="([^"]+)"',['title','url'],headers,patron_block=r'<div class="movies-letter">(.*?)<\/div>',action='peliculas_list',url_host=host)
def newest(categoria):
# import web_pdb; web_pdb.set_trace()
support.log(categoria)
itemlist = []
item = Item()
try:
if categoria == "peliculas":
item.url = host
item.action = "peliculas"
itemlist = peliculas(item)
if itemlist[-1].action == "peliculas":
itemlist.pop()
# Continua la ricerca in caso di errore
except:
import sys
for line in sys.exc_info():
logger.error("{0}".format(line))
return []
return itemlist
def search(item, texto):
support.log(texto)
item.url = "%s/index.php?do=search&story=%s&subaction=search" % (
host, texto)
try:
if item.extra == "movie":
return subIta(item)
if item.extra == "tvshow":
return peliculas_tv(item)
# Continua la ricerca in caso di errore
except:
import sys
for line in sys.exc_info():
logger.error("%s" % line)
return []
def peliculas(item):
support.log()
itemlist = []
data = httptools.downloadpage(item.url, headers=headers).data
patron = r'<div class="cover_kapsul ml-mask".*?<a href="(.*?)">(.*?)<\/a>.*?<img .*?src="(.*?)".*?<div class="trdublaj">(.*?)<\/div>.(<div class="sub_ita">(.*?)<\/div>|())'
matches = scrapertoolsV2.find_multiple_matches(data, patron)
for scrapedurl, scrapedtitle, scrapedthumbnail, scrapedquality, subDiv, subText, empty in matches:
info = scrapertoolsV2.find_multiple_matches(data, r'<span class="ml-label">([0-9]+)+<\/span>.*?<span class="ml-label">(.*?)<\/span>.*?<p class="ml-cat".*?<p>(.*?)<\/p>.*?<a href="(.*?)" class="ml-watch">')
infoLabels = {}
for infoLabels['year'], duration, scrapedplot, checkUrl in info:
if checkUrl == scrapedurl:
break
infoLabels['duration'] = int(duration.replace(' min', '')) * 60 # calcolo la durata in secondi
scrapedthumbnail = host + scrapedthumbnail
scrapedtitle = scrapertoolsV2.decodeHtmlentities(scrapedtitle)
fulltitle = scrapedtitle
if subDiv:
fulltitle += support.typo(subText + ' _ () color limegreen')
fulltitle += support.typo(scrapedquality.strip()+ ' _ [] color blue')
itemlist.append(
Item(channel=item.channel,
action="findvideos",
contentType=item.contenType,
contentTitle=scrapedtitle,
contentQuality=scrapedquality.strip(),
plot=scrapedplot,
title=fulltitle,
fulltitle=scrapedtitle,
show=scrapedtitle,
url=scrapedurl,
infoLabels=infoLabels,
thumbnail=scrapedthumbnail))
tmdb.set_infoLabels_itemlist(itemlist, seekTmdb=True)
support.nextPage(itemlist,item,data,'<span>[^<]+</span>[^<]+<a href="(.*?)">')
return itemlist
def peliculas_list(item):
support.log()
block = r'<tbody>(.*)<\/tbody>'
patron = r'<td class="mlnh-thumb"><a href="([^"]+)" title="([^"]+)".*?> <img.*?src="([^"]+)".*?<td class="mlnh-3">([0-9]+)<\/td><td class="mlnh-4">(.*?)<\/td>'
return support.scrape(item,patron, ['url','title','year','quality'],patron_block=block)
def findvideos(item):
support.log()
itemlist = support.server(item, headers=headers)
# Requerido para Filtrar enlaces
if __comprueba_enlaces__:
itemlist = servertools.check_list_links(itemlist, __comprueba_enlaces_num__)
# Requerido para FilterTools
itemlist = filtertools.get_links(itemlist, item, list_language)
# Requerido para AutoPlay
autoplay.start(itemlist, item)
support.videolibrary(itemlist, item, 'color blue')
return itemlist

View File

@@ -1,70 +0,0 @@
{
"id": "altadefinizioneclick",
"name": "AltadefinizioneClick",
"active": true,
"adult": false,
"language": ["ita"],
"thumbnail": "https:\/\/raw.githubusercontent.com\/Zanzibar82\/images\/master\/posters\/altadefinizioneclick.png",
"bannermenu": "https:\/\/raw.githubusercontent.com\/Zanzibar82\/images\/master\/posters\/altadefinizioneciclk.png",
"categories": ["tvshow","movie","vosi"],
"settings": [
{
"id": "include_in_global_search",
"type": "bool",
"label": "Includi ricerca globale",
"default": true,
"enabled": true,
"visible": true
},
{
"id": "include_in_newest_peliculas",
"type": "bool",
"label": "Includi in Novità - Film",
"default": true,
"enabled": true,
"visible": true
},
{
"id": "include_in_newest_peliculas",
"type": "bool",
"label": "Includi in Novità - Film",
"default": true,
"enabled": true,
"visible": true
},
{
"id": "include_in_newest_italiano",
"type": "bool",
"label": "Includi in Novità - Italiano",
"default": true,
"enabled": true,
"visible": true
},
{
"id": "comprueba_enlaces",
"type": "bool",
"label": "Verifica se i link esistono",
"default": false,
"enabled": true,
"visible": true
},
{
"id": "comprueba_enlaces_num",
"type": "list",
"label": "Numero de link da verificare",
"default": 1,
"enabled": true,
"visible": "eq(-1,true)",
"lvalues": [ "5", "10", "15", "20" ]
},
{
"id": "filter_languages",
"type": "list",
"label": "Mostra link in lingua...",
"default": 0,
"enabled": true,
"visible": true,
"lvalues": ["Non filtrare","IT"]
}
]
}

View File

@@ -1,109 +0,0 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# Canale per altadefinizioneclick
# ----------------------------------------------------------
import re
from channels import autoplay, filtertools, support
from core import servertools
from core.item import Item
from platformcode import logger, config
host = "https://altadefinizione.center" ### <- cambio Host da .fm a .center
IDIOMAS = {'Italiano': 'IT'}
list_language = IDIOMAS.values()
list_servers = ['openload', 'streamango', "vidoza", "thevideo", "okru", 'youtube']
list_quality = ['1080p']
__comprueba_enlaces__ = config.get_setting('comprueba_enlaces', 'altadefinizioneclick')
__comprueba_enlaces_num__ = config.get_setting('comprueba_enlaces_num', 'altadefinizioneclick')
headers = [['Referer', host]]
def mainlist(item):
support.log()
itemlist = []
support.menu(itemlist, 'Film', 'peliculas', host + "/nuove-uscite/")
support.menu(itemlist, 'Per Genere submenu', 'menu', host, args='Film')
support.menu(itemlist, 'Per Anno submenu', 'menu', host, args='Anno')
support.menu(itemlist, 'Sub-IIA', 'peliculas', host + "/sub-ita/")
support.menu(itemlist, 'Cerca...', 'search', host, 'movie')
autoplay.init(item.channel, list_servers, list_quality)
autoplay.show_option(item.channel, itemlist)
return itemlist
def search(item, texto):
support.log("search ", texto)
item.extra = 'search'
item.url = host + "/?s=" + texto
try:
return peliculas(item)
# Continua la ricerca in caso di errore
except:
import sys
for line in sys.exc_info():
logger.error("%s" % line)
return []
def newest(categoria):
support.log(categoria)
itemlist = []
item = Item()
try:
if categoria == "peliculas":
item.url = host + "/nuove-uscite/"
item.action = "peliculas"
itemlist = peliculas(item)
if itemlist[-1].action == "peliculas":
itemlist.pop()
# Continua la ricerca in caso di errore
except:
import sys
for line in sys.exc_info():
logger.error("{0}".format(line))
return []
return itemlist
def menu(item):
support.log()
itemlist = support.scrape(item, '<li><a href="(.*?)">(.*?)</a></li>', ['url', 'title'], headers, patron_block='<ul class="listSubCat" id="'+ str(item.args) + '">(.*?)</ul>', action='peliculas')
return support.thumb(itemlist)
def peliculas(item):
support.log()
if item.extra == 'search':
itemlist = support.scrape(item, r'<a href="([^"]+)">\s*<div[^=]+=[^=]+=[^=]+=[^=]+=[^=]+="(.*?)"[^>]+>[^<]+<[^>]+>\s*<h[^=]+="titleFilm">(.*?)<', ['url', 'thumb', 'title'], headers, patronNext='<a class="next page-numbers" href="([^"]+)">')
else:
itemlist = support.scrape(item, r'<img width[^s]+src="([^"]+)[^>]+>[^>]+>[^>]+>[^>]+><a href="([^"]+)">([^<]+)<\/a>[^>]+>[^>]+>[^>]+>(?:[^>]+>|)[^I]+IMDB\:\s*([^<]+)<', ['thumb', 'url', 'title', 'rating'], headers, patronNext='<a class="next page-numbers" href="([^"]+)">')
for item in itemlist:
item.title = re.sub(r'.\(.*?\)', '', item.title)
return itemlist
def findvideos(item):
support.log()
itemlist = support.hdpass_get_servers(item)
if __comprueba_enlaces__:
itemlist = servertools.check_list_links(itemlist, __comprueba_enlaces_num__)
itemlist = filtertools.get_links(itemlist, item, list_language)
autoplay.start(itemlist, item)
support.videolibrary(itemlist, item ,'color blue bold')
return itemlist

View File

@@ -1,70 +0,0 @@
{
"id": "altadefinizionehd",
"name": "AltadefinizioneHD",
"active": true,
"adult": false,
"language": ["ita"],
"thumbnail": "https://altadefinizione.doctor/wp-content/uploads/2019/02/logo.png",
"bannermenu": "https://altadefinizione.doctor/wp-content/uploads/2019/02/logo.png",
"categories": ["tvshow","movie"],
"settings": [
{
"id": "include_in_global_search",
"type": "bool",
"label": "Includi in Ricerca Globale",
"default": true,
"enabled": true,
"visible": true
},
{
"id": "include_in_newest_peliculas",
"type": "bool",
"label": "Includi in Novità - Film",
"default": true,
"enabled": true,
"visible": true
},
{
"id": "include_in_newest_series",
"type": "bool",
"label": "Includi in Novità - Serie TV",
"default": true,
"enabled": true,
"visible": true
},
{
"id": "include_in_newest_italiano",
"type": "bool",
"label": "Includi in Novità - Italiano",
"default": true,
"enabled": true,
"visible": true
},
{
"id": "comprueba_enlaces",
"type": "bool",
"label": "Verifica se i link esistono",
"default": false,
"enabled": true,
"visible": true
},
{
"id": "comprueba_enlaces_num",
"type": "list",
"label": "Numero de link da verificare",
"default": 1,
"enabled": true,
"visible": "eq(-1,true)",
"lvalues": [ "1", "3", "5", "10" ]
},
{
"id": "filter_languages",
"type": "list",
"label": "Mostra link in lingua...",
"default": 0,
"enabled": true,
"visible": true,
"lvalues": ["Non filtrare","IT"]
}
]
}

View File

@@ -1,264 +0,0 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# Canale per Altadefinizione HD
# ----------------------------------------------------------
import re
from core import httptools, scrapertools, servertools, tmdb
from platformcode import logger, config
from core.item import Item
from channels import autoplay
from channelselector import thumb
host = "https://altadefinizione.doctor"
headers = [['Referer', host]]
list_servers = ['openload']
list_quality = ['default']
def mainlist(item):
logger.info("[altadefinizionehd.py] mainlist")
autoplay.init(item.channel, list_servers, list_quality)
itemlist = [Item(channel=item.channel,
action="video",
title="[B]Film[/B]",
url=host + '/movies/',
thumbnail=NovitaThumbnail,
fanart=FilmFanart),
Item(channel=item.channel,
action="menu",
title="[B] > Film per Genere[/B]",
url=host,
extra='GENERE',
thumbnail=NovitaThumbnail,
fanart=FilmFanart),
Item(channel=item.channel,
action="menu",
title="[B] > Film per Anno[/B]",
url=host,
extra='ANNO',
thumbnail=NovitaThumbnail,
fanart=FilmFanart),
Item(channel=item.channel,
action="video",
title="Film Sub-Ita",
url=host + "/genre/sub-ita/",
thumbnail=NovitaThumbnail,
fanart=FilmFanart),
Item(channel=item.channel,
action="video",
title="Film Rip",
url=host + "/genre/dvdrip-bdrip-brrip/",
thumbnail=NovitaThumbnail,
fanart=FilmFanart),
Item(channel=item.channel,
action="video",
title="Film al Cinema",
url=host + "/genre/cinema/",
thumbnail=NovitaThumbnail,
fanart=FilmFanart),
Item(channel=item.channel,
action="search",
extra="movie",
title="[COLOR blue]Cerca Film...[/COLOR]",
thumbnail=CercaThumbnail,
fanart=FilmFanart)]
autoplay.show_option(item.channel, itemlist)
itemlist = thumb(itemlist)
return itemlist
def menu(item):
logger.info("[altadefinizionehd.py] menu")
itemlist = []
data = httptools.downloadpage(item.url, headers=headers).data
logger.info("[altadefinizionehd.py] DATA"+data)
patron = r'<li id="menu.*?><a href="#">FILM PER ' + item.extra + r'<\/a><ul class="sub-menu">(.*?)<\/ul>'
logger.info("[altadefinizionehd.py] BLOCK"+patron)
block = scrapertools.find_single_match(data, patron)
logger.info("[altadefinizionehd.py] BLOCK"+block)
patron = r'<li id=[^>]+><a href="(.*?)">(.*?)<\/a><\/li>'
matches = re.compile(patron, re.DOTALL).findall(block)
for url, title in matches:
itemlist.append(
Item(channel=item.channel,
action='video',
title=title,
url=url))
return itemlist
def newest(categoria):
logger.info("[altadefinizionehd.py] newest" + categoria)
itemlist = []
item = Item()
try:
if categoria == "peliculas":
item.url = host
item.action = "video"
itemlist = video(item)
if itemlist[-1].action == "video":
itemlist.pop()
# Continua la ricerca in caso di errore
except:
import sys
for line in sys.exc_info():
logger.error("{0}".format(line))
return []
return itemlist
def video(item):
logger.info("[altadefinizionehd.py] video")
itemlist = []
data = httptools.downloadpage(item.url, headers=headers).data
logger.info("[altadefinizionehd.py] Data" +data)
if 'archive-content' in data:
regex = r'<div id="archive-content".*?>(.*?)<div class="pagination'
else:
regex = r'<div class="items".*?>(.*?)<div class="pagination'
block = scrapertools.find_single_match(data, regex)
logger.info("[altadefinizionehd.py] Block" +block)
patron = r'<article .*?class="item movies">.*?<img src="([^"]+)".*?<span class="quality">(.*?)<\/span>.*?<a href="([^"]+)">.*?<h4>([^<]+)<\/h4>(.*?)<\/article>'
matches = re.compile(patron, re.DOTALL).findall(block)
for scrapedthumb, scrapedquality, scrapedurl, scrapedtitle, scrapedinfo in matches:
title = scrapedtitle + " [" + scrapedquality + "]"
patron = r'IMDb: (.*?)<\/span> <span>(.*?)<\/span>.*?"texto">(.*?)<\/div>'
matches = re.compile(patron, re.DOTALL).findall(scrapedinfo)
logger.info("[altadefinizionehd.py] MATCHES" + str(matches))
for rating, year, plot in matches:
infoLabels = {}
infoLabels['Year'] = year
infoLabels['Rating'] = rating
infoLabels['Plot'] = plot
itemlist.append(
Item(channel=item.channel,
action="findvideos",
contentType="movie",
title=title,
fulltitle=scrapedtitle,
infoLabels=infoLabels,
url=scrapedurl,
thumbnail=scrapedthumb))
tmdb.set_infoLabels_itemlist(itemlist, seekTmdb=True)
patron = '<a class='+ "'arrow_pag'" + ' href="([^"]+)"'
next_page = scrapertools.find_single_match(data, patron)
if next_page != "":
itemlist.append(
Item(channel=item.channel,
action="video",
title="[COLOR blue]" + config.get_localized_string(30992) + "[/COLOR]",
url=next_page,
thumbnail=thumb()))
return itemlist
def search(item, texto):
logger.info("[altadefinizionehd.py] init texto=[" + texto + "]")
item.url = host + "/?s=" + texto
return search_page(item)
def search_page(item):
itemlist = []
data = httptools.downloadpage(item.url, headers=headers).data
patron = r'<img src="([^"]+)".*?.*?<a href="([^"]+)">(.*?)<\/a>'
matches = re.compile(patron, re.DOTALL).findall(data)
for scrapedthumbnail, scrapedurl, scrapedtitle in matches:
scrapedtitle = scrapertools.decodeHtmlentities(scrapedtitle)
itemlist.append(
Item(channel=item.channel,
action="findvideos",
title=scrapedtitle,
fulltitle=scrapedtitle,
url=scrapedurl,
thumbnail=scrapedthumbnail))
tmdb.set_infoLabels_itemlist(itemlist, seekTmdb=True)
patron = '<a class='+ "'arrow_pag'" + ' href="([^"]+)"'
next_page = scrapertools.find_single_match(data, patron)
if next_page != "":
itemlist.append(
Item(channel=item.channel,
action="search_page",
title="[COLOR blue]" + config.get_localized_string(30992) + "[/COLOR]",
url=next_page,
thumbnail=thumb()))
return itemlist
def findvideos(item):
data = httptools.downloadpage(item.url).data
patron = r"<li id='player-.*?'.*?class='dooplay_player_option'\sdata-type='(.*?)'\sdata-post='(.*?)'\sdata-nume='(.*?)'>.*?'title'>(.*?)</"
matches = re.compile(patron, re.IGNORECASE).findall(data)
itemlist = []
for scrapedtype, scrapedpost, scrapednume, scrapedtitle in matches:
itemlist.append(
Item(channel=item.channel,
action="play",
fulltitle=item.title + " [" + scrapedtitle + "]",
show=scrapedtitle,
title=item.title + " [COLOR blue][" + scrapedtitle + "][/COLOR]",
url=host + "/wp-admin/admin-ajax.php",
post=scrapedpost,
server=scrapedtitle,
nume=scrapednume,
type=scrapedtype,
extra=item.extra,
folder=True))
autoplay.start(itemlist, item)
return itemlist
def play(item):
import urllib
payload = urllib.urlencode({'action': 'doo_player_ajax', 'post': item.post, 'nume': item.nume, 'type': item.type})
data = httptools.downloadpage(item.url, post=payload).data
patron = r"<iframe.*src='(([^']+))'\s"
matches = re.compile(patron, re.IGNORECASE).findall(data)
url = matches[0][0]
url = url.strip()
data = httptools.downloadpage(url, headers=headers).data
itemlist = servertools.find_video_items(data=data)
return itemlist
NovitaThumbnail = "https://superrepo.org/static/images/icons/original/xplugin.video.moviereleases.png.pagespeed.ic.j4bhi0Vp3d.png"
GenereThumbnail = "https://farm8.staticflickr.com/7562/15516589868_13689936d0_o.png"
FilmFanart = "https://superrepo.org/static/images/fanart/original/script.artwork.downloader.jpg"
CercaThumbnail = "http://dc467.4shared.com/img/fEbJqOum/s7/13feaf0c8c0/Search"
CercaFanart = "https://i.ytimg.com/vi/IAlbvyBdYdY/maxresdefault.jpg"
ListTxt = "[COLOR orange]Torna a video principale [/COLOR]"
AvantiTxt = config.get_localized_string(30992)
AvantiImg = "http://2.bp.blogspot.com/-fE9tzwmjaeQ/UcM2apxDtjI/AAAAAAAAeeg/WKSGM2TADLM/s1600/pager+old.png"
thumbnail = "http://orig03.deviantart.net/6889/f/2014/079/7/b/movies_and_popcorn_folder_icon_by_matheusgrilo-d7ay4tw.png"

View File

@@ -1,15 +0,0 @@
{
"id": "analdin",
"name": "analdin",
"active": true,
"adult": true,
"language": ["*"],
"thumbnail": "https://www.analdin.com/images/logo-retina.png",
"banner": "",
"categories": [
"adult"
],
"settings": [
]
}

View File

@@ -1,113 +0,0 @@
# -*- coding: utf-8 -*-
#------------------------------------------------------------
import urlparse,urllib2,urllib,re
import os, sys
from platformcode import config, logger
from core import scrapertools
from core.item import Item
from core import servertools
from core import httptools
host = 'https://www.analdin.com/es'
def mainlist(item):
logger.info()
itemlist = []
itemlist.append( Item(channel=item.channel, title="Nuevas" , action="lista", url=host + "/más-reciente/"))
itemlist.append( Item(channel=item.channel, title="Mas Vistas" , action="lista", url=host + "/más-visto/"))
itemlist.append( Item(channel=item.channel, title="Mejor valorada" , action="lista", url=host + "/mejor-valorado/"))
itemlist.append( Item(channel=item.channel, title="Canal" , action="catalogo", url=host))
itemlist.append( Item(channel=item.channel, title="Categorias" , action="categorias", url=host + "/categorías/"))
itemlist.append( Item(channel=item.channel, title="Buscar", action="search"))
return itemlist
def search(item, texto):
logger.info()
texto = texto.replace(" ", "+")
item.url = host + "/?s=%s" % texto
try:
return lista(item)
except:
import sys
for line in sys.exc_info():
logger.error("%s" % line)
return []
def catalogo(item):
logger.info()
itemlist = []
data = httptools.downloadpage(item.url).data
data = scrapertools.find_single_match(data,'<strong class="popup-title">Canales</strong>(.*?)<strong>Models</strong>')
data = re.sub(r"\n|\r|\t|&nbsp;|<br>", "", data)
patron = '<li><a class="item" href="([^"]+)" title="([^"]+)">'
matches = re.compile(patron,re.DOTALL).findall(data)
for scrapedurl,scrapedtitle in matches:
scrapedplot = ""
scrapedthumbnail = ""
itemlist.append( Item(channel=item.channel, action="lista", title=scrapedtitle, url=scrapedurl,
thumbnail=scrapedthumbnail, plot=scrapedplot) )
next_page = scrapertools.find_single_match(data,'<li class="arrow"><a rel="next" href="([^"]+)">&raquo;</a>')
if next_page!="":
next_page = urlparse.urljoin(item.url,next_page)
itemlist.append(item.clone(action="catalogo", title="Página Siguiente >>", text_color="blue", url=next_page) )
return itemlist
def categorias(item):
logger.info()
itemlist = []
data = httptools.downloadpage(item.url).data
data = re.sub(r"\n|\r|\t|&nbsp;|<br>", "", data)
patron = '<a class="item" href="([^"]+)" title="([^"]+)">.*?'
patron += 'src="([^"]+)".*?'
patron += '<div class="videos">([^"]+)</div>'
matches = re.compile(patron,re.DOTALL).findall(data)
for scrapedurl,scrapedtitle,scrapedthumbnail,cantidad in matches:
scrapedplot = ""
scrapedtitle = scrapedtitle + " (" + cantidad + ")"
scrapedurl = urlparse.urljoin(item.url,scrapedurl)
itemlist.append( Item(channel=item.channel, action="lista", title=scrapedtitle, url=scrapedurl,
fanart=scrapedthumbnail, thumbnail=scrapedthumbnail, plot=scrapedplot) )
return sorted(itemlist, key=lambda i: i.title)
def lista(item):
logger.info()
itemlist = []
data = httptools.downloadpage(item.url).data
data = re.sub(r"\n|\r|\t|&nbsp;|<br>", "", data)
patron = '<a class="popup-video-link" href="([^"]+)".*?'
patron += 'thumb="([^"]+)".*?'
patron += '<div class="duration">(.*?)</div>.*?'
patron += '<strong class="title">\s*([^"]+)</strong>'
matches = re.compile(patron,re.DOTALL).findall(data)
for scrapedurl,scrapedthumbnail,scrapedtime,scrapedtitle in matches:
url = urlparse.urljoin(item.url,scrapedurl)
title = "[COLOR yellow]" + scrapedtime + "[/COLOR] " + scrapedtitle
thumbnail = scrapedthumbnail
plot = ""
itemlist.append( Item(channel=item.channel, action="play", title=title, url=url, thumbnail=thumbnail, plot=plot,
fanart=thumbnail, contentTitle = title))
next_page = scrapertools.find_single_match(data,'<li class="next"><a href="([^"]+)"')
if next_page!="":
next_page = urlparse.urljoin(item.url,next_page)
itemlist.append( Item(channel=item.channel, action="lista", title="Página Siguiente >>", text_color="blue",
url=next_page) )
return itemlist
def play(item):
logger.info()
itemlist = []
data = httptools.downloadpage(item.url).data
patron = 'video_url: \'([^\']+)\''
matches = re.compile(patron,re.DOTALL).findall(data)
for scrapedurl in matches:
url = scrapedurl
itemlist.append(item.clone(action="play", title=url, fulltitle = item.title, url=url))
return itemlist

View File

@@ -1,36 +0,0 @@
{
"id": "animeforce",
"name": "AnimeForce",
"language": ["ita"],
"active": true,
"adult": false,
"thumbnail": "http://www.animeforce.org/wp-content/uploads/2013/05/logo-animeforce.png",
"banner": "http://www.animeforce.org/wp-content/uploads/2013/05/logo-animeforce.png",
"categories": ["anime"],
"settings": [
{
"id": "include_in_global_search",
"type": "bool",
"label": "Incluir en busqueda global",
"default": false,
"enabled": false,
"visible": false
},
{
"id": "include_in_newest_anime",
"type": "bool",
"label": "Includi in Novità - Anime",
"default": true,
"enabled": true,
"visible": true
},
{
"id": "include_in_newest_italiano",
"type": "bool",
"label": "Includi in Novità - Italiano",
"default": true,
"enabled": true,
"visible": true
}
]
}

View File

@@ -1,504 +0,0 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# Ringraziamo Icarus crew
# Canale per http://animeinstreaming.net/
# ------------------------------------------------------------
import re, urllib, urlparse
from core import httptools, scrapertools, servertools, tmdb
from core.item import Item
from platformcode import config, logger
from servers.decrypters import adfly
host = "https://ww1.animeforce.org"
IDIOMAS = {'Italiano': 'IT'}
list_language = IDIOMAS.values()
headers = [['Referer', host]]
PERPAGE = 20
# -----------------------------------------------------------------
def mainlist(item):
log("mainlist", "mainlist", item.channel)
itemlist = [Item(channel=item.channel,
action="lista_anime",
title="[COLOR azure]Anime [/COLOR]- [COLOR lightsalmon]Lista Completa[/COLOR]",
url=host + "/lista-anime/",
thumbnail=CategoriaThumbnail,
fanart=CategoriaFanart),
Item(channel=item.channel,
action="animeaggiornati",
title="[COLOR azure]Anime Aggiornati[/COLOR]",
url=host,
thumbnail=CategoriaThumbnail,
fanart=CategoriaFanart),
Item(channel=item.channel,
action="ultimiep",
title="[COLOR azure]Ultimi Episodi[/COLOR]",
url=host,
thumbnail=CategoriaThumbnail,
fanart=CategoriaFanart),
Item(channel=item.channel,
action="search",
title="[COLOR yellow]Cerca ...[/COLOR]",
thumbnail="http://dc467.4shared.com/img/fEbJqOum/s7/13feaf0c8c0/Search")]
return itemlist
# =================================================================
# -----------------------------------------------------------------
def newest(categoria):
log("newest", "newest" + categoria)
itemlist = []
item = Item()
try:
if categoria == "anime":
item.url = host
item.action = "ultimiep"
itemlist = ultimiep(item)
if itemlist[-1].action == "ultimiep":
itemlist.pop()
# Continua la ricerca in caso di errore
except:
import sys
for line in sys.exc_info():
logger.error("{0}".format(line))
return []
return itemlist
# =================================================================
# -----------------------------------------------------------------
def search(item, texto):
log("search", "search", item.channel)
item.url = host + "/?s=" + texto
try:
return search_anime(item)
# Continua la ricerca in caso di errore
except:
import sys
for line in sys.exc_info():
logger.error("%s" % line)
return []
# =================================================================
# -----------------------------------------------------------------
def search_anime(item):
log("search_anime", "search_anime", item.channel)
itemlist = []
data = httptools.downloadpage(item.url).data
patron = r'<a href="([^"]+)"><img.*?src="([^"]+)".*?title="([^"]+)".*?/>'
matches = re.compile(patron, re.DOTALL).findall(data)
for scrapedurl, scrapedthumbnail, scrapedtitle in matches:
scrapedtitle = scrapertools.decodeHtmlentities(scrapedtitle)
if "Sub Ita Download & Streaming" in scrapedtitle or "Sub Ita Streaming":
if 'episodio' in scrapedtitle.lower():
itemlist.append(episode_item(item, scrapedtitle, scrapedurl, scrapedthumbnail))
else:
scrapedtitle, eptype = clean_title(scrapedtitle, simpleClean=True)
cleantitle, eptype = clean_title(scrapedtitle)
scrapedurl, total_eps = create_url(scrapedurl, cleantitle)
itemlist.append(
Item(channel=item.channel,
action="episodios",
text_color="azure",
contentType="tvshow",
title=scrapedtitle,
url=scrapedurl,
fulltitle=cleantitle,
show=cleantitle,
thumbnail=scrapedthumbnail))
tmdb.set_infoLabels_itemlist(itemlist, seekTmdb=True)
# Next Page
next_page = scrapertools.find_single_match(data, r'<link rel="next" href="([^"]+)"[^/]+/>')
if next_page != "":
itemlist.append(
Item(channel=item.channel,
action="search_anime",
text_bold=True,
title="[COLOR lightgreen]" + config.get_localized_string(30992) + "[/COLOR]",
url=next_page,
thumbnail="http://2.bp.blogspot.com/-fE9tzwmjaeQ/UcM2apxDtjI/AAAAAAAAeeg/WKSGM2TADLM/s1600/pager+old.png"))
return itemlist
# =================================================================
# -----------------------------------------------------------------
def animeaggiornati(item):
log("animeaggiornati", "animeaggiornati", item.channel)
itemlist = []
data = httptools.downloadpage(item.url, headers=headers).data
patron = r'<img.*?src="([^"]+)"[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+><a href="([^"]+)">([^<]+)</a>'
matches = re.compile(patron, re.DOTALL).findall(data)
for scrapedthumbnail, scrapedurl, scrapedtitle in matches:
scrapedtitle = scrapertools.decodeHtmlentities(scrapedtitle)
if 'Streaming' in scrapedtitle:
cleantitle, eptype = clean_title(scrapedtitle)
# Creazione URL
scrapedurl, total_eps = create_url(scrapedurl, scrapedtitle)
itemlist.append(
Item(channel=item.channel,
action="episodios",
text_color="azure",
contentType="tvshow",
title=cleantitle,
url=scrapedurl,
fulltitle=cleantitle,
show=cleantitle,
thumbnail=scrapedthumbnail))
tmdb.set_infoLabels_itemlist(itemlist, seekTmdb=True)
return itemlist
# =================================================================
# -----------------------------------------------------------------
def ultimiep(item):
log("ultimiep", "ultimiep", item.channel)
itemlist = []
data = httptools.downloadpage(item.url, headers=headers).data
patron = r'<img.*?src="([^"]+)"[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+>[^>]+><a href="([^"]+)">([^<]+)</a>'
matches = re.compile(patron, re.DOTALL).findall(data)
for scrapedthumbnail, scrapedurl, scrapedtitle in matches:
scrapedtitle = scrapertools.decodeHtmlentities(scrapedtitle)
if 'Streaming' in scrapedtitle:
itemlist.append(episode_item(item, scrapedtitle, scrapedurl, scrapedthumbnail))
tmdb.set_infoLabels_itemlist(itemlist, seekTmdb=True)
return itemlist
# =================================================================
# -----------------------------------------------------------------
def lista_anime(item):
log("lista_anime", "lista_anime", item.channel)
itemlist = []
p = 1
if '{}' in item.url:
item.url, p = item.url.split('{}')
p = int(p)
# Carica la pagina
data = httptools.downloadpage(item.url).data
# Estrae i contenuti
patron = r'<li>\s*<strong>\s*<a\s*href="([^"]+?)">([^<]+?)</a>\s*</strong>\s*</li>'
matches = re.compile(patron, re.DOTALL).findall(data)
scrapedplot = ""
scrapedthumbnail = ""
for i, (scrapedurl, scrapedtitle) in enumerate(matches):
if (p - 1) * PERPAGE > i: continue
if i >= p * PERPAGE: break
# Pulizia titolo
scrapedtitle = scrapertools.decodeHtmlentities(scrapedtitle).strip()
cleantitle, eptype = clean_title(scrapedtitle, simpleClean=True)
itemlist.append(
Item(channel=item.channel,
extra=item.extra,
action="episodios",
text_color="azure",
contentType="tvshow",
title=cleantitle,
url=scrapedurl,
thumbnail=scrapedthumbnail,
fulltitle=cleantitle,
show=cleantitle,
plot=scrapedplot,
folder=True))
tmdb.set_infoLabels_itemlist(itemlist, seekTmdb=True)
if len(matches) >= p * PERPAGE:
scrapedurl = item.url + '{}' + str(p + 1)
itemlist.append(
Item(channel=item.channel,
extra=item.extra,
action="lista_anime",
title="[COLOR lightgreen]" + config.get_localized_string(30992) + "[/COLOR]",
url=scrapedurl,
thumbnail="http://2.bp.blogspot.com/-fE9tzwmjaeQ/UcM2apxDtjI/AAAAAAAAeeg/WKSGM2TADLM/s1600/pager+old.png",
folder=True))
return itemlist
# =================================================================
# -----------------------------------------------------------------
def episodios(item):
itemlist = []
data = httptools.downloadpage(item.url).data
patron = '<td style="[^"]*?">\s*.*?<strong>(.*?)</strong>.*?\s*</td>\s*<td style="[^"]*?">\s*<a href="([^"]+?)"[^>]+>\s*<img.*?src="([^"]+?)".*?/>\s*</a>\s*</td>'
matches = re.compile(patron, re.DOTALL).findall(data)
vvvvid_videos = False
for scrapedtitle, scrapedurl, scrapedimg in matches:
if 'nodownload' in scrapedimg or 'nostreaming' in scrapedimg:
continue
if 'vvvvid' in scrapedurl.lower():
if not vvvvid_videos: vvvvid_videos = True
itemlist.append(Item(title='I Video VVVVID Non sono supportati', text_color="red"))
continue
scrapedtitle = scrapertools.decodeHtmlentities(scrapedtitle)
scrapedtitle = re.sub(r'<[^>]*?>', '', scrapedtitle)
scrapedtitle = '[COLOR azure][B]' + scrapedtitle + '[/B][/COLOR]'
itemlist.append(
Item(channel=item.channel,
action="findvideos",
contentType="episode",
title=scrapedtitle,
url=urlparse.urljoin(host, scrapedurl),
fulltitle=scrapedtitle,
show=scrapedtitle,
plot=item.plot,
fanart=item.fanart,
thumbnail=item.thumbnail))
# Comandi di servizio
if config.get_videolibrary_support() and len(itemlist) != 0 and not vvvvid_videos:
itemlist.append(
Item(channel=item.channel,
title=config.get_localized_string(30161),
text_color="yellow",
text_bold=True,
url=item.url,
action="add_serie_to_library",
extra="episodios",
show=item.show))
return itemlist
# ==================================================================
# -----------------------------------------------------------------
def findvideos(item):
logger.info("kod.animeforce findvideos")
itemlist = []
if item.extra:
data = httptools.downloadpage(item.url, headers=headers).data
blocco = scrapertools.find_single_match(data, r'%s(.*?)</tr>' % item.extra)
url = scrapertools.find_single_match(blocco, r'<a href="([^"]+)"[^>]*>')
if 'vvvvid' in url.lower():
itemlist = [Item(title='I Video VVVVID Non sono supportati', text_color="red")]
return itemlist
if 'http' not in url: url = "".join(['https:', url])
else:
url = item.url
if 'adf.ly' in url:
url = adfly.get_long_url(url)
elif 'bit.ly' in url:
url = httptools.downloadpage(url, only_headers=True, follow_redirects=False).headers.get("location")
if 'animeforce' in url:
headers.append(['Referer', item.url])
data = httptools.downloadpage(url, headers=headers).data
itemlist.extend(servertools.find_video_items(data=data))
for videoitem in itemlist:
videoitem.title = item.title + videoitem.title
videoitem.fulltitle = item.fulltitle
videoitem.show = item.show
videoitem.thumbnail = item.thumbnail
videoitem.channel = item.channel
videoitem.contentType = item.contentType
url = url.split('&')[0]
data = httptools.downloadpage(url, headers=headers).data
patron = """<source\s*src=(?:"|')([^"']+?)(?:"|')\s*type=(?:"|')video/mp4(?:"|')>"""
matches = re.compile(patron, re.DOTALL).findall(data)
headers.append(['Referer', url])
for video in matches:
itemlist.append(Item(channel=item.channel, action="play", title=item.title,
url=video + '|' + urllib.urlencode(dict(headers)), folder=False))
else:
itemlist.extend(servertools.find_video_items(data=url))
for videoitem in itemlist:
videoitem.title = item.title + videoitem.title
videoitem.fulltitle = item.fulltitle
videoitem.show = item.show
videoitem.thumbnail = item.thumbnail
videoitem.channel = item.channel
videoitem.contentType = item.contentType
return itemlist
# ==================================================================
# =================================================================
# Funzioni di servizio
# -----------------------------------------------------------------
def scrapedAll(url="", patron=""):
data = httptools.downloadpage(url).data
MyPatron = patron
matches = re.compile(MyPatron, re.DOTALL).findall(data)
scrapertools.printMatches(matches)
return matches
# =================================================================
# -----------------------------------------------------------------
def create_url(url, title, eptype=""):
logger.info()
if 'download' not in url:
url = url.replace('-streaming', '-download-streaming')
total_eps = ""
if not eptype:
url = re.sub(r'episodio?-?\d+-?(?:\d+-|)[oav]*', '', url)
else: # Solo se è un episodio passa
total_eps = scrapertools.find_single_match(title.lower(), r'\((\d+)-(?:episodio|sub-ita)\)') # Questo numero verrà rimosso dall'url
if total_eps: url = url.replace('%s-' % total_eps, '')
url = re.sub(r'%s-?\d*-' % eptype.lower(), '', url)
url = url.replace('-fine', '')
return url, total_eps
# =================================================================
# -----------------------------------------------------------------
def clean_title(title, simpleClean=False):
logger.info()
title = title.replace("Streaming", "").replace("&", "")
title = title.replace("Download", "")
title = title.replace("Sub Ita", "")
cleantitle = title.replace("#038;", "").replace("amp;", "").strip()
if '(Fine)' in title:
cleantitle = cleantitle.replace('(Fine)', '').strip() + " (Fine)"
eptype = ""
if not simpleClean:
if "episodio" in title.lower():
eptype = scrapertools.find_single_match(title, "((?:Episodio?|OAV))")
cleantitle = re.sub(r'%s\s*\d*\s*(?:\(\d+\)|)' % eptype, '', title).strip()
if 'episodio' not in eptype.lower():
cleantitle = re.sub(r'Episodio?\s*\d+\s*(?:\(\d+\)|)\s*[\(OAV\)]*', '', cleantitle).strip()
if '(Fine)' in title:
cleantitle = cleantitle.replace('(Fine)', '')
return cleantitle, eptype
# =================================================================
# -----------------------------------------------------------------
def episode_item(item, scrapedtitle, scrapedurl, scrapedthumbnail):
scrapedtitle, eptype = clean_title(scrapedtitle, simpleClean=True)
cleantitle, eptype = clean_title(scrapedtitle)
# Creazione URL
scrapedurl, total_eps = create_url(scrapedurl, scrapedtitle, eptype)
epnumber = ""
if 'episodio' in eptype.lower():
epnumber = scrapertools.find_single_match(scrapedtitle.lower(), r'episodio?\s*(\d+)')
eptype += ":? %s%s" % (epnumber, (r" \(%s\):?" % total_eps) if total_eps else "")
extra = "<tr>\s*<td[^>]+><strong>(?:[^>]+>|)%s(?:[^>]+>[^>]+>|[^<]*|[^>]+>)</strong>" % eptype
item = Item(channel=item.channel,
action="findvideos",
contentType="tvshow",
title=scrapedtitle,
text_color="azure",
url=scrapedurl,
fulltitle=cleantitle,
extra=extra,
show=cleantitle,
thumbnail=scrapedthumbnail)
return item
# =================================================================
# -----------------------------------------------------------------
def scrapedSingle(url="", single="", patron=""):
data = httptools.downloadpage(url).data
paginazione = scrapertools.find_single_match(data, single)
matches = re.compile(patron, re.DOTALL).findall(paginazione)
scrapertools.printMatches(matches)
return matches
# =================================================================
# -----------------------------------------------------------------
def Crea_Url(pagina="1", azione="ricerca", categoria="", nome=""):
# esempio
# chiamate.php?azione=ricerca&cat=&nome=&pag=
Stringa = host + "chiamate.php?azione=" + azione + "&cat=" + categoria + "&nome=" + nome + "&pag=" + pagina
log("crea_Url", Stringa)
return Stringa
# =================================================================
# -----------------------------------------------------------------
def log(funzione="", stringa="", canale=""):
logger.debug("[" + canale + "].[" + funzione + "] " + stringa)
# =================================================================
# =================================================================
# riferimenti di servizio
# -----------------------------------------------------------------
AnimeThumbnail = "http://img15.deviantart.net/f81c/i/2011/173/7/6/cursed_candies_anime_poster_by_careko-d3jnzg9.jpg"
AnimeFanart = "https://i.ytimg.com/vi/IAlbvyBdYdY/maxresdefault.jpg"
CategoriaThumbnail = "http://static.europosters.cz/image/750/poster/street-fighter-anime-i4817.jpg"
CategoriaFanart = "https://i.ytimg.com/vi/IAlbvyBdYdY/maxresdefault.jpg"
CercaThumbnail = "http://dc467.4shared.com/img/fEbJqOum/s7/13feaf0c8c0/Search"
CercaFanart = "https://i.ytimg.com/vi/IAlbvyBdYdY/maxresdefault.jpg"
AvantiTxt = config.get_localized_string(30992)
AvantiImg = "http://2.bp.blogspot.com/-fE9tzwmjaeQ/UcM2apxDtjI/AAAAAAAAeeg/WKSGM2TADLM/s1600/pager+old.png"

View File

@@ -1,62 +0,0 @@
{
"id": "animeleggendari",
"name": "AnimeLeggendari",
"active": true,
"adult": false,
"language": ["ita"],
"thumbnail": "https://animeleggendari.com/wp-content/uploads/2018/01/123header.jpg",
"bannermenu": "https://animeleggendari.com/wp-content/uploads/2018/01/123header.jpg",
"categories": ["anime"],
"settings": [
{
"id": "include_in_global_search",
"type": "bool",
"label": "Includi ricerca globale",
"default": false,
"enabled": false,
"visible": false
},
{
"id": "include_in_newest_anime",
"type": "bool",
"label": "Includi in Novità - Anime",
"default": false,
"enabled": false,
"visible": false
},
{
"id": "include_in_newest_italiano",
"type": "bool",
"label": "Includi in Novità - Italiano",
"default": true,
"enabled": true,
"visible": true
},
{
"id": "comprueba_enlaces",
"type": "bool",
"label": "Verifica se i link esistono",
"default": false,
"enabled": true,
"visible": true
},
{
"id": "comprueba_enlaces_num",
"type": "list",
"label": "Numero de link da verificare",
"default": 1,
"enabled": true,
"visible": "eq(-1,true)",
"lvalues": [ "1", "3", "5", "10" ]
},
{
"id": "filter_languages",
"type": "list",
"label": "Mostra link in lingua...",
"default": 0,
"enabled": true,
"visible": true,
"lvalues": ["Non filtrare", "IT"]
}
]
}

View File

@@ -1,221 +0,0 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# Ringraziamo Icarus crew
# Canale per animeleggendari
# ------------------------------------------------------------
import re
from channels import autoplay
from channels import filtertools, support
from core import servertools, httptools, scrapertools, tmdb
from platformcode import logger, config
from core.item import Item
host = "https://animeleggendari.com"
# Richiesto per Autoplay
IDIOMAS = {'Italiano': 'IT'}
list_language = IDIOMAS.values()
list_servers = ['openload', 'streamango']
list_quality = ['default']
__comprueba_enlaces__ = config.get_setting('comprueba_enlaces', 'animeleggendari')
__comprueba_enlaces_num__ = config.get_setting('comprueba_enlaces_num', 'animeleggendari')
def mainlist(item):
logger.info('[animeleggendari.py] mainlist')
# Richiesto per Autoplay
autoplay.init(item.channel, list_servers, list_quality)
itemlist = [Item(channel=item.channel,
action="lista_anime",
title="[B]Anime Leggendari[/B]",
url="%s/category/anime-leggendari/" % host,
thumbnail="http://orig03.deviantart.net/6889/f/2014/079/7/b/movies_and_popcorn_folder_icon_by_matheusgrilo-d7ay4tw.png"),
Item(channel=item.channel,
action="lista_anime",
title="Anime [B]ITA[/B]",
url="%s/category/anime-ita/" % host,
thumbnail="http://orig03.deviantart.net/6889/f/2014/079/7/b/movies_and_popcorn_folder_icon_by_matheusgrilo-d7ay4tw.png"),
Item(channel=item.channel,
action="lista_anime",
title="Anime [B]SUB ITA[/B]",
url="%s/category/anime-sub-ita/" % host,
thumbnail="http://orig03.deviantart.net/6889/f/2014/079/7/b/movies_and_popcorn_folder_icon_by_matheusgrilo-d7ay4tw.png"),
Item(channel=item.channel,
action="lista_anime",
title="Conclusi",
url="%s/category/serie-anime-concluse/" % host,
thumbnail="http://orig03.deviantart.net/6889/f/2014/079/7/b/movies_and_popcorn_folder_icon_by_matheusgrilo-d7ay4tw.png"),
Item(channel=item.channel,
action="lista_anime",
title="In Corso",
url="%s/category/anime-in-corso/" % host,
thumbnail="http://orig03.deviantart.net/6889/f/2014/079/7/b/movies_and_popcorn_folder_icon_by_matheusgrilo-d7ay4tw.png"),
Item(channel=item.channel,
action="generi",
title="Generi >",
url=host,
thumbnail="http://orig03.deviantart.net/6889/f/2014/079/7/b/movies_and_popcorn_folder_icon_by_matheusgrilo-d7ay4tw.png"),
Item(channel=item.channel,
action="search",
title="[B]Cerca...[/B]",
thumbnail="http://dc467.4shared.com/img/fEbJqOum/s7/13feaf0c8c0/Search")]
# Autoplay visualizza voce menu
autoplay.show_option(item.channel, itemlist)
return itemlist
def search(item, texto):
logger.info('[animeleggendari.py] search')
item.url = host + "/?s=" + texto
try:
return lista_anime(item)
# Continua la ricerca in caso di errore
except:
import sys
for line in sys.exc_info():
logger.error("%s" % line)
return []
def generi(item):
logger.info('[animeleggendari.py] generi')
itemlist = []
data = httptools.downloadpage(item.url).data.replace('\n','').replace('\t','')
logger.info("[animeleggendari.py] generi= "+data)
blocco =scrapertools.find_single_match(data, r'Generi.*?<ul.*?>(.*?)<\/ul>')
logger.info("[animeleggendari.py] blocco= "+blocco)
patron = '<a href="([^"]+)">([^<]+)<'
matches = re.compile(patron, re.DOTALL).findall(blocco)
logger.info("[animeleggendari.py] matches= "+str(matches))
for scrapedurl, scrapedtitle in matches:
title = scrapedtitle.replace('Anime ','')
itemlist.append(
Item(channel=item.channel,
action="lista_anime",
title=title,
url=scrapedurl))
return itemlist
def lista_anime(item):
logger.info('[animeleggendari.py] lista_anime')
itemlist = []
data = httptools.downloadpage(item.url).data
patron = r'<a class="[^"]+" href="([^"]+)" title="([^"]+)"><img[^s]+src="([^"]+)"[^>]+'
matches = re.compile(patron, re.DOTALL).findall(data)
for scrapedurl, scrapedtitle, scrapedthumbnail in matches:
scrapedtitle = scrapertools.decodeHtmlentities(scrapedtitle.strip()).replace("streaming", "")
if 'top 10 anime da vedere' in scrapedtitle.lower(): continue
lang = scrapertools.find_single_match(scrapedtitle, r"((?:SUB ITA|ITA))")
cleantitle = scrapedtitle.replace(lang, "").replace('(Streaming & Download)', '')
cleantitle = cleantitle.replace('OAV', '').replace('OVA', '').replace('MOVIE', '')
itemlist.append(
Item(channel=item.channel,
action="episodios",
contentType="tvshow" if 'movie' not in scrapedtitle.lower() and 'ova' not in scrapedtitle.lower() else "movie",
text_color="azure",
title=scrapedtitle.replace('(Streaming & Download)', '').replace(lang, '[B][' + lang + '][/B]'),
fulltitle=cleantitle,
url=scrapedurl,
show=cleantitle,
thumbnail=scrapedthumbnail,
folder=True))
tmdb.set_infoLabels_itemlist(itemlist, seekTmdb=True)
patronvideos = r'<a class="next page-numbers" href="([^"]+)">'
matches = re.compile(patronvideos, re.DOTALL).findall(data)
if len(matches) > 0:
itemlist.append(
Item(channel=item.channel,
action="lista_anime",
title="[COLOR lightgreen]" + config.get_localized_string(30992) + "[/COLOR]",
url=scrapedurl,
thumbnail="http://2.bp.blogspot.com/-fE9tzwmjaeQ/UcM2apxDtjI/AAAAAAAAeeg/WKSGM2TADLM/s1600/pager+old.png",
folder=True))
return itemlist
def episodios(item):
logger.info('[animeleggendari.py] episodios')
itemlist = []
data = httptools.downloadpage(item.url).data
blocco = scrapertools.find_single_match(data, r'(?:<p style="text-align: left;">|<div class="pagination clearfix">\s*)(.*?)</span></a></div>')
# Il primo episodio è la pagina stessa
itemlist.append(
Item(channel=item.channel,
action="findvideos",
contentType=item.contentType,
title="Episodio: 1",
text_color="azure",
fulltitle="%s %s %s " % (support.color(item.title, "deepskyblue"), support.color("|", "azure"), support.color("1", "orange")),
url=item.url,
thumbnail=item.thumbnail,
folder=True))
if blocco != "":
patron = r'<a href="([^"]+)".*?><span class="pagelink">(\d+)</span></a>'
matches = re.compile(patron, re.DOTALL).findall(data)
for scrapedurl, scrapednumber in matches:
itemlist.append(
Item(channel=item.channel,
action="findvideos",
contentType=item.contentType,
title="Episodio: %s" % scrapednumber,
text_color="azure",
fulltitle="%s %s %s " % (support.color(item.title, "deepskyblue"), support.color("|", "azure"), support.color(scrapednumber, "orange")),
url=scrapedurl,
thumbnail=item.thumbnail,
folder=True))
if config.get_videolibrary_support() and len(itemlist) != 0:
itemlist.append(
Item(channel=item.channel,
title="[COLOR lightblue]%s[/COLOR]" % config.get_localized_string(30161),
url=item.url,
action="add_serie_to_library",
extra="episodi",
show=item.show))
return itemlist
def findvideos(item):
logger.info('[animeleggendari.py] findvideos')
data = httptools.downloadpage(item.url).data
itemlist = servertools.find_video_items(data=data)
for videoitem in itemlist:
server = re.sub(r'[-\[\]\s]+', '', videoitem.title)
videoitem.title = "".join(["[%s] " % support.color(server.capitalize(), 'orange'), item.title])
videoitem.fulltitle = item.fulltitle
videoitem.show = item.show
videoitem.thumbnail = item.thumbnail
videoitem.channel = item.channel
# Richiesto per Verifica se i link esistono
if __comprueba_enlaces__:
itemlist = servertools.check_list_links(itemlist, __comprueba_enlaces_num__)
# Richiesto per FilterTools
itemlist = filtertools.get_links(itemlist, item, list_language)
# Autoplay
autoplay.start(itemlist, item)
return itemlist

View File

@@ -1,52 +0,0 @@
{
"id": "animespace",
"name": "AnimeSpace",
"active": true,
"adult": false,
"language": [],
"thumbnail": "",
"banner": "",
"categories": [
"anime",
"vos"
],
"settings": [
{
"id": "include_in_global_search",
"type": "bool",
"label": "Incluir en busqueda global",
"default": false,
"enabled": false,
"visible": false
},
{
"id": "filter_languages",
"type": "list",
"label": "Mostrar enlaces en idioma...",
"default": 0,
"enabled": true,
"visible": true,
"lvalues": [
"No filtrar",
"VOSE"
]
},
{
"id": "comprueba_enlaces_num",
"type": "list",
"label": "Número de enlaces a verificar",
"default": 1,
"enabled": true,
"visible": "eq(-1,true)",
"lvalues": [ "5", "10", "15", "20" ]
},
{
"id": "include_in_newest_anime",
"type": "bool",
"label": "Incluir en Novedades - Episodios de anime",
"default": true,
"enabled": true,
"visible": true
}
]
}

View File

@@ -1,264 +0,0 @@
# -*- coding: utf-8 -*-
# -*- Channel AnimeSpace -*-
# -*- Created for Alfa-addon -*-
# -*- By the Alfa Develop Group -*-
import re
import urllib
from core import httptools
from core import scrapertools
from core import servertools
from channelselector import get_thumb
from core import tmdb
from core.item import Item
from platformcode import logger, config
from channels import autoplay
from channels import filtertools
from channels import renumbertools
host = "https://animespace.tv/"
__comprueba_enlaces__ = config.get_setting('comprueba_enlaces', 'animespace')
__comprueba_enlaces_num__ = config.get_setting('comprueba_enlaces_num', 'animespace')
IDIOMAS = {'VOSE': 'VOSE'}
list_language = IDIOMAS.values()
list_quality = []
list_servers = ['directo', 'openload', 'streamango']
def mainlist(item):
logger.info()
autoplay.init(item.channel, list_servers, list_quality)
itemlist = []
itemlist.append(Item(channel=item.channel, title="Nuevos Episodios",
action="new_episodes",
thumbnail=get_thumb('new_episodes', auto=True),
url=host))
itemlist.append(Item(channel=item.channel, title="Ultimas",
action="list_all",
thumbnail=get_thumb('last', auto=True),
url=host + 'emision'))
itemlist.append(Item(channel=item.channel, title="Todas",
action="list_all",
thumbnail=get_thumb('all', auto=True),
url=host + 'animes'))
itemlist.append(Item(channel=item.channel, title="Anime",
action="list_all",
thumbnail=get_thumb('anime', auto=True),
url=host + 'categoria/anime'))
itemlist.append(Item(channel=item.channel, title="Películas",
action="list_all",
thumbnail=get_thumb('movies', auto=True),
url=host + 'categoria/pelicula'))
itemlist.append(Item(channel=item.channel, title="OVAs",
action="list_all",
thumbnail='',
url=host + 'categoria/ova'))
itemlist.append(Item(channel=item.channel, title="ONAs",
action="list_all",
thumbnail='',
url=host + 'categoria/ona'))
itemlist.append(Item(channel=item.channel, title="Especiales",
action="list_all",
thumbnail='',
url=host + 'categoria/especial'))
itemlist.append(Item(channel=item.channel, title="Buscar",
action="search",
url=host + 'search?q=',
thumbnail=get_thumb('search', auto=True),
fanart='https://s30.postimg.cc/pei7txpa9/buscar.png'
))
autoplay.show_option(item.channel, itemlist)
itemlist = renumbertools.show_option(item.channel, itemlist)
return itemlist
def get_source(url):
logger.info()
data = httptools.downloadpage(url).data
data = re.sub(r'\n|\r|\t|&nbsp;|<br>|\s{2,}', "", data)
return data
def list_all(item):
logger.info()
itemlist = []
data = get_source(item.url)
patron = '<article.*?href="([^"]+)">.*?src="([^"]+)".*?'
patron += '<h3 class="Title">([^<]+)</h3>.*?"fecha">([^<]+)<.*?</i>([^<]+)'
matches = re.compile(patron, re.DOTALL).findall(data)
for scrapedurl, scrapedthumbnail, scrapedtitle, year, type in matches:
type = type.strip().lower()
url = scrapedurl
thumbnail = scrapedthumbnail
lang = 'VOSE'
title = scrapedtitle
context = renumbertools.context(item)
context2 = autoplay.context
context.extend(context2)
new_item= Item(channel=item.channel,
action='episodios',
title=title,
url=url,
thumbnail=thumbnail,
language = lang,
infoLabels={'year':year}
)
if type != 'anime':
new_item.contentTitle=title
else:
new_item.plot=type
new_item.contentSerieName=title
new_item.context = context
itemlist.append(new_item)
# Paginacion
next_page = scrapertools.find_single_match(data,
'"page-item active">.*?</a>.*?<a class="page-link" href="([^"]+)">')
if next_page != "":
actual_page = scrapertools.find_single_match(item.url, '([^\?]+)?')
itemlist.append(Item(channel=item.channel,
action="list_all",
title=">> Página siguiente",
url=actual_page + next_page,
thumbnail='https://s16.postimg.cc/9okdu7hhx/siguiente.png'
))
tmdb.set_infoLabels(itemlist, seekTmdb=True)
return itemlist
def search(item, texto):
logger.info()
texto = texto.replace(" ", "+")
item.url = item.url + texto
try:
if texto != '':
return list_all(item)
else:
return []
except:
import sys
for line in sys.exc_info():
logger.error("%s" % line)
return []
def new_episodes(item):
logger.info()
itemlist = []
full_data = get_source(item.url)
data = scrapertools.find_single_match(full_data, '<section class="caps">.*?</section>')
patron = '<article.*?<a href="([^"]+)">.*?src="([^"]+)".*?'
patron += '<span class="episode">.*?</i>([^<]+)</span>.*?<h2 class="Title">([^<]+)</h2>'
matches = re.compile(patron, re.DOTALL).findall(data)
for scrapedurl, scrapedthumbnail, epi, scrapedtitle in matches:
url = scrapedurl
lang = 'VOSE'
title = '%s - %s' % (scrapedtitle, epi)
itemlist.append(Item(channel=item.channel, title=title, url=url, thumbnail=scrapedthumbnail,
action='findvideos', language=lang))
return itemlist
def episodios(item):
logger.info()
itemlist = []
data = get_source(item.url)
patron = '<a class="item" href="([^"]+)">'
matches = re.compile(patron, re.DOTALL).findall(data)
infoLabels = item.infoLabels
for scrapedurl in matches:
episode = scrapertools.find_single_match(scrapedurl, '.*?capitulo-(\d+)')
lang = 'VOSE'
season, episode = renumbertools.numbered_for_tratk(item.channel, item.contentSerieName, 1, int(episode))
title = "%sx%s - %s" % (season, str(episode).zfill(2),item.contentSerieName)
url = scrapedurl
infoLabels['season'] = season
infoLabels['episode'] = episode
itemlist.append(Item(channel=item.channel, title=title, contentSerieName=item.contentSerieName, url=url,
action='findvideos', language=lang, infoLabels=infoLabels))
tmdb.set_infoLabels_itemlist(itemlist, seekTmdb=True)
itemlist = itemlist[::-1]
if item.contentSerieName != '' and config.get_videolibrary_support() and len(itemlist) > 0:
itemlist.append(
Item(channel=item.channel, title='[COLOR yellow]Añadir esta serie a la videoteca[/COLOR]', url=item.url,
action="add_serie_to_library", extra="episodios", contentSerieName=item.contentSerieName,
extra1='library'))
return itemlist
def findvideos(item):
import urllib
logger.info()
itemlist = []
data = get_source(item.url)
patron = 'id="Opt\d+">.*?src=(.*?) frameborder'
matches = re.compile(patron, re.DOTALL).findall(data)
for scrapedurl in matches:
server = ''
scrapedurl = scrapedurl.replace('&quot;', '')
new_data = get_source(scrapedurl)
if "/stream/" in scrapedurl:
scrapedurl = scrapertools.find_single_match(new_data, '<source src="([^"]+)"')
server = "directo"
else:
scrapedurl = scrapertools.find_single_match(scrapedurl, '.*?url=([^&]+)?')
scrapedurl = urllib.unquote(scrapedurl)
if scrapedurl != '':
itemlist.append(Item(channel=item.channel, title='%s', url=scrapedurl, action='play',
language = item.language, infoLabels=item.infoLabels, server=server))
itemlist = servertools.get_servers_itemlist(itemlist, lambda x: x.title % x.server.capitalize())
if __comprueba_enlaces__:
itemlist = servertools.check_list_links(itemlist, __comprueba_enlaces_num__)
# Requerido para FilterTools
itemlist = filtertools.get_links(itemlist, item, list_language)
# Requerido para AutoPlay
autoplay.start(itemlist, item)
return itemlist
def newest(categoria):
itemlist = []
item = Item()
if categoria == 'anime':
item.url=host
itemlist = new_episodes(item)
return itemlist

View File

@@ -1,37 +0,0 @@
{
"id": "animesubita",
"name": "AnimeSubIta",
"active": true,
"adult": false,
"language": ["ita"],
"thumbnail": "animesubita.png",
"bannermenu": "animesubita.png",
"categories": ["anime"],
"settings": [
{
"id": "include_in_global_search",
"type": "bool",
"label": "Includi ricerca globale",
"default": true,
"enabled": true,
"visible": true
},
{
"id": "include_in_newest_anime",
"type": "bool",
"label": "Includi in Novità - Anime",
"default": true,
"enabled": true,
"visible": true
},
{
"id": "include_in_newest_italiano",
"type": "bool",
"label": "Includi in Novità - Italiano",
"default": true,
"enabled": true,
"visible": true
}
]
}

View File

@@ -1,344 +0,0 @@
# -*- coding: utf-8 -*-
# Ringraziamo Icarus crew
# ------------------------------------------------------------
# Ringraziamo Icarus crew
# Canale per AnimeSubIta
# ------------------------------------------------------------
import re, urllib, urlparse
from core import servertools, httptools, scrapertools, tmdb
from platformcode import logger, config
from core.item import Item
from channels import support
host = "http://www.animesubita.org"
PERPAGE = 20
# ----------------------------------------------------------------------------------------------------------------
def mainlist(item):
logger.info()
itemlist = [Item(channel=item.channel,
action="lista_anime_completa",
title=support.color("Lista Anime", "azure"),
url="%s/lista-anime/" % host,
thumbnail="http://orig03.deviantart.net/6889/f/2014/079/7/b/movies_and_popcorn_folder_icon_by_matheusgrilo-d7ay4tw.png"),
Item(channel=item.channel,
action="ultimiep",
title=support.color("Ultimi Episodi", "azure"),
url="%s/category/ultimi-episodi/" % host,
thumbnail="http://orig03.deviantart.net/6889/f/2014/079/7/b/movies_and_popcorn_folder_icon_by_matheusgrilo-d7ay4tw.png"),
Item(channel=item.channel,
action="lista_anime",
title=support.color("Anime in corso", "azure"),
url="%s/category/anime-in-corso/" % host,
thumbnail="http://orig03.deviantart.net/6889/f/2014/079/7/b/movies_and_popcorn_folder_icon_by_matheusgrilo-d7ay4tw.png"),
Item(channel=item.channel,
action="categorie",
title=support.color("Categorie", "azure"),
url="%s/generi/" % host,
thumbnail="http://orig03.deviantart.net/6889/f/2014/079/7/b/movies_and_popcorn_folder_icon_by_matheusgrilo-d7ay4tw.png"),
Item(channel=item.channel,
action="search",
title=support.color("Cerca anime ...", "yellow"),
extra="anime",
thumbnail="http://dc467.4shared.com/img/fEbJqOum/s7/13feaf0c8c0/Search")
]
return itemlist
# ================================================================================================================
# ----------------------------------------------------------------------------------------------------------------
def newest(categoria):
logger.info()
itemlist = []
item = Item()
try:
if categoria == "anime":
item.url = host
item.action = "ultimiep"
itemlist = ultimiep(item)
if itemlist[-1].action == "ultimiep":
itemlist.pop()
# Continua l'esecuzione in caso di errore
except:
import sys
for line in sys.exc_info():
logger.error("{0}".format(line))
return []
return itemlist
# ================================================================================================================
# ----------------------------------------------------------------------------------------------------------------
def search(item, texto):
logger.info()
item.url = host + "/?s=" + texto
try:
return lista_anime(item)
# Continua la ricerca in caso di errore
except:
import sys
for line in sys.exc_info():
logger.error("%s" % line)
return []
# ================================================================================================================
# ----------------------------------------------------------------------------------------------------------------
def categorie(item):
logger.info()
itemlist = []
data = httptools.downloadpage(item.url).data
patron = r'<li><a title="[^"]+" href="([^"]+)">([^<]+)</a>'
matches = re.compile(patron, re.DOTALL).findall(data)
for scrapedurl, scrapedtitle in matches:
itemlist.append(
Item(channel=item.channel,
action="lista_anime",
title=scrapedtitle.replace('Anime', '').strip(),
text_color="azure",
url=scrapedurl,
thumbnail=item.thumbnail,
folder=True))
return itemlist
# ================================================================================================================
# ----------------------------------------------------------------------------------------------------------------
def ultimiep(item):
logger.info("ultimiep")
itemlist = lista_anime(item, False, False)
for itm in itemlist:
title = scrapertools.decodeHtmlentities(itm.title)
# Pulizia titolo
title = title.replace("Streaming", "").replace("&", "")
title = title.replace("Download", "")
title = title.replace("Sub Ita", "").strip()
eptype = scrapertools.find_single_match(title, "((?:Episodio?|OAV))")
cleantitle = re.sub(r'%s\s*\d*\s*(?:\(\d+\)|)' % eptype, '', title).strip()
# Creazione URL
url = re.sub(r'%s-?\d*-' % eptype.lower(), '', itm.url)
if "-streaming" not in url:
url = url.replace("sub-ita", "sub-ita-streaming")
epnumber = ""
if 'episodio' in eptype.lower():
epnumber = scrapertools.find_single_match(title.lower(), r'episodio?\s*(\d+)')
eptype += ":? " + epnumber
extra = "<tr>\s*<td[^>]+><strong>(?:[^>]+>|)%s(?:[^>]+>[^>]+>|[^<]*|[^>]+>)</strong>" % eptype
itm.title = support.color(title, 'azure').strip()
itm.action = "findvideos"
itm.url = url
itm.fulltitle = cleantitle
itm.extra = extra
itm.show = re.sub(r'Episodio\s*', '', title)
itm.thumbnail = item.thumbnail
tmdb.set_infoLabels_itemlist(itemlist, seekTmdb=True)
return itemlist
# ================================================================================================================
# ----------------------------------------------------------------------------------------------------------------
def lista_anime(item, nextpage=True, show_lang=True):
logger.info()
itemlist = []
data = httptools.downloadpage(item.url).data
blocco = scrapertools.find_single_match(data, r'<div class="post-list group">(.*?)</nav><!--/.pagination-->')
# patron = r'<a href="([^"]+)" title="([^"]+)">\s*<img[^s]+src="([^"]+)"[^>]+>' # Patron con thumbnail, Kodi non scarica le immagini dal sito
patron = r'<a href="([^"]+)" title="([^"]+)">'
matches = re.compile(patron, re.DOTALL).findall(blocco)
for scrapedurl, scrapedtitle in matches:
scrapedtitle = scrapertools.decodeHtmlentities(scrapedtitle)
scrapedtitle = re.sub(r'\s+', ' ', scrapedtitle)
# Pulizia titolo
scrapedtitle = scrapedtitle.replace("Streaming", "").replace("&", "")
scrapedtitle = scrapedtitle.replace("Download", "")
lang = scrapertools.find_single_match(scrapedtitle, r"([Ss][Uu][Bb]\s*[Ii][Tt][Aa])")
scrapedtitle = scrapedtitle.replace("Sub Ita", "").strip()
eptype = scrapertools.find_single_match(scrapedtitle, "((?:Episodio?|OAV))")
cleantitle = re.sub(r'%s\s*\d*\s*(?:\(\d+\)|)' % eptype, '', scrapedtitle)
cleantitle = cleantitle.replace(lang, "").strip()
itemlist.append(
Item(channel=item.channel,
action="episodi",
contentType="tvshow" if 'oav' not in scrapedtitle.lower() else "movie",
title=color(scrapedtitle.replace(lang, "(%s)" % support.color(lang, "red") if show_lang else "").strip(), 'azure'),
fulltitle=cleantitle,
url=scrapedurl,
show=cleantitle,
folder=True))
tmdb.set_infoLabels_itemlist(itemlist, seekTmdb=True)
if nextpage:
patronvideos = r'<link rel="next" href="([^"]+)"\s*/>'
matches = re.compile(patronvideos, re.DOTALL).findall(data)
if len(matches) > 0:
scrapedurl = matches[0]
itemlist.append(
Item(channel=item.channel,
action="lista_anime",
title="[COLOR lightgreen]" + config.get_localized_string(30992) + "[/COLOR]",
url=scrapedurl,
thumbnail="http://2.bp.blogspot.com/-fE9tzwmjaeQ/UcM2apxDtjI/AAAAAAAAeeg/WKSGM2TADLM/s1600/pager+old.png",
folder=True))
return itemlist
# ================================================================================================================
# ----------------------------------------------------------------------------------------------------------------
def lista_anime_completa(item):
logger.info()
itemlist = []
p = 1
if '{}' in item.url:
item.url, p = item.url.split('{}')
p = int(p)
data = httptools.downloadpage(item.url).data
blocco = scrapertools.find_single_match(data, r'<ul class="lcp_catlist"[^>]+>(.*?)</ul>')
patron = r'<a href="([^"]+)"[^>]+>([^<]+)</a>'
matches = re.compile(patron, re.DOTALL).findall(blocco)
for i, (scrapedurl, scrapedtitle) in enumerate(matches):
if (p - 1) * PERPAGE > i: continue
if i >= p * PERPAGE: break
scrapedtitle = scrapertools.decodeHtmlentities(scrapedtitle.strip())
cleantitle = scrapedtitle.replace("Sub Ita Streaming", "").replace("Ita Streaming", "")
itemlist.append(
Item(channel=item.channel,
action="episodi",
contentType="tvshow" if 'oav' not in scrapedtitle.lower() else "movie",
title=support.color(scrapedtitle, 'azure'),
fulltitle=cleantitle,
show=cleantitle,
url=scrapedurl,
folder=True))
tmdb.set_infoLabels_itemlist(itemlist, seekTmdb=True)
if len(matches) >= p * PERPAGE:
scrapedurl = item.url + '{}' + str(p + 1)
itemlist.append(
Item(channel=item.channel,
extra=item.extra,
action="lista_anime_completa",
title="[COLOR lightgreen]" + config.get_localized_string(30992) + "[/COLOR]",
url=scrapedurl,
thumbnail="http://2.bp.blogspot.com/-fE9tzwmjaeQ/UcM2apxDtjI/AAAAAAAAeeg/WKSGM2TADLM/s1600/pager+old.png",
folder=True))
return itemlist
# ================================================================================================================
# ----------------------------------------------------------------------------------------------------------------
def episodi(item):
logger.info()
itemlist = []
data = httptools.downloadpage(item.url).data
patron = '<td style="[^"]*?">\s*.*?<strong>(.*?)</strong>.*?\s*</td>\s*<td style="[^"]*?">\s*<a href="([^"]+?)"[^>]+>\s*<img.*?src="([^"]+?)".*?/>\s*</a>\s*</td>'
matches = re.compile(patron, re.DOTALL).findall(data)
for scrapedtitle, scrapedurl, scrapedimg in matches:
if 'nodownload' in scrapedimg or 'nostreaming' in scrapedimg:
continue
if 'vvvvid' in scrapedurl.lower():
itemlist.append(Item(title='I Video VVVVID Non sono supportati'))
continue
scrapedtitle = scrapertools.decodeHtmlentities(scrapedtitle)
scrapedtitle = re.sub(r'<[^>]*?>', '', scrapedtitle)
scrapedtitle = '[COLOR azure][B]' + scrapedtitle + '[/B][/COLOR]'
itemlist.append(
Item(channel=item.channel,
action="findvideos",
contentType="episode",
title=scrapedtitle,
url=urlparse.urljoin(host, scrapedurl),
fulltitle=item.title,
show=scrapedtitle,
plot=item.plot,
fanart=item.thumbnail,
thumbnail=item.thumbnail))
# Comandi di servizio
if config.get_videolibrary_support() and len(itemlist) != 0:
itemlist.append(
Item(channel=item.channel,
title="[COLOR lightblue]%s[/COLOR]" % config.get_localized_string(30161),
url=item.url,
action="add_serie_to_library",
extra="episodios",
show=item.show))
return itemlist
# ================================================================================================================
# ----------------------------------------------------------------------------------------------------------------
def findvideos(item):
logger.info()
itemlist = []
headers = {'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; rv:52.0) Gecko/20100101 Firefox/52.0'}
if item.extra:
data = httptools.downloadpage(item.url, headers=headers).data
blocco = scrapertools.find_single_match(data, r'%s(.*?)</tr>' % item.extra)
item.url = scrapertools.find_single_match(blocco, r'<a href="([^"]+)"[^>]+>')
patron = r'http:\/\/link[^a]+animesubita[^o]+org\/[^\/]+\/.*?(episodio\d*)[^p]+php(\?.*)'
for phpfile, scrapedurl in re.findall(patron, item.url, re.DOTALL):
url = "%s/%s.php%s" % (host, phpfile, scrapedurl)
headers['Referer'] = url
data = httptools.downloadpage(url, headers=headers).data
# ------------------------------------------------
cookies = ""
matches = re.compile('(.%s.*?)\n' % host.replace("http://", "").replace("www.", ""), re.DOTALL).findall(config.get_cookie_data())
for cookie in matches:
name = cookie.split('\t')[5]
value = cookie.split('\t')[6]
cookies += name + "=" + value + ";"
headers['Cookie'] = cookies[:-1]
# ------------------------------------------------
scrapedurl = scrapertools.find_single_match(data, r'<source src="([^"]+)"[^>]+>')
url = scrapedurl + '|' + urllib.urlencode(headers)
itemlist.append(
Item(channel=item.channel,
action="play",
text_color="azure",
title="[%s] %s" % (support.color("Diretto", "orange"), item.title),
fulltitle=item.fulltitle,
url=url,
thumbnail=item.thumbnail,
fanart=item.thumbnail,
plot=item.plot))
return itemlist

View File

@@ -1,36 +0,0 @@
{
"id": "animetubeita",
"name": "Animetubeita",
"active": true,
"adult": false,
"language": ["ita"],
"thumbnail": "http:\/\/i.imgur.com\/rQPx1iQ.png",
"bannermenu": "http:\/\/i.imgur.com\/rQPx1iQ.png",
"categories": ["anime"],
"settings": [
{
"id": "include_in_global_search",
"type": "bool",
"label": "Includi ricerca globale",
"default": false,
"enabled": false,
"visible": false
},
{
"id": "include_in_newest_anime",
"type": "bool",
"label": "Includi in Novità - Anime",
"default": false,
"enabled": false,
"visible": false
},
{
"id": "include_in_newest_italiano",
"type": "bool",
"label": "Includi in Novità - Italiano",
"default": true,
"enabled": true,
"visible": true
}
]
}

View File

@@ -1,364 +0,0 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# Ringraziamo Icarus crew
# Canale per animetubeita
# ----------------------------------------------------------
import re, urllib
from core import httptools, scrapertools, tmdb
from platformcode import logger, config
from core.item import Item
host = "http://www.animetubeita.com"
hostlista = host + "/lista-anime/"
hostgeneri = host + "/generi/"
hostcorso = host + "/category/serie-in-corso/"
def mainlist(item):
log("animetubeita", "mainlist", item.channel)
itemlist = [Item(channel=item.channel,
action="lista_home",
title="[COLOR azure]Home[/COLOR]",
url=host,
thumbnail=AnimeThumbnail,
fanart=AnimeFanart),
# Item(channel=item.channel,
# action="lista_anime",
# title="[COLOR azure]A-Z[/COLOR]",
# url=hostlista,
# thumbnail=AnimeThumbnail,
# fanart=AnimeFanart),
Item(channel=item.channel,
action="lista_genere",
title="[COLOR azure]Genere[/COLOR]",
url=hostgeneri,
thumbnail=CategoriaThumbnail,
fanart=CategoriaFanart),
Item(channel=item.channel,
action="lista_in_corso",
title="[COLOR azure]Serie in Corso[/COLOR]",
url=hostcorso,
thumbnail=CategoriaThumbnail,
fanart=CategoriaFanart),
Item(channel=item.channel,
action="search",
title="[COLOR lime]Cerca...[/COLOR]",
url=host + "/?s=",
thumbnail=CercaThumbnail,
fanart=CercaFanart)]
return itemlist
def lista_home(item):
log("animetubeita", "lista_home", item.channel)
itemlist = []
patron = '<h2 class="title"><a href="(.*?)" rel="bookmark" title=".*?">.*?<img.*?src="(.*?)".*?<strong>Titolo</strong></td>.*?<td>(.*?)</td>.*?<td><strong>Trama</strong></td>.*?<td>(.*?)</'
for scrapedurl, scrapedthumbnail, scrapedtitle, scrapedplot in scrapedAll(item.url, patron):
title = scrapertools.decodeHtmlentities(scrapedtitle)
title = title.split("Sub")[0]
fulltitle = re.sub(r'[Ee]pisodio? \d+', '', title)
scrapedplot = scrapertools.decodeHtmlentities(scrapedplot)
itemlist.append(
Item(channel=item.channel,
action="dl_s",
contentType="tvshow",
title="[COLOR azure]" + title + "[/COLOR]",
fulltitle=fulltitle,
url=scrapedurl,
thumbnail=scrapedthumbnail,
fanart=scrapedthumbnail,
show=fulltitle,
plot=scrapedplot))
tmdb.set_infoLabels_itemlist(itemlist, seekTmdb=True)
# Paginazione
# ===========================================================
data = httptools.downloadpage(item.url).data
patron = '<link rel="next" href="(.*?)"'
next_page = scrapertools.find_single_match(data, patron)
if next_page != "":
itemlist.append(
Item(channel=item.channel,
action="lista_home",
title=AvantiTxt,
url=next_page,
thumbnail=AvantiImg,
folder=True))
# ===========================================================
return itemlist
# def lista_anime(item):
# log("animetubeita", "lista_anime", item.channel)
# itemlist = []
# patron = '<li.*?class="page_.*?href="(.*?)">(.*?)</a></li>'
# for scrapedurl, scrapedtitle in scrapedAll(item.url, patron):
# title = scrapertools.decodeHtmlentities(scrapedtitle)
# title = title.split("Sub")[0]
# log("url:[" + scrapedurl + "] scrapedtitle:[" + title + "]")
# itemlist.append(
# Item(channel=item.channel,
# action="dettaglio",
# contentType="tvshow",
# title="[COLOR azure]" + title + "[/COLOR]",
# url=scrapedurl,
# show=title,
# thumbnail="",
# fanart=""))
# tmdb.set_infoLabels_itemlist(itemlist, seekTmdb=True)
# return itemlist
def lista_genere(item):
log("lista_anime_genere", "lista_genere", item.channel)
itemlist = []
data = httptools.downloadpage(item.url).data
bloque = scrapertools.find_single_match(data,
'<div class="hentry page post-1 odd author-admin clear-block">(.*?)<div id="disqus_thread">')
patron = '<li class="cat-item cat-item.*?"><a href="(.*?)" >(.*?)</a>'
matches = re.compile(patron, re.DOTALL).findall(bloque)
scrapertools.printMatches(matches)
for scrapedurl, scrapedtitle in matches:
itemlist.append(
Item(channel=item.channel,
action="lista_generi",
title='[COLOR lightsalmon][B]' + scrapedtitle + '[/B][/COLOR]',
url=scrapedurl,
fulltitle=scrapedtitle,
show=scrapedtitle,
thumbnail=item.thumbnail))
return itemlist
def lista_generi(item):
log("animetubeita", "lista_generi", item.channel)
itemlist = []
patron = '<h2 class="title"><a href="(.*?)" rel="bookmark" title=".*?">.*?<img.*?src="(.*?)".*?<strong>Titolo</strong></td>.*?<td>(.*?)</td>.*?<td><strong>Trama</strong></td>.*?<td>(.*?)</'
for scrapedurl, scrapedthumbnail, scrapedtitle, scrapedplot in scrapedAll(item.url, patron):
title = scrapertools.decodeHtmlentities(scrapedtitle)
title = title.split("Sub")[0]
fulltitle = re.sub(r'[Ee]pisodio? \d+', '', title)
scrapedplot = scrapertools.decodeHtmlentities(scrapedplot)
itemlist.append(
Item(channel=item.channel,
action="dettaglio",
title="[COLOR azure]" + title + "[/COLOR]",
contentType="tvshow",
fulltitle=fulltitle,
url=scrapedurl,
thumbnail=scrapedthumbnail,
show=fulltitle,
fanart=scrapedthumbnail,
plot=scrapedplot))
tmdb.set_infoLabels_itemlist(itemlist, seekTmdb=True)
# Paginazione
# ===========================================================
data = httptools.downloadpage(item.url).data
patron = '<link rel="next" href="(.*?)"'
next_page = scrapertools.find_single_match(data, patron)
if next_page != "":
itemlist.append(
Item(channel=item.channel,
action="lista_generi",
title=AvantiTxt,
url=next_page,
thumbnail=AvantiImg,
folder=True))
# ===========================================================
return itemlist
def lista_in_corso(item):
log("animetubeita", "lista_home", item.channel)
itemlist = []
patron = '<h2 class="title"><a href="(.*?)" rel="bookmark" title="Link.*?>(.*?)</a></h2>.*?<img.*?src="(.*?)".*?<td><strong>Trama</strong></td>.*?<td>(.*?)</td>'
for scrapedurl, scrapedtitle, scrapedthumbnail, scrapedplot in scrapedAll(item.url, patron):
title = scrapertools.decodeHtmlentities(scrapedtitle)
title = title.split("Sub")[0]
fulltitle = re.sub(r'[Ee]pisodio? \d+', '', title)
scrapedplot = scrapertools.decodeHtmlentities(scrapedplot)
itemlist.append(
Item(channel=item.channel,
action="dettaglio",
title="[COLOR azure]" + title + "[/COLOR]",
contentType="tvshow",
fulltitle=fulltitle,
url=scrapedurl,
thumbnail=scrapedthumbnail,
show=fulltitle,
fanart=scrapedthumbnail,
plot=scrapedplot))
tmdb.set_infoLabels_itemlist(itemlist, seekTmdb=True)
# Paginazione
# ===========================================================
data = httptools.downloadpage(item.url).data
patron = '<link rel="next" href="(.*?)"'
next_page = scrapertools.find_single_match(data, patron)
if next_page != "":
itemlist.append(
Item(channel=item.channel,
action="lista_in_corso",
title=AvantiTxt,
url=next_page,
thumbnail=AvantiImg,
folder=True))
# ===========================================================
return itemlist
def dl_s(item):
log("animetubeita", "dl_s", item.channel)
itemlist = []
encontrados = set()
# 1
patron = '<p><center><a.*?href="(.*?)"'
for scrapedurl in scrapedAll(item.url, patron):
if scrapedurl in encontrados: continue
encontrados.add(scrapedurl)
title = "DOWNLOAD & STREAMING"
itemlist.append(Item(channel=item.channel,
action="dettaglio",
title="[COLOR azure]" + title + "[/COLOR]",
url=scrapedurl,
thumbnail=item.thumbnail,
fanart=item.thumbnail,
plot=item.plot,
folder=True))
# 2
patron = '<p><center>.*?<a.*?href="(.*?)"'
for scrapedurl in scrapedAll(item.url, patron):
if scrapedurl in encontrados: continue
encontrados.add(scrapedurl)
title = "DOWNLOAD & STREAMING"
itemlist.append(Item(channel=item.channel,
action="dettaglio",
title="[COLOR azure]" + title + "[/COLOR]",
url=scrapedurl,
thumbnail=item.thumbnail,
fanart=item.thumbnail,
plot=item.plot,
folder=True))
return itemlist
def dettaglio(item):
log("animetubeita", "dettaglio", item.channel)
itemlist = []
headers = {'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; rv:52.0) Gecko/20100101 Firefox/52.0'}
episodio = 1
patron = r'<a href="http:\/\/link[^a]+animetubeita[^c]+com\/[^\/]+\/[^s]+((?:stream|strm))[^p]+php(\?.*?)"'
for phpfile, scrapedurl in scrapedAll(item.url, patron):
title = "Episodio " + str(episodio)
episodio += 1
url = "%s/%s.php%s" % (host, phpfile, scrapedurl)
headers['Referer'] = url
data = httptools.downloadpage(url, headers=headers).data
# ------------------------------------------------
cookies = ""
matches = re.compile('(.animetubeita.com.*?)\n', re.DOTALL).findall(config.get_cookie_data())
for cookie in matches:
name = cookie.split('\t')[5]
value = cookie.split('\t')[6]
cookies += name + "=" + value + ";"
headers['Cookie'] = cookies[:-1]
# ------------------------------------------------
url = scrapertools.find_single_match(data, """<source src="([^"]+)" type='video/mp4'>""")
url += '|' + urllib.urlencode(headers)
itemlist.append(Item(channel=item.channel,
action="play",
title="[COLOR azure]" + title + "[/COLOR]",
url=url,
thumbnail=item.thumbnail,
fanart=item.thumbnail,
plot=item.plot))
return itemlist
def search(item, texto):
log("animetubeita", "search", item.channel)
item.url = item.url + texto
try:
return lista_home(item)
except:
import sys
for line in sys.exc_info():
logger.error("%s" % line)
return []
def scrapedAll(url="", patron=""):
matches = []
data = httptools.downloadpage(url).data
MyPatron = patron
matches = re.compile(MyPatron, re.DOTALL).findall(data)
scrapertools.printMatches(matches)
return matches
def scrapedSingle(url="", single="", patron=""):
matches = []
data = httptools.downloadpage(url).data
elemento = scrapertools.find_single_match(data, single)
matches = re.compile(patron, re.DOTALL).findall(elemento)
scrapertools.printMatches(matches)
return matches
def log(funzione="", stringa="", canale=""):
logger.debug("[" + canale + "].[" + funzione + "] " + stringa)
AnimeThumbnail = "http://img15.deviantart.net/f81c/i/2011/173/7/6/cursed_candies_anime_poster_by_careko-d3jnzg9.jpg"
AnimeFanart = "http://www.animetubeita.com/wp-content/uploads/21407_anime_scenery.jpg"
CategoriaThumbnail = "http://static.europosters.cz/image/750/poster/street-fighter-anime-i4817.jpg"
CategoriaFanart = "http://www.animetubeita.com/wp-content/uploads/21407_anime_scenery.jpg"
CercaThumbnail = "http://dc467.4shared.com/img/fEbJqOum/s7/13feaf0c8c0/Search"
CercaFanart = "https://i.ytimg.com/vi/IAlbvyBdYdY/maxresdefault.jpg"
AvantiTxt = config.get_localized_string(30992)
AvantiImg = "http://2.bp.blogspot.com/-fE9tzwmjaeQ/UcM2apxDtjI/AAAAAAAAeeg/WKSGM2TADLM/s1600/pager+old.png"

View File

@@ -1,61 +0,0 @@
{
"id": "animeworld",
"name": "AnimeWorld",
"active": true,
"adult": false,
"language": ["ita"],
"thumbnail": "https://cdn.animeworld.it/static/images/general/logoaw.png",
"categories": ["anime"],
"settings": [
{
"id": "include_in_global_search",
"type": "bool",
"label": "Includi ricerca globale",
"default": false,
"enabled": false,
"visible": false
},
{
"id": "include_in_newest_anime",
"type": "bool",
"label": "Includi in Novità - Anime",
"default": true,
"enabled": true,
"visible": true
},
{
"id": "include_in_newest_italiano",
"type": "bool",
"label": "Includi in Novità - Italiano",
"default": true,
"enabled": true,
"visible": true
},
{
"id": "comprueba_enlaces",
"type": "bool",
"label": "Verifica se i link esistono",
"default": false,
"enabled": true,
"visible": true
},
{
"id": "comprueba_enlaces_num",
"type": "list",
"label": "Numero de link da verificare",
"default": 1,
"enabled": true,
"visible": "eq(-1,true)",
"lvalues": [ "1", "3", "5", "10" ]
},
{
"id": "filter_languages",
"type": "list",
"label": "Mostra link in lingua...",
"default": 0,
"enabled": true,
"visible": true,
"lvalues": ["No filtrar","Italiano"]
}
]
}

View File

@@ -1,425 +0,0 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# Canale per animeworld
# ----------------------------------------------------------
import re, urlparse
from core import httptools, scrapertoolsV2, servertools, tmdb, tvdb
from core.item import Item
from platformcode import logger, config
from channels import autoplay, filtertools, support, autorenumber
from channelselector import thumb
host = "https://www.animeworld.it"
headers = [['Referer', host]]
IDIOMAS = {'Italiano': 'Italiano'}
list_language = IDIOMAS.values()
list_servers = ['diretto']
list_quality = []
__comprueba_enlaces__ = config.get_setting('comprueba_enlaces', 'animeworld')
__comprueba_enlaces_num__ = config.get_setting('comprueba_enlaces_num', 'animeworld')
def mainlist(item):
logger.info("[animeworld.py] mainlist")
itemlist =[]
support.menu(itemlist, '[B] > Anime ITA[/B]', 'build_menu', host+'/filter?language[]=1')
support.menu(itemlist, '[B] > Anime SUB[/B]', 'build_menu', host+'/filter?language[]=0')
support.menu(itemlist, ' > Anime A-Z', 'alfabetico', host+'/az-list')
support.menu(itemlist, 'Anime - Ultimi Aggiunti', 'alfabetico', host+'/newest')
support.menu(itemlist, 'Anime - Ultimi Episodi', 'alfabetico', host+'/newest')
support.menu(itemlist, '[COLOR blue]Cerca...[/COLOR]', 'search')
autoplay.init(item.channel, list_servers, list_quality)
autoplay.show_option(item.channel, itemlist)
return itemlist
# Crea Menu Filtro ======================================================
def build_menu(item):
itemlist = []
itemlist.append(Item(
channel=item.channel,
action="video",
title="[B]Tutti[/B]",
url=item.url,
thumbnail=CategoriaThumbnail,
fanart=CategoriaFanart))
data = httptools.downloadpage(item.url).data
data = re.sub(r'\n|\t','',data)
data = re.sub(r'>\s*<','><',data)
block = scrapertoolsV2.find_single_match(data, r'<form class="filters.*?>(.*?)<\/form>')
matches = re.compile(r'<button class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown"> (.*?) <span.*?>(.*?)<\/ul>', re.DOTALL).findall(block)
for title, html in matches:
itemlist.append(
Item(channel=item.channel,
action='build_sub_menu',
contentType="tvshow",
title='[B] > ' + title + '[/B]',
fulltitle=title,
show=title,
url=item.url,
html=html))
# Elimina FLingua dal Menu
itemlist.pop(6)
itemlist.pop(6)
itemlist = thumb(itemlist)
return itemlist
# Crea SottoMenu Filtro ======================================================
def build_sub_menu(item):
itemlist = []
matches = re.compile(r'<input.*?name="(.*?)" value="(.*?)".*?><label.*?>(.*?)<\/label>', re.DOTALL).findall(item.html)
for name, value, title in matches:
itemlist.append(
Item(channel=item.channel,
action='video',
contentType="tvshow",
title='[B]' + title + ' >[/B]',
fulltitle=title,
show=title,
url=item.url + '&' + name + '=' + value,
plot=""))
itemlist = thumb(itemlist)
return itemlist
# Novità ======================================================
def newest(categoria):
logger.info("[animeworld.py] newest")
itemlist = []
item = Item()
try:
if categoria == "anime":
item.url = host + '/newest'
item.action = "video"
itemlist = video(item)
if itemlist[-1].action == "video":
itemlist.pop()
# Continua la ricerca in caso di errore
except:
import sys
for line in sys.exc_info():
logger.error("{0}".format(line))
return []
return itemlist
# Cerca ===========================================================
def search(item, texto):
logger.info(texto)
item.url = host + '/search?keyword=' + texto
try:
return video(item)
# Continua la ricerca in caso di errore
except:
import sys
for line in sys.exc_info():
logger.error("%s" % line)
return []
# Lista A-Z ====================================================
def alfabetico(item):
logger.info("[animeworld.py] alfabetico")
itemlist = []
data = httptools.downloadpage(item.url).data
data = re.sub(r'\n|\t','',data)
data = re.sub(r'>\s*<','><',data)
block = scrapertoolsV2.find_single_match(data, r'<span>.*?A alla Z.<\/span>.*?<ul>(.*?)<\/ul>')
matches = re.compile('<a href="([^"]+)" title="([^"]+)">', re.DOTALL).findall(block)
scrapertoolsV2.printMatches(matches)
for url, title in matches:
itemlist.append(
Item(channel=item.channel,
action='lista_anime',
contentType="tvshow",
title=title,
fulltitle=title,
show=title,
url=url,
plot=""))
return itemlist
def lista_anime(item):
logger.info("[animeworld.py] lista_anime")
itemlist = []
# Carica la pagina
data = httptools.downloadpage(item.url).data
data = re.sub(r'\n|\t','',data)
data = re.sub(r'>\s*<','><',data)
# Estrae i contenuti
patron = r'<div class="item"><a href="([^"]+)".*?src="([^"]+)".*?data-jtitle="([^"]+)".*?>([^<]+)<\/a><p>(.*?)<\/p>'
matches = re.compile(patron, re.DOTALL).findall(data)
for scrapedurl, scrapedthumb, scrapedoriginal, scrapedtitle, scrapedplot in matches:
if scrapedoriginal == scrapedtitle:
scrapedoriginal=''
else:
scrapedoriginal = ' - [ ' + scrapedoriginal + ' ]'
year = ''
lang = ''
if '(' in scrapedtitle:
year = scrapertoolsV2.find_single_match(scrapedtitle, r'(\([0-9]+\))')
lang = scrapertoolsV2.find_single_match(scrapedtitle, r'(\([a-zA-Z]+\))')
title = scrapedtitle.replace(year,'').replace(lang,'')
original = scrapedoriginal.replace(year,'').replace(lang,'')
title = '[B]' + title + '[/B]' + year + lang + original
itemlist.append(
Item(channel=item.channel,
extra=item.extra,
contentType="tvshow",
action="episodios",
text_color="azure",
title=title,
url=scrapedurl,
thumbnail=scrapedthumb,
fulltitle=title,
show=title,
plot=scrapedplot,
folder=True))
tmdb.set_infoLabels_itemlist(itemlist, seekTmdb=True)
autorenumber.renumber(itemlist)
# Next page
next_page = scrapertoolsV2.find_single_match(data, '<a class="page-link" href="([^"]+)" rel="next"')
if next_page != '':
itemlist.append(
Item(channel=item.channel,
action='lista_anime',
title='[B]' + config.get_localized_string(30992) + ' >[/B]',
url=next_page,
contentType=item.contentType,
thumbnail=thumb()))
return itemlist
def video(item):
logger.info("[animeworld.py] video")
itemlist = []
data = httptools.downloadpage(item.url).data
data = re.sub(r'\n|\t','',data)
data = re.sub(r'>\s*<','><',data)
patron = r'<a href="([^"]+)" class="poster.*?><img src="([^"]+)"(.*?)data-jtitle="([^"]+)" .*?>(.*?)<\/a>'
matches = re.compile(patron, re.DOTALL).findall(data)
for scrapedurl, scrapedthumb ,scrapedinfo, scrapedoriginal, scrapedtitle in matches:
# Cerca Info come anno o lingua nel Titolo
year = ''
lang = ''
if '(' in scrapedtitle:
year = scrapertoolsV2.find_single_match(scrapedtitle, r'( \([0-9]+\))')
lang = scrapertoolsV2.find_single_match(scrapedtitle, r'( \([a-zA-Z]+\))')
# Rimuove Anno e Lingua nel Titolo
title = scrapedtitle.replace(year,'').replace(lang,'')
original = scrapedoriginal.replace(year,'').replace(lang,'')
# Compara Il Titolo con quello originale
if original == title:
original=''
else:
original = ' - [ ' + scrapedoriginal + ' ]'
# cerca info supplementari
ep = ''
ep = scrapertoolsV2.find_single_match(scrapedinfo, '<div class="ep">(.*?)<')
if ep != '':
ep = ' - ' + ep
ova = ''
ova = scrapertoolsV2.find_single_match(scrapedinfo, '<div class="ova">(.*?)<')
if ova != '':
ova = ' - (' + ova + ')'
ona = ''
ona = scrapertoolsV2.find_single_match(scrapedinfo, '<div class="ona">(.*?)<')
if ona != '':
ona = ' - (' + ona + ')'
movie = ''
movie = scrapertoolsV2.find_single_match(scrapedinfo, '<div class="movie">(.*?)<')
if movie != '':
movie = ' - (' + movie + ')'
special = ''
special = scrapertoolsV2.find_single_match(scrapedinfo, '<div class="special">(.*?)<')
if special != '':
special = ' - (' + special + ')'
# Concatena le informazioni
info = ep + lang + year + ova + ona + movie + special
# Crea il title da visualizzare
long_title = '[B]' + title + '[/B]' + info + original
# Controlla se sono Episodi o Film
if movie == '':
contentType = 'tvshow'
action = 'episodios'
else:
contentType = 'movie'
action = 'findvideos'
itemlist.append(
Item(channel=item.channel,
contentType=contentType,
action=action,
title=long_title,
url=scrapedurl,
fulltitle=title,
show=title,
thumbnail=scrapedthumb,
context = autoplay.context))
tmdb.set_infoLabels_itemlist(itemlist, seekTmdb=True)
autorenumber.renumber(itemlist)
# Next page
next_page = scrapertoolsV2.find_single_match(data, '<a class="page-link" href=".*?page=([^"]+)" rel="next"')
if next_page != '':
itemlist.append(
Item(channel=item.channel,
action='video',
title='[B]' + config.get_localized_string(30992) + ' >[/B]',
url=re.sub('&page=([^"]+)', '', item.url) + '&page=' + next_page,
contentType=item.contentType,
thumbnail=thumb()))
return itemlist
def episodios(item):
logger.info("[animeworld.py] episodios")
itemlist = []
data = httptools.downloadpage(item.url).data.replace('\n', '')
data = re.sub(r'>\s*<', '><', data)
block = scrapertoolsV2.find_single_match(data, r'<div class="widget servers".*?>(.*?)<div id="download"')
block = scrapertoolsV2.find_single_match(block,r'<div class="server.*?>(.*?)<div class="server.*?>')
patron = r'<li><a.*?href="([^"]+)".*?>(.*?)<\/a>'
matches = re.compile(patron, re.DOTALL).findall(block)
for scrapedurl, scrapedtitle in matches:
scrapedtitle = '[B] Episodio ' + scrapedtitle + '[/B]'
itemlist.append(
Item(
channel=item.channel,
action="findvideos",
contentType="episode",
title=scrapedtitle,
url=urlparse.urljoin(host, scrapedurl),
fulltitle=scrapedtitle,
show=scrapedtitle,
plot=item.plot,
fanart=item.thumbnail,
thumbnail=item.thumbnail))
autorenumber.renumber(itemlist, item,'bold')
# Aggiungi a Libreria
if config.get_videolibrary_support() and len(itemlist) != 0:
itemlist.append(
Item(
channel=item.channel,
title="[COLOR lightblue]%s[/COLOR]" % config.get_localized_string(30161),
url=item.url,
action="add_serie_to_library",
extra="episodios",
show=item.show))
return itemlist
def findvideos(item):
logger.info("[animeworld.py] findvideos")
itemlist = []
anime_id = scrapertoolsV2.find_single_match(item.url, r'.*\..*?\/(.*)')
data = httptools.downloadpage(host + "/ajax/episode/serverPlayer?id=" + anime_id).data
patron = '<source src="([^"]+)"'
matches = re.compile(patron, re.DOTALL).findall(data)
for video in matches:
itemlist.append(
Item(
channel=item.channel,
action="play",
title=item.title + " [[COLOR orange]Diretto[/COLOR]]",
url=video,
server='directo',
contentType=item.contentType,
folder=False))
# Requerido para Filtrar enlaces
if __comprueba_enlaces__:
itemlist = servertools.check_list_links(itemlist, __comprueba_enlaces_num__)
# Requerido para FilterTools
itemlist = filtertools.get_links(itemlist, item, list_language)
# Requerido para AutoPlay
autoplay.start(itemlist, item)
return itemlist
# riferimenti di servizio ====================================================
AnimeThumbnail = "http://img15.deviantart.net/f81c/i/2011/173/7/6/cursed_candies_anime_poster_by_careko-d3jnzg9.jpg"
AnimeFanart = "https://i.ytimg.com/vi/IAlbvyBdYdY/maxresdefault.jpg"
CategoriaThumbnail = "http://static.europosters.cz/image/750/poster/street-fighter-anime-i4817.jpg"
CategoriaFanart = "https://i.ytimg.com/vi/IAlbvyBdYdY/maxresdefault.jpg"
CercaThumbnail = "http://dc467.4shared.com/img/fEbJqOum/s7/13feaf0c8c0/Search"
CercaFanart = "https://i.ytimg.com/vi/IAlbvyBdYdY/maxresdefault.jpg"
AvantiTxt = config.get_localized_string(30992)
AvantiImg = "http://2.bp.blogspot.com/-fE9tzwmjaeQ/UcM2apxDtjI/AAAAAAAAeeg/WKSGM2TADLM/s1600/pager+old.png"

View File

@@ -1,724 +0,0 @@
# -*- coding: utf-8 -*-
import os
from core import channeltools
from core import jsontools
from core.item import Item
from platformcode import config, logger
from platformcode import platformtools
from platformcode import launcher
from time import sleep
from platformcode.config import get_setting
__channel__ = "autoplay"
PLAYED = False
autoplay_node = {}
def context():
'''
Agrega la opcion Configurar AutoPlay al menu contextual
:return:
'''
_context = ""
if config.is_xbmc():
_context = [{"title": config.get_localized_string(60071),
"action": "autoplay_config",
"channel": "autoplay"}]
return _context
context = context()
def show_option(channel, itemlist, text_color='yellow', thumbnail=None, fanart=None):
'''
Agrega la opcion Configurar AutoPlay en la lista recibida
:param channel: str
:param itemlist: list (lista donde se desea integrar la opcion de configurar AutoPlay)
:param text_color: str (color para el texto de la opcion Configurar Autoplay)
:param thumbnail: str (direccion donde se encuentra el thumbnail para la opcion Configurar Autoplay)
:return:
'''
from channelselector import get_thumb
logger.info()
if not config.is_xbmc():
return itemlist
if thumbnail == None:
thumbnail = get_thumb('autoplay.png')
if fanart == None:
fanart = get_thumb('autoplay.png')
plot_autoplay = config.get_localized_string(60399)
itemlist.append(
Item(channel=__channel__,
title=config.get_localized_string(60071),
action="autoplay_config",
text_color=text_color,
thumbnail=thumbnail,
fanart=fanart,
plot=plot_autoplay,
from_channel=channel
))
return itemlist
def start(itemlist, item):
'''
Metodo principal desde donde se reproduce automaticamente los enlaces
- En caso la opcion de personalizar activa utilizara las opciones definidas por el usuario.
- En caso contrario intentara reproducir cualquier enlace que cuente con el idioma preferido.
:param itemlist: list (lista de items listos para reproducir, o sea con action='play')
:param item: item (el item principal del canal)
:return: intenta autoreproducir, en caso de fallar devuelve el itemlist que recibio en un principio
'''
logger.info()
global PLAYED
global autoplay_node
PLAYED = False
base_item = item
if not config.is_xbmc():
#platformtools.dialog_notification('AutoPlay ERROR', 'Sólo disponible para XBMC/Kodi')
return itemlist
if not autoplay_node:
# Obtiene el nodo AUTOPLAY desde el json
autoplay_node = jsontools.get_node_from_file('autoplay', 'AUTOPLAY')
channel_id = item.channel
if item.channel == 'videolibrary':
autoplay_node = jsontools.get_node_from_file('autoplay', 'AUTOPLAY')
channel_id = item.contentChannel
try:
active = autoplay_node['status']
except:
active = is_active(item.channel)
if not channel_id in autoplay_node or not active:
return itemlist
# Agrega servidores y calidades que no estaban listados a autoplay_node
new_options = check_value(channel_id, itemlist)
# Obtiene el nodo del canal desde autoplay_node
channel_node = autoplay_node.get(channel_id, {})
# Obtiene los ajustes des autoplay para este canal
settings_node = channel_node.get('settings', {})
if get_setting('autoplay') or settings_node['active']:
url_list_valid = []
autoplay_list = []
autoplay_b = []
favorite_servers = []
favorite_quality = []
# Guarda el valor actual de "Accion y Player Mode" en preferencias
user_config_setting_action = config.get_setting("default_action")
user_config_setting_player = config.get_setting("player_mode")
# Habilita la accion "Ver en calidad alta" (si el servidor devuelve más de una calidad p.e. gdrive)
if user_config_setting_action != 2:
config.set_setting("default_action", 2)
if user_config_setting_player != 0:
config.set_setting("player_mode", 0)
# Informa que AutoPlay esta activo
#platformtools.dialog_notification('AutoPlay Activo', '', sound=False)
# Prioridades a la hora de ordenar itemlist:
# 0: Servidores y calidades
# 1: Calidades y servidores
# 2: Solo servidores
# 3: Solo calidades
# 4: No ordenar
if (settings_node['custom_servers'] and settings_node['custom_quality']):
priority = settings_node['priority'] # 0: Servidores y calidades o 1: Calidades y servidores
elif settings_node['custom_servers']:
priority = 2 # Solo servidores
elif settings_node['custom_quality']:
priority = 3 # Solo calidades
else:
priority = 4 # No ordenar
# Obtiene las listas servidores, calidades disponibles desde el nodo del json de AutoPlay
server_list = channel_node.get('servers', [])
for server in server_list:
server = server.lower()
quality_list = channel_node.get('quality', [])
# Si no se definen calidades la se asigna default como calidad unica
if len(quality_list) == 0:
quality_list =['default']
# Se guardan los textos de cada servidor y calidad en listas p.e. favorite_servers = ['openload',
# 'streamcloud']
for num in range(1, 4):
favorite_servers.append(channel_node['servers'][settings_node['server_%s' % num]].lower())
favorite_quality.append(channel_node['quality'][settings_node['quality_%s' % num]])
# Se filtran los enlaces de itemlist y que se correspondan con los valores de autoplay
for item in itemlist:
autoplay_elem = dict()
b_dict = dict()
# Comprobamos q se trata de un item de video
if 'server' not in item:
continue
# Agrega la opcion configurar AutoPlay al menu contextual
if 'context' not in item:
item.context = list()
if not filter(lambda x: x['action'] == 'autoplay_config', context):
item.context.append({"title": config.get_localized_string(60071),
"action": "autoplay_config",
"channel": "autoplay",
"from_channel": channel_id})
# Si no tiene calidad definida le asigna calidad 'default'
if item.quality == '':
item.quality = 'default'
# Se crea la lista para configuracion personalizada
if priority < 2: # 0: Servidores y calidades o 1: Calidades y servidores
# si el servidor y la calidad no se encuentran en las listas de favoritos o la url esta repetida,
# descartamos el item
if item.server.lower() not in favorite_servers or item.quality not in favorite_quality \
or item.url in url_list_valid:
item.type_b = True
b_dict['videoitem']= item
autoplay_b.append(b_dict)
continue
autoplay_elem["indice_server"] = favorite_servers.index(item.server.lower())
autoplay_elem["indice_quality"] = favorite_quality.index(item.quality)
elif priority == 2: # Solo servidores
# si el servidor no se encuentra en la lista de favoritos o la url esta repetida,
# descartamos el item
if item.server.lower() not in favorite_servers or item.url in url_list_valid:
item.type_b = True
b_dict['videoitem'] = item
autoplay_b.append(b_dict)
continue
autoplay_elem["indice_server"] = favorite_servers.index(item.server.lower())
elif priority == 3: # Solo calidades
# si la calidad no se encuentra en la lista de favoritos o la url esta repetida,
# descartamos el item
if item.quality not in favorite_quality or item.url in url_list_valid:
item.type_b = True
b_dict['videoitem'] = item
autoplay_b.append(b_dict)
continue
autoplay_elem["indice_quality"] = favorite_quality.index(item.quality)
else: # No ordenar
# si la url esta repetida, descartamos el item
if item.url in url_list_valid:
continue
# Si el item llega hasta aqui lo añadimos al listado de urls validas y a autoplay_list
url_list_valid.append(item.url)
item.plan_b=True
autoplay_elem['videoitem'] = item
# autoplay_elem['server'] = item.server
# autoplay_elem['quality'] = item.quality
autoplay_list.append(autoplay_elem)
# Ordenamos segun la prioridad
if priority == 0: # Servidores y calidades
autoplay_list.sort(key=lambda orden: (orden['indice_server'], orden['indice_quality']))
elif priority == 1: # Calidades y servidores
autoplay_list.sort(key=lambda orden: (orden['indice_quality'], orden['indice_server']))
elif priority == 2: # Solo servidores
autoplay_list.sort(key=lambda orden: orden['indice_server'])
elif priority == 3: # Solo calidades
autoplay_list.sort(key=lambda orden: orden['indice_quality'])
# Se prepara el plan b, en caso de estar activo se agregan los elementos no favoritos al final
try:
plan_b = settings_node['plan_b']
except:
plan_b = True
text_b = ''
if plan_b:
autoplay_list.extend(autoplay_b)
# Si hay elementos en la lista de autoplay se intenta reproducir cada elemento, hasta encontrar uno
# funcional o fallen todos
if autoplay_list or (plan_b and autoplay_b):
#played = False
max_intentos = 5
max_intentos_servers = {}
# Si se esta reproduciendo algo detiene la reproduccion
if platformtools.is_playing():
platformtools.stop_video()
for autoplay_elem in autoplay_list:
play_item = Item
# Si no es un elemento favorito si agrega el texto plan b
if autoplay_elem['videoitem'].type_b:
text_b = '(Plan B)'
if not platformtools.is_playing() and not PLAYED:
videoitem = autoplay_elem['videoitem']
if videoitem.server.lower() not in max_intentos_servers:
max_intentos_servers[videoitem.server.lower()] = max_intentos
# Si se han alcanzado el numero maximo de intentos de este servidor saltamos al siguiente
if max_intentos_servers[videoitem.server.lower()] == 0:
continue
lang = " "
if hasattr(videoitem, 'language') and videoitem.language != "":
lang = " '%s' " % videoitem.language
platformtools.dialog_notification("AutoPlay %s" %text_b, "%s%s%s" % (
videoitem.server.upper(), lang, videoitem.quality.upper()), sound=False)
# TODO videoitem.server es el id del server, pero podria no ser el nombre!!!
# Intenta reproducir los enlaces
# Si el canal tiene metodo play propio lo utiliza
channel = __import__('channels.%s' % channel_id, None, None, ["channels.%s" % channel_id])
if hasattr(channel, 'play'):
resolved_item = getattr(channel, 'play')(videoitem)
if len(resolved_item) > 0:
if isinstance(resolved_item[0], list):
videoitem.video_urls = resolved_item
else:
videoitem = resolved_item[0]
# Si no directamente reproduce y marca como visto
# Verifica si el item viene de la videoteca
try:
if base_item.contentChannel =='videolibrary':
# Marca como visto
from platformcode import xbmc_videolibrary
xbmc_videolibrary.mark_auto_as_watched(base_item)
# Rellena el video con los datos del item principal y reproduce
play_item = base_item.clone(url=videoitem)
platformtools.play_video(play_item.url, autoplay=True)
else:
# Si no viene de la videoteca solo reproduce
platformtools.play_video(videoitem, autoplay=True)
except:
pass
sleep(3)
try:
if platformtools.is_playing():
PLAYED = True
break
except:
logger.debug(str(len(autoplay_list)))
# Si hemos llegado hasta aqui es por q no se ha podido reproducir
max_intentos_servers[videoitem.server.lower()] -= 1
# Si se han alcanzado el numero maximo de intentos de este servidor
# preguntar si queremos seguir probando o lo ignoramos
if max_intentos_servers[videoitem.server.lower()] == 0:
text = config.get_localized_string(60072) % videoitem.server.upper()
if not platformtools.dialog_yesno("AutoPlay", text,
config.get_localized_string(60073)):
max_intentos_servers[videoitem.server.lower()] = max_intentos
# Si no quedan elementos en la lista se informa
if autoplay_elem == autoplay_list[-1]:
platformtools.dialog_notification('AutoPlay', config.get_localized_string(60072))
else:
platformtools.dialog_notification(config.get_localized_string(60074), config.get_localized_string(60075))
if new_options:
platformtools.dialog_notification("AutoPlay", config.get_localized_string(60076), sound=False)
# Restaura si es necesario el valor previo de "Accion y Player Mode" en preferencias
if user_config_setting_action != 2:
config.set_setting("default_action", user_config_setting_action)
if user_config_setting_player != 0:
config.set_setting("player_mode", user_config_setting_player)
return itemlist
def init(channel, list_servers, list_quality, reset=False):
'''
Comprueba la existencia de canal en el archivo de configuracion de Autoplay y si no existe lo añade.
Es necesario llamar a esta funcion al entrar a cualquier canal que incluya la funcion Autoplay.
:param channel: (str) id del canal
:param list_servers: (list) lista inicial de servidores validos para el canal. No es necesario incluirlos todos,
ya que la lista de servidores validos se ira actualizando dinamicamente.
:param list_quality: (list) lista inicial de calidades validas para el canal. No es necesario incluirlas todas,
ya que la lista de calidades validas se ira actualizando dinamicamente.
:return: (bool) True si la inicializacion ha sido correcta.
'''
logger.info()
change = False
result = True
if not config.is_xbmc():
# platformtools.dialog_notification('AutoPlay ERROR', 'Sólo disponible para XBMC/Kodi')
result = False
else:
autoplay_path = os.path.join(config.get_data_path(), "settings_channels", 'autoplay_data.json')
if os.path.exists(autoplay_path):
autoplay_node = jsontools.get_node_from_file('autoplay', "AUTOPLAY")
else:
change = True
autoplay_node = {"AUTOPLAY": {}}
if channel not in autoplay_node or reset:
change = True
# Se comprueba que no haya calidades ni servidores duplicados
if 'default' not in list_quality:
list_quality.append('default')
# list_servers = list(set(list_servers))
# list_quality = list(set(list_quality))
# Creamos el nodo del canal y lo añadimos
channel_node = {"servers": list_servers,
"quality": list_quality,
"settings": {
"active": False,
"plan_b": True,
"custom_servers": False,
"custom_quality": False,
"priority": 0}}
for n in range(1, 4):
s = c = 0
if len(list_servers) >= n:
s = n - 1
if len(list_quality) >= n:
c = n - 1
channel_node["settings"]["server_%s" % n] = s
channel_node["settings"]["quality_%s" % n] = c
autoplay_node[channel] = channel_node
if change:
result, json_data = jsontools.update_node(autoplay_node, 'autoplay', 'AUTOPLAY')
if not result:
heading = config.get_localized_string(60077)
msj = config.get_localized_string(60078)
icon = 1
platformtools.dialog_notification(heading, msj, icon, sound=False)
return result
def check_value(channel, itemlist):
''' comprueba la existencia de un valor en la lista de servidores o calidades
si no existiera los agrega a la lista en el json
:param channel: str
:param values: list (una de servidores o calidades)
:param value_type: str (server o quality)
:return: list
'''
logger.info()
global autoplay_node
change = False
if not autoplay_node:
# Obtiene el nodo AUTOPLAY desde el json
autoplay_node = jsontools.get_node_from_file('autoplay', 'AUTOPLAY')
channel_node = autoplay_node.get(channel)
server_list = channel_node.get('servers')
if not server_list:
server_list = channel_node['servers'] = list()
quality_list = channel_node.get('quality')
if not quality_list:
quality_list = channel_node['quality'] = list()
for item in itemlist:
if item.server.lower() not in server_list and item.server !='':
server_list.append(item.server.lower())
change = True
if item.quality not in quality_list and item.quality !='':
quality_list.append(item.quality)
change = True
if change:
change, json_data = jsontools.update_node(autoplay_node, 'autoplay', 'AUTOPLAY')
return change
def autoplay_config(item):
logger.info()
global autoplay_node
dict_values = {}
list_controls = []
channel_parameters = channeltools.get_channel_parameters(item.from_channel)
channel_name = channel_parameters['title']
if not autoplay_node:
# Obtiene el nodo AUTOPLAY desde el json
autoplay_node = jsontools.get_node_from_file('autoplay', 'AUTOPLAY')
channel_node = autoplay_node.get(item.from_channel, {})
settings_node = channel_node.get('settings', {})
allow_option = True
active_settings = {"id": "active", "label": config.get_localized_string(60079),
"color": "0xffffff99", "type": "bool", "default": False, "enabled": allow_option,
"visible": allow_option}
list_controls.append(active_settings)
dict_values['active'] = settings_node.get('active', False)
# Idioma
status_language = config.get_setting("filter_languages", item.from_channel)
if not status_language:
status_language = 0
set_language = {"id": "language", "label": config.get_localized_string(60080), "color": "0xffffff99",
"type": "list", "default": 0, "enabled": "eq(-1,true)", "visible": True,
"lvalues": get_languages(item.from_channel)}
list_controls.append(set_language)
dict_values['language'] = status_language
separador = {"id": "label", "label": " "
"_________________________________________________________________________________________",
"type": "label", "enabled": True, "visible": True}
list_controls.append(separador)
# Seccion servidores favoritos
server_list = channel_node.get("servers", [])
if not server_list:
enabled = False
server_list = ["No disponible"]
else:
enabled = "eq(-3,true)"
custom_servers_settings = {"id": "custom_servers", "label": config.get_localized_string(60081), "color": "0xff66ffcc",
"type": "bool", "default": False, "enabled": enabled, "visible": True}
list_controls.append(custom_servers_settings)
if dict_values['active'] and enabled:
dict_values['custom_servers'] = settings_node.get('custom_servers', False)
else:
dict_values['custom_servers'] = False
for num in range(1, 4):
pos1 = num + 3
default = num - 1
if default > len(server_list) - 1:
default = 0
set_servers = {"id": "server_%s" % num, "label": u" \u2665" + config.get_localized_string(60082) % num,
"color": "0xfffcab14", "type": "list", "default": default,
"enabled": "eq(-%s,true)+eq(-%s,true)" % (pos1, num), "visible": True,
"lvalues": server_list}
list_controls.append(set_servers)
dict_values["server_%s" % num] = settings_node.get("server_%s" % num, 0)
if settings_node.get("server_%s" % num, 0) > len(server_list) - 1:
dict_values["server_%s" % num] = 0
# Seccion Calidades favoritas
quality_list = channel_node.get("quality", [])
if not quality_list:
enabled = False
quality_list = ["No disponible"]
else:
enabled = "eq(-7,true)"
custom_quality_settings = {"id": "custom_quality", "label": config.get_localized_string(60083), "color": "0xff66ffcc",
"type": "bool", "default": False, "enabled": enabled, "visible": True}
list_controls.append(custom_quality_settings)
if dict_values['active'] and enabled:
dict_values['custom_quality'] = settings_node.get('custom_quality', False)
else:
dict_values['custom_quality'] = False
for num in range(1, 4):
pos1 = num + 7
default = num - 1
if default > len(quality_list) - 1:
default = 0
set_quality = {"id": "quality_%s" % num, "label": u" \u2665 Calidad Favorita %s" % num,
"color": "0xfff442d9", "type": "list", "default": default,
"enabled": "eq(-%s,true)+eq(-%s,true)" % (pos1, num), "visible": True,
"lvalues": quality_list}
list_controls.append(set_quality)
dict_values["quality_%s" % num] = settings_node.get("quality_%s" % num, 0)
if settings_node.get("quality_%s" % num, 0) > len(quality_list) - 1:
dict_values["quality_%s" % num] = 0
# Plan B
dict_values['plan_b'] = settings_node.get('plan_b', False)
enabled = "eq(-4,true)|eq(-8,true)"
plan_b = {"id": "plan_b", "label": config.get_localized_string(70172),
"color": "0xffffff99",
"type": "bool", "default": False, "enabled": enabled, "visible": True}
list_controls.append(plan_b)
# Seccion Prioridades
priority_list = [config.get_localized_string(70174), config.get_localized_string(70175)]
set_priority = {"id": "priority", "label": config.get_localized_string(60085),
"color": "0xffffff99", "type": "list", "default": 0,
"enabled": True, "visible": "eq(-5,true)+eq(-9,true)+eq(-12,true)", "lvalues": priority_list}
list_controls.append(set_priority)
dict_values["priority"] = settings_node.get("priority", 0)
# Abrir cuadro de dialogo
platformtools.show_channel_settings(list_controls=list_controls, dict_values=dict_values, callback='save',
item=item, caption='%s - AutoPlay' % channel_name,
custom_button={'visible': True,
'function': "reset",
'close': True,
'label': 'Reset'})
def save(item, dict_data_saved):
'''
Guarda los datos de la ventana de configuracion
:param item: item
:param dict_data_saved: dict
:return:
'''
logger.info()
global autoplay_node
if not autoplay_node:
# Obtiene el nodo AUTOPLAY desde el json
autoplay_node = jsontools.get_node_from_file('autoplay', 'AUTOPLAY')
new_config = dict_data_saved
if not new_config['active']:
new_config['language']=0
channel_node = autoplay_node.get(item.from_channel)
config.set_setting("filter_languages", dict_data_saved.pop("language"), item.from_channel)
channel_node['settings'] = dict_data_saved
result, json_data = jsontools.update_node(autoplay_node, 'autoplay', 'AUTOPLAY')
return result
def get_languages(channel):
'''
Obtiene los idiomas desde el json del canal
:param channel: str
:return: list
'''
logger.info()
list_language = ['No filtrar']
list_controls, dict_settings = channeltools.get_channel_controls_settings(channel)
for control in list_controls:
try:
if control["id"] == 'filter_languages':
list_language = control["lvalues"]
except:
pass
return list_language
def is_active(channel):
'''
Devuelve un booleano q indica si esta activo o no autoplay en el canal desde el que se llama
:return: True si esta activo autoplay para el canal desde el que se llama, False en caso contrario.
'''
logger.info()
global autoplay_node
if not config.is_xbmc():
return False
if not autoplay_node:
# Obtiene el nodo AUTOPLAY desde el json
autoplay_node = jsontools.get_node_from_file('autoplay', 'AUTOPLAY')
# Obtine el canal desde el q se hace la llamada
#import inspect
#module = inspect.getmodule(inspect.currentframe().f_back)
#canal = module.__name__.split('.')[1]
canal = channel
# Obtiene el nodo del canal desde autoplay_node
channel_node = autoplay_node.get(canal, {})
# Obtiene los ajustes des autoplay para este canal
settings_node = channel_node.get('settings', {})
return settings_node.get('active', False) or get_setting('autoplay')
def reset(item, dict):
channel_name = item.from_channel
channel = __import__('channels.%s' % channel_name, fromlist=["channels.%s" % channel_name])
list_servers = channel.list_servers
list_quality = channel.list_quality
init(channel_name, list_servers, list_quality, reset=True)
platformtools.dialog_notification('AutoPlay', config.get_localized_string(70523) % item.category)
return
def set_status(status):
logger.info()
# Obtiene el nodo AUTOPLAY desde el json
autoplay_node = jsontools.get_node_from_file('autoplay', 'AUTOPLAY')
autoplay_node['status'] = status
result, json_data = jsontools.update_node(autoplay_node, 'autoplay', 'AUTOPLAY')
def play_multi_channel(item, itemlist):
logger.info()
global PLAYED
actual_channel = ''
channel_videos = []
video_dict = dict()
set_status(True)
for video_item in itemlist:
if video_item.contentChannel != actual_channel:
actual_channel = video_item.contentChannel
elif is_active(actual_channel):
channel_videos.append(video_item)
video_dict[actual_channel] = channel_videos
for channel, videos in video_dict.items():
item.contentChannel = channel
if not PLAYED:
start(videos, item)
else:
break

View File

@@ -1,137 +0,0 @@
# -*- coding: utf-8 -*-
# --------------------------------------------------------------------------------
# autorenumber - Rinomina Automaticamente gli Episodi
# --------------------------------------------------------------------------------
import os
try:
import xbmcgui
except:
xbmcgui = None
from platformcode import config
from core import jsontools, tvdb
from core.item import Item
from platformcode import platformtools
from channels.support import typo, log
TAG_TVSHOW_RENUMERATE = "TVSHOW_AUTORENUMBER"
TAG_SEASON_EPISODE = "season_episode"
__channel__ = "autorenumber"
def access():
allow = False
if config.is_xbmc():
allow = True
return allow
def context():
if access():
_context = [{"title": config.get_localized_string(70585),
"action": "config_item",
"channel": "autorenumber"}]
return _context
def config_item(item):
log(item)
tvdb.find_and_set_infoLabels(item)
data = ''
data = add_season(data)
if not item.infoLabels['tvdb_id']:
heading = 'TVDB ID'
item.infoLabels['tvdb_id'] = platformtools.dialog_numeric(0, heading)
data.append(item.infoLabels['tvdb_id'])
write_data(item.from_channel, item.show, data)
def add_season(data=None):
log("data= ", data)
heading = config.get_localized_string(70686)
season = platformtools.dialog_numeric(0, heading)
if season != "":
heading = config.get_localized_string(70687)
episode = platformtools.dialog_numeric(0, heading)
if episode != "":
return [int(season), int(episode)]
def write_data(channel, show, data):
log()
dict_series = jsontools.get_node_from_file(channel, TAG_TVSHOW_RENUMERATE)
tvshow = show.strip()
list_season_episode = dict_series.get(tvshow, {}).get(TAG_SEASON_EPISODE, [])
if data:
dict_renumerate = {TAG_SEASON_EPISODE: data}
dict_series[tvshow] = dict_renumerate
else:
dict_series.pop(tvshow, None)
result, json_data = jsontools.update_node(dict_series, channel, TAG_TVSHOW_RENUMERATE)
if result:
if data:
message = config.get_localized_string(60446)
else:
message = config.get_localized_string(60444)
else:
message = config.get_localized_string(70593)
heading = show.strip()
platformtools.dialog_notification(heading, message)
def renumber(itemlist, item='', typography=''):
log()
if item:
try:
dict_series = jsontools.get_node_from_file(item.channel, TAG_TVSHOW_RENUMERATE)
SERIES = dict_series[item.show]['season_episode']
S = SERIES[0]
E = SERIES[1]
ID = SERIES[2]
page = 1
epList = []
exist = True
item.infoLabels['tvdb_id'] = ID
tvdb.set_infoLabels_item(item)
while exist:
data = tvdb.otvdb_global.get_list_episodes(ID,page)
if data:
for episodes in data['data']:
if episodes['airedSeason'] >= S:
if episodes['airedEpisodeNumber'] >= E:
epList.append(str(episodes['airedSeason']) + 'x' + str(episodes['airedEpisodeNumber']))
page = page + 1
else:
exist = False
ep = 0
for item in itemlist:
item.title = typo(epList[ep] + ' - ', typography) + item.title
ep = ep + 1
except:
return itemlist
else:
for item in itemlist:
if item.contentType != 'movie':
if item.context:
context2 = item.context
item.context = context() + context2
else:
item.context = context()
return itemlist

View File

@@ -1,22 +0,0 @@
{
"id": "bleachportal",
"name": "BleachPortal",
"language": ["ita"],
"active": true,
"adult": false,
"fanart": "http://i39.tinypic.com/35ibvcx.jpg",
"thumbnail": "http://www.bleachportal.it/images/index_r1_c1.jpg",
"banner": "http://cgi.di.uoa.gr/~std05181/images/bleach.jpg",
"categories": ["anime"],
"settings": [
{
"id": "include_in_global_search",
"type": "bool",
"label": "Incluir en busqueda global",
"default": false,
"enabled": false,
"visible": false
}
]
}

View File

@@ -1,117 +0,0 @@
# -*- coding: utf-8 -*-
# Ringraziamo Icarus crew
# ------------------------------------------------------------
# XBMC Plugin
# Canale per http://bleachportal.it
# ------------------------------------------------------------
import re
from core import scrapertools, httptools
from platformcode import logger
from core.item import Item
host = "http://www.bleachportal.it"
def mainlist(item):
logger.info("[BleachPortal.py]==> mainlist")
itemlist = [Item(channel=item.channel,
action="episodi",
title="[COLOR azure] Bleach [/COLOR] - [COLOR deepskyblue]Lista Episodi[/COLOR]",
url=host + "/streaming/bleach/stream_bleach.htm",
thumbnail="http://i45.tinypic.com/286xp3m.jpg",
fanart="http://i40.tinypic.com/5jsinb.jpg",
extra="bleach"),
Item(channel=item.channel,
action="episodi",
title="[COLOR azure] D.Gray Man [/COLOR] - [COLOR deepskyblue]Lista Episodi[/COLOR]",
url=host + "/streaming/d.gray-man/stream_dgray-man.htm",
thumbnail="http://i59.tinypic.com/9is3tf.jpg",
fanart="http://wallpapercraft.net/wp-content/uploads/2016/11/Cool-D-Gray-Man-Background.jpg",
extra="dgrayman")]
return itemlist
def episodi(item):
logger.info("[BleachPortal.py]==> episodi")
itemlist = []
data = httptools.downloadpage(item.url).data
patron = '<td>?[<span\s|<width="\d+%"\s]+?class="[^"]+">\D+([\d\-]+)\s?<[^<]+<[^<]+<[^<]+<[^<]+<.*?\s+?.*?<span style="[^"]+">([^<]+).*?\s?.*?<a href="\.*(/?[^"]+)">'
matches = re.compile(patron, re.DOTALL).findall(data)
animetitle = "Bleach" if item.extra == "bleach" else "D.Gray Man"
for scrapednumber, scrapedtitle, scrapedurl in matches:
scrapedtitle = scrapedtitle.decode('latin1').encode('utf8')
itemlist.append(
Item(channel=item.channel,
action="findvideos",
title="[COLOR azure]%s Ep: [COLOR deepskyblue]%s[/COLOR][/COLOR]" % (animetitle, scrapednumber),
url=item.url.replace("stream_bleach.htm",scrapedurl) if "stream_bleach.htm" in item.url else item.url.replace("stream_dgray-man.htm", scrapedurl),
plot=scrapedtitle,
extra=item.extra,
thumbnail=item.thumbnail,
fanart=item.fanart,
fulltitle="[COLOR red]%s Ep: %s[/COLOR] | [COLOR deepskyblue]%s[/COLOR]" % (animetitle, scrapednumber, scrapedtitle)))
if item.extra == "bleach":
itemlist.append(
Item(channel=item.channel,
action="oav",
title="[B][COLOR azure] OAV e Movies [/COLOR][/B]",
url=item.url.replace("stream_bleach.htm", "stream_bleach_movie_oav.htm"),
extra=item.extra,
thumbnail=item.thumbnail,
fanart=item.fanart))
return list(reversed(itemlist))
def oav(item):
logger.info("[BleachPortal.py]==> oav")
itemlist = []
data = httptools.downloadpage(item.url).data
patron = '<td>?[<span\s|<width="\d+%"\s]+?class="[^"]+">-\s+(.*?)<[^<]+<[^<]+<[^<]+<[^<]+<.*?\s+?.*?<span style="[^"]+">([^<]+).*?\s?.*?<a href="\.*(/?[^"]+)">'
matches = re.compile(patron, re.DOTALL).findall(data)
for scrapednumber, scrapedtitle, scrapedurl in matches:
itemlist.append(
Item(channel=item.channel,
action="findvideos",
title="[COLOR deepskyblue] " + scrapednumber + " [/COLOR]",
url=item.url.replace("stream_bleach_movie_oav.htm", scrapedurl),
plot=scrapedtitle,
extra=item.extra,
thumbnail=item.thumbnail,
fulltitle="[COLOR red]" + scrapednumber + "[/COLOR] | [COLOR deepskyblue]" + scrapedtitle + "[/COLOR]"))
return list(reversed(itemlist))
def findvideos(item):
logger.info("[BleachPortal.py]==> findvideos")
itemlist = []
if "bleach//" in item.url:
item.url = re.sub(r'\w+//', "", item.url)
data = httptools.downloadpage(item.url).data
if "bleach" in item.extra:
video = scrapertools.find_single_match(data, 'file: "(.*?)",')
else:
video = scrapertools.find_single_match(data, 'file=(.*?)&').rsplit('/', 1)[-1]
itemlist.append(
Item(channel=item.channel,
action="play",
title="[[COLOR orange]Diretto[/COLOR]] [B]%s[/B]" % item.title,
url=item.url.replace(item.url.split("/")[-1], "/" + video),
thumbnail=item.thumbnail,
fulltitle=item.fulltitle))
return itemlist

View File

@@ -1,48 +0,0 @@
{
"id": "bloghorror",
"name": "BlogHorror",
"active": true,
"adult": false,
"language": [],
"thumbnail": "https://i.postimg.cc/gcgQhKTL/2018-10-10_20_34_57-_Peliculas_de_Terror_BLOGHORROR.png",
"banner": "",
"categories": [
"movie",
"vo",
"torrent"
],
"settings": [
{
"id": "include_in_global_search",
"type": "bool",
"label": "Incluir en busqueda global",
"default": false,
"enabled": false,
"visible": false
},
{
"id": "include_in_newest_peliculas",
"type": "bool",
"label": "Incluir en Novedades - Peliculas",
"default": true,
"enabled": true,
"visible": true
},
{
"id": "include_in_newest_torrent",
"type": "bool",
"label": "Incluir en Novedades - Torrent",
"default": true,
"enabled": true,
"visible": true
},
{
"id": "include_in_newest_terror",
"type": "bool",
"label": "Incluir en Novedades - terror",
"default": true,
"enabled": true,
"visible": true
}
]
}

View File

@@ -1,234 +0,0 @@
# -*- coding: utf-8 -*-
# -*- Channel BlogHorror -*-
# -*- Created for Alfa-addon -*-
# -*- By the Alfa Develop Group -*-
import os
import re
from channels import autoplay
from channels import filtertools
from core import httptools
from core import scrapertools
from core import servertools
from core import tmdb
from core.item import Item
from platformcode import config, logger
from channelselector import get_thumb
host = 'http://bloghorror.com/'
fanart = 'http://bloghorror.com/wp-content/uploads/2015/04/bloghorror-2017-x.jpg'
def get_source(url):
logger.info()
data = httptools.downloadpage(url).data
data = re.sub(r'\n|\r|\t|&nbsp;|<br>|\s{2,}', "", data)
return data
def mainlist(item):
logger.info()
itemlist = []
itemlist.append(Item(channel=item.channel, fanart=fanart, title="Todas", action="list_all",
url=host+'/category/terror', thumbnail=get_thumb('all', auto=True)))
itemlist.append(Item(channel=item.channel, fanart=fanart, title="Asiaticas", action="list_all",
url=host+'/category/asiatico', thumbnail=get_thumb('asiaticas', auto=True)))
itemlist.append(Item(channel=item.channel, fanart=fanart, title = 'Buscar', action="search", url=host + '?s=', pages=3,
thumbnail=get_thumb('search', auto=True)))
return itemlist
def list_all(item):
logger.info()
itemlist = []
data = get_source(item.url)
patron = '<article id="post-\d+".*?data-background="([^"]+)".*?href="([^"]+)".*?<h3.*?internal">([^<]+)'
matches = re.compile(patron, re.DOTALL).findall(data)
for scrapedthumbnail, scrapedurl, scrapedtitle in matches:
url = scrapedurl
title = scrapertools.find_single_match(scrapedtitle, '(.*?)(?:|\(|\| )\d{4}').strip()
year = scrapertools.find_single_match(scrapedtitle, '(\d{4})')
thumbnail = scrapedthumbnail
new_item = Item(channel=item.channel, fanart=fanart, title=title, url=url, action='findvideos',
thumbnail=thumbnail, infoLabels={'year':year})
new_item.contentTitle=title
itemlist.append(new_item)
tmdb.set_infoLabels_itemlist(itemlist, seekTmdb=True)
# Paginacion
if itemlist != []:
next_page = scrapertools.find_single_match(data, 'page-numbers current.*?<a class="page-numbers" href="([^"]+)"')
if next_page != '':
itemlist.append(Item(channel=item.channel, fanart=fanart, action="list_all", title='Siguiente >>>', url=next_page))
else:
item.url=next_page
return itemlist
def section(item):
logger.info()
itemlist = []
data=get_source(host)
if item.title == 'Generos':
data = scrapertools.find_single_match(data, 'tabindex="0">Generos<.*?</ul>')
elif 'Años' in item.title:
data = scrapertools.find_single_match(data, 'tabindex="0">Año<.*?</ul>')
patron = 'href="([^"]+)">([^<]+)</a>'
matches = re.compile(patron, re.DOTALL).findall(data)
for url, title in matches:
itemlist.append(Item(channel=item.channel, fanart=fanart, title=title, url=url, action='list_all', pages=3))
return itemlist
def findvideos(item):
logger.info()
itemlist = []
full_data = get_source(item.url)
data = scrapertools.find_single_match(full_data, '>FICHA TECNICA:<.*?</ul>')
#patron = '(?:bold|strong>|<br/>|<em>)([^<]+)(?:</em>|<br/>).*?="(magnet[^"]+)"'
patron = '(?:<em>|<br/><em>|/> )(DVD|720|1080)(?:</em>|<br/>|</span>).*?="(magnet[^"]+)"'
matches = re.compile(patron, re.DOTALL).findall(data)
if len(matches) == 0:
patron = '<a href="(magnet[^"]+)"'
matches = re.compile(patron, re.DOTALL).findall(full_data)
patron_sub = 'href="(http://www.subdivx.com/bajar.php[^"]+)"'
sub_url = scrapertools.find_single_match(full_data, patron_sub)
sub_num = scrapertools.find_single_match(sub_url, 'u=(\d+)')
if sub_url == '':
sub = ''
lang = 'VO'
else:
try:
sub = get_sub_from_subdivx(sub_url, sub_num)
except:
sub = ''
lang = 'VOSE'
try:
for quality, scrapedurl in matches:
if quality.strip() not in ['DVD', '720', '1080']:
quality = 'DVD'
url = scrapedurl
if not config.get_setting('unify'):
title = ' [Torrent] [%s] [%s]' % (quality, lang)
else:
title = 'Torrent'
itemlist.append(Item(channel=item.channel, fanart=fanart, title=title, url=url, action='play',
server='torrent', quality=quality, language=lang, infoLabels=item.infoLabels,
subtitle=sub))
except:
for scrapedurl in matches:
quality = 'DVD'
url = scrapedurl
if not config.get_setting('unify'):
title = ' [Torrent] [%s] [%s]' % (quality, lang)
else:
title = 'Torrent'
itemlist.append(Item(channel=item.channel, fanart=fanart, title=title, url=url, action='play',
server='torrent', quality=quality, language=lang, infoLabels=item.infoLabels,
subtitle=sub))
if config.get_videolibrary_support() and len(itemlist) > 0 and item.extra != 'findvideos':
itemlist.append(Item(channel=item.channel,
title='[COLOR yellow]Añadir esta pelicula a la videoteca[/COLOR]',
url=item.url,
action="add_pelicula_to_library",
extra="findvideos",
contentTitle=item.contentTitle
))
return itemlist
def search(item, texto):
logger.info()
itemlist = []
texto = texto.replace(" ", "+")
item.url = item.url + texto
if texto != '':
try:
return list_all(item)
except:
itemlist.append(item.clone(url='', title='No hay elementos...', action=''))
return itemlist
def newest(categoria):
logger.info()
itemlist = []
item = Item()
try:
if categoria in ['peliculas', 'terror', 'torrent']:
item.url = host
itemlist = list_all(item)
if itemlist[-1].title == 'Siguiente >>>':
itemlist.pop()
except:
import sys
for line in sys.exc_info():
logger.error("{0}".format(line))
return []
return itemlist
def get_sub_from_subdivx(sub_url, sub_num):
logger.info()
import xbmc
from time import sleep
import urlparse
sub_dir = os.path.join(config.get_data_path(), 'temp_subs')
if os.path.exists(sub_dir):
for sub_file in os.listdir(sub_dir):
old_sub = os.path.join(sub_dir, sub_file)
os.remove(old_sub)
sub_data = httptools.downloadpage(sub_url, follow_redirects=False)
if 'x-frame-options' not in sub_data.headers:
sub_url = 'http://subdivx.com/sub%s/%s' % (sub_num, sub_data.headers['location'])
sub_url = sub_url.replace('http:///', '')
sub_data = httptools.downloadpage(sub_url).data
fichero_rar = os.path.join(config.get_data_path(), "subtitle.rar")
outfile = open(fichero_rar, 'wb')
outfile.write(sub_data)
outfile.close()
xbmc.executebuiltin("XBMC.Extract(%s, %s/temp_subs)" % (fichero_rar, config.get_data_path()))
sleep(1)
if len(os.listdir(sub_dir)) > 0:
sub = os.path.join(sub_dir, os.listdir(sub_dir)[0])
else:
sub = ''
else:
logger.info('sub no valido')
sub = ''
return sub

View File

@@ -1,15 +0,0 @@
{
"id": "bravoporn",
"name": "bravoporn",
"active": true,
"adult": true,
"language": ["*"],
"thumbnail": "http://www.bravoporn.com/v/images/logo.png",
"banner": "",
"categories": [
"adult"
],
"settings": [
]
}

View File

@@ -1,89 +0,0 @@
# -*- coding: utf-8 -*-
#------------------------------------------------------------
import urlparse,urllib2,urllib,re
import os, sys
from platformcode import config, logger
from core import scrapertools
from core.item import Item
from core import servertools
from core import httptools
host = 'http://www.bravoporn.com'
def mainlist(item):
logger.info()
itemlist = []
itemlist.append( Item(channel=item.channel, title="Nuevas" , action="lista", url=host +"/latest-updates/"))
itemlist.append( Item(channel=item.channel, title="Popular" , action="lista", url=host + "/most-popular/"))
itemlist.append( Item(channel=item.channel, title="Categorias" , action="categorias", url=host + "/c/"))
itemlist.append( Item(channel=item.channel, title="Buscar", action="search"))
return itemlist
def search(item, texto):
logger.info()
texto = texto.replace(" ", "+")
item.url = host + "/s/?q=%s" % texto
try:
return lista(item)
except:
import sys
for line in sys.exc_info():
logger.error("%s" % line)
return []
def categorias(item):
logger.info()
itemlist = []
data = httptools.downloadpage(item.url).data
data = re.sub(r"\n|\r|\t|&nbsp;|<br>", "", data)
patron = '<a href="([^"]+)" class="th">.*?'
patron += '<img src="([^"]+)".*?'
patron += '<span>([^"]+)</span>\s*(\d+) movies.*?</strong>'
matches = re.compile(patron,re.DOTALL).findall(data)
for scrapedurl,scrapedthumbnail,scrapedtitle,cantidad in matches:
scrapedplot = ""
scrapedtitle = scrapedtitle + " (" + cantidad + ")"
scrapedthumbnail = "http:" + scrapedthumbnail
scrapedurl = urlparse.urljoin(item.url,scrapedurl) + "/latest/"
itemlist.append( Item(channel=item.channel, action="lista", title=scrapedtitle, url=scrapedurl,
fanart=scrapedthumbnail, thumbnail=scrapedthumbnail, plot=scrapedplot) )
return itemlist
def lista(item):
logger.info()
itemlist = []
data = httptools.downloadpage(item.url).data
data = re.sub(r"\n|\r|\t|&nbsp;|<br>", "", data)
patron = '<div class=".*?video_block"><a href="([^"]+)".*?'
patron += '<img src="([^"]+)".*?alt="([^"]+)".*?'
patron += '<span class="time">([^"]+)</span>'
matches = re.compile(patron,re.DOTALL).findall(data)
for scrapedurl,scrapedthumbnail,scrapedtitle,duracion in matches:
url = urlparse.urljoin(item.url,scrapedurl)
title = "[COLOR yellow]" + duracion + "[/COLOR] " + scrapedtitle
thumbnail = "https:" + scrapedthumbnail
plot = ""
itemlist.append( Item(channel=item.channel, action="play", title=title, url=url, thumbnail=thumbnail,
fanart=thumbnail, plot=plot, contentTitle = scrapedtitle))
next_page = scrapertools.find_single_match(data,'<a href="([^"]+)" class="next" title="Next">Next</a>')
if next_page!="":
next_page = urlparse.urljoin(item.url,next_page)
itemlist.append(item.clone(action="lista", title="Página Siguiente >>", text_color="blue", url=next_page) )
return itemlist
def play(item):
logger.info()
itemlist = []
data = httptools.downloadpage(item.url).data
patron = '<source src="([^"]+)" type=\'video/mp4\' title="HQ" />'
matches = scrapertools.find_multiple_matches(data, patron)
for scrapedurl in matches:
itemlist.append(Item(channel=item.channel, action="play", title=item.title, url=scrapedurl))
return itemlist

View File

@@ -1,15 +0,0 @@
{
"id": "camwhoresbay",
"name": "camwhoresbay",
"active": true,
"adult": true,
"language": ["*"],
"thumbnail": "https://www.camwhoresbay.com/images/porntrex.ico",
"banner": "",
"categories": [
"adult"
],
"settings": [
]
}

View File

@@ -1,114 +0,0 @@
# -*- coding: utf-8 -*-
#------------------------------------------------------------
import urlparse,urllib2,urllib,re
import os, sys
from platformcode import config, logger
from core import scrapertools
from core.item import Item
from core import servertools
from core import httptools
host = 'https://www.camwhoresbay.com'
def mainlist(item):
logger.info()
itemlist = []
itemlist.append( Item(channel=item.channel, title="Nuevos" , action="lista", url=host + "/latest-updates/"))
itemlist.append( Item(channel=item.channel, title="Mejor valorados" , action="lista", url=host + "/top-rated/"))
itemlist.append( Item(channel=item.channel, title="Mas vistos" , action="lista", url=host + "/most-popular/"))
itemlist.append( Item(channel=item.channel, title="Categorias" , action="categorias", url=host + "/categories/"))
itemlist.append( Item(channel=item.channel, title="Buscar", action="search"))
return itemlist
def search(item, texto):
logger.info()
item.url = "%s/search/%s/" % (host, texto.replace("+", "-"))
item.extra = texto
try:
return lista(item)
# Se captura la excepción, para no interrumpir al buscador global si un canal falla
except:
import sys
for line in sys.exc_info():
logger.error("%s" % line)
return []
def categorias(item):
logger.info()
itemlist = []
data = httptools.downloadpage(item.url).data
patron = '<a class="item" href="([^"]+)" title="([^"]+)">.*?'
patron += '<img class="thumb" src="([^"]+)".*?'
patron += '<div class="videos">([^"]+)</div>'
matches = re.compile(patron,re.DOTALL).findall(data)
scrapertools.printMatches(matches)
for scrapedurl,scrapedtitle,scrapedthumbnail,cantidad in matches:
scrapedtitle = scrapedtitle + " (" + cantidad + ")"
scrapedplot = ""
itemlist.append( Item(channel=item.channel, action="lista", title=scrapedtitle, url=scrapedurl,
fanart=scrapedthumbnail, thumbnail=scrapedthumbnail, plot=scrapedplot) )
return sorted(itemlist, key=lambda i: i.title)
def lista(item):
logger.info()
itemlist = []
data = httptools.downloadpage(item.url).data
patron = '<div class="video-item ">.*?'
patron += '<a href="([^"]+)" title="([^"]+)" class="thumb">.*?'
patron += 'data-original="([^"]+)".*?'
patron += '<i class="fa fa-clock-o"></i>(.*?)</div>'
matches = re.compile(patron,re.DOTALL).findall(data)
for scrapedurl,scrapedtitle,scrapedthumbnail,scrapedtime in matches:
url = urlparse.urljoin(item.url,scrapedurl)
title = "[COLOR yellow]" + scrapedtime + "[/COLOR] " + scrapedtitle
thumbnail = scrapedthumbnail
plot = ""
itemlist.append( Item(channel=item.channel, action="play", title=title, url=url, thumbnail=thumbnail, plot=plot,
contentTitle = scrapedtitle, fanart=thumbnail))
if item.extra:
next_page = scrapertools.find_single_match(data, '<li class="next">.*?from_videos\+from_albums:(\d+)')
if next_page:
if "from_videos=" in item.url:
next_page = re.sub(r'&from_videos=(\d+)', '&from_videos=%s' % next_page, item.url)
else:
next_page = "%s?mode=async&function=get_block&block_id=list_videos_videos_list_search_result" \
"&q=%s&category_ids=&sort_by=post_date&from_videos=%s" % (item.url, item.extra, next_page)
itemlist.append(item.clone(action="lista", title="Página Siguiente >>", text_color="blue", url=next_page))
else:
next_page = scrapertools.find_single_match(data, '<li class="next"><a href="([^"]+)"')
if next_page and not next_page.startswith("#"):
next_page = urlparse.urljoin(item.url,next_page)
itemlist.append(item.clone(action="lista", title="Página Siguiente >>", text_color="blue", url=next_page) )
else:
next_page = scrapertools.find_single_match(data, '<li class="next">.*?from:(\d+)')
if next_page:
if "from" in item.url:
next_page = re.sub(r'&from=(\d+)', '&from=%s' % next_page, item.url)
else:
next_page = "%s?mode=async&function=get_block&block_id=list_videos_common_videos_list&sort_by=post_date&from=%s" % (
item.url, next_page)
itemlist.append(item.clone(action="lista", title="Página Siguiente >>", text_color="blue", url=next_page))
return itemlist
def play(item):
logger.info()
itemlist = []
data = httptools.downloadpage(item.url).data
scrapedurl = scrapertools.find_single_match(data, 'video_alt_url3: \'([^\']+)\'')
if scrapedurl == "" :
scrapedurl = scrapertools.find_single_match(data, 'video_alt_url2: \'([^\']+)\'')
if scrapedurl == "" :
scrapedurl = scrapertools.find_single_match(data, 'video_alt_url: \'([^\']+)\'')
if scrapedurl == "" :
scrapedurl = scrapertools.find_single_match(data, 'video_url: \'([^\']+)\'')
itemlist.append(Item(channel=item.channel, action="play", title=scrapedurl, fulltitle=item.title, url=scrapedurl,
thumbnail=item.thumbnail, plot=item.plot, show=item.title, server="directo"))
return itemlist

Some files were not shown because too many files have changed in this diff Show More