Merge pull request #27 from alfa-jor/develop

Created branch develop
This commit is contained in:
Alfa
2017-08-13 11:21:18 +02:00
committed by GitHub
395 changed files with 10246 additions and 1849 deletions

106
mediaserver/HTTPServer.py Normal file
View File

@@ -0,0 +1,106 @@
# -*- coding: utf-8 -*-
import random
import re
import threading
import time
import traceback
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from platformcode import config, logger
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(BaseHTTPRequestHandler):
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 do_GET(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=\"Introduce el nombre de usuario y clave para acceder a alfa\"')
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 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 start(fnc_info):
server.fnc_info = fnc_info
threading.Thread(target=server.serve_forever).start()
def stop():
server.socket.close()
server.shutdown()

674
mediaserver/LICENSE Normal file
View File

@@ -0,0 +1,674 @@
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

89
mediaserver/WebSocket.py Normal file
View File

@@ -0,0 +1,89 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# HTTPServer
# ------------------------------------------------------------
import os
import random
import traceback
from threading import Thread
import WebSocketServer
from core import jsontools as json
from platformcode import config, platformtools, logger
class HandleWebSocket(WebSocketServer.WebSocket):
def handleMessage(self):
try:
if self.data:
json_message = json.load(str(self.data))
if "request" in json_message:
t = 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 handleConnected(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())
self.close()
def handleClose(self):
self.controller.__del__()
del self.controller
self.server.fnc_info()
port = config.get_setting("websocket.port")
server = WebSocketServer.SimpleWebSocketServer("", int(port), HandleWebSocket)
def start(fnc_info):
server.fnc_info = fnc_info
Thread(target=server.serveforever).start()
def stop():
server.close()
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.")

1
mediaserver/__init__.py Normal file
View File

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

103
mediaserver/alfa.py Normal file
View File

@@ -0,0 +1,103 @@
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# Launcher
# ------------------------------------------------------------
import os
import sys
import threading
import time
from functools import wraps
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 HTTPServer
import WebSocket
http_port = config.get_setting("server.port")
websocket_port = config.get_setting("websocket.port")
myip = config.get_local_ip()
def ThreadNameWrap(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__ = ThreadNameWrap(threading.Thread.__init__)
if sys.version_info < (2, 7, 11):
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
def MostrarInfo():
os.system('cls' if os.name == 'nt' else 'clear')
print ("--------------------------------------------------------------------")
print ("Alfa Iniciado")
print ("La URL para acceder es http://%s:%s" % (myip, http_port))
print ("WebSocket Server iniciado en ws://%s:%s" % (myip, websocket_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 ("--------------------------------------------------------------------")
conexiones = []
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:
HTTPServer.start(MostrarInfo)
WebSocket.start(MostrarInfo)
# Da por levantado el servicio
logger.info("--------------------------------------------------------------------")
logger.info("Alfa Iniciado")
logger.info("La URL para acceder es http://%s:%s" % (myip, http_port))
logger.info("WebSocket Server iniciado en ws://%s:%s" % (myip, websocket_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("--------------------------------------------------------------------")
MostrarInfo()
start = True
while start:
time.sleep(1)
except KeyboardInterrupt:
print 'Deteniendo el servidor HTTP...'
HTTPServer.stop()
print 'Deteniendo el servidor WebSocket...'
WebSocket.stop()
print 'Alfa Detenido'
start = False
# Inicia el programa
start()

View File

@@ -0,0 +1,648 @@
'''
The MIT License (MIT)
Copyright (c) 2013 Dave P.
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.
'''
import SocketServer
import hashlib
import base64
import socket
import struct
import ssl
import time
import sys
import errno
import logging
from BaseHTTPServer import BaseHTTPRequestHandler
from StringIO import StringIO
from select import select
class HTTPRequest(BaseHTTPRequestHandler):
def __init__(self, request_text):
self.rfile = StringIO(request_text)
self.raw_requestline = self.rfile.readline()
self.error_code = self.error_message = None
self.parse_request()
class WebSocket(object):
handshakeStr = (
"HTTP/1.1 101 Switching Protocols\r\n"
"Upgrade: WebSocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Accept: %(acceptstr)s\r\n\r\n"
)
hixiehandshakedStr = (
"HTTP/1.1 101 WebSocket Protocol Handshake\r\n"
"Upgrade: WebSocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Origin: %(origin)s\r\n"
"Sec-WebSocket-Location: %(type)s://%(host)s%(location)s\r\n\r\n"
)
hixie75handshakedStr = (
"HTTP/1.1 101 Web Socket Protocol Handshake\r\n"
"Upgrade: WebSocket\r\n"
"Connection: Upgrade\r\n"
"WebSocket-Origin: %(origin)s\r\n"
"WebSocket-Location: %(type)s://%(host)s%(location)s\r\n\r\n"
)
GUIDStr = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
STREAM = 0x0
TEXT = 0x1
BINARY = 0x2
CLOSE = 0x8
PING = 0x9
PONG = 0xA
HEADERB1 = 1
HEADERB2 = 3
LENGTHSHORT = 4
LENGTHLONG = 5
MASK = 6
PAYLOAD = 7
def __init__(self, server, sock, address):
self.server = server
self.client = sock
self.address = address
self.handshaked = False
self.headerbuffer = ''
self.readdraftkey = False
self.draftkey = ''
self.headertoread = 2048
self.hixie76 = False
self.fin = 0
self.data = None
self.opcode = 0
self.hasmask = 0
self.maskarray = None
self.length = 0
self.lengtharray = None
self.index = 0
self.request = None
self.usingssl = False
self.state = self.HEADERB1
# restrict the size of header and payload for security reasons
self.maxheader = 65536
self.maxpayload = 4194304
def close(self):
self.client.close()
self.state = self.HEADERB1
self.hasmask = False
self.handshaked = False
self.readdraftkey = False
self.hixie76 = False
self.headertoread = 2048
self.headerbuffer = ''
self.data = ''
def handleMessage(self):
pass
def handleConnected(self):
pass
def handleClose(self):
pass
def handlePacket(self):
# close
if self.opcode == self.CLOSE:
self.sendClose()
raise Exception("received client close")
# ping
elif self.opcode == self.PING:
pass
# pong
elif self.opcode == self.PONG:
pass
# data
elif self.opcode == self.STREAM or self.opcode == self.TEXT or self.opcode == self.BINARY:
self.handleMessage()
def handleData(self):
# do the HTTP header and handshake
if self.handshaked is False:
data = self.client.recv(self.headertoread)
if data:
# accumulate
self.headerbuffer += data
if len(self.headerbuffer) >= self.maxheader:
raise Exception('header exceeded allowable size')
# we need to read the entire 8 bytes of after the HTTP header, ensure we do
if self.readdraftkey is True:
self.draftkey += self.headerbuffer
read = self.headertoread - len(self.headerbuffer)
if read != 0:
self.headertoread = read
else:
# complete hixie76 handshake
self.handshake_hixie76()
# indicates end of HTTP header
elif '\r\n\r\n' in self.headerbuffer:
self.request = HTTPRequest(self.headerbuffer)
# hixie handshake
if self.request.headers.has_key('Sec-WebSocket-Key1'.lower()) and self.request.headers.has_key('Sec-WebSocket-Key2'.lower()):
# check if we have the key in our buffer
index = self.headerbuffer.find('\r\n\r\n') + 4
# determine how much of the 8 byte key we have
read = len(self.headerbuffer) - index
# do we have all the 8 bytes we need?
if read < 8:
self.headertoread = 8 - read
self.readdraftkey = True
if read > 0:
self.draftkey += self.headerbuffer[index:index+read]
else:
# get the key
self.draftkey += self.headerbuffer[index:index+8]
# complete hixie handshake
self.handshake_hixie76()
# handshake rfc 6455
elif self.request.headers.has_key('Sec-WebSocket-Key'.lower()):
key = self.request.headers['Sec-WebSocket-Key'.lower()]
hStr = self.handshakeStr % { 'acceptstr' : base64.b64encode(hashlib.sha1(key + self.GUIDStr).digest()) }
self.sendBuffer(hStr)
self.handshaked = True
self.headerbuffer = ''
try:
self.handleConnected()
except:
pass
# hixie 75
else:
self.handshake_hixie75()
#raise Exception('Sec-WebSocket-Key does not exist')
# remote connection has been closed
else:
raise Exception("remote socket closed")
# else do normal data
else:
data = self.client.recv(2048)
if data:
for val in data:
if self.hixie76 is False:
self.parseMessage(ord(val))
else:
self.parseMessage_hixie76(ord(val))
else:
raise Exception("remote socket closed")
def handshake_hixie75(self):
typestr = 'ws'
if self.usingssl is True:
typestr = 'wss'
response = self.hixie75handshakedStr % { 'type' : typestr, 'origin' : self.request.headers['Origin'.lower()], 'host' : self.request.headers['Host'.lower()], 'location' : self.request.path }
self.sendBuffer(response)
self.handshaked = True
self.headerbuffer = ''
self.hixie76 = True
try:
self.handleConnected()
except:
pass
def handshake_hixie76(self):
k1 = self.request.headers['Sec-WebSocket-Key1'.lower()]
k2 = self.request.headers['Sec-WebSocket-Key2'.lower()]
spaces1 = k1.count(" ")
spaces2 = k2.count(" ")
num1 = int("".join([c for c in k1 if c.isdigit()])) / spaces1
num2 = int("".join([c for c in k2 if c.isdigit()])) / spaces2
key = ''
key += struct.pack('>I', num1)
key += struct.pack('>I', num2)
key += self.draftkey
typestr = 'ws'
if self.usingssl is True:
typestr = 'wss'
response = self.hixiehandshakedStr % { 'type' : typestr, 'origin' : self.request.headers['Origin'.lower()], 'host' : self.request.headers['Host'.lower()], 'location' : self.request.path }
self.sendBuffer(response)
self.sendBuffer(hashlib.md5(key).digest())
self.handshaked = True
self.hixie76 = True
self.headerbuffer = ''
try:
self.handleConnected()
except:
pass
def sendClose(self):
msg = bytearray()
if self.hixie76 is False:
msg.append(0x88)
msg.append(0x00)
self.sendBuffer(msg)
else:
pass
def sendBuffer(self, buff):
size = len(buff)
tosend = size
index = 0
while tosend > 0:
try:
# i should be able to send a bytearray
sent = self.client.send(str(buff[index:size]))
if sent == 0:
raise RuntimeError("socket connection broken")
index += sent
tosend -= sent
except socket.error as e:
# if we have full buffers then wait for them to drain and try again
if e.errno == errno.EAGAIN:
time.sleep(0.001)
else:
raise e
#if s is a string then websocket TEXT is sent else BINARY
def sendMessage(self, s):
if self.hixie76 is False:
header = bytearray()
isString = isinstance(s, str)
if isString is True:
header.append(0x81)
else:
header.append(0x82)
b2 = 0
length = len(s)
if length <= 125:
b2 |= length
header.append(b2)
elif length >= 126 and length <= 65535:
b2 |= 126
header.append(b2)
header.extend(struct.pack("!H", length))
else:
b2 |= 127
header.append(b2)
header.extend(struct.pack("!Q", length))
if length > 0:
self.sendBuffer(header + s)
else:
self.sendBuffer(header)
header = None
else:
msg = bytearray()
msg.append(0)
if len(s) > 0:
msg.extend(str(s).encode("UTF8"))
msg.append(0xFF)
self.sendBuffer(msg)
msg = None
def parseMessage_hixie76(self, byte):
if self.state == self.HEADERB1:
if byte == 0:
self.state = self.PAYLOAD
self.data = bytearray()
elif self.state == self.PAYLOAD:
if byte == 0xFF:
self.opcode = 1
self.length = len(self.data)
try:
self.handlePacket()
finally:
self.data = None
self.state = self.HEADERB1
else :
self.data.append(byte)
# if length exceeds allowable size then we except and remove the connection
if len(self.data) >= self.maxpayload:
raise Exception('payload exceeded allowable size')
def parseMessage(self, byte):
# read in the header
if self.state == self.HEADERB1:
# fin
self.fin = (byte & 0x80)
# get opcode
self.opcode = (byte & 0x0F)
self.state = self.HEADERB2
elif self.state == self.HEADERB2:
mask = byte & 0x80
length = byte & 0x7F
if mask == 128:
self.hasmask = True
else:
self.hasmask = False
if length <= 125:
self.length = length
# if we have a mask we must read it
if self.hasmask is True:
self.maskarray = bytearray()
self.state = self.MASK
else:
# if there is no mask and no payload we are done
if self.length <= 0:
try:
self.handlePacket()
finally:
self.state = self.HEADERB1
self.data = None
# we have no mask and some payload
else:
self.index = 0
self.data = bytearray()
self.state = self.PAYLOAD
elif length == 126:
self.lengtharray = bytearray()
self.state = self.LENGTHSHORT
elif length == 127:
self.lengtharray = bytearray()
self.state = self.LENGTHLONG
elif self.state == self.LENGTHSHORT:
self.lengtharray.append(byte)
if len(self.lengtharray) > 2:
raise Exception('short length exceeded allowable size')
if len(self.lengtharray) == 2:
self.length = struct.unpack_from('!H', str(self.lengtharray))[0]
if self.hasmask is True:
self.maskarray = bytearray()
self.state = self.MASK
else:
# if there is no mask and no payload we are done
if self.length <= 0:
try:
self.handlePacket()
finally:
self.state = self.HEADERB1
self.data = None
# we have no mask and some payload
else:
self.index = 0
self.data = bytearray()
self.state = self.PAYLOAD
elif self.state == self.LENGTHLONG:
self.lengtharray.append(byte)
if len(self.lengtharray) > 8:
raise Exception('long length exceeded allowable size')
if len(self.lengtharray) == 8:
self.length = struct.unpack_from('!Q', str(self.lengtharray))[0]
if self.hasmask is True:
self.maskarray = bytearray()
self.state = self.MASK
else:
# if there is no mask and no payload we are done
if self.length <= 0:
try:
self.handlePacket()
finally:
self.state = self.HEADERB1
self.data = None
# we have no mask and some payload
else:
self.index = 0
self.data = bytearray()
self.state = self.PAYLOAD
# MASK STATE
elif self.state == self.MASK:
self.maskarray.append(byte)
if len(self.maskarray) > 4:
raise Exception('mask exceeded allowable size')
if len(self.maskarray) == 4:
# if there is no mask and no payload we are done
if self.length <= 0:
try:
self.handlePacket()
finally:
self.state = self.HEADERB1
self.data = None
# we have no mask and some payload
else:
self.index = 0
self.data = bytearray()
self.state = self.PAYLOAD
# PAYLOAD STATE
elif self.state == self.PAYLOAD:
if self.hasmask is True:
self.data.append( byte ^ self.maskarray[self.index % 4] )
else:
self.data.append( byte )
# if length exceeds allowable size then we except and remove the connection
if len(self.data) >= self.maxpayload:
raise Exception('payload exceeded allowable size')
# check if we have processed length bytes; if so we are done
if (self.index+1) == self.length:
try:
self.handlePacket()
finally:
self.state = self.HEADERB1
self.data = None
else:
self.index += 1
class SimpleWebSocketServer(object):
def __init__(self, host, port, websocketclass):
self.websocketclass = websocketclass
self.serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.serversocket.bind((host, port))
self.serversocket.listen(5)
self.connections = {}
self.listeners = [self.serversocket]
def decorateSocket(self, sock):
return sock
def constructWebSocket(self, sock, address):
return self.websocketclass(self, sock, address)
def close(self):
self.serversocket.close()
for conn in self.connections.itervalues():
try:
conn.handleClose()
except:
pass
conn.close()
def serveforever(self):
while True:
try:
rList, wList, xList = select(self.listeners, [], self.listeners, 1)
for ready in rList:
if ready == self.serversocket:
try:
sock, address = self.serversocket.accept()
newsock = self.decorateSocket(sock)
newsock.setblocking(0)
fileno = newsock.fileno()
self.listeners.append(fileno)
self.connections[fileno] = self.constructWebSocket(newsock, address)
except Exception as n:
#logging.debug(str(address) + ' ' + str(n))
if sock is not None:
sock.close()
else:
client = self.connections[ready]
try:
client.handleData()
except Exception as n:
#logging.debug(str(client.address) + ' ' + str(n))
try:
client.handleClose()
except:
pass
client.close()
del self.connections[ready]
self.listeners.remove(ready)
for failed in xList:
if failed == self.serversocket:
self.close()
raise Exception("server socket failed")
else:
client = self.connections[failed]
try:
client.handleClose()
except:
pass
client.close()
del self.connections[failed]
self.listeners.remove(failed)
except:
break
class SimpleSSLWebSocketServer(SimpleWebSocketServer):
def __init__(self, host, port, websocketclass, certfile, keyfile, version = ssl.PROTOCOL_TLSv1):
SimpleWebSocketServer.__init__(self, host, port, websocketclass)
self.cerfile = certfile
self.keyfile = keyfile
self.version = version
def close(self):
super(SimpleSSLWebSocketServer, self).close()
def decorateSocket(self, sock):
sslsock = ssl.wrap_socket(sock,
server_side=True,
certfile=self.cerfile,
keyfile=self.keyfile,
ssl_version=self.version)
return sslsock
def constructWebSocket(self, sock, address):
ws = self.websocketclass(self, sock, address)
ws.usingssl = True
return ws
def serveforever(self):
super(SimpleSSLWebSocketServer, self).serveforever()

View File

@@ -0,0 +1,12 @@
# -*- 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

@@ -0,0 +1,393 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# Parámetros de configuración (mediaserver)
# ------------------------------------------------------------
import os
import re
import threading
PLATFORM_NAME = "mediaserver"
PLUGIN_NAME = "alfa"
settings_dic = {}
settings_types = {}
adult_setting = {}
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():
Opciones = []
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"):
Opciones.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(Opciones)
# 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")
# Fijar adult_pin
adult_pin = ""
if get_setting("adult_request_password") == True:
adult_pin = get_setting("adult_password")
set_setting("adult_pin", adult_pin)
# Solo esta sesion:
id = threading.current_thread().name
if get_setting("adult_mode") == 2:
adult_setting[id] = True
set_setting("adult_mode", "0")
else:
adult_setting = {}
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=""):
"""
Retorna el valor de configuracion del parametro solicitado.
Devuelve el valor del parametro 'name' en la configuracion global o en la configuracion propia del canal 'channel'.
Si se especifica el nombre del canal busca en la ruta \addon_data\plugin.video.alfa\settings_channels el
archivo channel_data.json y lee el valor del parametro 'name'. 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 retornar el valor solicitado.
Si el parametro 'name' no existe en channel_data.json lo busca en la configuracion global y si ahi tampoco existe
devuelve un str vacio.
Parametros:
name -- nombre del parametro
channel [opcional] -- nombre del canal
Retorna:
value -- El valor del parametro 'name'
"""
# 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)
# 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)
# 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, "")
if name == "adult_mode":
global adult_setting
id = threading.current_thread().name
if adult_setting.get(id) == True:
value = "2"
# hack para devolver el tipo correspondiente
global settings_types
if settings_types.get(name) in ['enum', 'number']:
value = int(value)
elif settings_types.get(name) == 'bool':
value = value == 'true'
elif not settings_types.has_key(name):
try:
t = eval(value)
value = t[0](t[1])
except:
value = None
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
global settings_types
if settings_types.get(name) == 'bool':
if value:
new_value = "true"
else:
new_value = "false"
elif settings_types.get(name):
new_value = str(value)
else:
if isinstance(value, basestring):
new_value = "(%s, %s)" % (type(value).__name__, repr(value))
else:
new_value = "(%s, %s)" % (type(value).__name__, value)
settings_dic[name] = new_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('<string id="%s">([^<]+)<' % code, translations)
if len(cadenas) > 0:
dev = cadenas[0]
else:
dev = "%d" % code
try:
dev = dev.encode("utf-8")
except:
pass
return dev
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)
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
global settings_types
defaults = {}
from xml.etree import ElementTree
encontrado = False
# 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")
settings_types[target.get("id")] = target.get("type")
for key in defaults:
if not key 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())
# Literales
TRANSLATION_FILE_PATH = os.path.join(get_runtime_path(), "resources", "language", "Spanish", "strings.xml")
load_settings()

View File

@@ -0,0 +1,41 @@
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# Módulo para acciones en el cliente HTML
# ------------------------------------------------------------
import os
from inspect import isclass
from controller import Controller
from platformcode import logger
def load_controllers():
controllers = []
path = os.path.split(__file__)[0]
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

@@ -0,0 +1,129 @@
# -*- 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

@@ -0,0 +1,104 @@
# -*- 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()
respuesta = respuesta.replace("{$WSPORT}", str(config.get_setting("websocket.port")))
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

@@ -0,0 +1,788 @@
# -*- 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 import versiontools
from core.item import Item
from core.tmdb import Tmdb
from platformcode import launcher, logger
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:
self.client_ip = handler.client.getpeername()[0]
self.send_message({"action": "connect",
"data": {"version": "Alfa %s" % versiontools.get_current_plugin_version_tag(),
"date": versiontools.get_current_plugin_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")))
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
# Recorremos el itemlist
for item in itemlist:
if not item.thumbnail and item.action == "search": item.thumbnail = channelselector.get_thumb("search.png")
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")
if "http://media.xxxxx/" in item.thumbnail and not item.thumbnail.startswith(
"http://media.xxxxxxxx/thumb_"):
if parent_item.viewmode in ["banner", "channel"]:
item.thumbnail = channelselector.get_thumbnail_path("banner") + os.path.basename(item.thumbnail)
else:
item.thumbnail = channelselector.get_thumbnail_path() + os.path.basename(item.thumbnail)
# 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).replace(".py", "")
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 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

@@ -0,0 +1,188 @@
# -*- 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

@@ -0,0 +1,58 @@
# -*- 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

@@ -0,0 +1,199 @@
# -*- 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

@@ -0,0 +1,173 @@
# -*- 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

@@ -0,0 +1,79 @@
# -*- 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

@@ -0,0 +1,523 @@
# -*- 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:
PrintItems(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_pin") != "":
tecleado = platformtools.dialog_input("", "Contraseña para canales de adultos", True)
if tecleado is None or tecleado != config.get_setting("adult_pin"):
platformtools.render_items(None, item)
return
# Importa el canal para el item, todo item debe tener un canal, sino sale de la función
if item.channel: channelmodule = ImportarCanal(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 config.get_setting("check_for_plugin_updates"):
# logger.info("channelselector.mainlist Verificar actualizaciones activado")
#
# from core import updater
# try:
# version = updater.checkforupdates()
#
# if version:
# platformtools.dialog_ok("Versión " + version + " disponible",
# "Ya puedes descargar la nueva versión del plugin\ndesde el listado principal")
# itemlist.insert(0, Item(title="Actualizar Alfa a la versión " + version, version=version,
# channel="updater", action="update",
# thumbnail=os.path.join(config.get_runtime_path(), "resources", "images",
# "banner", "thumb_update.png")))
# except:
# platformtools.dialog_ok("No se puede conectar", "No ha sido posible comprobar",
# "si hay actualizaciones")
# logger.info("Fallo al verificar la actualización")
#
# else:
# logger.info("Verificar actualizaciones desactivado")
if item.action == "getchanneltypes":
itemlist = channelselector.getchanneltypes("banner_")
if item.action == "filterchannels":
itemlist = channelselector.filterchannels(item.channel_type, "banner_")
# 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
PrintItems(itemlist)
# Muestra los resultados en pantalla
platformtools.render_items(itemlist, item)
def ImportarCanal(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 PrintItems(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 = ImportarCanal(item)
videolibrarytools.add_tvshow(item, channel)
def download_all_episodes(item, first_episode="", preferred_server="vidspot", filter_language=""):
logger.info("show=" + item.show)
channel = ImportarCanal(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

@@ -0,0 +1,48 @@
# -*- 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))

View File

@@ -0,0 +1,107 @@
# -*- 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.

After

Width:  |  Height:  |  Size: 5.4 KiB

View File

@@ -0,0 +1,7 @@
<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

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

View File

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

View File

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

View File

@@ -0,0 +1,7 @@
<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

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

View File

@@ -0,0 +1,7 @@
<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

@@ -0,0 +1,10 @@
<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

@@ -0,0 +1,10 @@
<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

@@ -0,0 +1,10 @@
<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

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

View File

@@ -0,0 +1,10 @@
<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

@@ -0,0 +1,6 @@
<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

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

View File

@@ -0,0 +1,7 @@
<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

@@ -0,0 +1,5 @@
<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.

After

Width:  |  Height:  |  Size: 85 KiB

View File

@@ -0,0 +1,503 @@
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

@@ -0,0 +1,107 @@
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

@@ -0,0 +1,739 @@
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

@@ -0,0 +1,674 @@
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);
//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 = "";
};
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

@@ -0,0 +1,79 @@
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

@@ -0,0 +1,225 @@
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 = "http://media.tvalacarta.info/pelisalacarta/thumb_folder2.png";
}
else {
thumbnail.src = domain + "/proxy/" + encodeURIComponent(btoa(thumbnail.src));
}
if (thumbnail.parentNode == document.activeElement && document.activeElement.className != "item_menu"){
document.activeElement.onfocus();
};
};
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

@@ -0,0 +1,43 @@
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

@@ -0,0 +1,139 @@
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) {
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.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.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)
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)
};

View File

@@ -0,0 +1,15 @@
{
"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

@@ -0,0 +1,224 @@
<!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.hostname + ':{$WSPORT}'
</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="#">Saber más sobre Alfa</a> | <a href="#">Foro</a>
</div>
<div class="status" id="status">Desconectado</div>
</div>
</div>
</body>
</html>

View File

@@ -0,0 +1,51 @@
<?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 default="8081" id="websocket.port" label="Puerto WebSocket" 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="channel_language" type="labelenum" values="all|es|en|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:" 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 canal 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=""/>
<!--<setting type="sep"/>-->
<!--<setting label="Actualizaciones" type="lsep"/>-->
<!--<setting id="plugin_updates_available" type="number" label="Number of updates available" default="0" visible="false"/>-->
<!--<setting id="check_for_plugin_updates" type="bool" label="30001" default="true"/>-->
<!--<setting id="check_for_channel_updates" type="bool" label="30004" default="true"/>-->
</category>
<!-- Path downloads and subtitles -->
<category label="30501">
<!--setting id="subtitulo" type="bool" label="30021" default="false"/>
<setting id="subtitle_type" type="enum" lvalues="30432|30434|30433" label ="30431" enable ="eq(-1,true)" default="0"/>
<setting id="subtitlepath_folder" type="folder" source="" enable = "eq(-1,0)+eq(-2,true)" label="30435" default=""/>
<setting id="subtitlepath_file" type="file" source="" enable = "eq(-2,2)+eq(-3,true)" label="30436" default=""/>
<setting id="subtitlepath_keyboard" type="text" enable ="eq(-3,1)+eq(-4,true)" label="30437" default=""/>
<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="Nombre de carpetas" type="lsep"/>
<setting id="folder_tvshows" type="text" label="Series" default="SERIES"/>
<setting id="folder_movies" type="text" label="Peliculas" default="CINE"/>
</category>
</settings>

View File

@@ -1,26 +1,26 @@
# -*- coding: utf-8 -*-
from core import config
from core import httptools
from core import logger
from core import scrapertools
from core import servertools
from core.item import Item
from platformcode import config, logger
host = "http://allcalidad.com/"
def mainlist(item):
logger.info()
itemlist = []
itemlist.append(Item(channel = item.channel, title = "Novedades", action = "peliculas", url = host))
itemlist.append(Item(channel = item.channel, title = "Por género", action = "generos_years", url = host, extra = "Genero" ))
itemlist.append(Item(channel = item.channel, title = "Por año", action = "generos_years", url = host, extra = ">Año<"))
itemlist.append(Item(channel = item.channel, title = "Favoritas", action = "peliculas", url = host + "/favorites" ))
itemlist.append(Item(channel = item.channel, title = ""))
itemlist.append(Item(channel = item.channel, title = "Buscar", action = "search", url = host + "?s="))
itemlist.append(Item(channel=item.channel, title="Novedades", action="peliculas", url=host))
itemlist.append(Item(channel=item.channel, title="Por género", action="generos_years", url=host, extra="Genero"))
itemlist.append(Item(channel=item.channel, title="Por año", action="generos_years", url=host, extra=">Año<"))
itemlist.append(Item(channel=item.channel, title="Favoritas", action="peliculas", url=host + "/favorites"))
itemlist.append(Item(channel=item.channel, title=""))
itemlist.append(Item(channel=item.channel, title="Buscar", action="search", url=host + "?s="))
return itemlist
def newest(categoria):
logger.info()
itemlist = []
@@ -44,10 +44,10 @@ def newest(categoria):
def search(item, texto):
logger.info()
texto = texto.replace(" ","+")
texto = texto.replace(" ", "+")
item.url = item.url + texto
item.extra = "busca"
if texto!='':
if texto != '':
return peliculas(item)
else:
return []
@@ -57,17 +57,17 @@ def generos_years(item):
logger.info()
itemlist = []
data = httptools.downloadpage(item.url).data
patron = '(?s)%s(.*?)</ul></div>' %item.extra
patron = '(?s)%s(.*?)</ul></div>' % item.extra
bloque = scrapertools.find_single_match(data, patron)
patron = 'href="([^"]+)'
patron = 'href="([^"]+)'
patron += '">([^<]+)'
matches = scrapertools.find_multiple_matches(bloque, patron)
for url, titulo in matches:
itemlist.append(Item(channel = item.channel,
action = "peliculas",
title = titulo,
url = url
))
itemlist.append(Item(channel=item.channel,
action="peliculas",
title=titulo,
url=url
))
return itemlist
@@ -86,22 +86,22 @@ def peliculas(item):
year = scrapertools.find_single_match(varios, 'Año.*?kinopoisk">([^<]+)')
year = scrapertools.find_single_match(year, '[0-9]{4}')
mtitulo = titulo + " (" + idioma + ") (" + year + ")"
new_item = Item(channel = item.channel,
action = "findvideos",
title = mtitulo,
fulltitle = titulo,
thumbnail = thumbnail,
url = url,
contentTitle = titulo,
contentType="movie"
)
new_item = Item(channel=item.channel,
action="findvideos",
title=mtitulo,
fulltitle=titulo,
thumbnail=thumbnail,
url=url,
contentTitle=titulo,
contentType="movie"
)
if year:
new_item.infoLabels['year'] = int(year)
itemlist.append(new_item)
url_pagina = scrapertools.find_single_match(data, 'next" href="([^"]+)')
if url_pagina != "":
pagina = "Pagina: " + scrapertools.find_single_match(url_pagina, "page/([0-9]+)")
itemlist.append(Item(channel = item.channel, action = "peliculas", title = pagina, url = url_pagina))
itemlist.append(Item(channel=item.channel, action="peliculas", title=pagina, url=url_pagina))
return itemlist
@@ -120,24 +120,25 @@ def findvideos(item):
elif "vimeo" in url:
url += "|" + "http://www.allcalidad.com"
itemlist.append(
Item(channel = item.channel,
action = "play",
title = titulo,
fulltitle = item.fulltitle,
thumbnail = item.thumbnail,
server = "",
url = url
Item(channel=item.channel,
action="play",
title=titulo,
fulltitle=item.fulltitle,
thumbnail=item.thumbnail,
server=server,
url=url
))
itemlist = servertools.get_servers_itemlist(itemlist, lambda i: i.title % i.server.capitalize())
if itemlist:
itemlist.append(Item(channel = item.channel))
itemlist.append(Item(channel=item.channel))
itemlist.append(item.clone(channel="trailertools", title="Buscar Tráiler", action="buscartrailer", context="",
text_color="magenta"))
# Opción "Añadir esta película a la biblioteca de KODI"
if item.extra != "library":
if config.get_videolibrary_support():
itemlist.append(Item(channel=item.channel, title="Añadir a la videoteca", text_color="green",
filtro=True, action="add_pelicula_to_library", url=item.url, thumbnail = item.thumbnail,
filtro=True, action="add_pelicula_to_library", url=item.url,
thumbnail=item.thumbnail,
infoLabels={'title': item.fulltitle}, fulltitle=item.fulltitle,
extra="library"))
return itemlist

View File

@@ -2,12 +2,11 @@
import string
from core import config
from core import httptools
from core import logger
from core import scrapertools
from core import servertools
from core.item import Item
from platformcode import config, logger
__modo_grafico__ = config.get_setting('modo_grafico', "allpeliculas")
__perfil__ = int(config.get_setting('perfil', "allpeliculas"))
@@ -366,7 +365,7 @@ def episodios(item):
for item in itemlist:
if item.infoLabels["episodio_titulo"]:
item.title = "%dx%02d: %s" % (
item.contentSeason, item.contentEpisodeNumber, item.infoLabels["episodio_titulo"])
item.contentSeason, item.contentEpisodeNumber, item.infoLabels["episodio_titulo"])
else:
item.title = "%dx%02d: %s" % (item.contentSeason, item.contentEpisodeNumber, item.title)

View File

@@ -5,13 +5,12 @@ import re
import unicodedata
from threading import Thread
from core import config
from core import httptools
from core import logger
from core import scrapertools
from core import servertools
from core import tmdb
from core.item import Item
from platformcode import config, logger
__modo_grafico__ = config.get_setting('modo_grafico', "ver-pelis")
@@ -255,14 +254,14 @@ def get_art(item):
if id == None:
if item.contentType == "movie":
urlbing_imdb = "http://www.bing.com/search?q=%s+%s+tv+series+site:imdb.com" % (
item.fulltitle.replace(' ', '+'), year)
item.fulltitle.replace(' ', '+'), year)
data = browser(urlbing_imdb)
data = re.sub(r"\n|\r|\t|\s{2}|&nbsp;|http://ssl-proxy.my-addr.org/myaddrproxy.php/", "", data)
subdata_imdb = scrapertools.find_single_match(data,
'<li class="b_algo">(.*?)h="ID.*?<strong>.*?TV Series')
else:
urlbing_imdb = "http://www.bing.com/search?q=%s+%s+site:imdb.com" % (
item.fulltitle.replace(' ', '+'), year)
item.fulltitle.replace(' ', '+'), year)
data = browser(urlbing_imdb)
data = re.sub(r"\n|\r|\t|\s{2}|&nbsp;|http://ssl-proxy.my-addr.org/myaddrproxy.php/", "", data)
subdata_imdb = scrapertools.find_single_match(data, '<li class="b_algo">(.*?)h="ID.*?<strong>')
@@ -282,7 +281,7 @@ def get_art(item):
title = scrapertools.find_single_match(item.fulltitle, '\(.*?\)')
if item.contentType != "movie":
urlbing_imdb = "http://www.bing.com/search?q=%s+%s+tv+series+site:imdb.com" % (
title.replace(' ', '+'), year)
title.replace(' ', '+'), year)
data = browser(urlbing_imdb)
data = re.sub(r"\n|\r|\t|\s{2}|&nbsp;|http://ssl-proxy.my-addr.org/myaddrproxy.php/", "",
data)
@@ -290,7 +289,7 @@ def get_art(item):
'<li class="b_algo">(.*?)h="ID.*?<strong>.*?TV Series')
else:
urlbing_imdb = "http://www.bing.com/search?q=%s+%s+site:imdb.com" % (
title.replace(' ', '+'), year)
title.replace(' ', '+'), year)
data = browser(urlbing_imdb)
data = re.sub(r"\n|\r|\t|\s{2}|&nbsp;|http://ssl-proxy.my-addr.org/myaddrproxy.php/", "",
data)

View File

@@ -6,9 +6,9 @@ import urlparse
from channels import renumbertools
from core import httptools
from core import jsontools
from core import logger
from core import scrapertools
from core.item import Item
from platformcode import logger
HOST = "https://animeflv.net/"

View File

@@ -5,12 +5,11 @@ import urlparse
from os import path
from channels import renumbertools
from core import config
from core import filetools
from core import httptools
from core import logger
from core import scrapertools
from core.item import Item
from platformcode import config, logger
CHANNEL_HOST = "http://animeflv.me/"
CHANNEL_DEFAULT_HEADERS = [

View File

@@ -6,9 +6,9 @@ import urlparse
from channels import renumbertools
from core import httptools
from core import jsontools
from core import logger
from core import scrapertools
from core.item import Item
from platformcode import logger
HOST = "https://animeflv.ru/"

View File

@@ -3,11 +3,10 @@
import re
import urlparse
from core import config
from core import httptools
from core import logger
from core import scrapertools
from core.item import Item
from platformcode import config, logger
CHANNEL_HOST = "http://animeid.tv/"

View File

@@ -4,10 +4,10 @@ import re
import urllib
from core import httptools
from core import logger
from core import scrapertools
from core.item import Item
from core import servertools
from core.item import Item
from platformcode import logger
tgenero = {"Comedia": "https://s7.postimg.org/ne9g9zgwb/comedia.png",
"Drama": "https://s16.postimg.org/94sia332d/drama.png",

View File

@@ -3,20 +3,20 @@
import re
from channels import renumbertools
from core import config
from channelselector import get_thumb
from core import httptools
from core import logger
from core import scrapertools
from core import servertools
from core import tmdb
from core.item import Item
from platformcode import config, logger
host = "http://www.anitoonstv.com"
def mainlist(item):
logger.info()
thumb_series = config.get_thumb("thumb_channels_tvshow.png")
thumb_series = get_thumb("channels_tvshow.png")
itemlist = list()

View File

@@ -2,11 +2,10 @@
import urllib
from core import config
from core import httptools
from core import logger
from core import scrapertools
from core.item import Item
from platformcode import config, logger
host = "http://www.area-documental.com"
__perfil__ = int(config.get_setting('perfil', "areadocumental"))

View File

@@ -3,10 +3,9 @@
import os
from core import channeltools
from core import config
from core import jsontools
from core import logger
from core.item import Item
from platformcode import config, logger
from platformcode import platformtools
__channel__ = "autoplay"

View File

@@ -3,10 +3,10 @@
import re
import urlparse
from core import logger
from core import scrapertools
from core import servertools
from core.item import Item
from platformcode import logger
def mainlist(item):

View File

@@ -4,9 +4,9 @@ import re
import urllib
from core import jsontools as json
from core import logger
from core import scrapertools
from core.item import Item
from platformcode import logger
url_api = ""
beeg_salt = ""

View File

@@ -6,9 +6,9 @@ import urllib
import urllib2
import urlparse
from core import logger
from core import scrapertools
from core.item import Item
from platformcode import logger
try:
import xbmc

View File

@@ -7,14 +7,13 @@ from threading import Thread
import xbmc
import xbmcgui
from core import config
from core import httptools
from core import logger
from core import scrapertools
from core import servertools
from core import tmdb
from core.item import Item
from core.scrapertools import decodeHtmlentities as dhe
from platformcode import config, logger
try:
_create_unverified_https_context = ssl._create_unverified_context

View File

@@ -6,10 +6,10 @@ import urllib
import urllib2
import xbmcgui
from core import logger
from core import scrapertools
from core import servertools
from core.item import Item
from platformcode import logger
## Cargar los datos con la librería 'requests'

View File

@@ -1,8 +1,8 @@
# -*- coding: utf-8 -*-
from core import httptools
from core import logger
from core import scrapertools
from platformcode import logger
host = "http://www.canalporno.com"

View File

@@ -3,13 +3,13 @@
import re
from channels import renumbertools
from core import config
from channelselector import get_thumb
from core import httptools
from core import logger
from core import scrapertools
from core import servertools
from core import tmdb
from core.item import Item
from platformcode import config, logger
host = "http://www.cartoon-latino.com/"
@@ -17,8 +17,7 @@ host = "http://www.cartoon-latino.com/"
def mainlist(item):
logger.info()
thumb_series = config.get_thumb("thumb_channels_tvshow.png")
thumb_series_az = config.get_thumb("thumb_channels_tvshow_az.png")
thumb_series = get_thumb("channels_tvshow.png")
itemlist = list()

View File

@@ -3,10 +3,10 @@
import re
from core import httptools
from core import logger
from core import scrapertools
from core import tmdb
from core.item import Item
from platformcode import logger
host = 'http://www.ciberdocumentales.com'

View File

@@ -2,12 +2,11 @@
import re
from core import config
from core import httptools
from core import logger
from core import scrapertools
from core import servertools
from core.item import Item
from platformcode import config, logger
host = "http://www.cineasiaenlinea.com/"
# Configuracion del canal

View File

@@ -5,13 +5,12 @@ import urlparse
from channels import autoplay
from channels import filtertools
from core import config
from core import httptools
from core import logger
from core import scrapertools
from core import servertools
from core import tmdb
from core.item import Item
from platformcode import config, logger
IDIOMAS = {'latino': 'Latino', 'castellano': 'Español', 'portugues': 'Portugues'}
list_language = IDIOMAS.values()
@@ -285,16 +284,16 @@ def findvideos(item):
patron = 'target="_blank".*? service=".*?" data="(.*?)"><li>(.*?)<\/li>'
matches = re.compile(patron, re.DOTALL).findall(data)
server_url = {'YourUpload':'https://www.yourupload.com/embed/',
'Openload':'https://openload.co/embed/',
'TVM':'https://thevideo.me/embed-',
'Trailer':'',
'BitTorrent':'',
'Mega':'',
'MediaFire':''}
server_url = {'YourUpload': 'https://www.yourupload.com/embed/',
'Openload': 'https://openload.co/embed/',
'TVM': 'https://thevideo.me/embed-',
'Trailer': '',
'BitTorrent': '',
'Mega': '',
'MediaFire': ''}
for video_cod, server_id in matches:
if server_id not in ['BitTorrent', 'Mega', 'MediaFire', 'Trailer','']:
if server_id not in ['BitTorrent', 'Mega', 'MediaFire', 'Trailer', '']:
video_id = dec(video_cod)
if server_id in server_url:
@@ -302,23 +301,22 @@ def findvideos(item):
thumbnail = servertools.guess_server_thumbnail(server_id)
if server_id == 'TVM':
server = 'thevideo.me'
url= server_url[server_id]+video_id+'.html'
url = server_url[server_id] + video_id + '.html'
else:
url = server_url[server_id]+video_id
title = item.contentTitle +' (%s)'%server
url = server_url[server_id] + video_id
title = item.contentTitle + ' (%s)' % server
quality = 'default'
if server_id not in ['BitTorrent', 'Mega', 'MediaFire', 'Trailer']:
if url not in duplicados:
itemlist.append(item.clone(action = 'play',
itemlist.append(item.clone(action='play',
title=title,
fulltitle=item.contentTitle,
url=url,
language=IDIOMAS[item.language],
thumbnail = thumbnail,
thumbnail=thumbnail,
quality=quality,
server = server
server=server
))
duplicados.append(url)
@@ -330,7 +328,7 @@ def findvideos(item):
autoplay.start(itemlist, item)
#itemlist.append(trailer_item)
# itemlist.append(trailer_item)
if config.get_videolibrary_support() and len(itemlist) > 0 and item.extra != 'findvideos':
itemlist.append(
Item(channel=item.channel,

View File

@@ -3,13 +3,12 @@
import re
import urlparse
from core import config
from core import httptools
from core import jsontools
from core import logger
from core import scrapertools
from core import servertools
from core.item import Item
from platformcode import config, logger
__modo_grafico__ = config.get_setting('modo_grafico', 'cinefox')
__perfil__ = int(config.get_setting('perfil', "cinefox"))
@@ -33,17 +32,17 @@ def mainlist(item):
itemlist = []
itemlist.append(item.clone(action="seccion_peliculas", title="Películas", fanart="http://i.imgur.com/PjJaW8o.png",
url= host + "/catalogue?type=peliculas"))
url=host + "/catalogue?type=peliculas"))
# Seccion series
itemlist.append(item.clone(action="seccion_series", title="Series",
url= host + "/ultimos-capitulos", fanart="http://i.imgur.com/9loVksV.png"))
url=host + "/ultimos-capitulos", fanart="http://i.imgur.com/9loVksV.png"))
itemlist.append(item.clone(action="peliculas", title="Documentales", fanart="http://i.imgur.com/Q7fsFI6.png",
url= host + "/catalogue?type=peliculas&genre=documental"))
url=host + "/catalogue?type=peliculas&genre=documental"))
if config.get_setting("adult_mode") != 0:
itemlist.append(item.clone(action="peliculas", title="Sección Adultos +18",
url= host + "/catalogue?type=adultos",
url=host + "/catalogue?type=adultos",
fanart="http://i.imgur.com/kIvE1Zh.png"))
itemlist.append(item.clone(title="Buscar...", action="local_search"))
@@ -245,7 +244,7 @@ def filtrado(item, values):
item.valores = "Filtro: " + ", ".join(sorted(strings))
item.strings = ""
item.url = host + "/catalogue?type=%s&genre=%s&release=%s&quality=%s&language=%s&order=%s" % \
(item.extra, genero, year, calidad, idioma, order)
(item.extra, genero, year, calidad, idioma, order)
return globals()[item.extra](item)
@@ -255,11 +254,11 @@ def seccion_peliculas(item):
itemlist = []
# Seccion peliculas
itemlist.append(item.clone(action="peliculas", title="Novedades", fanart="http://i.imgur.com/PjJaW8o.png",
url= host + "/catalogue?type=peliculas"))
url=host + "/catalogue?type=peliculas"))
itemlist.append(item.clone(action="peliculas", title="Estrenos",
url= host + "/estrenos-de-cine", fanart="http://i.imgur.com/PjJaW8o.png"))
url=host + "/estrenos-de-cine", fanart="http://i.imgur.com/PjJaW8o.png"))
itemlist.append(item.clone(action="filtro", title="Filtrar películas", extra="peliculas",
url= host + "/catalogue?type=peliculas",
url=host + "/catalogue?type=peliculas",
fanart="http://i.imgur.com/PjJaW8o.png"))
# Filtros personalizados para peliculas
for i in range(1, 4):
@@ -269,21 +268,22 @@ def seccion_peliculas(item):
new_item = item.clone()
new_item.values = filtros
itemlist.append(new_item.clone(action="filtro", title=title, fanart="http://i.imgur.com/PjJaW8o.png",
url= host + "/catalogue?type=peliculas", extra="peliculas"))
url=host + "/catalogue?type=peliculas", extra="peliculas"))
itemlist.append(item.clone(action="mapa", title="Mapa de películas", extra="peliculas",
url= host + "/mapa-de-peliculas",
url=host + "/mapa-de-peliculas",
fanart="http://i.imgur.com/PjJaW8o.png"))
return itemlist
def seccion_series(item):
logger.info()
itemlist = []
# Seccion series
itemlist.append(item.clone(action="ultimos", title="Últimos capítulos",
url= host + "/ultimos-capitulos", fanart="http://i.imgur.com/9loVksV.png"))
url=host + "/ultimos-capitulos", fanart="http://i.imgur.com/9loVksV.png"))
itemlist.append(item.clone(action="series", title="Series recientes",
url= host + "/catalogue?type=series",
url=host + "/catalogue?type=series",
fanart="http://i.imgur.com/9loVksV.png"))
itemlist.append(item.clone(action="filtro", title="Filtrar series", extra="series",
url=host + "/catalogue?type=series",
@@ -296,9 +296,9 @@ def seccion_series(item):
new_item = item.clone()
new_item.values = filtros
itemlist.append(new_item.clone(action="filtro", title=title, fanart="http://i.imgur.com/9loVksV.png",
url= host + "/catalogue?type=series", extra="series"))
url=host + "/catalogue?type=series", extra="series"))
itemlist.append(item.clone(action="mapa", title="Mapa de series", extra="series",
url= host + "/mapa-de-series",
url=host + "/mapa-de-series",
fanart="http://i.imgur.com/9loVksV.png"))
return itemlist
@@ -476,7 +476,7 @@ def menu_info(item):
item.infoLabels["plot"] = scrapertools.htmlclean(sinopsis)
id = scrapertools.find_single_match(item.url, '/(\d+)/')
data_trailer = httptools.downloadpage( host + "/media/trailer?idm=%s&mediaType=1" % id).data
data_trailer = httptools.downloadpage(host + "/media/trailer?idm=%s&mediaType=1" % id).data
trailer_url = jsontools.load(data_trailer)["video"]["url"]
if trailer_url != "":
item.infoLabels["trailer"] = trailer_url
@@ -539,14 +539,15 @@ def episodios(item):
itemlist.reverse()
if "episodios" not in item.extra and not item.path:
id = scrapertools.find_single_match(item.url, '/(\d+)/')
data_trailer = httptools.downloadpage( host + "/media/trailer?idm=%s&mediaType=1" % id).data
data_trailer = httptools.downloadpage(host + "/media/trailer?idm=%s&mediaType=1" % id).data
item.infoLabels["trailer"] = jsontools.load(data_trailer)["video"]["url"]
itemlist.append(item.clone(channel="trailertools", action="buscartrailer", title="Buscar Tráiler",
text_color="magenta"))
if config.get_videolibrary_support():
itemlist.append(Item(channel=item.channel, action="add_serie_to_library", text_color=color5,
title="Añadir serie a la videoteca", show=item.show, thumbnail=item.thumbnail,
url=item.url, fulltitle=item.fulltitle, fanart=item.fanart, extra="episodios###episodios",
url=item.url, fulltitle=item.fulltitle, fanart=item.fanart,
extra="episodios###episodios",
contentTitle=item.fulltitle))
return itemlist
@@ -633,7 +634,7 @@ def findvideos(item):
itemlist.extend(get_enlaces(item, url, "de Descarga"))
if extra == "media":
data_trailer = httptools.downloadpage( host + "/media/trailer?idm=%s&mediaType=1" % id).data
data_trailer = httptools.downloadpage(host + "/media/trailer?idm=%s&mediaType=1" % id).data
trailer_url = jsontools.load(data_trailer)["video"]["url"]
if trailer_url != "":
item.infoLabels["trailer"] = trailer_url
@@ -662,18 +663,20 @@ def get_enlaces(item, url, type):
if type == "Online":
gg = httptools.downloadpage(item.url, add_referer=True).data
bloque = scrapertools.find_single_match(gg, 'class="tab".*?button show')
patron = 'a href="#([^"]+)'
patron = 'a href="#([^"]+)'
patron += '.*?language-ES-medium ([^"]+)'
patron += '.*?</i>([^<]+)'
matches = scrapertools.find_multiple_matches(bloque, patron)
for scrapedopcion, scrapedlanguage, scrapedcalidad in matches:
google_url = scrapertools.find_single_match(bloque, 'id="%s.*?src="([^"]+)' %scrapedopcion)
google_url = scrapertools.find_single_match(bloque, 'id="%s.*?src="([^"]+)' % scrapedopcion)
if "medium-es" in scrapedlanguage: language = "Castellano"
if "medium-en" in scrapedlanguage: language = "Ingles"
if "medium-vs" in scrapedlanguage: language = "VOSE"
if "medium-la" in scrapedlanguage: language = "Latino"
titulo = " [%s/%s]" %(language, scrapedcalidad.strip())
itemlist.append(item.clone(action="play", url=google_url, title=" Ver en Gvideo"+titulo, text_color=color2, extra="", server = "gvideo"))
titulo = " [%s/%s]" % (language, scrapedcalidad.strip())
itemlist.append(
item.clone(action="play", url=google_url, title=" Ver en Gvideo" + titulo, text_color=color2,
extra="", server="gvideo"))
patron = '<div class="available-source".*?data-url="([^"]+)".*?class="language.*?title="([^"]+)"' \
'.*?class="source-name.*?>\s*([^<]+)<.*?<span class="quality-text">([^<]+)<'
matches = scrapertools.find_multiple_matches(data, patron)
@@ -747,6 +750,6 @@ def select_page(item):
dialog = xbmcgui.Dialog()
number = dialog.numeric(0, "Introduce el número de página")
if number != "":
item.url = re.sub(r'page=(\d+)', "page="+number, item.url)
item.url = re.sub(r'page=(\d+)', "page=" + number, item.url)
return peliculas(item)

View File

@@ -3,13 +3,12 @@
import re
import urlparse
from core import config
from core import httptools
from core import logger
from core import scrapertools
from core import servertools
from core import tmdb
from core.item import Item
from platformcode import config, logger
host = 'http://cinefoxtv.net/'
headers = [['User-Agent', 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0'],

View File

@@ -3,12 +3,11 @@
import re
import urlparse
from core import config
from core import httptools
from core import logger
from core import scrapertools
from core import servertools
from core.item import Item
from platformcode import config, logger
host = "http://www.cinehindi.com/"

View File

@@ -3,11 +3,10 @@
import os
import re
from core import config
from core import logger
from core import scrapertools
from core import servertools
from core.item import Item
from platformcode import config, logger
IMAGES_PATH = os.path.join(config.get_runtime_path(), 'resources', 'images', 'cinetemagay')

View File

@@ -2,14 +2,12 @@
import urlparse
from core import config
from core import httptools
from core import logger
from core import scrapertools
from core import servertools
from core import tmdb
from core.item import Item
from platformcode import config, logger
CHANNEL_HOST = "http://www.cinetux.net/"
@@ -34,7 +32,7 @@ def mainlist(item):
data = httptools.downloadpage(CHANNEL_HOST).data
total = scrapertools.find_single_match(data, "TENEMOS\s<b>(.*?)</b>")
titulo = "Peliculas (%s)" %total
titulo = "Peliculas (%s)" % total
itemlist.append(item.clone(title=titulo, text_color=color2, action="", text_bold=True))
itemlist.append(item.clone(action="peliculas", title=" Novedades", url=CHANNEL_HOST + "pelicula",
thumbnail="https://raw.githubusercontent.com/master-1970/resources/master/images/genres"
@@ -134,7 +132,7 @@ def peliculas(item):
# Descarga la página
data = httptools.downloadpage(item.url).data
patron = '(?s)class="(?:result-item|item movies)">.*?<img src="([^"]+)'
patron = '(?s)class="(?:result-item|item movies)">.*?<img src="([^"]+)'
patron += '.*?alt="([^"]+)"'
patron += '(.*?)'
patron += 'href="([^"]+)"'
@@ -144,7 +142,7 @@ def peliculas(item):
calidad = scrapertools.find_single_match(calidad, '.*?quality">([^<]+)')
try:
fulltitle = scrapedtitle
year = scrapedyear.replace("&nbsp;","")
year = scrapedyear.replace("&nbsp;", "")
if "/" in fulltitle:
fulltitle = fulltitle.split(" /", 1)[0]
scrapedtitle = "%s (%s)" % (fulltitle, year)
@@ -159,7 +157,7 @@ def peliculas(item):
new_item.infoLabels['year'] = int(year)
itemlist.append(new_item)
try:
#tmdb.set_infoLabels(itemlist, __modo_grafico__)
# tmdb.set_infoLabels(itemlist, __modo_grafico__)
a = 1
except:
pass
@@ -183,13 +181,13 @@ def destacadas(item):
# Extrae las entradas (carpetas)
bloque = scrapertools.find_single_match(data, 'peliculas_destacadas.*?class="single-page')
patron = '(?s)title="([^"]+)"'
patron = '(?s)title="([^"]+)"'
patron += '.href="([^"]+)"'
patron += '.*?src="([^"]+)'
matches = scrapertools.find_multiple_matches(bloque, patron)
for scrapedtitle, scrapedurl, scrapedthumbnail in matches:
for scrapedtitle, scrapedurl, scrapedthumbnail in matches:
scrapedurl = "http://www.cinetux.net" + scrapedurl
scrapedtitle = scrapedtitle.replace("Ver ","")
scrapedtitle = scrapedtitle.replace("Ver ", "")
new_item = item.clone(action="findvideos", title=scrapedtitle, fulltitle=scrapedtitle,
url=scrapedurl, thumbnail=scrapedthumbnail,
contentTitle=scrapedtitle, contentType="movie")
@@ -198,7 +196,8 @@ def destacadas(item):
# Extrae el paginador
next_page_link = scrapertools.find_single_match(data, '<a href="([^"]+)"\s+><span [^>]+>&raquo;</span>')
if next_page_link:
itemlist.append(item.clone(action="destacadas", title=">> Página siguiente", url=next_page_link, text_color=color3))
itemlist.append(
item.clone(action="destacadas", title=">> Página siguiente", url=next_page_link, text_color=color3))
return itemlist
@@ -235,7 +234,7 @@ def idioma(item):
return itemlist
def findvideos(item):
logger.info()
itemlist = []
@@ -253,7 +252,7 @@ def findvideos(item):
year = scrapertools.find_single_match(item.title, "\(([0-9]+)")
if year and item.extra != "library":
item.infoLabels['year'] = int(year)
item.infoLabels['year'] = int(year)
# Ampliamos datos en tmdb
if not item.infoLabels['plot']:
try:
@@ -280,7 +279,7 @@ def findvideos(item):
if itemlist:
itemlist.append(item.clone(channel="trailertools", title="Buscar Tráiler", action="buscartrailer", context="",
text_color="magenta"))
text_color="magenta"))
# Opción "Añadir esta película a la videoteca"
if item.extra != "library":
if config.get_videolibrary_support():
@@ -288,7 +287,7 @@ def findvideos(item):
filtro=True, action="add_pelicula_to_library", url=item.url,
infoLabels={'title': item.fulltitle}, fulltitle=item.fulltitle,
extra="library"))
else:
itemlist.append(item.clone(title="No hay enlaces disponibles", action="", text_color=color3))
@@ -299,9 +298,9 @@ def bloque_enlaces(data, filtro_idioma, dict_idiomas, type, item):
logger.info()
lista_enlaces = []
matches = []
if type == "online" : t_tipo = "Ver Online"
if type == "online": t_tipo = "Ver Online"
if type == "descarga": t_tipo = "Descargar"
data = data.replace("\n","")
data = data.replace("\n", "")
if type == "online":
patron = '(?is)class="playex.*?visualizaciones'
bloque1 = scrapertools.find_single_match(data, patron)
@@ -311,18 +310,18 @@ def bloque_enlaces(data, filtro_idioma, dict_idiomas, type, item):
lazy = ""
if "lazy" in bloque1:
lazy = "lazy-"
patron = '(?s)id="%s".*?metaframe.*?%ssrc="([^"]+)' %(scrapedoption, lazy)
patron = '(?s)id="%s".*?metaframe.*?%ssrc="([^"]+)' % (scrapedoption, lazy)
url = scrapertools.find_single_match(bloque1, patron)
if "goo.gl" in url:
url = httptools.downloadpage(url, follow_redirects=False, only_headers=True).headers.get("location","")
url = httptools.downloadpage(url, follow_redirects=False, only_headers=True).headers.get("location", "")
if "www.cinetux.me" in url:
server = scrapertools.find_single_match(url, "player/(.*?)\.")
else:
server = servertools.get_server_from_url(url)
matches.append([url, server, "", language.strip(), t_tipo])
bloque2 = scrapertools.find_single_match(data, '(?s)box_links.*?dt_social_single')
bloque2 = bloque2.replace("\t","").replace("\r","")
patron = '(?s)optn" href="([^"]+)'
bloque2 = bloque2.replace("\t", "").replace("\r", "")
patron = '(?s)optn" href="([^"]+)'
patron += '.*?title="([^"]+)'
patron += '.*?src.*?src="[^>]+"?/>([^<]+)'
patron += '.*?src="[^>]+"?/>([^<]+)'
@@ -343,11 +342,12 @@ def bloque_enlaces(data, filtro_idioma, dict_idiomas, type, item):
if filtro_idioma == 3 or item.filtro:
lista_enlaces.append(item.clone(title=title, action="play", text_color=color2,
url=scrapedurl, server=scrapedserver, idioma=scrapedlanguage, extra=item.url))
url=scrapedurl, server=scrapedserver, idioma=scrapedlanguage,
extra=item.url))
else:
idioma = dict_idiomas[language]
if idioma == filtro_idioma:
lista_enlaces.append(item.clone(title=title, text_color=color2, action="play", url=scrapedurl,
lista_enlaces.append(item.clone(title=title, text_color=color2, action="play", url=scrapedurl,
extra=item.url))
else:
if language not in filtrados:
@@ -368,7 +368,7 @@ def play(item):
data = httptools.downloadpage(item.url, headers={'Referer': item.extra}).data.replace("\\", "")
id = scrapertools.find_single_match(data, 'img src="[^#]+#(.*?)"')
item.url = "https://youtube.googleapis.com/embed/?status=ok&hl=es&allow_embed=1&ps=docs&partnerid=30&hd=1&autoplay=0&cc_load_policy=1&showinfo=0&docid=" + id
itemlist = servertools.find_video_items(data = item.url)
itemlist = servertools.find_video_items(data=item.url)
elif "links" in item.url or "www.cinetux.me" in item.url:
data = httptools.downloadpage(item.url).data
scrapedurl = scrapertools.find_single_match(data, '<a href="(http[^"]+)')
@@ -377,9 +377,10 @@ def play(item):
if scrapedurl == "":
scrapedurl = scrapertools.find_single_match(data, 'replace."([^"]+)"')
elif "goo.gl" in scrapedurl:
scrapedurl = httptools.downloadpage(scrapedurl, follow_redirects=False, only_headers=True).headers.get("location", "")
scrapedurl = httptools.downloadpage(scrapedurl, follow_redirects=False, only_headers=True).headers.get(
"location", "")
item.url = scrapedurl
itemlist = servertools.find_video_items(data = item.url)
itemlist = servertools.find_video_items(data=item.url)
else:
return [item]
return itemlist

View File

@@ -2,12 +2,11 @@
import re
from core import config
from core import httptools
from core import logger
from core import scrapertools
from core import tmdb
from core.item import Item
from platformcode import config, logger
host = "http://www.clasicofilm.com/"
# Configuracion del canal
@@ -61,7 +60,7 @@ def search(item, texto):
cx = scrapertools.find_single_match(data, "var cx = '([^']+)'")
texto = texto.replace(" ", "%20")
item.url = "https://www.googleapis.com/customsearch/v1element?key=AIzaSyCVAXiUzRYsML1Pv6RwSG1gunmMikTzQqY&rsz=filtered_cse&num=20&hl=es&sig=0c3990ce7a056ed50667fe0c3873c9b6&cx=%s&q=%s&sort=&googlehost=www.google.com&start=0" % (
cx, texto)
cx, texto)
try:
return busqueda(item)

View File

@@ -3,12 +3,11 @@
import re
import threading
from core import config
from core import filetools
from core import httptools
from core import logger
from core import scrapertools
from core.item import Item
from platformcode import config, logger
__perfil__ = config.get_setting('perfil', "copiapop")

View File

@@ -4,10 +4,10 @@ import re
import urlparse
import xbmc
from core import logger
from core import scrapertools
from core import servertools
from core.item import Item
from platformcode import logger
# Main list manual

View File

@@ -3,11 +3,10 @@
import re
import urllib
from core import config
from core import httptools
from core import logger
from core import scrapertools
from core.item import Item
from platformcode import config, logger
__perfil__ = config.get_setting('perfil', "crunchyroll")

View File

@@ -6,10 +6,10 @@ import urlparse
import xbmc
import xbmcgui
from core import logger
from core import scrapertools, httptools
from core.item import Item
from core.scrapertools import decodeHtmlentities as dhe
from platformcode import logger
ACTION_SHOW_FULLSCREEN = 36
ACTION_GESTURE_SWIPE_LEFT = 511

View File

@@ -4,11 +4,10 @@ import re
import urllib
import urlparse
from core import config
from core import httptools
from core import logger
from core import scrapertools
from core.item import Item
from platformcode import config, logger
def mainlist(item):

View File

@@ -1,8 +1,8 @@
# -*- coding: utf-8 -*-
from core import httptools
from core import logger
from core import scrapertools
from platformcode import logger
def mainlist(item):

View File

@@ -3,17 +3,17 @@
import re
import urlparse
from channelselector import get_thumbnail_path
from core import logger
from channelselector import get_thumb
from core import scrapertools
from core import servertools
from core.item import Item
from core.tmdb import Tmdb
from platformcode import logger
from servers.decrypters import expurl
def agrupa_datos(data):
## Agrupa los datos
# Agrupa los datos
data = re.sub(r'\n|\r|\t|&nbsp;|<br>|<!--.*?-->', '', data)
data = re.sub(r'\s+', ' ', data)
data = re.sub(r'>\s<', '><', data)
@@ -23,7 +23,7 @@ def agrupa_datos(data):
def mainlist(item):
logger.info()
thumb_buscar = get_thumbnail_path() + "thumb_search.png"
thumb_buscar = get_thumb("search.png")
itemlist = []
itemlist.append(Item(channel=item.channel, title="Últimas agregadas", action="agregadas",

View File

@@ -3,12 +3,11 @@
import re
import urllib
from core import config
from core import httptools
from core import logger
from core import scrapertools
from core import servertools
from core.item import Item
from platformcode import config, logger
__modo_grafico__ = config.get_setting("modo_grafico", "descargasmix")
__perfil__ = config.get_setting("perfil", "descargasmix")

View File

@@ -3,10 +3,10 @@
import re
import urlparse
from core import logger
from core import scrapertools
from core import servertools
from core.item import Item
from platformcode import logger
def mainlist(item):

View File

@@ -5,10 +5,10 @@ import urllib
import urlparse
from core import httptools
from core import logger
from core import scrapertools
from core import servertools
from core.item import Item
from platformcode import logger
def mainlist(item):

View File

@@ -7,13 +7,12 @@ from threading import Thread
import xbmc
import xbmcgui
from core import config
from core import httptools
from core import logger
from core import scrapertools
from core import tmdb
from core.item import Item
from core.scrapertools import decodeHtmlentities as dhe
from platformcode import config, logger
header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0'}
@@ -490,14 +489,14 @@ class TextBox2(xbmcgui.WindowDialog):
self.addControl(self.plot)
self.plot.setAnimations(
[('conditional', 'effect=zoom delay=2000 center=auto start=0 end=100 time=800 condition=true ',), (
'conditional',
'effect=rotate delay=2000 center=auto aceleration=6000 start=0% end=360% time=800 condition=true',),
'conditional',
'effect=rotate delay=2000 center=auto aceleration=6000 start=0% end=360% time=800 condition=true',),
('WindowClose', 'effect=zoom center=auto start=100% end=-0% time=600 condition=true',)])
self.addControl(self.fanart)
self.fanart.setAnimations(
[('WindowOpen', 'effect=slide start=0,-700 delay=1000 time=2500 tween=bounce condition=true',), (
'conditional',
'effect=rotate center=auto start=0% end=360% delay=3000 time=2500 tween=bounce condition=true',),
'conditional',
'effect=rotate center=auto start=0% end=360% delay=3000 time=2500 tween=bounce condition=true',),
('WindowClose', 'effect=slide end=0,-700% time=1000 condition=true',)])
self.addControl(self.title)
self.title.setText(self.getTitle)
@@ -743,14 +742,14 @@ def get_art(item):
if id == None:
if item.contentType == "movie":
urlbing_imdb = "http://www.bing.com/search?q=%s+%s+tv+series+site:imdb.com" % (
item.fulltitle.replace(' ', '+'), year)
item.fulltitle.replace(' ', '+'), year)
data = browser(urlbing_imdb)
data = re.sub(r"\n|\r|\t|\s{2}|&nbsp;|http://ssl-proxy.my-addr.org/myaddrproxy.php/", "", data)
subdata_imdb = scrapertools.find_single_match(data,
'<li class="b_algo">(.*?)h="ID.*?<strong>.*?TV Series')
else:
urlbing_imdb = "http://www.bing.com/search?q=%s+%s+site:imdb.com" % (
item.fulltitle.replace(' ', '+'), year)
item.fulltitle.replace(' ', '+'), year)
data = browser(urlbing_imdb)
data = re.sub(r"\n|\r|\t|\s{2}|&nbsp;|http://ssl-proxy.my-addr.org/myaddrproxy.php/", "", data)
subdata_imdb = scrapertools.find_single_match(data, '<li class="b_algo">(.*?)h="ID.*?<strong>')
@@ -770,7 +769,7 @@ def get_art(item):
title = scrapertools.find_single_match(item.fulltitle, '\(.*?\)')
if item.contentType != "movie":
urlbing_imdb = "http://www.bing.com/search?q=%s+%s+tv+series+site:imdb.com" % (
title.replace(' ', '+'), year)
title.replace(' ', '+'), year)
data = browser(urlbing_imdb)
data = re.sub(r"\n|\r|\t|\s{2}|&nbsp;|http://ssl-proxy.my-addr.org/myaddrproxy.php/", "",
data)
@@ -778,7 +777,7 @@ def get_art(item):
'<li class="b_algo">(.*?)h="ID.*?<strong>.*?TV Series')
else:
urlbing_imdb = "http://www.bing.com/search?q=%s+%s+site:imdb.com" % (
title.replace(' ', '+'), year)
title.replace(' ', '+'), year)
data = browser(urlbing_imdb)
data = re.sub(r"\n|\r|\t|\s{2}|&nbsp;|http://ssl-proxy.my-addr.org/myaddrproxy.php/", "",
data)

View File

@@ -4,11 +4,10 @@ import re
import urllib
import urlparse
from core import config
from core import jsontools
from core import logger
from core import scrapertools
from core.item import Item
from platformcode import config, logger
host = "http://www.documaniatv.com/"
account = config.get_setting("documaniatvaccount", "documaniatv")

View File

@@ -3,9 +3,9 @@
import re
from core import httptools
from core import logger
from core import scrapertools
from core.item import Item
from platformcode import logger
HOST = "http://documentales-online.com/"

View File

@@ -6,13 +6,12 @@ import urlparse
from channels import autoplay
from channels import filtertools
from core import config
from core import httptools
from core import logger
from core import scrapertools
from core import servertools
from core import tmdb
from core.item import Item
from platformcode import config, logger
IDIOMAS = {'latino': 'Latino'}
list_language = IDIOMAS.values()

View File

@@ -3,9 +3,9 @@
import re
import urlparse
from core import logger
from core import scrapertools
from core.item import Item
from platformcode import logger
host = "http://doramastv.com/"
DEFAULT_HEADERS = []

View File

@@ -7,15 +7,14 @@ import os
import re
import time
from core import config
from core import filetools
from core import videolibrarytools
from core import logger
from core import scraper
from core import scrapertools
from core import servertools
from core import videolibrarytools
from core.downloader import Downloader
from core.item import Item
from platformcode import config, logger
from platformcode import platformtools
STATUS_COLORS = {0: "orange", 1: "orange", 2: "green", 3: "red"}
@@ -52,7 +51,7 @@ def mainlist(item):
itemlist):
title = TITLE_TVSHOW % (
STATUS_COLORS[i.downloadStatus], i.downloadProgress, i.contentSerieName, i.contentChannel)
STATUS_COLORS[i.downloadStatus], i.downloadProgress, i.contentSerieName, i.contentChannel)
itemlist.append(Item(title=title, channel="descargas", action="mainlist", contentType="tvshow",
contentSerieName=i.contentSerieName, contentChannel=i.contentChannel,
@@ -61,8 +60,9 @@ def mainlist(item):
else:
s = \
filter(lambda x: x.contentSerieName == i.contentSerieName and x.contentChannel == i.contentChannel,
itemlist)[0]
filter(
lambda x: x.contentSerieName == i.contentSerieName and x.contentChannel == i.contentChannel,
itemlist)[0]
s.downloadProgress.append(i.downloadProgress)
downloadProgress = sum(s.downloadProgress) / len(s.downloadProgress)
@@ -71,7 +71,7 @@ def mainlist(item):
s.downloadStatus = i.downloadStatus
s.title = TITLE_TVSHOW % (
STATUS_COLORS[s.downloadStatus], downloadProgress, i.contentSerieName, i.contentChannel)
STATUS_COLORS[s.downloadStatus], downloadProgress, i.contentSerieName, i.contentChannel)
# Peliculas
elif i.contentType == "movie" or i.contentType == "video":
@@ -149,7 +149,7 @@ def clean_all(item):
if fichero.endswith(".json"):
download_item = Item().fromjson(filetools.read(os.path.join(DOWNLOAD_LIST_PATH, fichero)))
if not item.contentType == "tvshow" or (
item.contentSerieName == download_item.contentSerieName and item.contentChannel == download_item.contentChannel):
item.contentSerieName == download_item.contentSerieName and item.contentChannel == download_item.contentChannel):
filetools.remove(os.path.join(DOWNLOAD_LIST_PATH, fichero))
platformtools.itemlist_refresh()
@@ -161,7 +161,7 @@ def clean_ready(item):
if fichero.endswith(".json"):
download_item = Item().fromjson(filetools.read(os.path.join(DOWNLOAD_LIST_PATH, fichero)))
if not item.contentType == "tvshow" or (
item.contentSerieName == download_item.contentSerieName and item.contentChannel == download_item.contentChannel):
item.contentSerieName == download_item.contentSerieName and item.contentChannel == download_item.contentChannel):
if download_item.downloadStatus == STATUS_CODES.completed:
filetools.remove(os.path.join(DOWNLOAD_LIST_PATH, fichero))
@@ -175,7 +175,7 @@ def restart_error(item):
download_item = Item().fromjson(filetools.read(os.path.join(DOWNLOAD_LIST_PATH, fichero)))
if not item.contentType == "tvshow" or (
item.contentSerieName == download_item.contentSerieName and item.contentChannel == download_item.contentChannel):
item.contentSerieName == download_item.contentSerieName and item.contentChannel == download_item.contentChannel):
if download_item.downloadStatus == STATUS_CODES.error:
if filetools.isfile(
os.path.join(config.get_setting("downloadpath"), download_item.downloadFilename)):
@@ -196,7 +196,7 @@ def download_all(item):
filetools.read(os.path.join(DOWNLOAD_LIST_PATH, fichero)))
if not item.contentType == "tvshow" or (
item.contentSerieName == download_item.contentSerieName and item.contentChannel == download_item.contentChannel):
item.contentSerieName == download_item.contentSerieName and item.contentChannel == download_item.contentChannel):
if download_item.downloadStatus in [STATUS_CODES.stoped, STATUS_CODES.canceled]:
res = start_download(download_item)
platformtools.itemlist_refresh()
@@ -339,7 +339,7 @@ def get_server_position(server):
if server in servers:
pos = [s for s in sorted(servers, key=lambda x: (sum(servers[x]["speeds"]) / (len(servers[x]["speeds"]) or 1),
float(sum(servers[x]["success"])) / (
len(servers[x]["success"]) or 1)), reverse=True)]
len(servers[x]["success"]) or 1)), reverse=True)]
return pos.index(server) + 1
else:
return 0
@@ -532,7 +532,7 @@ def download_from_server(item):
return {"downloadStatus": STATUS_CODES.error}
progreso.close()
logger.info("contentAction: %s | contentChannel: %s | server: %s | url: %s" % (
item.contentAction, item.contentChannel, item.server, item.url))
item.contentAction, item.contentChannel, item.server, item.url))
if not item.server or not item.url or not item.contentAction == "play" or item.server in unsupported_servers:
logger.error("El Item no contiene los parametros necesarios.")
@@ -677,7 +677,7 @@ def start_download(item):
def get_episodes(item):
logger.info("contentAction: %s | contentChannel: %s | contentType: %s" % (
item.contentAction, item.contentChannel, item.contentType))
item.contentAction, item.contentChannel, item.contentType))
# El item que pretendemos descargar YA es un episodio
if item.contentType == "episode":
@@ -727,7 +727,7 @@ def get_episodes(item):
episode.contentTitle = re.sub("\[[^\]]+\]|\([^\)]+\)|\d*x\d*\s*-", "", episode.title).strip()
episode.downloadFilename = filetools.validate_path(os.path.join(item.downloadFilename, "%dx%0.2d - %s" % (
episode.contentSeason, episode.contentEpisodeNumber, episode.contentTitle.strip())))
episode.contentSeason, episode.contentEpisodeNumber, episode.contentTitle.strip())))
itemlist.append(episode)
# Cualquier otro resultado no nos vale, lo ignoramos
@@ -785,7 +785,7 @@ def save_download(item):
def save_download_video(item):
logger.info("contentAction: %s | contentChannel: %s | contentTitle: %s" % (
item.contentAction, item.contentChannel, item.contentTitle))
item.contentAction, item.contentChannel, item.contentTitle))
set_movie_title(item)
@@ -802,7 +802,7 @@ def save_download_video(item):
def save_download_movie(item):
logger.info("contentAction: %s | contentChannel: %s | contentTitle: %s" % (
item.contentAction, item.contentChannel, item.contentTitle))
item.contentAction, item.contentChannel, item.contentTitle))
progreso = platformtools.dialog_progress("Descargas", "Obteniendo datos de la pelicula")
@@ -830,7 +830,7 @@ def save_download_movie(item):
def save_download_tvshow(item):
logger.info("contentAction: %s | contentChannel: %s | contentType: %s | contentSerieName: %s" % (
item.contentAction, item.contentChannel, item.contentType, item.contentSerieName))
item.contentAction, item.contentChannel, item.contentType, item.contentSerieName))
progreso = platformtools.dialog_progress("Descargas", "Obteniendo datos de la serie")

View File

@@ -3,9 +3,9 @@
import re
import urlparse
from core import logger
from core import scrapertools
from core.item import Item
from platformcode import logger
def mainlist(item):

View File

@@ -3,9 +3,9 @@
import re
import urlparse
from core import logger
from core import scrapertools
from core.item import Item
from platformcode import logger
BASE_URL = 'http://www.elitetorrent.wesconference.net'

View File

@@ -3,10 +3,10 @@
import re
import urlparse
from core import logger
from core import scrapertools
from core import servertools
from core.item import Item
from platformcode import logger
def mainlist(item):

View File

@@ -5,7 +5,7 @@ import urlparse
from core import httptools
from core import jsontools
from core import logger
from platformcode import logger
def mainlist(item):

View File

@@ -3,9 +3,9 @@
import re
import urlparse
from core import logger
from core import scrapertools
from core.item import Item
from platformcode import logger
def mainlist(item):

View File

@@ -4,13 +4,12 @@ import re
from channels import autoplay
from channels import filtertools
from core import config
from core import httptools
from core import logger
from core import scrapertools
from core import servertools
from core import tmdb
from core.item import Item
from platformcode import config, logger
host = 'http://www.estadepelis.com/'
headers = [['User-Agent', 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0'],

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