mirror of
https://github.com/rembo10/headphones.git
synced 2026-05-21 11:05:32 +01:00
Merge branch 'develop'
This commit is contained in:
1
.gitignore
vendored
1
.gitignore
vendored
@@ -10,6 +10,7 @@
|
||||
*.db-journal
|
||||
*.ini
|
||||
logs/*
|
||||
cache/*
|
||||
|
||||
# OS generated files #
|
||||
######################
|
||||
|
||||
@@ -12,9 +12,11 @@ $commands¶meters[&optionalparameters]:
|
||||
|
||||
getIndex (fetch data from index page. Returns: ArtistName, ArtistSortName, ArtistID, Status, DateAdded,
|
||||
[LatestAlbum, ReleaseDate, AlbumID], HaveTracks, TotalTracks,
|
||||
IncludeExtras)
|
||||
IncludeExtras, LastUpdated, [ArtworkURL, ThumbURL]: a remote url to the artwork/thumbnail. To get the cached image path, see getArtistArt command.
|
||||
ThumbURL is added/updated when an artist is added/updated. If your using the database method to get the artwork,
|
||||
it's more reliable to use the ThumbURL than the ArtworkURL)
|
||||
|
||||
getArtist&id=$artistid (fetch artist data. returns the artist object (see above) and album info: Status, AlbumASIN, DateAdded, AlbumTitle, ArtistName, ReleaseDate, AlbumID, ArtistID, Type)
|
||||
getArtist&id=$artistid (fetch artist data. returns the artist object (see above) and album info: Status, AlbumASIN, DateAdded, AlbumTitle, ArtistName, ReleaseDate, AlbumID, ArtistID, Type, ArtworkURL: hosted image path. For cached image, see getAlbumArt command)
|
||||
|
||||
getAlbum&id=$albumid (fetch data from album page. Returns the album object, a description object and a tracks object. Tracks contain: AlbumASIN, AlbumTitle, TrackID, Format, TrackDuration (ms), ArtistName, TrackTitle, AlbumID, ArtistID, Location, TrackNumber, CleanName (stripped of punctuation /styling), BitRate)
|
||||
|
||||
@@ -52,4 +54,13 @@ checkGithub (updates the version information above and returns getVersion data)
|
||||
|
||||
shutdown (shut down headphones)
|
||||
restart (restart headphones)
|
||||
update (update headphones - you may want to check the install type in get version and not allow this if type==exe)
|
||||
update (update headphones - you may want to check the install type in get version and not allow this if type==exe)
|
||||
|
||||
getArtistArt&id=$artistid (Returns either a relative path to the cached image, or a remote url if the image can't be saved to the cache dir)
|
||||
getAlbumArt&id=$albumid (see above)
|
||||
|
||||
getArtistInfo&id=$artistid (Returns Summary and Content, both formatted in html)
|
||||
getAlbumInfo&id=$albumid (See above, returns Summary and Content)
|
||||
|
||||
getArtistThumb&id=$artistid (Returns either a relative path to the cached thumbnail artist image, or an http:// address if the cache dir can't be written to)
|
||||
getAlbumThumb&id=$albumid (see above)
|
||||
674
COPYING
Normal file
674
COPYING
Normal 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>.
|
||||
@@ -1,4 +1,19 @@
|
||||
#!/usr/bin/env python
|
||||
# This file is part of Headphones.
|
||||
#
|
||||
# Headphones 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.
|
||||
#
|
||||
# Headphones 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 Headphones. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import os, sys, locale
|
||||
import time
|
||||
|
||||
@@ -120,19 +135,19 @@ def main():
|
||||
headphones.start()
|
||||
|
||||
while True:
|
||||
if not headphones.SIGNAL:
|
||||
time.sleep(1)
|
||||
else:
|
||||
logger.info('Received signal: ' + headphones.SIGNAL)
|
||||
if headphones.SIGNAL == 'shutdown':
|
||||
headphones.shutdown()
|
||||
elif headphones.SIGNAL == 'restart':
|
||||
headphones.shutdown(restart=True)
|
||||
else:
|
||||
headphones.shutdown(restart=True, update=True)
|
||||
|
||||
headphones.SIGNAL = None
|
||||
|
||||
if not headphones.SIGNAL:
|
||||
time.sleep(1)
|
||||
else:
|
||||
logger.info('Received signal: ' + headphones.SIGNAL)
|
||||
if headphones.SIGNAL == 'shutdown':
|
||||
headphones.shutdown()
|
||||
elif headphones.SIGNAL == 'restart':
|
||||
headphones.shutdown(restart=True)
|
||||
else:
|
||||
headphones.shutdown(restart=True, update=True)
|
||||
|
||||
headphones.SIGNAL = None
|
||||
|
||||
return
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
36
README.md
36
README.md
@@ -2,33 +2,43 @@
|
||||
|
||||
###Installation and Notes
|
||||
|
||||
This is a pretty early release of a third-party add-on for SABnzbd.
|
||||
This is a relatively early release of a third-party add-on for SABnzbd. It's been around for about a year, and while
|
||||
quite functional, there are still a lot of kinks to work out!
|
||||
|
||||
To run it, just double-click the Headphones.py file (in Windows - you may need to right click and click 'Open With' -> Python) or launch a terminal, cd into the Headphones directory and run 'python headphones.py'.
|
||||
|
||||
For additional startup options, type 'python Headphones.py -h' or 'python Headphones.py --help'
|
||||
|
||||
###Screenshots
|
||||
(note: These screenshots are a little out of date and the interface has gone through a little bit of an overhaul. Updated shots coming soon!)
|
||||
|
||||
First Run
|
||||
Homepage (Artist Overview)
|
||||
|
||||

|
||||

|
||||
|
||||
Artist Search Results
|
||||
One of the many settings pages....
|
||||
|
||||

|
||||

|
||||
|
||||
Album Selection
|
||||
It might even know you better than you know yourself:
|
||||
|
||||

|
||||

|
||||
|
||||
iTunes/Import
|
||||
Import Your Favorite Artists:
|
||||
|
||||

|
||||

|
||||
|
||||
If you run into any issues, visit http://github.com/rembo10/headphones and report an issue.
|
||||
Artist Search Results (also search by album!):
|
||||
|
||||
This is free software so feel free to use it/modify it as you wish.
|
||||

|
||||
|
||||
If you have any ideas for the next release, also make sure to post that here!
|
||||
Artist Page with Bio & Album Overview:
|
||||
|
||||

|
||||
|
||||
Album Page with track overview:
|
||||
|
||||

|
||||
|
||||
If you run into any issues, visit http://headphones.codeshy.com/forum and report an issue.
|
||||
|
||||
This is free software under the GPL v3 open source license - so feel free to do with it what you wish.
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
<div class="table_wrapper">
|
||||
<div id="albumheader" class="clearfix">
|
||||
<div id="albumImg">
|
||||
<img src="http://ec1.images-amazon.com/images/P/${album['AlbumASIN']}.01.LZZZZZZZ.jpg" height="200" width="200" alt="albumart" class="albumArt" rel="dialog">
|
||||
<img height="200" alt="" class="albumArt">
|
||||
</div>
|
||||
|
||||
<h1><a href="http://musicbrainz.org/release-group/${album['AlbumID']}">${album['AlbumTitle']}</a></h1>
|
||||
@@ -41,9 +41,7 @@
|
||||
|
||||
%>
|
||||
<div class="albuminfo">
|
||||
%if description:
|
||||
<p>${description['Summary']}</p>
|
||||
%endif
|
||||
<div id="albumInfo"></div>
|
||||
<ul>
|
||||
<li>Tracks: <span>${totaltracks}</span></li>
|
||||
<li>Duration: <span>${albumduration}</span></li>
|
||||
@@ -128,9 +126,30 @@
|
||||
<%def name="javascriptIncludes()">
|
||||
<script src="js/libs/jquery.dataTables.min.js"></script>
|
||||
<script>
|
||||
|
||||
function getAlbumArt() {
|
||||
var id = "${album['AlbumID']}";
|
||||
var name = "${album['AlbumTitle']}";
|
||||
var image = $("div#albumImg img");
|
||||
if ( !image.hasClass('done') ) {
|
||||
image.addClass('done');
|
||||
getArtwork(image,id,name,'album');
|
||||
}
|
||||
}
|
||||
|
||||
function getAlbumInfo() {
|
||||
var id = "${album['AlbumID']}";
|
||||
var elem = $("#albumInfo");
|
||||
getInfo(elem,id,'album');
|
||||
}
|
||||
|
||||
$(document).ready(function() {
|
||||
getAlbumInfo("${album['ArtistName']}","${album['AlbumTitle']}","#albumheader .albumArt",3);
|
||||
getAlbumInfo();
|
||||
getAlbumArt();
|
||||
initActions();
|
||||
setTimeout(function(){
|
||||
initFancybox();
|
||||
},1000);
|
||||
|
||||
$('#track_table').dataTable({
|
||||
"aaSorting": [],
|
||||
@@ -139,8 +158,6 @@
|
||||
"bPaginate": false
|
||||
});
|
||||
});
|
||||
$(window).load(function(){
|
||||
initFancybox();
|
||||
});
|
||||
|
||||
</script>
|
||||
</%def>
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
<%def name="body()">
|
||||
<div id="artistheader" class="clearfix">
|
||||
<div id="artistImg">
|
||||
<img class="albumArt" src="http://ec1.images-amazon.com/images/P/None.01.MZZZZZZZ.jpg" width="200" height="200" alt="${artist['ArtistName']}"/>
|
||||
<img id="artistImage" class="albumArt" alt="" />
|
||||
</div>
|
||||
<h1>
|
||||
%if artist['Status'] == 'Loading':
|
||||
@@ -109,7 +109,7 @@
|
||||
%>
|
||||
<tr class="grade${grade}">
|
||||
<td id="select"><input type="checkbox" name="${album['AlbumID']}" class="checkbox" /></td>
|
||||
<td id="albumart"><img src="http://ec1.images-amazon.com/images/P/${album['AlbumASIN']}.01.MZZZZZZZ.jpg" height="50" width="50"></td>
|
||||
<td id="albumart"><img class="albumArt" title="${album['AlbumID']}" height="64" width="64"></td>
|
||||
<td id="albumname"><a href="albumPage?AlbumID=${album['AlbumID']}">${album['AlbumTitle']}</a></td>
|
||||
<td id="reldate">${album['ReleaseDate']}</td>
|
||||
<td id="type">${album['Type']}</td>
|
||||
@@ -148,11 +148,42 @@
|
||||
<script src="js/libs/jquery.dataTables.min.js"></script>
|
||||
|
||||
<script>
|
||||
|
||||
function getArtistArt() {
|
||||
var id = "${artist['ArtistID']}";
|
||||
var name = "${artist['ArtistName']}";
|
||||
var image = $("div#artistImg img#artistImage");
|
||||
if ( !image.hasClass('done') ) {
|
||||
image.addClass('done');
|
||||
getArtwork(image,id,name,'artist');
|
||||
}
|
||||
}
|
||||
|
||||
function getAlbumArt() {
|
||||
$("table#album_table tr td#albumart").each(function(){
|
||||
var id = $(this).children('img').attr('title');
|
||||
var image = $(this).children('img');
|
||||
if ( !image.hasClass('done') ) {
|
||||
image.addClass('done');
|
||||
getThumb(image,id,'album');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function getArtistBio() {
|
||||
var id = "${artist['ArtistID']}";
|
||||
var elem = $("#artistBio");
|
||||
getInfo(elem,id,'artist');
|
||||
}
|
||||
|
||||
|
||||
function initThisPage() {
|
||||
%if artist['Status'] == 'Loading':
|
||||
showMsg("Getting artist information",true);
|
||||
%endif
|
||||
|
||||
getArtistArt();
|
||||
getArtistBio();
|
||||
getAlbumArt();
|
||||
$('#album_table').dataTable({
|
||||
"bDestroy": true,
|
||||
"aoColumns": [
|
||||
@@ -181,22 +212,15 @@
|
||||
|
||||
});
|
||||
resetFilters("albums");
|
||||
replaceEmptyAlbum("table#album_table td#albumart img","${artist['ArtistName']}");
|
||||
setTimeout(function(){
|
||||
initFancybox();
|
||||
},1000);
|
||||
},1500)
|
||||
}
|
||||
|
||||
$(document).ready(function() {
|
||||
getArtistInfo("${artist['ArtistName']}","#artistImg img",3,"${artist['ArtistID']}");
|
||||
initActions();
|
||||
initThisPage();
|
||||
});
|
||||
$(window).load(function(){
|
||||
replaceEmptyAlbum("table#album_table td#albumart img","${artist['ArtistName']}");
|
||||
setTimeout(function(){
|
||||
initFancybox();
|
||||
},1000)
|
||||
});
|
||||
|
||||
</script>
|
||||
</%def>
|
||||
|
||||
@@ -96,10 +96,9 @@
|
||||
<a href="#main" id="toTop"><span>Back to top</span></a>
|
||||
</div>
|
||||
|
||||
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
|
||||
<script>!window.jQuery && document.write(unescape('%3Cscript src="js/libs/jquery-1.7.2.min.js"%3E%3C/script%3E'))</script>
|
||||
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.19/jquery-ui.min.js"></script>
|
||||
<script>!window.jQuery && document.write(unescape('%3Cscript src="js/libs/jquery-ui.min.js"%3E%3C/script%3E'))</script>
|
||||
<script src="js/libs/jquery-1.7.2.min.js"></script>
|
||||
<script src="js/libs/jquery-ui.min.js"></script>
|
||||
|
||||
${next.javascriptIncludes()}
|
||||
|
||||
<script src="js/plugins.js"></script>
|
||||
|
||||
@@ -129,6 +129,54 @@ table.display td.center {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
|
||||
* Little hack to handle the two tables on the upcoming page
|
||||
*/
|
||||
table.display_no_select {
|
||||
margin: 20px auto;
|
||||
clear: both;
|
||||
border:1px solid #EEE;
|
||||
width: 100%;
|
||||
|
||||
/* Note Firefox 3.5 and before have a bug with border-collapse
|
||||
* ( https://bugzilla.mozilla.org/show%5Fbug.cgi?id=155955 )
|
||||
* border-spacing: 0; is one possible option. Conditional-css.com is
|
||||
* useful for this kind of thing
|
||||
*
|
||||
* Further note IE 6/7 has problems when calculating widths with border width.
|
||||
* It subtracts one px relative to the other browsers from the first column, and
|
||||
* adds one to the end...
|
||||
*
|
||||
* If you want that effect I'd suggest setting a border-top/left on th/td's and
|
||||
* then filling in the gaps with other borders.
|
||||
*/
|
||||
}
|
||||
|
||||
table.display_no_select thead th {
|
||||
padding: 3px 18px 3px 10px;
|
||||
background-color: white;
|
||||
font-weight: bold;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
table.display_no_select tfoot th {
|
||||
padding: 3px 18px 3px 10px;
|
||||
border-top: 1px solid black;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
table.display_no_select tr.heading2 td {
|
||||
border-bottom: 1px solid #aaa;
|
||||
}
|
||||
|
||||
table.display_no_select td {
|
||||
padding: 8px 10px;
|
||||
font-size: 16px;
|
||||
}
|
||||
table
|
||||
table.display_no_select td.center {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
|
||||
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
|
||||
|
||||
@@ -158,6 +158,8 @@ img.albumArt {
|
||||
float: left;
|
||||
min-height: 100%;
|
||||
min-width: 100%;
|
||||
max-width: 300px;
|
||||
max-height: 300px;
|
||||
position: relative;
|
||||
}
|
||||
.title {
|
||||
@@ -750,12 +752,6 @@ div#searchbar .mini-icon {
|
||||
margin-left: 6px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
a#vipserver {
|
||||
margin-left: 100px;
|
||||
color: blue;
|
||||
size: 95%;
|
||||
font-weight: bold;
|
||||
}
|
||||
.configtable legend {
|
||||
font-size: 16px;
|
||||
font-weight: bold;
|
||||
@@ -1363,6 +1359,12 @@ div#artistheader h3 span {
|
||||
text-align: center;
|
||||
vertical-align: middle;
|
||||
}
|
||||
#upcoming_table td#albumart img,
|
||||
#wanted_table td#albumart img {
|
||||
background: #FFF;
|
||||
border: 1px solid #ccc;
|
||||
padding: 3px;
|
||||
}
|
||||
#upcoming_table th#albumart,
|
||||
#wanted_table th#albumart {
|
||||
min-width: 50px;
|
||||
|
||||
@@ -84,6 +84,8 @@ img {
|
||||
float: left;
|
||||
min-height: 100%;
|
||||
min-width: 100%;
|
||||
max-width: 250px;
|
||||
max-height: 300px;
|
||||
position: relative;
|
||||
}
|
||||
}
|
||||
@@ -1083,6 +1085,15 @@ div#albumheader .albuminfo li span, div#artistheader h3 span {
|
||||
text-align: center;
|
||||
vertical-align: middle;
|
||||
}
|
||||
#upcoming_table, #wanted_table {
|
||||
td#albumart {
|
||||
img {
|
||||
background: #FFF;
|
||||
border: 1px solid #ccc;
|
||||
padding: 3px;
|
||||
}
|
||||
}
|
||||
}
|
||||
#upcoming_table th#albumart, #wanted_table th#albumart {
|
||||
min-width: 50px;
|
||||
text-align: center;
|
||||
|
||||
File diff suppressed because one or more lines are too long
Binary file not shown.
|
Before Width: | Height: | Size: 6.8 KiB After Width: | Height: | Size: 8.8 KiB |
@@ -53,7 +53,7 @@
|
||||
|
||||
%>
|
||||
<tr class="grade${grade}">
|
||||
<td id="albumart"><div id="artistImg"><img class="albumArt"/></div></td>
|
||||
<td id="albumart"><div id="artistImg"><img class="albumArt" alt=""/></div></td>
|
||||
<td id="name"><span title="${artist['ArtistSortName']}"></span><a href="artistPage?ArtistID=${artist['ArtistID']}" title="${artist['ArtistID']}">${artist['ArtistName']}</a></td>
|
||||
<td id="status">${artist['Status']}</td>
|
||||
<td id="album"><span title="${releasedate}"></span><a href="albumPage?AlbumID=${artist['AlbumID']}">${albumdisplay}</a></td>
|
||||
@@ -74,11 +74,10 @@
|
||||
function getArtistArt() {
|
||||
$("table#artist_table tr td#name").each(function(){
|
||||
var id = $(this).children('a').attr('title');
|
||||
var artist = $(this).children('a').text();
|
||||
var image = $(this).parent().find("td#albumart img");
|
||||
if ( !image.hasClass('done') ) {
|
||||
image.addClass('done');
|
||||
getArtistInfo(artist,image,1,id);
|
||||
getThumb(image,id,'artist');
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -114,4 +113,4 @@
|
||||
});
|
||||
</script>
|
||||
|
||||
</%def>
|
||||
</%def>
|
||||
|
||||
@@ -1,153 +1,100 @@
|
||||
function getArtistInfo(name,imgElem,size,artistID) {
|
||||
var apikey = "690e1ed3bc00bc91804cd8f7fe5ed6d4";
|
||||
function getThumb(imgElem,id,type) {
|
||||
|
||||
// Get Data by Artist ID
|
||||
if ( type == 'artist' ) {
|
||||
var thumbURL = "getThumb?ArtistID=" + id;
|
||||
// var imgURL = "getArtwork?ArtistID=" + id;
|
||||
} else {
|
||||
var thumbURL = "getThumb?AlbumID=" + id;
|
||||
// var imgURL = "getArtwork?AlbumID=" + id;
|
||||
}
|
||||
// Get Data from the cache by Artist ID
|
||||
$.ajax({
|
||||
url: "http://ws.audioscrobbler.com/2.0/?method=artist.getInfo&mbid="+ artistID +"&api_key="+ apikey+"&format=json",
|
||||
dataType: "jsonp",
|
||||
url: thumbURL,
|
||||
cache: true,
|
||||
success: function(data){
|
||||
if ( data.artist !== undefined ) {
|
||||
var imageUrl = data.artist.image[size]['#text'];
|
||||
if ( data == "" ) {
|
||||
var imageUrl = "interfaces/default/images/no-cover-artist.png";
|
||||
}
|
||||
if (data.error) {
|
||||
getArtistName();
|
||||
} else {
|
||||
if ( data.artist === undefined || imageUrl == "" || imageUrl == undefined ) {
|
||||
var imageLarge = "#";
|
||||
var imageUrl = "interfaces/default/images/no-cover-artist.png";
|
||||
} else {
|
||||
var artist = data.artist.mbid;
|
||||
var artistBio = data.artist.bio.summary;
|
||||
var imageLarge = data.artist.image[4]['#text'];
|
||||
var imageUrl = data.artist.image[size]['#text'];
|
||||
}
|
||||
var artistBio = artistBio;
|
||||
var image = imgElem;
|
||||
var bio = $('#artistBio');
|
||||
$(image).attr("src",imageUrl).removeAttr("width").removeAttr("height").hide().fadeIn();
|
||||
if ( bio.length > 0 ) $(bio).append(artistBio);
|
||||
$(image).wrap('<a href="'+ imageLarge +'" rel="dialog" title="' + name + '"></a>');
|
||||
else {
|
||||
var imageUrl = data;
|
||||
}
|
||||
$(imgElem).attr("src",imageUrl).hide().fadeIn();
|
||||
// $(imgElem).wrap('<a href="'+ imgURL +'" rel="dialog" title="' + name + '"></a>');
|
||||
}
|
||||
}
|
||||
});
|
||||
// If not found get by Name
|
||||
function getArtistName() {
|
||||
$.ajax({
|
||||
url: "http://ws.audioscrobbler.com/2.0/?method=artist.getInfo&artist="+ name +"&api_key="+ apikey+"&format=json",
|
||||
dataType: "jsonp",
|
||||
success: function(data){
|
||||
if ( data.artist !== undefined ) {
|
||||
var imageUrl = data.artist.image[size]['#text'];
|
||||
}
|
||||
if ( data.artist === undefined || imageUrl == "" ) {
|
||||
var imageLarge = "#";
|
||||
var imageUrl = "interfaces/default/images/no-cover-artist.png";
|
||||
} else {
|
||||
var artist = data.artist.name;
|
||||
var artistBio = data.artist.bio.summary;
|
||||
var imageLarge = data.artist.image[4]['#text'];
|
||||
var imageUrl = data.artist.image[size]['#text'];
|
||||
}
|
||||
var artistBio = artistBio;
|
||||
var image = imgElem;
|
||||
var bio = $('#artistBio');
|
||||
$(image).attr("src",imageUrl).removeAttr("width").removeAttr("height").hide().fadeIn();
|
||||
if ( bio.length > 0 ) $(bio).append(artistBio);
|
||||
$(image).wrap('<a href="'+ imageLarge +'" rel="dialog" title="' + artist + '"></a>');
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function getAlbumInfo(name, album, elem,size) {
|
||||
var apikey = "690e1ed3bc00bc91804cd8f7fe5ed6d4";
|
||||
var dimensions = getOriginalWidthOfImg(this);
|
||||
var cover = $(elem);
|
||||
function getArtwork(imgElem,id,name,type) {
|
||||
|
||||
if ( dimensions <= 1) {
|
||||
// Get Data
|
||||
$.ajax({
|
||||
url: "http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=" + apikey + "&artist="+ name +"&album="+ album +"&format=json&callback=?",
|
||||
dataType: "jsonp",
|
||||
success: function(data){
|
||||
if ( data.artist !== undefined ) {
|
||||
var imageUrl = data.artist.image[size]['#text'];
|
||||
}
|
||||
if (data.album === undefined || imageUrl == "") {
|
||||
if ( elem.width() == 50 ) {
|
||||
var imageUrl = "interfaces/default/images/no-cover-artist.png";
|
||||
} else {
|
||||
var imageUrl = "interfaces/default/images/no-cover-art.png";
|
||||
}
|
||||
} else {
|
||||
var imageUrl = data.album.image[size]['#text'];
|
||||
var imageLarge = data.album.image[3]['#text'];
|
||||
}
|
||||
$(cover).error(function(){
|
||||
if ( elem.width() == 50 ) {
|
||||
var imageUrl = "interfaces/default/images/no-cover-artist.png";
|
||||
} else {
|
||||
var imageUrl = "interfaces/default/images/no-cover-art.png";
|
||||
}
|
||||
$(elem).css("background", "url("+ imageUrl+") center top no-repeat");
|
||||
});
|
||||
if ( imageUrl == "") {
|
||||
if ( elem.width() == 50 ) {
|
||||
var imageUrl = "interfaces/default/images/no-cover-artist.png";
|
||||
} else {
|
||||
var imageUrl = "interfaces/default/images/no-cover-art.png";
|
||||
}
|
||||
$(elem).css("background", "url("+ imageUrl+") center top no-repeat");
|
||||
}
|
||||
$(elem).css("background", "url("+ imageUrl+") center top no-repeat");
|
||||
$(elem).wrap('<a href="'+ imageLarge +'" rel="dialog" title="' + name + '"></a>');
|
||||
}
|
||||
});
|
||||
if ( type == 'artist' ) {
|
||||
var artworkURL = "getArtwork?ArtistID=" + id;
|
||||
} else {
|
||||
var artworkURL = "getArtwork?AlbumID=" + id;
|
||||
}
|
||||
// Get Data from the cache by Artist ID
|
||||
$.ajax({
|
||||
url: artworkURL,
|
||||
cache: true,
|
||||
success: function(data){
|
||||
if ( data == "" || data == undefined ) {
|
||||
var imageUrl = "interfaces/default/images/no-cover-artist.png";
|
||||
}
|
||||
else {
|
||||
var imageUrl = data;
|
||||
}
|
||||
$(imgElem).attr("src",imageUrl).hide().fadeIn();
|
||||
$(imgElem).wrap('<a href="'+ imageUrl +'" rel="dialog" title="' + name + '"></a>');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function getOriginalWidthOfImg(img_element) {
|
||||
var t = new Image();
|
||||
t.src = (img_element.getAttribute ? img_element.getAttribute("src") : false) || img_element.src;
|
||||
return t.width;
|
||||
function getInfo(elem,id,type) {
|
||||
|
||||
if ( type == 'artist' ) {
|
||||
var infoURL = "getInfo?ArtistID=" + id;
|
||||
} else {
|
||||
var infoURL = "getInfo?AlbumID=" + id;
|
||||
}
|
||||
// Get Data from the cache by ID
|
||||
$.ajax({
|
||||
url: infoURL,
|
||||
cache: true,
|
||||
dataType: "json",
|
||||
success: function(data){
|
||||
var summary = data.Summary;
|
||||
$(elem).append(summary);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function replaceEmptyAlbum(elem,name) {
|
||||
var album = $(elem);
|
||||
var artist = name;
|
||||
var albumname;
|
||||
var apikey = "690e1ed3bc00bc91804cd8f7fe5ed6d4";
|
||||
// Loop through every album art and get the albums with no cover
|
||||
$(album).each(function(e){
|
||||
var dimensions = getOriginalWidthOfImg(this);
|
||||
var cover = $(this);
|
||||
var url;
|
||||
albumname = cover.closest("tr").find("#albumname a").text();
|
||||
if ( dimensions <= 1) {
|
||||
url = "http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=" + apikey + "&artist="+ artist +"&album="+ albumname +"&format=json&callback=?";
|
||||
var imageUrl;
|
||||
$.getJSON(url, function(data, response) {
|
||||
if (data.album === undefined) {
|
||||
imageUrl = "interfaces/default/images/no-cover-art.png";
|
||||
} else {
|
||||
imageUrl = data.album.image[3]['#text'];
|
||||
imageLarge = data.album.image[4]['#text'];
|
||||
// If Last.fm don't provide a cover then use standard
|
||||
}
|
||||
$(cover).error(function(){
|
||||
imageUrl = "interfaces/default/images/no-cover-art.png";
|
||||
$(this).hide().attr("src", imageUrl).show();
|
||||
})
|
||||
if ( imageUrl == "") {
|
||||
imageUrl = "interfaces/default/images/no-cover-art.png";
|
||||
$(this).hide().attr("src", imageUrl).show();
|
||||
}
|
||||
$(cover).hide().attr("src", imageUrl).show();
|
||||
$(cover).wrap('<a href="'+ imageLarge +'" rel="dialog" title="' + artist + " - " + albumname + '"></a>');
|
||||
});
|
||||
}
|
||||
});
|
||||
function getImageLinks(elem,id,type) {
|
||||
|
||||
if ( type == 'artist' ) {
|
||||
var infoURL = "getImageLinks?ArtistID=" + id;
|
||||
} else {
|
||||
var infoURL = "getImageLinks?AlbumID=" + id;
|
||||
}
|
||||
// Get Data from the cache by ID
|
||||
$.ajax({
|
||||
url: infoURL,
|
||||
cache: true,
|
||||
dataType: "json",
|
||||
success: function(data){
|
||||
if ( data.thumbnail == "" || data.thumbnail == undefined ) {
|
||||
var thumbnail = "interfaces/default/images/no-cover-artist.png";
|
||||
}
|
||||
else {
|
||||
var thumbnail = data.thumbnail;
|
||||
}
|
||||
if ( data.artwork == "" || data.artwork == undefined ) {
|
||||
var artwork = "interfaces/default/images/no-cover-artist.png";
|
||||
}
|
||||
else {
|
||||
var artwork = data.artwork;
|
||||
}
|
||||
$(elem).attr("src", thumbnail);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function initHeader() {
|
||||
@@ -211,7 +158,8 @@ function initActions() {
|
||||
$("#subhead_menu #menu_link_scan").button({ icons: { primary: "ui-icon-search"} });
|
||||
}
|
||||
|
||||
function refreshSubmenu(url) {
|
||||
function refreshSubmenu() {
|
||||
var url = $(location).attr('href');
|
||||
$("#subhead_container").load(url + " #subhead_menu",function(){
|
||||
initActions();
|
||||
});
|
||||
@@ -361,7 +309,7 @@ function doAjaxCall(url,elem,reload,form) {
|
||||
feedback.fadeOut(function(){
|
||||
feedback.removeClass('success');
|
||||
});
|
||||
if ( reload == true ) refreshSubmenu(url);
|
||||
if ( reload == true ) refreshSubmenu();
|
||||
if ( reload == "table") {
|
||||
console.log('refresh'); refreshTable();
|
||||
}
|
||||
|
||||
@@ -59,8 +59,8 @@
|
||||
%>
|
||||
<tr class="grade${grade}">
|
||||
<td id="select"><input type="checkbox" name="${artist['ArtistID']}" class="checkbox" /></td>
|
||||
<td id="albumart"><div id="artistImg"><img class="albumArt" src="http://ec1.images-amazon.com/images/P/${artist['AlbumID']}.01.MZZZZZZZ.jpg" height="50" width="50"></div></td>
|
||||
<td id="name"><span title="${artist['ArtistSortName']}"></span><a href="artistPage?ArtistID=${artist['ArtistID']}">${artist['ArtistName']}</a></td>
|
||||
<td id="albumart"><div id="artistImg"><img class="albumArt" height="50" width="50"></div></td>
|
||||
<td id="name"><span title="${artist['ArtistSortName']}"></span><a href="artistPage?ArtistID=${artist['ArtistID']}" title="${artist['ArtistID']}">${artist['ArtistName']}</a></td>
|
||||
<td id="status">${artist['Status']}</td>
|
||||
<td id="album"><span title="${releasedate}"></span><a href="albumPage?AlbumID=${artist['AlbumID']}">${albumdisplay}</a></td>
|
||||
</tr>
|
||||
@@ -78,13 +78,19 @@
|
||||
<%def name="javascriptIncludes()">
|
||||
<script src="js/libs/jquery.dataTables.min.js"></script>
|
||||
<script>
|
||||
function getArtistArt() {
|
||||
$("table#artist_table tr td#name").each(function(){
|
||||
var id = $(this).children('a').attr('title');
|
||||
var image = $(this).parent().find("td#albumart img");
|
||||
if ( !image.hasClass('done') ) {
|
||||
image.addClass('done');
|
||||
getThumb(image,id,'artist');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function initThisPage() {
|
||||
$("table#artist_table tr td#name").each(function(){
|
||||
var artist = $(this).children('a').text();
|
||||
var image = $(this).parent().find("td#albumart img");
|
||||
getArtistInfo(artist,image,1);
|
||||
});
|
||||
getArtistArt();
|
||||
$('#artist_table').dataTable({
|
||||
"bDestroy":true,
|
||||
"aoColumns": [
|
||||
@@ -108,4 +114,4 @@
|
||||
initFancybox();
|
||||
});
|
||||
</script>
|
||||
</%def>
|
||||
</%def>
|
||||
|
||||
@@ -26,8 +26,12 @@
|
||||
else:
|
||||
grade = 'Z'
|
||||
%>
|
||||
<tr class="grade${grade}">
|
||||
<td id="albumart"><div id="artistImg"><img class="albumArt" src="http://ec1.images-amazon.com/images/P/${result['uniquename']}.01.MZZZZZZZ.jpg" height="50" width="50"></div></td>
|
||||
<tr class="grade${grade}">
|
||||
%if type == 'album':
|
||||
<td id="albumart"><div id="artistImg"><img title="${result['albumid']}" class="albumArt" height="50" width="50"></div></td>
|
||||
%else:
|
||||
<td id="albumart"><div id="artistImg"><img title="${result['id']}" class="albumArt" height="50" width="50"></div></td>
|
||||
%endif
|
||||
%if type == 'album':
|
||||
<td id="albumname"><a href="${result['albumurl']}">${result['title']}</a></td>
|
||||
%endif
|
||||
@@ -55,20 +59,18 @@
|
||||
<script src="js/libs/jquery.dataTables.min.js"></script>
|
||||
|
||||
<script>
|
||||
function initThisPage() {
|
||||
$("table#searchresults_table tr td#artistname").each(function(){
|
||||
var artist = $(this).children('a').attr('title');
|
||||
var image = $(this).parent().find("td#albumart img");
|
||||
var album = $(this).prev().text();
|
||||
var getId = $(this).children('a').attr('href');
|
||||
var id = getId.substr(30);
|
||||
%if type == 'artist':
|
||||
getArtistInfo(artist,image,1,id);
|
||||
%endif
|
||||
%if type == 'album':
|
||||
getAlbumInfo(artist,album,image,1);
|
||||
%endif
|
||||
function getArt() {
|
||||
$("table#searchresults_table tr td#albumart img").each(function(){
|
||||
var id = $(this).attr('title');
|
||||
var image = $(this);
|
||||
if ( !image.hasClass('done') ) {
|
||||
image.addClass('done');
|
||||
getImageLinks(image,id,"${type}");
|
||||
}
|
||||
});
|
||||
}
|
||||
function initThisPage() {
|
||||
getArt();
|
||||
$('#searchresults_table').dataTable(
|
||||
{
|
||||
"bDestroy": true,
|
||||
@@ -95,4 +97,4 @@
|
||||
initFancybox();
|
||||
});
|
||||
</script>
|
||||
</%def>
|
||||
</%def>
|
||||
|
||||
@@ -40,7 +40,7 @@
|
||||
%for album in wanted:
|
||||
<tr class="gradeZ">
|
||||
<td id="select"><input type="checkbox" name="${album['AlbumID']}" class="checkbox" /></th>
|
||||
<td id="albumart"><img src="http://ec1.images-amazon.com/images/P/${album['AlbumASIN']}.01.MZZZZZZZ.jpg" height="50" width="50"></td>
|
||||
<td id="albumart"><img title="${album['AlbumID']}" height="64" width="64"></td>
|
||||
<td id="artistname">${album['ArtistName']}</td>
|
||||
<td id="albumname"><a href="albumPage?AlbumID=${album['AlbumID']}">${album['AlbumTitle']}</a></td>
|
||||
<td id="reldate">${album['ReleaseDate']}</td>
|
||||
@@ -56,7 +56,7 @@
|
||||
<h1 class="clearfix"><img src="interfaces/default/images/icon_upcoming.png" alt="Upcoming Albums"/>Upcoming Albums</h1>
|
||||
</div>
|
||||
<div class="table_wrapper">
|
||||
<table class="display" id="upcoming_table">
|
||||
<table class="display_no_select" id="upcoming_table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th id="albumart"></th>
|
||||
@@ -70,7 +70,7 @@
|
||||
<tbody>
|
||||
%for album in upcoming:
|
||||
<tr class="gradeZ">
|
||||
<td id="albumart"><img src="http://ec1.images-amazon.com/images/P/${album['AlbumASIN']}.01.MZZZZZZZ.jpg" height="50" width="50"></td>
|
||||
<td id="albumart"><img title="${album['AlbumID']}" height="64" width="64"></td>
|
||||
<td id="artistname">${album['ArtistName']}</td>
|
||||
<td id="albumname"><a href="albumPage?AlbumID=${album['AlbumID']}">${album['AlbumTitle']}</a></td>
|
||||
<td id="reldate">${album['ReleaseDate']}</td>
|
||||
@@ -90,7 +90,19 @@
|
||||
<%def name="javascriptIncludes()">
|
||||
<script src="js/libs/jquery.dataTables.min.js"></script>
|
||||
<script>
|
||||
|
||||
function getAlbumArt() {
|
||||
$("td#albumart img").each(function(){
|
||||
var id = $(this).attr('title');
|
||||
var image = $(this);
|
||||
if ( !image.hasClass('done') ) {
|
||||
image.addClass('done');
|
||||
getThumb(image,id,'album');
|
||||
}
|
||||
});
|
||||
}
|
||||
function initThisPage() {
|
||||
getAlbumArt();
|
||||
$('#wanted_table').dataTable({
|
||||
"bDestroy":true,
|
||||
"bFilter": false,
|
||||
@@ -103,8 +115,5 @@
|
||||
$(document).ready(function() {
|
||||
initThisPage();
|
||||
});
|
||||
$(window).load(function(){
|
||||
replaceEmptyAlbum("table#wanted_table td#albumart img","interfaces/default/images/no-cover-art.png");
|
||||
});
|
||||
</script>
|
||||
</%def>
|
||||
</%def>
|
||||
|
||||
4
data/js/libs/jquery-1.7.2.min.js
vendored
Normal file
4
data/js/libs/jquery-1.7.2.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
121
data/js/libs/jquery-ui.min.js
vendored
Normal file
121
data/js/libs/jquery-ui.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
@@ -1,3 +1,18 @@
|
||||
# This file is part of Headphones.
|
||||
#
|
||||
# Headphones 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.
|
||||
#
|
||||
# Headphones 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 Headphones. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from __future__ import with_statement
|
||||
|
||||
import os, sys, subprocess
|
||||
@@ -325,7 +340,7 @@ def initialize():
|
||||
|
||||
INTERFACE = check_setting_str(CFG, 'General', 'interface', 'default')
|
||||
FOLDER_PERMISSIONS = check_setting_str(CFG, 'General', 'folder_permissions', '0755')
|
||||
|
||||
|
||||
ENCODERFOLDER = check_setting_str(CFG, 'General', 'encoderfolder', '')
|
||||
ENCODER = check_setting_str(CFG, 'General', 'encoder', 'ffmpeg')
|
||||
BITRATE = check_setting_int(CFG, 'General', 'bitrate', 192)
|
||||
@@ -363,7 +378,7 @@ def initialize():
|
||||
# update folder formats in the config & bump up config version
|
||||
if CONFIG_VERSION == '0':
|
||||
from headphones.helpers import replace_all
|
||||
file_values = { 'tracknumber': 'Track', 'title': 'Title','artist' : 'Artist', 'album' : 'Album', 'year' : 'Year' }
|
||||
file_values = { 'tracknumber': 'Track', 'title': 'Title','artist' : 'Artist', 'album' : 'Album', 'year' : 'Year' }
|
||||
folder_values = { 'artist' : 'Artist', 'album':'Album', 'year' : 'Year', 'releasetype' : 'Type', 'first' : 'First', 'lowerfirst' : 'first' }
|
||||
FILE_FORMAT = replace_all(FILE_FORMAT, file_values)
|
||||
FOLDER_FORMAT = replace_all(FOLDER_FORMAT, folder_values)
|
||||
@@ -372,34 +387,34 @@ def initialize():
|
||||
|
||||
if CONFIG_VERSION == '1':
|
||||
|
||||
from headphones.helpers import replace_all
|
||||
from headphones.helpers import replace_all
|
||||
|
||||
file_values = { 'Track': '$Track',
|
||||
'Title': '$Title',
|
||||
'Artist': '$Artist',
|
||||
'Album': '$Album',
|
||||
'Year': '$Year',
|
||||
'track': '$track',
|
||||
'title': '$title',
|
||||
'artist': '$artist',
|
||||
'album': '$album',
|
||||
'year': '$year'
|
||||
}
|
||||
folder_values = { 'Artist': '$Artist',
|
||||
'Album': '$Album',
|
||||
'Year': '$Year',
|
||||
'Type': '$Type',
|
||||
'First': '$First',
|
||||
'artist': '$artist',
|
||||
'album': '$album',
|
||||
'year': '$year',
|
||||
'type': '$type',
|
||||
'first': '$first'
|
||||
}
|
||||
FILE_FORMAT = replace_all(FILE_FORMAT, file_values)
|
||||
FOLDER_FORMAT = replace_all(FOLDER_FORMAT, folder_values)
|
||||
|
||||
CONFIG_VERSION = '2'
|
||||
file_values = { 'Track': '$Track',
|
||||
'Title': '$Title',
|
||||
'Artist': '$Artist',
|
||||
'Album': '$Album',
|
||||
'Year': '$Year',
|
||||
'track': '$track',
|
||||
'title': '$title',
|
||||
'artist': '$artist',
|
||||
'album': '$album',
|
||||
'year': '$year'
|
||||
}
|
||||
folder_values = { 'Artist': '$Artist',
|
||||
'Album': '$Album',
|
||||
'Year': '$Year',
|
||||
'Type': '$Type',
|
||||
'First': '$First',
|
||||
'artist': '$artist',
|
||||
'album': '$album',
|
||||
'year': '$year',
|
||||
'type': '$type',
|
||||
'first': '$first'
|
||||
}
|
||||
FILE_FORMAT = replace_all(FILE_FORMAT, file_values)
|
||||
FOLDER_FORMAT = replace_all(FOLDER_FORMAT, folder_values)
|
||||
|
||||
CONFIG_VERSION = '2'
|
||||
|
||||
if not LOG_DIR:
|
||||
LOG_DIR = os.path.join(DATA_DIR, 'logs')
|
||||
@@ -435,12 +450,12 @@ def initialize():
|
||||
|
||||
# Check for new versions
|
||||
if CHECK_GITHUB_ON_STARTUP:
|
||||
try:
|
||||
LATEST_VERSION = versioncheck.checkGithub()
|
||||
except:
|
||||
LATEST_VERSION = CURRENT_VERSION
|
||||
try:
|
||||
LATEST_VERSION = versioncheck.checkGithub()
|
||||
except:
|
||||
LATEST_VERSION = CURRENT_VERSION
|
||||
else:
|
||||
LATEST_VERSION = CURRENT_VERSION
|
||||
LATEST_VERSION = CURRENT_VERSION
|
||||
|
||||
__INITIALIZED__ = True
|
||||
return True
|
||||
@@ -657,13 +672,13 @@ def dbcheck():
|
||||
|
||||
conn=sqlite3.connect(DB_FILE)
|
||||
c=conn.cursor()
|
||||
c.execute('CREATE TABLE IF NOT EXISTS artists (ArtistID TEXT UNIQUE, ArtistName TEXT, ArtistSortName TEXT, DateAdded TEXT, Status TEXT, IncludeExtras INTEGER, LatestAlbum TEXT, ReleaseDate TEXT, AlbumID TEXT, HaveTracks INTEGER, TotalTracks INTEGER, LastUpdated TEXT)')
|
||||
c.execute('CREATE TABLE IF NOT EXISTS albums (ArtistID TEXT, ArtistName TEXT, AlbumTitle TEXT, AlbumASIN TEXT, ReleaseDate TEXT, DateAdded TEXT, AlbumID TEXT UNIQUE, Status TEXT, Type TEXT)')
|
||||
c.execute('CREATE TABLE IF NOT EXISTS artists (ArtistID TEXT UNIQUE, ArtistName TEXT, ArtistSortName TEXT, DateAdded TEXT, Status TEXT, IncludeExtras INTEGER, LatestAlbum TEXT, ReleaseDate TEXT, AlbumID TEXT, HaveTracks INTEGER, TotalTracks INTEGER, LastUpdated TEXT, ArtworkURL TEXT, ThumbURL TEXT)')
|
||||
c.execute('CREATE TABLE IF NOT EXISTS albums (ArtistID TEXT, ArtistName TEXT, AlbumTitle TEXT, AlbumASIN TEXT, ReleaseDate TEXT, DateAdded TEXT, AlbumID TEXT UNIQUE, Status TEXT, Type TEXT, ArtworkURL TEXT, ThumbURL TEXT)')
|
||||
c.execute('CREATE TABLE IF NOT EXISTS tracks (ArtistID TEXT, ArtistName TEXT, AlbumTitle TEXT, AlbumASIN TEXT, AlbumID TEXT, TrackTitle TEXT, TrackDuration, TrackID TEXT, TrackNumber INTEGER, Location TEXT, BitRate INTEGER, CleanName TEXT, Format TEXT)')
|
||||
c.execute('CREATE TABLE IF NOT EXISTS snatched (AlbumID TEXT, Title TEXT, Size INTEGER, URL TEXT, DateAdded TEXT, Status TEXT, FolderName TEXT)')
|
||||
c.execute('CREATE TABLE IF NOT EXISTS have (ArtistName TEXT, AlbumTitle TEXT, TrackNumber TEXT, TrackTitle TEXT, TrackLength TEXT, BitRate TEXT, Genre TEXT, Date TEXT, TrackID TEXT, Location TEXT, CleanName TEXT, Format TEXT)')
|
||||
c.execute('CREATE TABLE IF NOT EXISTS lastfmcloud (ArtistName TEXT, ArtistID TEXT, Count INTEGER)')
|
||||
c.execute('CREATE TABLE IF NOT EXISTS descriptions (ReleaseGroupID TEXT, ReleaseID TEXT, Summary TEXT, Content TEXT)')
|
||||
c.execute('CREATE TABLE IF NOT EXISTS descriptions (ArtistID TEXT, ReleaseGroupID TEXT, ReleaseID TEXT, Summary TEXT, Content TEXT, LastUpdated TEXT)')
|
||||
c.execute('CREATE TABLE IF NOT EXISTS releases (ReleaseID TEXT, ReleaseGroupID TEXT, UNIQUE(ReleaseID, ReleaseGroupID))')
|
||||
c.execute('CREATE INDEX IF NOT EXISTS tracks_albumid ON tracks(AlbumID ASC)')
|
||||
c.execute('CREATE INDEX IF NOT EXISTS album_artistid_reldate ON albums(ArtistID ASC, ReleaseDate DESC)')
|
||||
@@ -752,7 +767,37 @@ def dbcheck():
|
||||
try:
|
||||
c.execute('SELECT LastUpdated from artists')
|
||||
except sqlite3.OperationalError:
|
||||
c.execute('ALTER TABLE artists ADD COLUMN LastUpdated TEXT DEFAULT NULL')
|
||||
c.execute('ALTER TABLE artists ADD COLUMN LastUpdated TEXT DEFAULT NULL')
|
||||
|
||||
try:
|
||||
c.execute('SELECT ArtworkURL from artists')
|
||||
except sqlite3.OperationalError:
|
||||
c.execute('ALTER TABLE artists ADD COLUMN ArtworkURL TEXT DEFAULT NULL')
|
||||
|
||||
try:
|
||||
c.execute('SELECT ArtworkURL from albums')
|
||||
except sqlite3.OperationalError:
|
||||
c.execute('ALTER TABLE albums ADD COLUMN ArtworkURL TEXT DEFAULT NULL')
|
||||
|
||||
try:
|
||||
c.execute('SELECT ThumbURL from artists')
|
||||
except sqlite3.OperationalError:
|
||||
c.execute('ALTER TABLE artists ADD COLUMN ThumbURL TEXT DEFAULT NULL')
|
||||
|
||||
try:
|
||||
c.execute('SELECT ThumbURL from albums')
|
||||
except sqlite3.OperationalError:
|
||||
c.execute('ALTER TABLE albums ADD COLUMN ThumbURL TEXT DEFAULT NULL')
|
||||
|
||||
try:
|
||||
c.execute('SELECT ArtistID from descriptions')
|
||||
except sqlite3.OperationalError:
|
||||
c.execute('ALTER TABLE descriptions ADD COLUMN ArtistID TEXT DEFAULT NULL')
|
||||
|
||||
try:
|
||||
c.execute('SELECT LastUpdated from descriptions')
|
||||
except sqlite3.OperationalError:
|
||||
c.execute('ALTER TABLE descriptions ADD COLUMN LastUpdated TEXT DEFAULT NULL')
|
||||
|
||||
conn.commit()
|
||||
c.close()
|
||||
@@ -766,9 +811,9 @@ def shutdown(restart=False, update=False):
|
||||
config_write()
|
||||
|
||||
if not restart and not update:
|
||||
logger.info('Headphones is shutting down...')
|
||||
logger.info('Headphones is shutting down...')
|
||||
if update:
|
||||
logger.info('Headphones is updating...')
|
||||
logger.info('Headphones is updating...')
|
||||
try:
|
||||
versioncheck.update()
|
||||
except Exception, e:
|
||||
@@ -779,7 +824,7 @@ def shutdown(restart=False, update=False):
|
||||
os.remove(PIDFILE)
|
||||
|
||||
if restart:
|
||||
logger.info('Headphones is restarting...')
|
||||
logger.info('Headphones is restarting...')
|
||||
popen_list = [sys.executable, FULL_PATH]
|
||||
popen_list += ARGS
|
||||
if '--nolaunch' not in popen_list:
|
||||
|
||||
@@ -1,10 +1,25 @@
|
||||
# This file is part of Headphones.
|
||||
#
|
||||
# Headphones 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.
|
||||
#
|
||||
# Headphones 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 Headphones. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from headphones import db
|
||||
|
||||
def getAlbumArt(albumid):
|
||||
|
||||
myDB = db.DBConnection()
|
||||
asin = myDB.action('SELECT AlbumASIN from albums WHERE AlbumID=?', [albumid]).fetchone()[0]
|
||||
|
||||
url = 'http://ec1.images-amazon.com/images/P/%s.01.LZZZZZZZ.jpg' % asin
|
||||
|
||||
return url
|
||||
myDB = db.DBConnection()
|
||||
asin = myDB.action('SELECT AlbumASIN from albums WHERE AlbumID=?', [albumid]).fetchone()[0]
|
||||
|
||||
url = 'http://ec1.images-amazon.com/images/P/%s.01.LZZZZZZZ.jpg' % asin
|
||||
|
||||
return url
|
||||
|
||||
@@ -1,301 +1,376 @@
|
||||
# This file is part of Headphones.
|
||||
#
|
||||
# Headphones 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.
|
||||
#
|
||||
# Headphones 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 Headphones. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import headphones
|
||||
|
||||
from headphones import db, mb, importer, searcher, postprocessor, versioncheck, logger
|
||||
from headphones import db, mb, importer, searcher, cache, postprocessor, versioncheck, logger
|
||||
|
||||
import lib.simplejson as simplejson
|
||||
from xml.dom.minidom import Document
|
||||
import copy
|
||||
|
||||
cmd_list = [ 'getIndex', 'getArtist', 'getAlbum', 'getUpcoming', 'getWanted', 'getSimilar', 'getHistory', 'getLogs',
|
||||
'findArtist', 'findAlbum', 'addArtist', 'delArtist', 'pauseArtist', 'resumeArtist', 'refreshArtist',
|
||||
'queueAlbum', 'unqueueAlbum', 'forceSearch', 'forceProcess', 'getVersion', 'checkGithub',
|
||||
'shutdown', 'restart', 'update', ]
|
||||
'findArtist', 'findAlbum', 'addArtist', 'delArtist', 'pauseArtist', 'resumeArtist', 'refreshArtist',
|
||||
'queueAlbum', 'unqueueAlbum', 'forceSearch', 'forceProcess', 'getVersion', 'checkGithub',
|
||||
'shutdown', 'restart', 'update', 'getArtistArt', 'getAlbumArt', 'getArtistInfo', 'getAlbumInfo', 'getArtistThumb', 'getAlbumThumb']
|
||||
|
||||
class Api(object):
|
||||
|
||||
def __init__(self):
|
||||
|
||||
self.apikey = None
|
||||
self.cmd = None
|
||||
self.id = None
|
||||
|
||||
self.kwargs = None
|
||||
def __init__(self):
|
||||
|
||||
self.apikey = None
|
||||
self.cmd = None
|
||||
self.id = None
|
||||
|
||||
self.kwargs = None
|
||||
|
||||
self.data = None
|
||||
self.data = None
|
||||
|
||||
self.callback = None
|
||||
self.callback = None
|
||||
|
||||
|
||||
def checkParams(self,*args,**kwargs):
|
||||
|
||||
if not headphones.API_ENABLED:
|
||||
self.data = 'API not enabled'
|
||||
return
|
||||
if not headphones.API_KEY:
|
||||
self.data = 'API key not generated'
|
||||
return
|
||||
if len(headphones.API_KEY) != 32:
|
||||
self.data = 'API key not generated correctly'
|
||||
return
|
||||
|
||||
if 'apikey' not in kwargs:
|
||||
self.data = 'Missing api key'
|
||||
return
|
||||
|
||||
if kwargs['apikey'] != headphones.API_KEY:
|
||||
self.data = 'Incorrect API key'
|
||||
return
|
||||
else:
|
||||
self.apikey = kwargs.pop('apikey')
|
||||
|
||||
if 'cmd' not in kwargs:
|
||||
self.data = 'Missing parameter: cmd'
|
||||
return
|
||||
|
||||
if kwargs['cmd'] not in cmd_list:
|
||||
self.data = 'Unknown command: %s' % kwargs['cmd']
|
||||
return
|
||||
else:
|
||||
self.cmd = kwargs.pop('cmd')
|
||||
|
||||
self.kwargs = kwargs
|
||||
self.data = 'OK'
|
||||
|
||||
def checkParams(self,*args,**kwargs):
|
||||
|
||||
if not headphones.API_ENABLED:
|
||||
self.data = 'API not enabled'
|
||||
return
|
||||
if not headphones.API_KEY:
|
||||
self.data = 'API key not generated'
|
||||
return
|
||||
if len(headphones.API_KEY) != 32:
|
||||
self.data = 'API key not generated correctly'
|
||||
return
|
||||
|
||||
if 'apikey' not in kwargs:
|
||||
self.data = 'Missing api key'
|
||||
return
|
||||
|
||||
if kwargs['apikey'] != headphones.API_KEY:
|
||||
self.data = 'Incorrect API key'
|
||||
return
|
||||
else:
|
||||
self.apikey = kwargs.pop('apikey')
|
||||
|
||||
if 'cmd' not in kwargs:
|
||||
self.data = 'Missing parameter: cmd'
|
||||
return
|
||||
|
||||
if kwargs['cmd'] not in cmd_list:
|
||||
self.data = 'Unknown command: %s' % kwargs['cmd']
|
||||
return
|
||||
else:
|
||||
self.cmd = kwargs.pop('cmd')
|
||||
|
||||
self.kwargs = kwargs
|
||||
self.data = 'OK'
|
||||
|
||||
def fetchData(self):
|
||||
|
||||
if self.data == 'OK':
|
||||
logger.info('Recieved API command: ' + self.cmd)
|
||||
methodToCall = getattr(self, "_" + self.cmd)
|
||||
result = methodToCall(**self.kwargs)
|
||||
if 'callback' not in self.kwargs:
|
||||
if type(self.data) == type(''):
|
||||
return self.data
|
||||
else:
|
||||
return simplejson.dumps(self.data)
|
||||
else:
|
||||
self.callback = self.kwargs['callback']
|
||||
self.data = simplejson.dumps(self.data)
|
||||
self.data = self.callback + '(' + self.data + ');'
|
||||
return self.data
|
||||
else:
|
||||
return self.data
|
||||
|
||||
def _dic_from_query(self,query):
|
||||
|
||||
myDB = db.DBConnection()
|
||||
rows = myDB.select(query)
|
||||
|
||||
rows_as_dic = []
|
||||
|
||||
for row in rows:
|
||||
row_as_dic = dict(zip(row.keys(), row))
|
||||
rows_as_dic.append(row_as_dic)
|
||||
|
||||
return rows_as_dic
|
||||
|
||||
def _getIndex(self, **kwargs):
|
||||
|
||||
self.data = self._dic_from_query('SELECT * from artists order by ArtistSortName COLLATE NOCASE')
|
||||
return
|
||||
|
||||
def _getArtist(self, **kwargs):
|
||||
|
||||
if 'id' not in kwargs:
|
||||
self.data = 'Missing parameter: id'
|
||||
return
|
||||
else:
|
||||
self.id = kwargs['id']
|
||||
|
||||
artist = self._dic_from_query('SELECT * from artists WHERE ArtistID="' + self.id + '"')
|
||||
albums = self._dic_from_query('SELECT * from albums WHERE ArtistID="' + self.id + '" order by ReleaseDate DESC')
|
||||
|
||||
self.data = { 'artist': artist, 'albums': albums }
|
||||
return
|
||||
|
||||
def _getAlbum(self, **kwargs):
|
||||
|
||||
if 'id' not in kwargs:
|
||||
self.data = 'Missing parameter: id'
|
||||
return
|
||||
else:
|
||||
self.id = kwargs['id']
|
||||
|
||||
album = self._dic_from_query('SELECT * from albums WHERE AlbumID="' + self.id + '"')
|
||||
tracks = self._dic_from_query('SELECT * from tracks WHERE AlbumID="' + self.id + '"')
|
||||
description = self._dic_from_query('SELECT * from descriptions WHERE ReleaseGroupID="' + self.id + '"')
|
||||
|
||||
self.data = { 'album' : album, 'tracks' : tracks, 'description' : description }
|
||||
return
|
||||
|
||||
def _getHistory(self, **kwargs):
|
||||
self.data = self._dic_from_query('SELECT * from snatched order by DateAdded DESC')
|
||||
return
|
||||
|
||||
def _getUpcoming(self, **kwargs):
|
||||
self.data = self._dic_from_query("SELECT * from albums WHERE ReleaseDate > date('now') order by ReleaseDate DESC")
|
||||
return
|
||||
|
||||
def _getWanted(self, **kwargs):
|
||||
self.data = self._dic_from_query("SELECT * from albums WHERE Status='Wanted'")
|
||||
return
|
||||
|
||||
def _getSimilar(self, **kwargs):
|
||||
self.data = self._dic_from_query('SELECT * from lastfmcloud')
|
||||
return
|
||||
|
||||
def _getLogs(self, **kwargs):
|
||||
pass
|
||||
|
||||
def _findArtist(self, **kwargs):
|
||||
if 'name' not in kwargs:
|
||||
self.data = 'Missing parameter: name'
|
||||
return
|
||||
if 'limit' in kwargs:
|
||||
limit = kwargs['limit']
|
||||
else:
|
||||
limit=50
|
||||
|
||||
self.data = mb.findArtist(kwargs['name'], limit)
|
||||
def fetchData(self):
|
||||
|
||||
if self.data == 'OK':
|
||||
logger.info('Recieved API command: ' + self.cmd)
|
||||
methodToCall = getattr(self, "_" + self.cmd)
|
||||
result = methodToCall(**self.kwargs)
|
||||
if 'callback' not in self.kwargs:
|
||||
if type(self.data) == type(''):
|
||||
return self.data
|
||||
else:
|
||||
return simplejson.dumps(self.data)
|
||||
else:
|
||||
self.callback = self.kwargs['callback']
|
||||
self.data = simplejson.dumps(self.data)
|
||||
self.data = self.callback + '(' + self.data + ');'
|
||||
return self.data
|
||||
else:
|
||||
return self.data
|
||||
|
||||
def _dic_from_query(self,query):
|
||||
|
||||
myDB = db.DBConnection()
|
||||
rows = myDB.select(query)
|
||||
|
||||
rows_as_dic = []
|
||||
|
||||
for row in rows:
|
||||
row_as_dic = dict(zip(row.keys(), row))
|
||||
rows_as_dic.append(row_as_dic)
|
||||
|
||||
return rows_as_dic
|
||||
|
||||
def _getIndex(self, **kwargs):
|
||||
|
||||
self.data = self._dic_from_query('SELECT * from artists order by ArtistSortName COLLATE NOCASE')
|
||||
return
|
||||
|
||||
def _getArtist(self, **kwargs):
|
||||
|
||||
if 'id' not in kwargs:
|
||||
self.data = 'Missing parameter: id'
|
||||
return
|
||||
else:
|
||||
self.id = kwargs['id']
|
||||
|
||||
artist = self._dic_from_query('SELECT * from artists WHERE ArtistID="' + self.id + '"')
|
||||
albums = self._dic_from_query('SELECT * from albums WHERE ArtistID="' + self.id + '" order by ReleaseDate DESC')
|
||||
|
||||
self.data = { 'artist': artist, 'albums': albums }
|
||||
return
|
||||
|
||||
def _getAlbum(self, **kwargs):
|
||||
|
||||
if 'id' not in kwargs:
|
||||
self.data = 'Missing parameter: id'
|
||||
return
|
||||
else:
|
||||
self.id = kwargs['id']
|
||||
|
||||
album = self._dic_from_query('SELECT * from albums WHERE AlbumID="' + self.id + '"')
|
||||
tracks = self._dic_from_query('SELECT * from tracks WHERE AlbumID="' + self.id + '"')
|
||||
description = self._dic_from_query('SELECT * from descriptions WHERE ReleaseGroupID="' + self.id + '"')
|
||||
|
||||
self.data = { 'album' : album, 'tracks' : tracks, 'description' : description }
|
||||
return
|
||||
|
||||
def _getHistory(self, **kwargs):
|
||||
self.data = self._dic_from_query('SELECT * from snatched order by DateAdded DESC')
|
||||
return
|
||||
|
||||
def _getUpcoming(self, **kwargs):
|
||||
self.data = self._dic_from_query("SELECT * from albums WHERE ReleaseDate > date('now') order by ReleaseDate DESC")
|
||||
return
|
||||
|
||||
def _getWanted(self, **kwargs):
|
||||
self.data = self._dic_from_query("SELECT * from albums WHERE Status='Wanted'")
|
||||
return
|
||||
|
||||
def _getSimilar(self, **kwargs):
|
||||
self.data = self._dic_from_query('SELECT * from lastfmcloud')
|
||||
return
|
||||
|
||||
def _getLogs(self, **kwargs):
|
||||
pass
|
||||
|
||||
def _findArtist(self, **kwargs):
|
||||
if 'name' not in kwargs:
|
||||
self.data = 'Missing parameter: name'
|
||||
return
|
||||
if 'limit' in kwargs:
|
||||
limit = kwargs['limit']
|
||||
else:
|
||||
limit=50
|
||||
|
||||
self.data = mb.findArtist(kwargs['name'], limit)
|
||||
|
||||
def _findAlbum(self, **kwargs):
|
||||
if 'name' not in kwargs:
|
||||
self.data = 'Missing parameter: name'
|
||||
return
|
||||
if 'limit' in kwargs:
|
||||
limit = kwargs['limit']
|
||||
else:
|
||||
limit=50
|
||||
|
||||
self.data = mb.findRelease(kwargs['name'], limit)
|
||||
|
||||
def _addArtist(self, **kwargs):
|
||||
if 'id' not in kwargs:
|
||||
self.data = 'Missing parameter: id'
|
||||
return
|
||||
else:
|
||||
self.id = kwargs['id']
|
||||
|
||||
try:
|
||||
importer.addArtisttoDB(self.id)
|
||||
except Exception, e:
|
||||
self.data = e
|
||||
|
||||
return
|
||||
|
||||
def _delArtist(self, **kwargs):
|
||||
if 'id' not in kwargs:
|
||||
self.data = 'Missing parameter: id'
|
||||
return
|
||||
else:
|
||||
self.id = kwargs['id']
|
||||
|
||||
myDB = db.DBConnection()
|
||||
myDB.action('DELETE from artists WHERE ArtistID="' + self.id + '"')
|
||||
myDB.action('DELETE from albums WHERE ArtistID="' + self.id + '"')
|
||||
myDB.action('DELETE from tracks WHERE ArtistID="' + self.id + '"')
|
||||
|
||||
def _pauseArtist(self, **kwargs):
|
||||
if 'id' not in kwargs:
|
||||
self.data = 'Missing parameter: id'
|
||||
return
|
||||
else:
|
||||
self.id = kwargs['id']
|
||||
|
||||
myDB = db.DBConnection()
|
||||
controlValueDict = {'ArtistID': self.id}
|
||||
newValueDict = {'Status': 'Paused'}
|
||||
myDB.upsert("artists", newValueDict, controlValueDict)
|
||||
|
||||
def _resumeArtist(self, **kwargs):
|
||||
if 'id' not in kwargs:
|
||||
self.data = 'Missing parameter: id'
|
||||
return
|
||||
else:
|
||||
self.id = kwargs['id']
|
||||
|
||||
myDB = db.DBConnection()
|
||||
controlValueDict = {'ArtistID': self.id}
|
||||
newValueDict = {'Status': 'Active'}
|
||||
myDB.upsert("artists", newValueDict, controlValueDict)
|
||||
|
||||
def _refreshArtist(self, **kwargs):
|
||||
if 'id' not in kwargs:
|
||||
self.data = 'Missing parameter: id'
|
||||
return
|
||||
else:
|
||||
self.id = kwargs['id']
|
||||
|
||||
try:
|
||||
importer.addArtisttoDB(self.id)
|
||||
except Exception, e:
|
||||
self.data = e
|
||||
|
||||
return
|
||||
|
||||
def _queueAlbum(self, **kwargs):
|
||||
|
||||
if 'id' not in kwargs:
|
||||
self.data = 'Missing parameter: id'
|
||||
return
|
||||
else:
|
||||
self.id = kwargs['id']
|
||||
|
||||
if 'new' in kwargs:
|
||||
new = kwargs['new']
|
||||
else:
|
||||
new = False
|
||||
|
||||
if 'lossless' in kwargs:
|
||||
lossless = kwargs['lossless']
|
||||
else:
|
||||
lossless = False
|
||||
|
||||
myDB = db.DBConnection()
|
||||
controlValueDict = {'AlbumID': self.id}
|
||||
if lossless:
|
||||
newValueDict = {'Status': 'Wanted Lossless'}
|
||||
else:
|
||||
newValueDict = {'Status': 'Wanted'}
|
||||
myDB.upsert("albums", newValueDict, controlValueDict)
|
||||
searcher.searchforalbum(self.id, new)
|
||||
|
||||
def _unqueueAlbum(self, **kwargs):
|
||||
|
||||
if 'id' not in kwargs:
|
||||
self.data = 'Missing parameter: id'
|
||||
return
|
||||
else:
|
||||
self.id = kwargs['id']
|
||||
|
||||
myDB = db.DBConnection()
|
||||
controlValueDict = {'AlbumID': self.id}
|
||||
newValueDict = {'Status': 'Skipped'}
|
||||
myDB.upsert("albums", newValueDict, controlValueDict)
|
||||
|
||||
def _forceSearch(self, **kwargs):
|
||||
searcher.searchforalbum()
|
||||
|
||||
def _forceProcess(self, **kwargs):
|
||||
postprocessor.forcePostProcess()
|
||||
|
||||
def _getVersion(self, **kwargs):
|
||||
self.data = {
|
||||
'git_path' : headphones.GIT_PATH,
|
||||
'install_type' : headphones.INSTALL_TYPE,
|
||||
'current_version' : headphones.CURRENT_VERSION,
|
||||
'latest_version' : headphones.LATEST_VERSION,
|
||||
'commits_behind' : headphones.COMMITS_BEHIND,
|
||||
}
|
||||
|
||||
def _checkGithub(self, **kwargs):
|
||||
versioncheck.checkGithub()
|
||||
self._getVersion()
|
||||
|
||||
def _shutdown(self, **kwargs):
|
||||
headphones.SIGNAL = 'shutdown'
|
||||
|
||||
def _restart(self, **kwargs):
|
||||
headphones.SIGNAL = 'restart'
|
||||
|
||||
def _update(self, **kwargs):
|
||||
headphones.SIGNAL = 'update'
|
||||
def _findAlbum(self, **kwargs):
|
||||
if 'name' not in kwargs:
|
||||
self.data = 'Missing parameter: name'
|
||||
return
|
||||
if 'limit' in kwargs:
|
||||
limit = kwargs['limit']
|
||||
else:
|
||||
limit=50
|
||||
|
||||
self.data = mb.findRelease(kwargs['name'], limit)
|
||||
|
||||
def _addArtist(self, **kwargs):
|
||||
if 'id' not in kwargs:
|
||||
self.data = 'Missing parameter: id'
|
||||
return
|
||||
else:
|
||||
self.id = kwargs['id']
|
||||
|
||||
try:
|
||||
importer.addArtisttoDB(self.id)
|
||||
except Exception, e:
|
||||
self.data = e
|
||||
|
||||
return
|
||||
|
||||
def _delArtist(self, **kwargs):
|
||||
if 'id' not in kwargs:
|
||||
self.data = 'Missing parameter: id'
|
||||
return
|
||||
else:
|
||||
self.id = kwargs['id']
|
||||
|
||||
myDB = db.DBConnection()
|
||||
myDB.action('DELETE from artists WHERE ArtistID="' + self.id + '"')
|
||||
myDB.action('DELETE from albums WHERE ArtistID="' + self.id + '"')
|
||||
myDB.action('DELETE from tracks WHERE ArtistID="' + self.id + '"')
|
||||
|
||||
def _pauseArtist(self, **kwargs):
|
||||
if 'id' not in kwargs:
|
||||
self.data = 'Missing parameter: id'
|
||||
return
|
||||
else:
|
||||
self.id = kwargs['id']
|
||||
|
||||
myDB = db.DBConnection()
|
||||
controlValueDict = {'ArtistID': self.id}
|
||||
newValueDict = {'Status': 'Paused'}
|
||||
myDB.upsert("artists", newValueDict, controlValueDict)
|
||||
|
||||
def _resumeArtist(self, **kwargs):
|
||||
if 'id' not in kwargs:
|
||||
self.data = 'Missing parameter: id'
|
||||
return
|
||||
else:
|
||||
self.id = kwargs['id']
|
||||
|
||||
myDB = db.DBConnection()
|
||||
controlValueDict = {'ArtistID': self.id}
|
||||
newValueDict = {'Status': 'Active'}
|
||||
myDB.upsert("artists", newValueDict, controlValueDict)
|
||||
|
||||
def _refreshArtist(self, **kwargs):
|
||||
if 'id' not in kwargs:
|
||||
self.data = 'Missing parameter: id'
|
||||
return
|
||||
else:
|
||||
self.id = kwargs['id']
|
||||
|
||||
try:
|
||||
importer.addArtisttoDB(self.id)
|
||||
except Exception, e:
|
||||
self.data = e
|
||||
|
||||
return
|
||||
|
||||
def _queueAlbum(self, **kwargs):
|
||||
|
||||
if 'id' not in kwargs:
|
||||
self.data = 'Missing parameter: id'
|
||||
return
|
||||
else:
|
||||
self.id = kwargs['id']
|
||||
|
||||
if 'new' in kwargs:
|
||||
new = kwargs['new']
|
||||
else:
|
||||
new = False
|
||||
|
||||
if 'lossless' in kwargs:
|
||||
lossless = kwargs['lossless']
|
||||
else:
|
||||
lossless = False
|
||||
|
||||
myDB = db.DBConnection()
|
||||
controlValueDict = {'AlbumID': self.id}
|
||||
if lossless:
|
||||
newValueDict = {'Status': 'Wanted Lossless'}
|
||||
else:
|
||||
newValueDict = {'Status': 'Wanted'}
|
||||
myDB.upsert("albums", newValueDict, controlValueDict)
|
||||
searcher.searchforalbum(self.id, new)
|
||||
|
||||
def _unqueueAlbum(self, **kwargs):
|
||||
|
||||
if 'id' not in kwargs:
|
||||
self.data = 'Missing parameter: id'
|
||||
return
|
||||
else:
|
||||
self.id = kwargs['id']
|
||||
|
||||
myDB = db.DBConnection()
|
||||
controlValueDict = {'AlbumID': self.id}
|
||||
newValueDict = {'Status': 'Skipped'}
|
||||
myDB.upsert("albums", newValueDict, controlValueDict)
|
||||
|
||||
def _forceSearch(self, **kwargs):
|
||||
searcher.searchforalbum()
|
||||
|
||||
def _forceProcess(self, **kwargs):
|
||||
postprocessor.forcePostProcess()
|
||||
|
||||
def _getVersion(self, **kwargs):
|
||||
self.data = {
|
||||
'git_path' : headphones.GIT_PATH,
|
||||
'install_type' : headphones.INSTALL_TYPE,
|
||||
'current_version' : headphones.CURRENT_VERSION,
|
||||
'latest_version' : headphones.LATEST_VERSION,
|
||||
'commits_behind' : headphones.COMMITS_BEHIND,
|
||||
}
|
||||
|
||||
def _checkGithub(self, **kwargs):
|
||||
versioncheck.checkGithub()
|
||||
self._getVersion()
|
||||
|
||||
def _shutdown(self, **kwargs):
|
||||
headphones.SIGNAL = 'shutdown'
|
||||
|
||||
def _restart(self, **kwargs):
|
||||
headphones.SIGNAL = 'restart'
|
||||
|
||||
def _update(self, **kwargs):
|
||||
headphones.SIGNAL = 'update'
|
||||
|
||||
def _getArtistArt(self, **kwargs):
|
||||
|
||||
if 'id' not in kwargs:
|
||||
self.data = 'Missing parameter: id'
|
||||
return
|
||||
else:
|
||||
self.id = kwargs['id']
|
||||
|
||||
self.data = cache.getArtwork(ArtistID=self.id)
|
||||
|
||||
def _getAlbumArt(self, **kwargs):
|
||||
|
||||
if 'id' not in kwargs:
|
||||
self.data = 'Missing parameter: id'
|
||||
return
|
||||
else:
|
||||
self.id = kwargs['id']
|
||||
|
||||
self.data = cache.getArtwork(AlbumID=self.id)
|
||||
|
||||
def _getArtistInfo(self, **kwargs):
|
||||
|
||||
if 'id' not in kwargs:
|
||||
self.data = 'Missing parameter: id'
|
||||
return
|
||||
else:
|
||||
self.id = kwargs['id']
|
||||
|
||||
self.data = cache.getInfo(ArtistID=self.id)
|
||||
|
||||
def _getAlbumInfo(self, **kwargs):
|
||||
|
||||
if 'id' not in kwargs:
|
||||
self.data = 'Missing parameter: id'
|
||||
return
|
||||
else:
|
||||
self.id = kwargs['id']
|
||||
|
||||
self.data = cache.getInfo(AlbumID=self.id)
|
||||
|
||||
def _getArtistThumb(self, **kwargs):
|
||||
|
||||
if 'id' not in kwargs:
|
||||
self.data = 'Missing parameter: id'
|
||||
return
|
||||
else:
|
||||
self.id = kwargs['id']
|
||||
|
||||
self.data = cache.getThumb(ArtistID=self.id)
|
||||
|
||||
def _getAlbumThumb(self, **kwargs):
|
||||
|
||||
if 'id' not in kwargs:
|
||||
self.data = 'Missing parameter: id'
|
||||
return
|
||||
else:
|
||||
self.id = kwargs['id']
|
||||
|
||||
self.data = cache.getThumb(AlbumID=self.id)
|
||||
|
||||
520
headphones/cache.py
Normal file
520
headphones/cache.py
Normal file
@@ -0,0 +1,520 @@
|
||||
# This file is part of Headphones.
|
||||
#
|
||||
# Headphones 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.
|
||||
#
|
||||
# Headphones 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 Headphones. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import os
|
||||
import glob, urllib, urllib2
|
||||
|
||||
import lib.simplejson as simplejson
|
||||
|
||||
import headphones
|
||||
from headphones import db, helpers, logger
|
||||
|
||||
lastfm_apikey = "690e1ed3bc00bc91804cd8f7fe5ed6d4"
|
||||
|
||||
class Cache(object):
|
||||
"""
|
||||
This class deals with getting, storing and serving up artwork (album
|
||||
art, artist images, etc) and info/descriptions (album info, artist descrptions)
|
||||
to and from the cache folder. This can be called from within a web interface,
|
||||
for example, using the helper functions getInfo(id) and getArtwork(id), to utilize the cached
|
||||
images rather than having to retrieve them every time the page is reloaded.
|
||||
|
||||
So you can call cache.getArtwork(id) which will return an absolute path
|
||||
to the image file on the local machine, or if the cache directory
|
||||
doesn't exist, or can not be written to, it will return a url to the image.
|
||||
|
||||
Call cache.getInfo(id) to grab the artist/album info; will return the text description
|
||||
|
||||
The basic format for art in the cache is <musicbrainzid>.<date>.<ext>
|
||||
and for info it is <musicbrainzid>.<date>.txt
|
||||
"""
|
||||
|
||||
path_to_art_cache = os.path.join(headphones.CACHE_DIR, 'artwork')
|
||||
|
||||
id = None
|
||||
id_type = None # 'artist' or 'album' - set automatically depending on whether ArtistID or AlbumID is passed
|
||||
query_type = None # 'artwork','thumb' or 'info' - set automatically
|
||||
|
||||
artwork_files = []
|
||||
thumb_files = []
|
||||
|
||||
artwork_errors = False
|
||||
artwork_url = None
|
||||
|
||||
thumb_errors = False
|
||||
thumb_url = None
|
||||
|
||||
info_summary = None
|
||||
info_content = None
|
||||
|
||||
def __init__(self):
|
||||
|
||||
pass
|
||||
|
||||
def _exists(self, type):
|
||||
|
||||
self.artwork_files = glob.glob(os.path.join(self.path_to_art_cache, self.id + '*'))
|
||||
self.thumb_files = glob.glob(os.path.join(self.path_to_art_cache, 'T_' + self.id + '*'))
|
||||
|
||||
if type == 'artwork':
|
||||
|
||||
if self.artwork_files:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
elif type == 'thumb':
|
||||
|
||||
if self.thumb_files:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
def _get_age(self, date):
|
||||
# There's probably a better way to do this
|
||||
split_date = date.split('-')
|
||||
days_old = int(split_date[0])*365 + int(split_date[1])*30 + int(split_date[2])
|
||||
|
||||
return days_old
|
||||
|
||||
|
||||
def _is_current(self, filename=None, date=None):
|
||||
|
||||
if filename:
|
||||
base_filename = os.path.basename(filename)
|
||||
date = base_filename.split('.')[1]
|
||||
|
||||
# Calculate how old the cached file is based on todays date & file date stamp
|
||||
# helpers.today() returns todays date in yyyy-mm-dd format
|
||||
if self._get_age(helpers.today()) - self._get_age(date) < 30:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
def _get_thumb_url(self, data):
|
||||
|
||||
thumb_url = None
|
||||
|
||||
try:
|
||||
images = data[self.id_type]['image']
|
||||
except KeyError:
|
||||
return None
|
||||
|
||||
for image in images:
|
||||
if image['size'] == 'medium':
|
||||
thumb_url = image['#text']
|
||||
break
|
||||
|
||||
return thumb_url
|
||||
|
||||
def get_artwork_from_cache(self, ArtistID=None, AlbumID=None):
|
||||
'''
|
||||
Pass a musicbrainz id to this function (either ArtistID or AlbumID)
|
||||
'''
|
||||
|
||||
self.query_type = 'artwork'
|
||||
|
||||
if ArtistID:
|
||||
self.id = ArtistID
|
||||
self.id_type = 'artist'
|
||||
else:
|
||||
self.id = AlbumID
|
||||
self.id_type = 'album'
|
||||
|
||||
if self._exists('artwork') and self._is_current(filename=self.artwork_files[0]):
|
||||
return self.artwork_files[0]
|
||||
else:
|
||||
self._update_cache()
|
||||
# If we failed to get artwork, either return the url or the older file
|
||||
if self.artwork_errors and self.artwork_url:
|
||||
return self.artwork_url
|
||||
elif self._exists('artwork'):
|
||||
return self.artwork_files[0]
|
||||
else:
|
||||
return None
|
||||
|
||||
def get_thumb_from_cache(self, ArtistID=None, AlbumID=None):
|
||||
'''
|
||||
Pass a musicbrainz id to this function (either ArtistID or AlbumID)
|
||||
'''
|
||||
|
||||
self.query_type = 'thumb'
|
||||
|
||||
if ArtistID:
|
||||
self.id = ArtistID
|
||||
self.id_type = 'artist'
|
||||
else:
|
||||
self.id = AlbumID
|
||||
self.id_type = 'album'
|
||||
|
||||
if self._exists('thumb') and self._is_current(filename=self.thumb_files[0]):
|
||||
return self.thumb_files[0]
|
||||
else:
|
||||
self._update_cache()
|
||||
# If we failed to get artwork, either return the url or the older file
|
||||
if self.thumb_errors and self.thumb_url:
|
||||
return self.thumb_url
|
||||
elif self._exists('thumb'):
|
||||
return self.thumb_files[0]
|
||||
else:
|
||||
return None
|
||||
|
||||
def get_info_from_cache(self, ArtistID=None, AlbumID=None):
|
||||
|
||||
self.query_type = 'info'
|
||||
myDB = db.DBConnection()
|
||||
|
||||
if ArtistID:
|
||||
self.id = ArtistID
|
||||
self.id_type = 'artist'
|
||||
db_info = myDB.action('SELECT Summary, Content, LastUpdated FROM descriptions WHERE ArtistID=?', [self.id]).fetchone()
|
||||
else:
|
||||
self.id = AlbumID
|
||||
self.id_type = 'album'
|
||||
db_info = myDB.action('SELECT Summary, Content, LastUpdated FROM descriptions WHERE ReleaseGroupID=?', [self.id]).fetchone()
|
||||
|
||||
if not db_info or not db_info['LastUpdated'] or not self._is_current(date=db_info['LastUpdated']):
|
||||
|
||||
self._update_cache()
|
||||
info_dict = { 'Summary' : self.info_summary, 'Content' : self.info_content }
|
||||
return info_dict
|
||||
|
||||
else:
|
||||
info_dict = { 'Summary' : db_info['Summary'], 'Content' : db_info['Content'] }
|
||||
return info_dict
|
||||
|
||||
def get_image_links(self, ArtistID=None, AlbumID=None):
|
||||
'''
|
||||
Here we're just going to open up the last.fm url, grab the image links and return them
|
||||
Won't save any image urls, or save the artwork in the cache. Useful for search results, etc.
|
||||
'''
|
||||
if ArtistID:
|
||||
|
||||
self.id_type = 'artist'
|
||||
|
||||
params = { "method": "artist.getInfo",
|
||||
"api_key": lastfm_apikey,
|
||||
"mbid": ArtistID,
|
||||
"format": "json"
|
||||
}
|
||||
|
||||
url = "http://ws.audioscrobbler.com/2.0/?" + urllib.urlencode(params)
|
||||
logger.debug('Retrieving artist information from: ' + url)
|
||||
|
||||
try:
|
||||
result = urllib2.urlopen(url, timeout=20).read()
|
||||
except:
|
||||
logger.warn('Could not open url: ' + url)
|
||||
return
|
||||
|
||||
if result:
|
||||
|
||||
try:
|
||||
data = simplejson.JSONDecoder().decode(result)
|
||||
except:
|
||||
logger.warn('Could not parse data from url: ' + url)
|
||||
return
|
||||
|
||||
try:
|
||||
image_url = data['artist']['image'][-1]['#text']
|
||||
except KeyError:
|
||||
logger.debug('No artist image found on url: ' + url)
|
||||
image_url = None
|
||||
|
||||
thumb_url = self._get_thumb_url(data)
|
||||
if not thumb_url:
|
||||
logger.debug('No artist thumbnail image found on url: ' + url)
|
||||
|
||||
else:
|
||||
|
||||
self.id_type = 'album'
|
||||
|
||||
params = { "method": "album.getInfo",
|
||||
"api_key": lastfm_apikey,
|
||||
"mbid": AlbumID,
|
||||
"format": "json"
|
||||
}
|
||||
|
||||
url = "http://ws.audioscrobbler.com/2.0/?" + urllib.urlencode(params)
|
||||
logger.debug('Retrieving album information from: ' + url)
|
||||
|
||||
try:
|
||||
result = urllib2.urlopen(url, timeout=20).read()
|
||||
except:
|
||||
logger.warn('Could not open url: ' + url)
|
||||
return
|
||||
|
||||
if result:
|
||||
|
||||
try:
|
||||
data = simplejson.JSONDecoder().decode(result)
|
||||
except:
|
||||
logger.warn('Could not parse data from url: ' + url)
|
||||
return
|
||||
|
||||
try:
|
||||
image_url = data['artist']['image'][-1]['#text']
|
||||
except KeyError:
|
||||
logger.debug('No artist image found on url: ' + url)
|
||||
image_url = None
|
||||
|
||||
thumb_url = self._get_thumb_url(data)
|
||||
if not thumb_url:
|
||||
logger.debug('No artist thumbnail image found on url: ' + url)
|
||||
|
||||
image_dict = {'artwork' : image_url, 'thumbnail' : thumb_url }
|
||||
return image_dict
|
||||
|
||||
def _update_cache(self):
|
||||
'''
|
||||
Since we call the same url for both info and artwork, we'll update both at the same time
|
||||
'''
|
||||
myDB = db.DBConnection()
|
||||
|
||||
# Since lastfm uses release ids rather than release group ids for albums, we have to do a artist + album search for albums
|
||||
if self.id_type == 'artist':
|
||||
|
||||
params = { "method": "artist.getInfo",
|
||||
"api_key": lastfm_apikey,
|
||||
"mbid": self.id,
|
||||
"format": "json"
|
||||
}
|
||||
|
||||
url = "http://ws.audioscrobbler.com/2.0/?" + urllib.urlencode(params)
|
||||
logger.debug('Retrieving artist information from: ' + url)
|
||||
|
||||
try:
|
||||
result = urllib2.urlopen(url, timeout=20).read()
|
||||
except:
|
||||
logger.warn('Could not open url: ' + url)
|
||||
return
|
||||
|
||||
if result:
|
||||
|
||||
try:
|
||||
data = simplejson.JSONDecoder().decode(result)
|
||||
except:
|
||||
logger.warn('Could not parse data from url: ' + url)
|
||||
return
|
||||
try:
|
||||
self.info_summary = data['artist']['bio']['summary']
|
||||
except KeyError:
|
||||
logger.debug('No artist bio summary found on url: ' + url)
|
||||
self.info_summary = None
|
||||
try:
|
||||
self.info_content = data['artist']['bio']['content']
|
||||
except KeyError:
|
||||
logger.debug('No artist bio found on url: ' + url)
|
||||
self.info_content = None
|
||||
try:
|
||||
image_url = data['artist']['image'][-1]['#text']
|
||||
except KeyError:
|
||||
logger.debug('No artist image found on url: ' + url)
|
||||
image_url = None
|
||||
|
||||
thumb_url = self._get_thumb_url(data)
|
||||
if not thumb_url:
|
||||
logger.debug('No artist thumbnail image found on url: ' + url)
|
||||
|
||||
else:
|
||||
|
||||
dbartist = myDB.action('SELECT ArtistName, AlbumTitle FROM albums WHERE AlbumID=?', [self.id]).fetchone()
|
||||
|
||||
params = { "method": "album.getInfo",
|
||||
"api_key": lastfm_apikey,
|
||||
"artist": dbartist['ArtistName'].encode('utf-8'),
|
||||
"album": dbartist['AlbumTitle'].encode('utf-8'),
|
||||
"format": "json"
|
||||
}
|
||||
|
||||
url = "http://ws.audioscrobbler.com/2.0/?" + urllib.urlencode(params)
|
||||
|
||||
logger.debug('Retrieving artist information from: ' + url)
|
||||
try:
|
||||
result = urllib2.urlopen(url, timeout=20).read()
|
||||
except:
|
||||
logger.warn('Could not open url: ' + url)
|
||||
return
|
||||
|
||||
if result:
|
||||
try:
|
||||
data = simplejson.JSONDecoder().decode(result)
|
||||
except:
|
||||
logger.warn('Could not parse data from url: ' + url)
|
||||
return
|
||||
try:
|
||||
self.info_summary = data['album']['wiki']['summary']
|
||||
except KeyError:
|
||||
logger.debug('No album summary found from: ' + url)
|
||||
self.info_summary = None
|
||||
try:
|
||||
self.info_content = data['album']['wiki']['content']
|
||||
except KeyError:
|
||||
logger.debug('No album infomation found from: ' + url)
|
||||
self.info_content = None
|
||||
try:
|
||||
image_url = data['album']['image'][-1]['#text']
|
||||
except KeyError:
|
||||
logger.debug('No album image link found on url: ' + url)
|
||||
image_url = None
|
||||
|
||||
thumb_url = self._get_thumb_url(data)
|
||||
if not thumb_url:
|
||||
logger.debug('No album thumbnail image found on url: ' + url)
|
||||
|
||||
#Save the content & summary to the database no matter what if we've opened up the url
|
||||
if self.id_type == 'artist':
|
||||
controlValueDict = {"ArtistID": self.id}
|
||||
else:
|
||||
controlValueDict = {"ReleaseGroupID": self.id}
|
||||
|
||||
newValueDict = {"Summary": self.info_summary,
|
||||
"Content": self.info_content,
|
||||
"LastUpdated": helpers.today()}
|
||||
|
||||
myDB.upsert("descriptions", newValueDict, controlValueDict)
|
||||
|
||||
# Save the image URL to the database
|
||||
if image_url:
|
||||
if self.id_type == 'artist':
|
||||
myDB.action('UPDATE artists SET ArtworkURL=? WHERE ArtistID=?', [image_url, self.id])
|
||||
else:
|
||||
myDB.action('UPDATE albums SET ArtworkURL=? WHERE AlbumID=?', [image_url, self.id])
|
||||
|
||||
# Save the thumb URL to the database
|
||||
if thumb_url:
|
||||
if self.id_type == 'artist':
|
||||
myDB.action('UPDATE artists SET ThumbURL=? WHERE ArtistID=?', [thumb_url, self.id])
|
||||
else:
|
||||
myDB.action('UPDATE albums SET ThumbURL=? WHERE AlbumID=?', [thumb_url, self.id])
|
||||
|
||||
# Should we grab the artwork here if we're just grabbing thumbs or info?? Probably not since the files can be quite big
|
||||
if image_url and self.query_type == 'artwork':
|
||||
|
||||
try:
|
||||
artwork = urllib2.urlopen(image_url, timeout=20).read()
|
||||
except Exception, e:
|
||||
logger.error('Unable to open url "' + image_url + '". Error: ' + str(e))
|
||||
artwork = None
|
||||
|
||||
if artwork:
|
||||
|
||||
# Make sure the artwork dir exists:
|
||||
if not os.path.isdir(self.path_to_art_cache):
|
||||
try:
|
||||
os.makedirs(self.path_to_art_cache)
|
||||
except Exception, e:
|
||||
logger.error('Unable to create artwork cache dir. Error: ' + str(e))
|
||||
self.artwork_errors = True
|
||||
self.artwork_url = image_url
|
||||
|
||||
#Delete the old stuff
|
||||
for artwork_file in self.artwork_files:
|
||||
try:
|
||||
os.remove(artwork_file)
|
||||
except:
|
||||
logger.error('Error deleting file from the cache: ' + artwork_file)
|
||||
|
||||
ext = os.path.splitext(image_url)[1]
|
||||
|
||||
artwork_path = os.path.join(self.path_to_art_cache, self.id + '.' + helpers.today() + ext)
|
||||
try:
|
||||
f = open(artwork_path, 'wb')
|
||||
f.write(artwork)
|
||||
f.close()
|
||||
except Exception, e:
|
||||
logger.error('Unable to write to the cache dir: ' + str(e))
|
||||
self.artwork_errors = True
|
||||
self.artwork_url = image_url
|
||||
|
||||
# Grab the thumbnail as well if we're getting the full artwork (as long as it's missing/outdated
|
||||
if thumb_url and self.query_type in ['thumb','artwork'] and not (self.thumb_files and self._is_current(self.thumb_files[0])):
|
||||
|
||||
try:
|
||||
artwork = urllib2.urlopen(thumb_url, timeout=20).read()
|
||||
except Exception, e:
|
||||
logger.error('Unable to open url "' + thumb_url + '". Error: ' + str(e))
|
||||
artwork = None
|
||||
|
||||
if artwork:
|
||||
|
||||
# Make sure the artwork dir exists:
|
||||
if not os.path.isdir(self.path_to_art_cache):
|
||||
try:
|
||||
os.makedirs(self.path_to_art_cache)
|
||||
except Exception, e:
|
||||
logger.error('Unable to create artwork cache dir. Error: ' + str(e))
|
||||
self.thumb_errors = True
|
||||
self.thumb_url = thumb_url
|
||||
|
||||
#Delete the old stuff
|
||||
for thumb_file in self.thumb_files:
|
||||
try:
|
||||
os.remove(thumb_file)
|
||||
except:
|
||||
logger.error('Error deleting file from the cache: ' + thumb_file)
|
||||
|
||||
ext = os.path.splitext(image_url)[1]
|
||||
|
||||
thumb_path = os.path.join(self.path_to_art_cache, 'T_' + self.id + '.' + helpers.today() + ext)
|
||||
try:
|
||||
f = open(thumb_path, 'wb')
|
||||
f.write(artwork)
|
||||
f.close()
|
||||
except Exception, e:
|
||||
logger.error('Unable to write to the cache dir: ' + str(e))
|
||||
self.thumb_errors = True
|
||||
self.thumb_url = image_url
|
||||
|
||||
def getArtwork(ArtistID=None, AlbumID=None):
|
||||
|
||||
c = Cache()
|
||||
artwork_path = c.get_artwork_from_cache(ArtistID, AlbumID)
|
||||
|
||||
if not artwork_path:
|
||||
return None
|
||||
|
||||
if artwork_path.startswith('http://'):
|
||||
return artwork_path
|
||||
else:
|
||||
return "cache" + artwork_path[len(headphones.CACHE_DIR):]
|
||||
|
||||
def getThumb(ArtistID=None, AlbumID=None):
|
||||
|
||||
c = Cache()
|
||||
artwork_path = c.get_thumb_from_cache(ArtistID, AlbumID)
|
||||
|
||||
if not artwork_path:
|
||||
return None
|
||||
|
||||
if artwork_path.startswith('http://'):
|
||||
return artwork_path
|
||||
else:
|
||||
return "cache" + artwork_path[len(headphones.CACHE_DIR):]
|
||||
|
||||
def getInfo(ArtistID=None, AlbumID=None):
|
||||
|
||||
c = Cache()
|
||||
|
||||
info_dict = c.get_info_from_cache(ArtistID, AlbumID)
|
||||
|
||||
return info_dict
|
||||
|
||||
def getImageLinks(ArtistID=None, AlbumID=None):
|
||||
|
||||
c = Cache()
|
||||
image_links = c.get_image_links(ArtistID, AlbumID)
|
||||
|
||||
return image_links
|
||||
@@ -1,22 +1,21 @@
|
||||
# Author: Nic Wolfe <nic@wolfeden.ca>
|
||||
# URL: http://code.google.com/p/sickbeard/
|
||||
# This file is part of Headphones.
|
||||
#
|
||||
# This file is part of Sick Beard.
|
||||
# Headphones 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.
|
||||
#
|
||||
# Sick Beard 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.
|
||||
# Headphones 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.
|
||||
#
|
||||
# Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with Headphones. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
#########################################
|
||||
## Stolen from Sick-Beard's classes.py ##
|
||||
#########################################
|
||||
|
||||
import headphones
|
||||
|
||||
|
||||
@@ -1,3 +1,18 @@
|
||||
# This file is part of Headphones.
|
||||
#
|
||||
# Headphones 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.
|
||||
#
|
||||
# Headphones 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 Headphones. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
'''
|
||||
Created on Aug 1, 2011
|
||||
|
||||
@@ -159,4 +174,4 @@ ANY = Quality.combineQualities([Quality.B192, Quality.B256, Quality.B320, Qualit
|
||||
qualityPresets = (MP3, LOSSLESS, ANY)
|
||||
qualityPresetStrings = {MP3: "MP3 (All bitrates 192+)",
|
||||
LOSSLESS: "Lossless (flac)",
|
||||
ANY: "Any"}
|
||||
ANY: "Any"}
|
||||
|
||||
145
headphones/db.py
145
headphones/db.py
@@ -1,4 +1,21 @@
|
||||
# Stolen from sick beards db.py.
|
||||
# This file is part of Headphones.
|
||||
#
|
||||
# Headphones 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.
|
||||
#
|
||||
# Headphones 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 Headphones. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
#####################################
|
||||
## Stolen from Sick-Beard's db.py ##
|
||||
#####################################
|
||||
|
||||
from __future__ import with_statement
|
||||
|
||||
@@ -15,70 +32,70 @@ db_lock = threading.Lock()
|
||||
|
||||
def dbFilename(filename="headphones.db"):
|
||||
|
||||
return os.path.join(headphones.DATA_DIR, filename)
|
||||
return os.path.join(headphones.DATA_DIR, filename)
|
||||
|
||||
class DBConnection:
|
||||
|
||||
def __init__(self, filename="headphones.db"):
|
||||
|
||||
self.filename = filename
|
||||
self.connection = sqlite3.connect(dbFilename(filename), timeout=20)
|
||||
self.connection.row_factory = sqlite3.Row
|
||||
|
||||
def action(self, query, args=None):
|
||||
|
||||
with db_lock:
|
||||
def __init__(self, filename="headphones.db"):
|
||||
|
||||
self.filename = filename
|
||||
self.connection = sqlite3.connect(dbFilename(filename), timeout=20)
|
||||
self.connection.row_factory = sqlite3.Row
|
||||
|
||||
def action(self, query, args=None):
|
||||
|
||||
with db_lock:
|
||||
|
||||
if query == None:
|
||||
return
|
||||
|
||||
sqlResult = None
|
||||
attempt = 0
|
||||
|
||||
while attempt < 5:
|
||||
try:
|
||||
if args == None:
|
||||
#logger.debug(self.filename+": "+query)
|
||||
sqlResult = self.connection.execute(query)
|
||||
else:
|
||||
#logger.debug(self.filename+": "+query+" with args "+str(args))
|
||||
sqlResult = self.connection.execute(query, args)
|
||||
self.connection.commit()
|
||||
break
|
||||
except sqlite3.OperationalError, e:
|
||||
if "unable to open database file" in e.message or "database is locked" in e.message:
|
||||
logger.warn('Database Error: %s' % e)
|
||||
attempt += 1
|
||||
time.sleep(1)
|
||||
else:
|
||||
logger.error('Database error: %s' % e)
|
||||
raise
|
||||
except sqlite3.DatabaseError, e:
|
||||
logger.error('Fatal Error executing %s :: %s' % (query, e))
|
||||
raise
|
||||
|
||||
return sqlResult
|
||||
|
||||
def select(self, query, args=None):
|
||||
|
||||
sqlResults = self.action(query, args).fetchall()
|
||||
|
||||
if sqlResults == None:
|
||||
return []
|
||||
|
||||
return sqlResults
|
||||
|
||||
def upsert(self, tableName, valueDict, keyDict):
|
||||
|
||||
changesBefore = self.connection.total_changes
|
||||
|
||||
genParams = lambda myDict : [x + " = ?" for x in myDict.keys()]
|
||||
|
||||
query = "UPDATE "+tableName+" SET " + ", ".join(genParams(valueDict)) + " WHERE " + " AND ".join(genParams(keyDict))
|
||||
|
||||
self.action(query, valueDict.values() + keyDict.values())
|
||||
|
||||
if self.connection.total_changes == changesBefore:
|
||||
query = "INSERT INTO "+tableName+" (" + ", ".join(valueDict.keys() + keyDict.keys()) + ")" + \
|
||||
" VALUES (" + ", ".join(["?"] * len(valueDict.keys() + keyDict.keys())) + ")"
|
||||
self.action(query, valueDict.values() + keyDict.values())
|
||||
if query == None:
|
||||
return
|
||||
|
||||
sqlResult = None
|
||||
attempt = 0
|
||||
|
||||
while attempt < 5:
|
||||
try:
|
||||
if args == None:
|
||||
#logger.debug(self.filename+": "+query)
|
||||
sqlResult = self.connection.execute(query)
|
||||
else:
|
||||
#logger.debug(self.filename+": "+query+" with args "+str(args))
|
||||
sqlResult = self.connection.execute(query, args)
|
||||
self.connection.commit()
|
||||
break
|
||||
except sqlite3.OperationalError, e:
|
||||
if "unable to open database file" in e.message or "database is locked" in e.message:
|
||||
logger.warn('Database Error: %s' % e)
|
||||
attempt += 1
|
||||
time.sleep(1)
|
||||
else:
|
||||
logger.error('Database error: %s' % e)
|
||||
raise
|
||||
except sqlite3.DatabaseError, e:
|
||||
logger.error('Fatal Error executing %s :: %s' % (query, e))
|
||||
raise
|
||||
|
||||
return sqlResult
|
||||
|
||||
def select(self, query, args=None):
|
||||
|
||||
sqlResults = self.action(query, args).fetchall()
|
||||
|
||||
if sqlResults == None:
|
||||
return []
|
||||
|
||||
return sqlResults
|
||||
|
||||
def upsert(self, tableName, valueDict, keyDict):
|
||||
|
||||
changesBefore = self.connection.total_changes
|
||||
|
||||
genParams = lambda myDict : [x + " = ?" for x in myDict.keys()]
|
||||
|
||||
query = "UPDATE "+tableName+" SET " + ", ".join(genParams(valueDict)) + " WHERE " + " AND ".join(genParams(keyDict))
|
||||
|
||||
self.action(query, valueDict.values() + keyDict.values())
|
||||
|
||||
if self.connection.total_changes == changesBefore:
|
||||
query = "INSERT INTO "+tableName+" (" + ", ".join(valueDict.keys() + keyDict.keys()) + ")" + \
|
||||
" VALUES (" + ", ".join(["?"] * len(valueDict.keys() + keyDict.keys())) + ")"
|
||||
self.action(query, valueDict.values() + keyDict.values())
|
||||
|
||||
@@ -1,3 +1,18 @@
|
||||
# This file is part of Headphones.
|
||||
#
|
||||
# Headphones 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.
|
||||
#
|
||||
# Headphones 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 Headphones. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
def ex(e):
|
||||
"""
|
||||
Returns a string from the exception text if it exists.
|
||||
|
||||
@@ -1,3 +1,18 @@
|
||||
# This file is part of Headphones.
|
||||
#
|
||||
# Headphones 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.
|
||||
#
|
||||
# Headphones 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 Headphones. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import time
|
||||
from operator import itemgetter
|
||||
import datetime
|
||||
@@ -20,120 +35,120 @@ def multikeysort(items, columns):
|
||||
return sorted(items, cmp=comparer)
|
||||
|
||||
def checked(variable):
|
||||
if variable:
|
||||
return 'Checked'
|
||||
else:
|
||||
return ''
|
||||
|
||||
if variable:
|
||||
return 'Checked'
|
||||
else:
|
||||
return ''
|
||||
|
||||
def radio(variable, pos):
|
||||
|
||||
if variable == pos:
|
||||
return 'Checked'
|
||||
else:
|
||||
return ''
|
||||
|
||||
if variable == pos:
|
||||
return 'Checked'
|
||||
else:
|
||||
return ''
|
||||
|
||||
def latinToAscii(unicrap):
|
||||
"""
|
||||
From couch potato
|
||||
"""
|
||||
xlate = {0xc0:'A', 0xc1:'A', 0xc2:'A', 0xc3:'A', 0xc4:'A', 0xc5:'A',
|
||||
0xc6:'Ae', 0xc7:'C',
|
||||
0xc8:'E', 0xc9:'E', 0xca:'E', 0xcb:'E', 0x86:'e',
|
||||
0xcc:'I', 0xcd:'I', 0xce:'I', 0xcf:'I',
|
||||
0xd0:'Th', 0xd1:'N',
|
||||
0xd2:'O', 0xd3:'O', 0xd4:'O', 0xd5:'O', 0xd6:'O', 0xd8:'O',
|
||||
0xd9:'U', 0xda:'U', 0xdb:'U', 0xdc:'U',
|
||||
0xdd:'Y', 0xde:'th', 0xdf:'ss',
|
||||
0xe0:'a', 0xe1:'a', 0xe2:'a', 0xe3:'a', 0xe4:'a', 0xe5:'a',
|
||||
0xe6:'ae', 0xe7:'c',
|
||||
0xe8:'e', 0xe9:'e', 0xea:'e', 0xeb:'e', 0x0259:'e',
|
||||
0xec:'i', 0xed:'i', 0xee:'i', 0xef:'i',
|
||||
0xf0:'th', 0xf1:'n',
|
||||
0xf2:'o', 0xf3:'o', 0xf4:'o', 0xf5:'o', 0xf6:'o', 0xf8:'o',
|
||||
0xf9:'u', 0xfa:'u', 0xfb:'u', 0xfc:'u',
|
||||
0xfd:'y', 0xfe:'th', 0xff:'y',
|
||||
0xa1:'!', 0xa2:'{cent}', 0xa3:'{pound}', 0xa4:'{currency}',
|
||||
0xa5:'{yen}', 0xa6:'|', 0xa7:'{section}', 0xa8:'{umlaut}',
|
||||
0xa9:'{C}', 0xaa:'{^a}', 0xab:'<<', 0xac:'{not}',
|
||||
0xad:'-', 0xae:'{R}', 0xaf:'_', 0xb0:'{degrees}',
|
||||
0xb1:'{+/-}', 0xb2:'{^2}', 0xb3:'{^3}', 0xb4:"'",
|
||||
0xb5:'{micro}', 0xb6:'{paragraph}', 0xb7:'*', 0xb8:'{cedilla}',
|
||||
0xb9:'{^1}', 0xba:'{^o}', 0xbb:'>>',
|
||||
0xbc:'{1/4}', 0xbd:'{1/2}', 0xbe:'{3/4}', 0xbf:'?',
|
||||
0xd7:'*', 0xf7:'/'
|
||||
}
|
||||
"""
|
||||
From couch potato
|
||||
"""
|
||||
xlate = {0xc0:'A', 0xc1:'A', 0xc2:'A', 0xc3:'A', 0xc4:'A', 0xc5:'A',
|
||||
0xc6:'Ae', 0xc7:'C',
|
||||
0xc8:'E', 0xc9:'E', 0xca:'E', 0xcb:'E', 0x86:'e',
|
||||
0xcc:'I', 0xcd:'I', 0xce:'I', 0xcf:'I',
|
||||
0xd0:'Th', 0xd1:'N',
|
||||
0xd2:'O', 0xd3:'O', 0xd4:'O', 0xd5:'O', 0xd6:'O', 0xd8:'O',
|
||||
0xd9:'U', 0xda:'U', 0xdb:'U', 0xdc:'U',
|
||||
0xdd:'Y', 0xde:'th', 0xdf:'ss',
|
||||
0xe0:'a', 0xe1:'a', 0xe2:'a', 0xe3:'a', 0xe4:'a', 0xe5:'a',
|
||||
0xe6:'ae', 0xe7:'c',
|
||||
0xe8:'e', 0xe9:'e', 0xea:'e', 0xeb:'e', 0x0259:'e',
|
||||
0xec:'i', 0xed:'i', 0xee:'i', 0xef:'i',
|
||||
0xf0:'th', 0xf1:'n',
|
||||
0xf2:'o', 0xf3:'o', 0xf4:'o', 0xf5:'o', 0xf6:'o', 0xf8:'o',
|
||||
0xf9:'u', 0xfa:'u', 0xfb:'u', 0xfc:'u',
|
||||
0xfd:'y', 0xfe:'th', 0xff:'y',
|
||||
0xa1:'!', 0xa2:'{cent}', 0xa3:'{pound}', 0xa4:'{currency}',
|
||||
0xa5:'{yen}', 0xa6:'|', 0xa7:'{section}', 0xa8:'{umlaut}',
|
||||
0xa9:'{C}', 0xaa:'{^a}', 0xab:'<<', 0xac:'{not}',
|
||||
0xad:'-', 0xae:'{R}', 0xaf:'_', 0xb0:'{degrees}',
|
||||
0xb1:'{+/-}', 0xb2:'{^2}', 0xb3:'{^3}', 0xb4:"'",
|
||||
0xb5:'{micro}', 0xb6:'{paragraph}', 0xb7:'*', 0xb8:'{cedilla}',
|
||||
0xb9:'{^1}', 0xba:'{^o}', 0xbb:'>>',
|
||||
0xbc:'{1/4}', 0xbd:'{1/2}', 0xbe:'{3/4}', 0xbf:'?',
|
||||
0xd7:'*', 0xf7:'/'
|
||||
}
|
||||
|
||||
r = ''
|
||||
for i in unicrap:
|
||||
if xlate.has_key(ord(i)):
|
||||
r += xlate[ord(i)]
|
||||
elif ord(i) >= 0x80:
|
||||
pass
|
||||
else:
|
||||
r += str(i)
|
||||
return r
|
||||
|
||||
r = ''
|
||||
for i in unicrap:
|
||||
if xlate.has_key(ord(i)):
|
||||
r += xlate[ord(i)]
|
||||
elif ord(i) >= 0x80:
|
||||
pass
|
||||
else:
|
||||
r += str(i)
|
||||
return r
|
||||
|
||||
def convert_milliseconds(ms):
|
||||
|
||||
seconds = ms/1000
|
||||
gmtime = time.gmtime(seconds)
|
||||
if seconds > 3600:
|
||||
minutes = time.strftime("%H:%M:%S", gmtime)
|
||||
else:
|
||||
minutes = time.strftime("%M:%S", gmtime)
|
||||
seconds = ms/1000
|
||||
gmtime = time.gmtime(seconds)
|
||||
if seconds > 3600:
|
||||
minutes = time.strftime("%H:%M:%S", gmtime)
|
||||
else:
|
||||
minutes = time.strftime("%M:%S", gmtime)
|
||||
|
||||
return minutes
|
||||
|
||||
return minutes
|
||||
|
||||
def convert_seconds(s):
|
||||
|
||||
gmtime = time.gmtime(s)
|
||||
if s > 3600:
|
||||
minutes = time.strftime("%H:%M:%S", gmtime)
|
||||
else:
|
||||
minutes = time.strftime("%M:%S", gmtime)
|
||||
gmtime = time.gmtime(s)
|
||||
if s > 3600:
|
||||
minutes = time.strftime("%H:%M:%S", gmtime)
|
||||
else:
|
||||
minutes = time.strftime("%M:%S", gmtime)
|
||||
|
||||
return minutes
|
||||
|
||||
return minutes
|
||||
|
||||
def today():
|
||||
today = datetime.date.today()
|
||||
yyyymmdd = datetime.date.isoformat(today)
|
||||
return yyyymmdd
|
||||
|
||||
today = datetime.date.today()
|
||||
yyyymmdd = datetime.date.isoformat(today)
|
||||
return yyyymmdd
|
||||
|
||||
def now():
|
||||
now = datetime.datetime.now()
|
||||
return now.strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
now = datetime.datetime.now()
|
||||
return now.strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
def bytes_to_mb(bytes):
|
||||
|
||||
mb = int(bytes)/1048576
|
||||
size = '%.1f MB' % mb
|
||||
return size
|
||||
|
||||
mb = int(bytes)/1048576
|
||||
size = '%.1f MB' % mb
|
||||
return size
|
||||
|
||||
def replace_all(text, dic):
|
||||
for i, j in dic.iteritems():
|
||||
text = text.replace(i, j)
|
||||
return text
|
||||
|
||||
for i, j in dic.iteritems():
|
||||
text = text.replace(i, j)
|
||||
return text
|
||||
|
||||
def cleanName(string):
|
||||
|
||||
pass1 = latinToAscii(string).lower()
|
||||
out_string = re.sub('[\.\-\/\!\@\#\$\%\^\&\*\(\)\+\-\"\'\,\;\:\[\]\{\}\<\>\=\_]', '', pass1).encode('utf-8')
|
||||
|
||||
return out_string
|
||||
|
||||
pass1 = latinToAscii(string).lower()
|
||||
out_string = re.sub('[\.\-\/\!\@\#\$\%\^\&\*\(\)\+\-\"\'\,\;\:\[\]\{\}\<\>\=\_]', '', pass1).encode('utf-8')
|
||||
|
||||
return out_string
|
||||
|
||||
def cleanTitle(title):
|
||||
|
||||
title = re.sub('[\.\-\/\_]', ' ', title).lower()
|
||||
|
||||
# Strip out extra whitespace
|
||||
title = ' '.join(title.split())
|
||||
|
||||
title = title.title()
|
||||
|
||||
return title
|
||||
|
||||
title = re.sub('[\.\-\/\_]', ' ', title).lower()
|
||||
|
||||
# Strip out extra whitespace
|
||||
title = ' '.join(title.split())
|
||||
|
||||
title = title.title()
|
||||
|
||||
return title
|
||||
|
||||
def extract_data(s):
|
||||
|
||||
|
||||
from headphones import logger
|
||||
|
||||
#headphones default format
|
||||
@@ -161,18 +176,18 @@ def extract_data(s):
|
||||
return (name, album, year)
|
||||
|
||||
def extract_logline(s):
|
||||
# Default log format
|
||||
pattern = re.compile(r'(?P<timestamp>.*?)\s\-\s(?P<level>.*?)\s*\:\:\s(?P<thread>.*?)\s\:\s(?P<message>.*)', re.VERBOSE)
|
||||
match = pattern.match(s)
|
||||
if match:
|
||||
timestamp = match.group("timestamp")
|
||||
level = match.group("level")
|
||||
thread = match.group("thread")
|
||||
message = match.group("message")
|
||||
return (timestamp, level, thread, message)
|
||||
else:
|
||||
return None
|
||||
|
||||
# Default log format
|
||||
pattern = re.compile(r'(?P<timestamp>.*?)\s\-\s(?P<level>.*?)\s*\:\:\s(?P<thread>.*?)\s\:\s(?P<message>.*)', re.VERBOSE)
|
||||
match = pattern.match(s)
|
||||
if match:
|
||||
timestamp = match.group("timestamp")
|
||||
level = match.group("level")
|
||||
thread = match.group("thread")
|
||||
message = match.group("message")
|
||||
return (timestamp, level, thread, message)
|
||||
else:
|
||||
return None
|
||||
|
||||
def extract_song_data(s):
|
||||
|
||||
#headphones default format
|
||||
@@ -202,4 +217,4 @@ def extract_song_data(s):
|
||||
return (name, album, year)
|
||||
else:
|
||||
logger.info("Couldn't parse " + s + " into a valid Newbin format")
|
||||
return (name, album, year)
|
||||
return (name, album, year)
|
||||
|
||||
@@ -1,3 +1,18 @@
|
||||
# This file is part of Headphones.
|
||||
#
|
||||
# Headphones 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.
|
||||
#
|
||||
# Headphones 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 Headphones. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from lib.pyItunes import *
|
||||
import time
|
||||
import os
|
||||
@@ -7,369 +22,374 @@ import headphones
|
||||
from headphones import logger, helpers, db, mb, albumart, lastfm
|
||||
|
||||
various_artists_mbid = '89ad4ac3-39f7-470e-963a-56509c546377'
|
||||
|
||||
|
||||
def is_exists(artistid):
|
||||
|
||||
myDB = db.DBConnection()
|
||||
|
||||
# See if the artist is already in the database
|
||||
artistlist = myDB.select('SELECT ArtistID, ArtistName from artists WHERE ArtistID=?', [artistid])
|
||||
myDB = db.DBConnection()
|
||||
|
||||
# See if the artist is already in the database
|
||||
artistlist = myDB.select('SELECT ArtistID, ArtistName from artists WHERE ArtistID=?', [artistid])
|
||||
|
||||
if any(artistid in x for x in artistlist):
|
||||
logger.info(artistlist[0][1] + u" is already in the database. Updating 'have tracks', but not artist information")
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
if any(artistid in x for x in artistlist):
|
||||
logger.info(artistlist[0][1] + u" is already in the database. Updating 'have tracks', but not artist information")
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
def artistlist_to_mbids(artistlist, forced=False):
|
||||
|
||||
for artist in artistlist:
|
||||
|
||||
if forced:
|
||||
artist = unicode(artist, 'utf-8')
|
||||
|
||||
results = mb.findArtist(artist, limit=1)
|
||||
|
||||
if not results:
|
||||
logger.info('No results found for: %s' % artist)
|
||||
continue
|
||||
|
||||
try:
|
||||
artistid = results[0]['id']
|
||||
|
||||
except IndexError:
|
||||
logger.info('MusicBrainz query turned up no matches for: %s' % artist)
|
||||
continue
|
||||
|
||||
# Add to database if it doesn't exist
|
||||
if artistid != various_artists_mbid and not is_exists(artistid):
|
||||
addArtisttoDB(artistid)
|
||||
|
||||
# Just update the tracks if it does
|
||||
else:
|
||||
myDB = db.DBConnection()
|
||||
havetracks = len(myDB.select('SELECT TrackTitle from tracks WHERE ArtistID=?', [artistid])) + len(myDB.select('SELECT TrackTitle from have WHERE ArtistName like ?', [artist]))
|
||||
myDB.action('UPDATE artists SET HaveTracks=? WHERE ArtistID=?', [havetracks, artistid])
|
||||
|
||||
# Update the similar artist tag cloud:
|
||||
logger.info('Updating artist information from Last.fm')
|
||||
try:
|
||||
lastfm.getSimilar()
|
||||
except Exception, e:
|
||||
logger.warn('Failed to update arist information from Last.fm: %s' % e)
|
||||
|
||||
for artist in artistlist:
|
||||
|
||||
if forced:
|
||||
artist = unicode(artist, 'utf-8')
|
||||
|
||||
results = mb.findArtist(artist, limit=1)
|
||||
|
||||
if not results:
|
||||
logger.info('No results found for: %s' % artist)
|
||||
continue
|
||||
|
||||
try:
|
||||
artistid = results[0]['id']
|
||||
|
||||
except IndexError:
|
||||
logger.info('MusicBrainz query turned up no matches for: %s' % artist)
|
||||
continue
|
||||
|
||||
# Add to database if it doesn't exist
|
||||
if artistid != various_artists_mbid and not is_exists(artistid):
|
||||
addArtisttoDB(artistid)
|
||||
|
||||
# Just update the tracks if it does
|
||||
else:
|
||||
myDB = db.DBConnection()
|
||||
havetracks = len(myDB.select('SELECT TrackTitle from tracks WHERE ArtistID=?', [artistid])) + len(myDB.select('SELECT TrackTitle from have WHERE ArtistName like ?', [artist]))
|
||||
myDB.action('UPDATE artists SET HaveTracks=? WHERE ArtistID=?', [havetracks, artistid])
|
||||
|
||||
# Update the similar artist tag cloud:
|
||||
logger.info('Updating artist information from Last.fm')
|
||||
try:
|
||||
lastfm.getSimilar()
|
||||
except Exception, e:
|
||||
logger.warn('Failed to update arist information from Last.fm: %s' % e)
|
||||
|
||||
def addArtistIDListToDB(artistidlist):
|
||||
# Used to add a list of artist IDs to the database in a single thread
|
||||
logger.debug("Importer: Adding artist ids %s" % artistidlist)
|
||||
for artistid in artistidlist:
|
||||
addArtisttoDB(artistid)
|
||||
# Used to add a list of artist IDs to the database in a single thread
|
||||
logger.debug("Importer: Adding artist ids %s" % artistidlist)
|
||||
for artistid in artistidlist:
|
||||
addArtisttoDB(artistid)
|
||||
|
||||
def addArtisttoDB(artistid, extrasonly=False):
|
||||
|
||||
# Can't add various artists - throws an error from MB
|
||||
if artistid == various_artists_mbid:
|
||||
logger.warn('Cannot import Various Artists.')
|
||||
return
|
||||
|
||||
myDB = db.DBConnection()
|
||||
|
||||
# Putting this here to get around the circular import
|
||||
from headphones import cache
|
||||
|
||||
# Can't add various artists - throws an error from MB
|
||||
if artistid == various_artists_mbid:
|
||||
logger.warn('Cannot import Various Artists.')
|
||||
return
|
||||
|
||||
myDB = db.DBConnection()
|
||||
|
||||
# We need the current minimal info in the database instantly
|
||||
# so we don't throw a 500 error when we redirect to the artistPage
|
||||
# We need the current minimal info in the database instantly
|
||||
# so we don't throw a 500 error when we redirect to the artistPage
|
||||
|
||||
controlValueDict = {"ArtistID": artistid}
|
||||
controlValueDict = {"ArtistID": artistid}
|
||||
|
||||
# Don't replace a known artist name with an "Artist ID" placeholder
|
||||
# Don't replace a known artist name with an "Artist ID" placeholder
|
||||
|
||||
dbartist = myDB.action('SELECT * FROM artists WHERE ArtistID=?', [artistid]).fetchone()
|
||||
if dbartist is None:
|
||||
newValueDict = {"ArtistName": "Artist ID: %s" % (artistid),
|
||||
"Status": "Loading"}
|
||||
else:
|
||||
newValueDict = {"Status": "Loading"}
|
||||
dbartist = myDB.action('SELECT * FROM artists WHERE ArtistID=?', [artistid]).fetchone()
|
||||
if dbartist is None:
|
||||
newValueDict = {"ArtistName": "Artist ID: %s" % (artistid),
|
||||
"Status": "Loading"}
|
||||
else:
|
||||
newValueDict = {"Status": "Loading"}
|
||||
|
||||
myDB.upsert("artists", newValueDict, controlValueDict)
|
||||
|
||||
artist = mb.getArtist(artistid, extrasonly)
|
||||
|
||||
if not artist:
|
||||
logger.warn("Error fetching artist info. ID: " + artistid)
|
||||
if dbartist is None:
|
||||
newValueDict = {"ArtistName": "Fetch failed, try refreshing. (%s)" % (artistid),
|
||||
"Status": "Active"}
|
||||
else:
|
||||
newValueDict = {"Status": "Active"}
|
||||
myDB.upsert("artists", newValueDict, controlValueDict)
|
||||
return
|
||||
|
||||
if artist['artist_name'].startswith('The '):
|
||||
sortname = artist['artist_name'][4:]
|
||||
else:
|
||||
sortname = artist['artist_name']
|
||||
|
||||
myDB.upsert("artists", newValueDict, controlValueDict)
|
||||
|
||||
artist = mb.getArtist(artistid, extrasonly)
|
||||
|
||||
if not artist:
|
||||
logger.warn("Error fetching artist info. ID: " + artistid)
|
||||
if dbartist is None:
|
||||
newValueDict = {"ArtistName": "Fetch failed, try refreshing. (%s)" % (artistid),
|
||||
"Status": "Active"}
|
||||
else:
|
||||
newValueDict = {"Status": "Active"}
|
||||
myDB.upsert("artists", newValueDict, controlValueDict)
|
||||
return
|
||||
|
||||
if artist['artist_name'].startswith('The '):
|
||||
sortname = artist['artist_name'][4:]
|
||||
else:
|
||||
sortname = artist['artist_name']
|
||||
|
||||
|
||||
logger.info(u"Now adding/updating: " + artist['artist_name'])
|
||||
controlValueDict = {"ArtistID": artistid}
|
||||
newValueDict = {"ArtistName": artist['artist_name'],
|
||||
"ArtistSortName": sortname,
|
||||
"DateAdded": helpers.today(),
|
||||
"Status": "Loading"}
|
||||
|
||||
if headphones.INCLUDE_EXTRAS:
|
||||
newValueDict['IncludeExtras'] = 1
|
||||
|
||||
myDB.upsert("artists", newValueDict, controlValueDict)
|
||||
logger.info(u"Now adding/updating: " + artist['artist_name'])
|
||||
controlValueDict = {"ArtistID": artistid}
|
||||
newValueDict = {"ArtistName": artist['artist_name'],
|
||||
"ArtistSortName": sortname,
|
||||
"DateAdded": helpers.today(),
|
||||
"Status": "Loading"}
|
||||
|
||||
if headphones.INCLUDE_EXTRAS:
|
||||
newValueDict['IncludeExtras'] = 1
|
||||
|
||||
myDB.upsert("artists", newValueDict, controlValueDict)
|
||||
|
||||
for rg in artist['releasegroups']:
|
||||
|
||||
rgid = rg['id']
|
||||
|
||||
# check if the album already exists
|
||||
rg_exists = myDB.select("SELECT * from albums WHERE AlbumID=?", [rg['id']])
|
||||
|
||||
try:
|
||||
release_dict = mb.getReleaseGroup(rgid)
|
||||
except Exception, e:
|
||||
logger.info('Unable to get release information for %s - there may not be any official releases in this release group' % rg['title'])
|
||||
continue
|
||||
|
||||
if not release_dict:
|
||||
continue
|
||||
|
||||
logger.info(u"Now adding/updating album: " + rg['title'])
|
||||
controlValueDict = {"AlbumID": rg['id']}
|
||||
|
||||
if len(rg_exists):
|
||||
|
||||
newValueDict = {"AlbumASIN": release_dict['asin'],
|
||||
"ReleaseDate": release_dict['releasedate'],
|
||||
}
|
||||
|
||||
else:
|
||||
|
||||
newValueDict = {"ArtistID": artistid,
|
||||
"ArtistName": artist['artist_name'],
|
||||
"AlbumTitle": rg['title'],
|
||||
"AlbumASIN": release_dict['asin'],
|
||||
"ReleaseDate": release_dict['releasedate'],
|
||||
"DateAdded": helpers.today(),
|
||||
"Type": rg['type']
|
||||
}
|
||||
|
||||
if headphones.AUTOWANT_ALL:
|
||||
newValueDict['Status'] = "Wanted"
|
||||
elif release_dict['releasedate'] > helpers.today() and headphones.AUTOWANT_UPCOMING:
|
||||
newValueDict['Status'] = "Wanted"
|
||||
else:
|
||||
newValueDict['Status'] = "Skipped"
|
||||
|
||||
myDB.upsert("albums", newValueDict, controlValueDict)
|
||||
|
||||
try:
|
||||
lastfm.getAlbumDescription(rg['id'], artist['artist_name'], rg['title'])
|
||||
except Exception, e:
|
||||
logger.error('Attempt to retrieve album description from Last.fm failed: %s' % e)
|
||||
|
||||
# I changed the albumid from releaseid -> rgid, so might need to delete albums that have a releaseid
|
||||
for release in release_dict['releaselist']:
|
||||
myDB.action('DELETE from albums WHERE AlbumID=?', [release['releaseid']])
|
||||
myDB.action('DELETE from tracks WHERE AlbumID=?', [release['releaseid']])
|
||||
|
||||
for track in release_dict['tracks']:
|
||||
|
||||
cleanname = helpers.cleanName(artist['artist_name'] + ' ' + rg['title'] + ' ' + track['title'])
|
||||
|
||||
controlValueDict = {"TrackID": track['id'],
|
||||
"AlbumID": rg['id']}
|
||||
newValueDict = {"ArtistID": artistid,
|
||||
"ArtistName": artist['artist_name'],
|
||||
"AlbumTitle": rg['title'],
|
||||
"AlbumASIN": release_dict['asin'],
|
||||
"TrackTitle": track['title'],
|
||||
"TrackDuration": track['duration'],
|
||||
"TrackNumber": track['number'],
|
||||
"CleanName": cleanname
|
||||
}
|
||||
|
||||
match = myDB.action('SELECT Location, BitRate, Format from have WHERE CleanName=?', [cleanname]).fetchone()
|
||||
|
||||
if not match:
|
||||
match = myDB.action('SELECT Location, BitRate, Format from have WHERE ArtistName LIKE ? AND AlbumTitle LIKE ? AND TrackTitle LIKE ?', [artist['artist_name'], rg['title'], track['title']]).fetchone()
|
||||
if not match:
|
||||
match = myDB.action('SELECT Location, BitRate, Format from have WHERE TrackID=?', [track['id']]).fetchone()
|
||||
if match:
|
||||
newValueDict['Location'] = match['Location']
|
||||
newValueDict['BitRate'] = match['BitRate']
|
||||
newValueDict['Format'] = match['Format']
|
||||
myDB.action('DELETE from have WHERE Location=?', [match['Location']])
|
||||
|
||||
myDB.upsert("tracks", newValueDict, controlValueDict)
|
||||
|
||||
latestalbum = myDB.action('SELECT AlbumTitle, ReleaseDate, AlbumID from albums WHERE ArtistID=? order by ReleaseDate DESC', [artistid]).fetchone()
|
||||
totaltracks = len(myDB.select('SELECT TrackTitle from tracks WHERE ArtistID=?', [artistid]))
|
||||
havetracks = len(myDB.select('SELECT TrackTitle from tracks WHERE ArtistID=? AND Location IS NOT NULL', [artistid])) + len(myDB.select('SELECT TrackTitle from have WHERE ArtistName like ?', [artist['artist_name']]))
|
||||
for rg in artist['releasegroups']:
|
||||
|
||||
rgid = rg['id']
|
||||
|
||||
# check if the album already exists
|
||||
rg_exists = myDB.select("SELECT * from albums WHERE AlbumID=?", [rg['id']])
|
||||
|
||||
try:
|
||||
release_dict = mb.getReleaseGroup(rgid)
|
||||
except Exception, e:
|
||||
logger.info('Unable to get release information for %s - there may not be any official releases in this release group' % rg['title'])
|
||||
continue
|
||||
|
||||
if not release_dict:
|
||||
continue
|
||||
|
||||
logger.info(u"Now adding/updating album: " + rg['title'])
|
||||
controlValueDict = {"AlbumID": rg['id']}
|
||||
|
||||
if len(rg_exists):
|
||||
|
||||
newValueDict = {"AlbumASIN": release_dict['asin'],
|
||||
"ReleaseDate": release_dict['releasedate'],
|
||||
}
|
||||
|
||||
else:
|
||||
|
||||
newValueDict = {"ArtistID": artistid,
|
||||
"ArtistName": artist['artist_name'],
|
||||
"AlbumTitle": rg['title'],
|
||||
"AlbumASIN": release_dict['asin'],
|
||||
"ReleaseDate": release_dict['releasedate'],
|
||||
"DateAdded": helpers.today(),
|
||||
"Type": rg['type']
|
||||
}
|
||||
|
||||
if headphones.AUTOWANT_ALL:
|
||||
newValueDict['Status'] = "Wanted"
|
||||
elif release_dict['releasedate'] > helpers.today() and headphones.AUTOWANT_UPCOMING:
|
||||
newValueDict['Status'] = "Wanted"
|
||||
else:
|
||||
newValueDict['Status'] = "Skipped"
|
||||
|
||||
myDB.upsert("albums", newValueDict, controlValueDict)
|
||||
|
||||
# I changed the albumid from releaseid -> rgid, so might need to delete albums that have a releaseid
|
||||
for release in release_dict['releaselist']:
|
||||
myDB.action('DELETE from albums WHERE AlbumID=?', [release['releaseid']])
|
||||
myDB.action('DELETE from tracks WHERE AlbumID=?', [release['releaseid']])
|
||||
|
||||
for track in release_dict['tracks']:
|
||||
|
||||
cleanname = helpers.cleanName(artist['artist_name'] + ' ' + rg['title'] + ' ' + track['title'])
|
||||
|
||||
controlValueDict = {"TrackID": track['id'],
|
||||
"AlbumID": rg['id']}
|
||||
newValueDict = {"ArtistID": artistid,
|
||||
"ArtistName": artist['artist_name'],
|
||||
"AlbumTitle": rg['title'],
|
||||
"AlbumASIN": release_dict['asin'],
|
||||
"TrackTitle": track['title'],
|
||||
"TrackDuration": track['duration'],
|
||||
"TrackNumber": track['number'],
|
||||
"CleanName": cleanname
|
||||
}
|
||||
|
||||
match = myDB.action('SELECT Location, BitRate, Format from have WHERE CleanName=?', [cleanname]).fetchone()
|
||||
|
||||
if not match:
|
||||
match = myDB.action('SELECT Location, BitRate, Format from have WHERE ArtistName LIKE ? AND AlbumTitle LIKE ? AND TrackTitle LIKE ?', [artist['artist_name'], rg['title'], track['title']]).fetchone()
|
||||
if not match:
|
||||
match = myDB.action('SELECT Location, BitRate, Format from have WHERE TrackID=?', [track['id']]).fetchone()
|
||||
if match:
|
||||
newValueDict['Location'] = match['Location']
|
||||
newValueDict['BitRate'] = match['BitRate']
|
||||
newValueDict['Format'] = match['Format']
|
||||
myDB.action('DELETE from have WHERE Location=?', [match['Location']])
|
||||
|
||||
myDB.upsert("tracks", newValueDict, controlValueDict)
|
||||
|
||||
logger.debug(u"Updating album cache for " + rg['title'])
|
||||
cache.getThumb(AlbumID=rg['id'])
|
||||
|
||||
latestalbum = myDB.action('SELECT AlbumTitle, ReleaseDate, AlbumID from albums WHERE ArtistID=? order by ReleaseDate DESC', [artistid]).fetchone()
|
||||
totaltracks = len(myDB.select('SELECT TrackTitle from tracks WHERE ArtistID=?', [artistid]))
|
||||
havetracks = len(myDB.select('SELECT TrackTitle from tracks WHERE ArtistID=? AND Location IS NOT NULL', [artistid])) + len(myDB.select('SELECT TrackTitle from have WHERE ArtistName like ?', [artist['artist_name']]))
|
||||
|
||||
controlValueDict = {"ArtistID": artistid}
|
||||
|
||||
if latestalbum:
|
||||
newValueDict = {"Status": "Active",
|
||||
"LatestAlbum": latestalbum['AlbumTitle'],
|
||||
"ReleaseDate": latestalbum['ReleaseDate'],
|
||||
"AlbumID": latestalbum['AlbumID'],
|
||||
"TotalTracks": totaltracks,
|
||||
"HaveTracks": havetracks}
|
||||
else:
|
||||
newValueDict = {"Status": "Active",
|
||||
"TotalTracks": totaltracks,
|
||||
"HaveTracks": havetracks}
|
||||
|
||||
newValueDict['LastUpdated'] = helpers.now()
|
||||
|
||||
myDB.upsert("artists", newValueDict, controlValueDict)
|
||||
logger.info(u"Updating complete for: " + artist['artist_name'])
|
||||
|
||||
controlValueDict = {"ArtistID": artistid}
|
||||
|
||||
if latestalbum:
|
||||
newValueDict = {"Status": "Active",
|
||||
"LatestAlbum": latestalbum['AlbumTitle'],
|
||||
"ReleaseDate": latestalbum['ReleaseDate'],
|
||||
"AlbumID": latestalbum['AlbumID'],
|
||||
"TotalTracks": totaltracks,
|
||||
"HaveTracks": havetracks}
|
||||
else:
|
||||
newValueDict = {"Status": "Active",
|
||||
"TotalTracks": totaltracks,
|
||||
"HaveTracks": havetracks}
|
||||
|
||||
newValueDict['LastUpdated'] = helpers.now()
|
||||
|
||||
myDB.upsert("artists", newValueDict, controlValueDict)
|
||||
|
||||
logger.debug(u"Updating cache for: " + artist['artist_name'])
|
||||
cache.getThumb(ArtistID=artistid)
|
||||
|
||||
logger.info(u"Updating complete for: " + artist['artist_name'])
|
||||
|
||||
def addReleaseById(rid):
|
||||
|
||||
myDB = db.DBConnection()
|
||||
|
||||
myDB = db.DBConnection()
|
||||
|
||||
rgid = None
|
||||
artistid = None
|
||||
release_dict = None
|
||||
results = myDB.select("SELECT albums.ArtistID, releases.ReleaseGroupID from releases, albums WHERE releases.ReleaseID=? and releases.ReleaseGroupID=albums.AlbumID LIMIT 1", [rid])
|
||||
for result in results:
|
||||
rgid = result['ReleaseGroupID']
|
||||
artistid = result['ArtistID']
|
||||
logger.debug("Found a cached releaseid : releasegroupid relationship: " + rid + " : " + rgid)
|
||||
if not rgid:
|
||||
#didn't find it in the cache, get the information from MB
|
||||
logger.debug("Didn't find releaseID " + rid + " in the cache. Looking up its ReleaseGroupID")
|
||||
try:
|
||||
release_dict = mb.getRelease(rid)
|
||||
except Exception, e:
|
||||
logger.info('Unable to get release information for Release: ' + str(rid) + " " + str(e))
|
||||
return
|
||||
if not release_dict:
|
||||
logger.info('Unable to get release information for Release: ' + str(rid) + " no dict")
|
||||
return
|
||||
|
||||
rgid = release_dict['rgid']
|
||||
artistid = release_dict['artist_id']
|
||||
|
||||
#we don't want to make more calls to MB here unless we have to, could be happening quite a lot
|
||||
rg_exists = myDB.select("SELECT * from albums WHERE AlbumID=?", [rgid])
|
||||
|
||||
#make sure the artist exists since I don't know what happens later if it doesn't
|
||||
artist_exists = myDB.select("SELECT * from artists WHERE ArtistID=?", [artistid])
|
||||
|
||||
if not artist_exists and release_dict:
|
||||
if release_dict['artist_name'].startswith('The '):
|
||||
sortname = release_dict['artist_name'][4:]
|
||||
else:
|
||||
sortname = release_dict['artist_name']
|
||||
|
||||
|
||||
logger.info(u"Now manually adding: " + release_dict['artist_name'] + " - with status Paused")
|
||||
controlValueDict = {"ArtistID": release_dict['artist_id']}
|
||||
newValueDict = {"ArtistName": release_dict['artist_name'],
|
||||
"ArtistSortName": sortname,
|
||||
"DateAdded": helpers.today(),
|
||||
"Status": "Paused"}
|
||||
|
||||
if headphones.INCLUDE_EXTRAS:
|
||||
newValueDict['IncludeExtras'] = 1
|
||||
|
||||
myDB.upsert("artists", newValueDict, controlValueDict)
|
||||
|
||||
elif not artist_exists and not release_dict:
|
||||
logger.error("Artist does not exist in the database and did not get a valid response from MB. Skipping release.")
|
||||
return
|
||||
|
||||
if not rg_exists and release_dict: #it should never be the case that we have an rg and not the artist
|
||||
#but if it is this will fail
|
||||
logger.info(u"Now adding-by-id album (" + release_dict['title'] + ") from id: " + rgid)
|
||||
controlValueDict = {"AlbumID": rgid}
|
||||
rgid = None
|
||||
artistid = None
|
||||
release_dict = None
|
||||
results = myDB.select("SELECT albums.ArtistID, releases.ReleaseGroupID from releases, albums WHERE releases.ReleaseID=? and releases.ReleaseGroupID=albums.AlbumID LIMIT 1", [rid])
|
||||
for result in results:
|
||||
rgid = result['ReleaseGroupID']
|
||||
artistid = result['ArtistID']
|
||||
logger.debug("Found a cached releaseid : releasegroupid relationship: " + rid + " : " + rgid)
|
||||
if not rgid:
|
||||
#didn't find it in the cache, get the information from MB
|
||||
logger.debug("Didn't find releaseID " + rid + " in the cache. Looking up its ReleaseGroupID")
|
||||
try:
|
||||
release_dict = mb.getRelease(rid)
|
||||
except Exception, e:
|
||||
logger.info('Unable to get release information for Release: ' + str(rid) + " " + str(e))
|
||||
return
|
||||
if not release_dict:
|
||||
logger.info('Unable to get release information for Release: ' + str(rid) + " no dict")
|
||||
return
|
||||
|
||||
rgid = release_dict['rgid']
|
||||
artistid = release_dict['artist_id']
|
||||
|
||||
#we don't want to make more calls to MB here unless we have to, could be happening quite a lot
|
||||
rg_exists = myDB.select("SELECT * from albums WHERE AlbumID=?", [rgid])
|
||||
|
||||
#make sure the artist exists since I don't know what happens later if it doesn't
|
||||
artist_exists = myDB.select("SELECT * from artists WHERE ArtistID=?", [artistid])
|
||||
|
||||
if not artist_exists and release_dict:
|
||||
if release_dict['artist_name'].startswith('The '):
|
||||
sortname = release_dict['artist_name'][4:]
|
||||
else:
|
||||
sortname = release_dict['artist_name']
|
||||
|
||||
|
||||
logger.info(u"Now manually adding: " + release_dict['artist_name'] + " - with status Paused")
|
||||
controlValueDict = {"ArtistID": release_dict['artist_id']}
|
||||
newValueDict = {"ArtistName": release_dict['artist_name'],
|
||||
"ArtistSortName": sortname,
|
||||
"DateAdded": helpers.today(),
|
||||
"Status": "Paused"}
|
||||
|
||||
if headphones.INCLUDE_EXTRAS:
|
||||
newValueDict['IncludeExtras'] = 1
|
||||
|
||||
myDB.upsert("artists", newValueDict, controlValueDict)
|
||||
|
||||
elif not artist_exists and not release_dict:
|
||||
logger.error("Artist does not exist in the database and did not get a valid response from MB. Skipping release.")
|
||||
return
|
||||
|
||||
if not rg_exists and release_dict: #it should never be the case that we have an rg and not the artist
|
||||
#but if it is this will fail
|
||||
logger.info(u"Now adding-by-id album (" + release_dict['title'] + ") from id: " + rgid)
|
||||
controlValueDict = {"AlbumID": rgid}
|
||||
|
||||
newValueDict = {"ArtistID": release_dict['artist_id'],
|
||||
"ArtistName": release_dict['artist_name'],
|
||||
"AlbumTitle": release_dict['rg_title'],
|
||||
"AlbumASIN": release_dict['asin'],
|
||||
"ReleaseDate": release_dict['date'],
|
||||
"DateAdded": helpers.today(),
|
||||
"Status": 'Wanted',
|
||||
"Type": release_dict['rg_type']
|
||||
}
|
||||
|
||||
myDB.upsert("albums", newValueDict, controlValueDict)
|
||||
newValueDict = {"ArtistID": release_dict['artist_id'],
|
||||
"ArtistName": release_dict['artist_name'],
|
||||
"AlbumTitle": release_dict['rg_title'],
|
||||
"AlbumASIN": release_dict['asin'],
|
||||
"ReleaseDate": release_dict['date'],
|
||||
"DateAdded": helpers.today(),
|
||||
"Status": 'Wanted',
|
||||
"Type": release_dict['rg_type']
|
||||
}
|
||||
|
||||
myDB.upsert("albums", newValueDict, controlValueDict)
|
||||
|
||||
#keep a local cache of these so that external programs that are adding releasesByID don't hammer MB
|
||||
myDB.action('INSERT INTO releases VALUES( ?, ?)', [rid, release_dict['rgid']])
|
||||
|
||||
for track in release_dict['tracks']:
|
||||
|
||||
cleanname = helpers.cleanName(release_dict['artist_name'] + ' ' + release_dict['rg_title'] + ' ' + track['title'])
|
||||
|
||||
controlValueDict = {"TrackID": track['id'],
|
||||
"AlbumID": rgid}
|
||||
newValueDict = {"ArtistID": release_dict['artist_id'],
|
||||
"ArtistName": release_dict['artist_name'],
|
||||
"AlbumTitle": release_dict['rg_title'],
|
||||
"AlbumASIN": release_dict['asin'],
|
||||
"TrackTitle": track['title'],
|
||||
"TrackDuration": track['duration'],
|
||||
"TrackNumber": track['number'],
|
||||
"CleanName": cleanname
|
||||
}
|
||||
|
||||
match = myDB.action('SELECT Location, BitRate, Format from have WHERE CleanName=?', [cleanname]).fetchone()
|
||||
|
||||
if not match:
|
||||
match = myDB.action('SELECT Location, BitRate, Format from have WHERE ArtistName LIKE ? AND AlbumTitle LIKE ? AND TrackTitle LIKE ?', [release_dict['artist_name'], release_dict['rg_title'], track['title']]).fetchone()
|
||||
|
||||
if not match:
|
||||
match = myDB.action('SELECT Location, BitRate, Format from have WHERE TrackID=?', [track['id']]).fetchone()
|
||||
|
||||
if match:
|
||||
newValueDict['Location'] = match['Location']
|
||||
newValueDict['BitRate'] = match['BitRate']
|
||||
newValueDict['Format'] = match['Format']
|
||||
myDB.action('DELETE from have WHERE Location=?', [match['Location']])
|
||||
|
||||
myDB.upsert("tracks", newValueDict, controlValueDict)
|
||||
|
||||
#start a search for the album
|
||||
import searcher
|
||||
searcher.searchNZB(rgid, False)
|
||||
elif not rg_exists and not release_dict:
|
||||
logger.error("ReleaseGroup does not exist in the database and did not get a valid response from MB. Skipping release.")
|
||||
return
|
||||
else:
|
||||
logger.info('Release ' + str(rid) + " already exists in the database!")
|
||||
#keep a local cache of these so that external programs that are adding releasesByID don't hammer MB
|
||||
myDB.action('INSERT INTO releases VALUES( ?, ?)', [rid, release_dict['rgid']])
|
||||
|
||||
for track in release_dict['tracks']:
|
||||
|
||||
cleanname = helpers.cleanName(release_dict['artist_name'] + ' ' + release_dict['rg_title'] + ' ' + track['title'])
|
||||
|
||||
controlValueDict = {"TrackID": track['id'],
|
||||
"AlbumID": rgid}
|
||||
newValueDict = {"ArtistID": release_dict['artist_id'],
|
||||
"ArtistName": release_dict['artist_name'],
|
||||
"AlbumTitle": release_dict['rg_title'],
|
||||
"AlbumASIN": release_dict['asin'],
|
||||
"TrackTitle": track['title'],
|
||||
"TrackDuration": track['duration'],
|
||||
"TrackNumber": track['number'],
|
||||
"CleanName": cleanname
|
||||
}
|
||||
|
||||
match = myDB.action('SELECT Location, BitRate, Format from have WHERE CleanName=?', [cleanname]).fetchone()
|
||||
|
||||
if not match:
|
||||
match = myDB.action('SELECT Location, BitRate, Format from have WHERE ArtistName LIKE ? AND AlbumTitle LIKE ? AND TrackTitle LIKE ?', [release_dict['artist_name'], release_dict['rg_title'], track['title']]).fetchone()
|
||||
|
||||
if not match:
|
||||
match = myDB.action('SELECT Location, BitRate, Format from have WHERE TrackID=?', [track['id']]).fetchone()
|
||||
|
||||
if match:
|
||||
newValueDict['Location'] = match['Location']
|
||||
newValueDict['BitRate'] = match['BitRate']
|
||||
newValueDict['Format'] = match['Format']
|
||||
myDB.action('DELETE from have WHERE Location=?', [match['Location']])
|
||||
|
||||
myDB.upsert("tracks", newValueDict, controlValueDict)
|
||||
|
||||
#start a search for the album
|
||||
import searcher
|
||||
searcher.searchNZB(rgid, False)
|
||||
elif not rg_exists and not release_dict:
|
||||
logger.error("ReleaseGroup does not exist in the database and did not get a valid response from MB. Skipping release.")
|
||||
return
|
||||
else:
|
||||
logger.info('Release ' + str(rid) + " already exists in the database!")
|
||||
|
||||
def updateFormat():
|
||||
myDB = db.DBConnection()
|
||||
tracks = myDB.select('SELECT * from tracks WHERE Location IS NOT NULL and Format IS NULL')
|
||||
if len(tracks) > 0:
|
||||
logger.info('Finding media format for %s files' % len(tracks))
|
||||
for track in tracks:
|
||||
try:
|
||||
f = MediaFile(track['Location'])
|
||||
except Exception, e:
|
||||
logger.info("Exception from MediaFile for: " + track['Location'] + " : " + str(e))
|
||||
continue
|
||||
controlValueDict = {"TrackID": track['TrackID']}
|
||||
newValueDict = {"Format": f.format}
|
||||
myDB.upsert("tracks", newValueDict, controlValueDict)
|
||||
logger.info('Finished finding media format for %s files' % len(tracks))
|
||||
havetracks = myDB.select('SELECT * from have WHERE Location IS NOT NULL and Format IS NULL')
|
||||
if len(havetracks) > 0:
|
||||
logger.info('Finding media format for %s files' % len(havetracks))
|
||||
for track in havetracks:
|
||||
try:
|
||||
f = MediaFile(track['Location'])
|
||||
except Exception, e:
|
||||
logger.info("Exception from MediaFile for: " + track['Location'] + " : " + str(e))
|
||||
continue
|
||||
controlValueDict = {"TrackID": track['TrackID']}
|
||||
newValueDict = {"Format": f.format}
|
||||
myDB.upsert("have", newValueDict, controlValueDict)
|
||||
logger.info('Finished finding media format for %s files' % len(havetracks))
|
||||
myDB = db.DBConnection()
|
||||
tracks = myDB.select('SELECT * from tracks WHERE Location IS NOT NULL and Format IS NULL')
|
||||
if len(tracks) > 0:
|
||||
logger.info('Finding media format for %s files' % len(tracks))
|
||||
for track in tracks:
|
||||
try:
|
||||
f = MediaFile(track['Location'])
|
||||
except Exception, e:
|
||||
logger.info("Exception from MediaFile for: " + track['Location'] + " : " + str(e))
|
||||
continue
|
||||
controlValueDict = {"TrackID": track['TrackID']}
|
||||
newValueDict = {"Format": f.format}
|
||||
myDB.upsert("tracks", newValueDict, controlValueDict)
|
||||
logger.info('Finished finding media format for %s files' % len(tracks))
|
||||
havetracks = myDB.select('SELECT * from have WHERE Location IS NOT NULL and Format IS NULL')
|
||||
if len(havetracks) > 0:
|
||||
logger.info('Finding media format for %s files' % len(havetracks))
|
||||
for track in havetracks:
|
||||
try:
|
||||
f = MediaFile(track['Location'])
|
||||
except Exception, e:
|
||||
logger.info("Exception from MediaFile for: " + track['Location'] + " : " + str(e))
|
||||
continue
|
||||
controlValueDict = {"TrackID": track['TrackID']}
|
||||
newValueDict = {"Format": f.format}
|
||||
myDB.upsert("have", newValueDict, controlValueDict)
|
||||
logger.info('Finished finding media format for %s files' % len(havetracks))
|
||||
|
||||
@@ -1,3 +1,18 @@
|
||||
# This file is part of Headphones.
|
||||
#
|
||||
# Headphones 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.
|
||||
#
|
||||
# Headphones 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 Headphones. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import urllib
|
||||
from xml.dom import minidom
|
||||
from collections import defaultdict
|
||||
@@ -11,179 +26,179 @@ api_key = '395e6ec6bb557382fc41fde867bce66f'
|
||||
|
||||
|
||||
def getSimilar():
|
||||
|
||||
myDB = db.DBConnection()
|
||||
results = myDB.select('SELECT ArtistID from artists ORDER BY HaveTracks DESC')
|
||||
|
||||
artistlist = []
|
||||
|
||||
for result in results[:12]:
|
||||
|
||||
url = 'http://ws.audioscrobbler.com/2.0/?method=artist.getsimilar&mbid=%s&api_key=%s' % (result['ArtistID'], api_key)
|
||||
|
||||
try:
|
||||
data = urllib.urlopen(url).read()
|
||||
except:
|
||||
time.sleep(1)
|
||||
continue
|
||||
|
||||
if len(data) < 200:
|
||||
continue
|
||||
|
||||
d = minidom.parseString(data)
|
||||
node = d.documentElement
|
||||
artists = d.getElementsByTagName("artist")
|
||||
|
||||
for artist in artists:
|
||||
namenode = artist.getElementsByTagName("name")[0].childNodes
|
||||
mbidnode = artist.getElementsByTagName("mbid")[0].childNodes
|
||||
|
||||
for node in namenode:
|
||||
artist_name = node.data
|
||||
for node in mbidnode:
|
||||
artist_mbid = node.data
|
||||
|
||||
try:
|
||||
if not any(artist_mbid in x for x in results):
|
||||
artistlist.append((artist_name, artist_mbid))
|
||||
except:
|
||||
continue
|
||||
|
||||
count = defaultdict(int)
|
||||
|
||||
for artist, mbid in artistlist:
|
||||
count[artist, mbid] += 1
|
||||
|
||||
items = count.items()
|
||||
|
||||
top_list = sorted(items, key=lambda x: x[1], reverse=True)[:25]
|
||||
|
||||
random.shuffle(top_list)
|
||||
|
||||
myDB.action('''DELETE from lastfmcloud''')
|
||||
for tuple in top_list:
|
||||
artist_name, artist_mbid = tuple[0]
|
||||
count = tuple[1]
|
||||
myDB.action('INSERT INTO lastfmcloud VALUES( ?, ?, ?)', [artist_name, artist_mbid, count])
|
||||
|
||||
|
||||
myDB = db.DBConnection()
|
||||
results = myDB.select('SELECT ArtistID from artists ORDER BY HaveTracks DESC')
|
||||
|
||||
artistlist = []
|
||||
|
||||
for result in results[:12]:
|
||||
|
||||
url = 'http://ws.audioscrobbler.com/2.0/?method=artist.getsimilar&mbid=%s&api_key=%s' % (result['ArtistID'], api_key)
|
||||
|
||||
try:
|
||||
data = urllib.urlopen(url).read()
|
||||
except:
|
||||
time.sleep(1)
|
||||
continue
|
||||
|
||||
if len(data) < 200:
|
||||
continue
|
||||
|
||||
d = minidom.parseString(data)
|
||||
node = d.documentElement
|
||||
artists = d.getElementsByTagName("artist")
|
||||
|
||||
for artist in artists:
|
||||
namenode = artist.getElementsByTagName("name")[0].childNodes
|
||||
mbidnode = artist.getElementsByTagName("mbid")[0].childNodes
|
||||
|
||||
for node in namenode:
|
||||
artist_name = node.data
|
||||
for node in mbidnode:
|
||||
artist_mbid = node.data
|
||||
|
||||
try:
|
||||
if not any(artist_mbid in x for x in results):
|
||||
artistlist.append((artist_name, artist_mbid))
|
||||
except:
|
||||
continue
|
||||
|
||||
count = defaultdict(int)
|
||||
|
||||
for artist, mbid in artistlist:
|
||||
count[artist, mbid] += 1
|
||||
|
||||
items = count.items()
|
||||
|
||||
top_list = sorted(items, key=lambda x: x[1], reverse=True)[:25]
|
||||
|
||||
random.shuffle(top_list)
|
||||
|
||||
myDB.action('''DELETE from lastfmcloud''')
|
||||
for tuple in top_list:
|
||||
artist_name, artist_mbid = tuple[0]
|
||||
count = tuple[1]
|
||||
myDB.action('INSERT INTO lastfmcloud VALUES( ?, ?, ?)', [artist_name, artist_mbid, count])
|
||||
|
||||
def getArtists():
|
||||
|
||||
myDB = db.DBConnection()
|
||||
results = myDB.select('SELECT ArtistID from artists')
|
||||
myDB = db.DBConnection()
|
||||
results = myDB.select('SELECT ArtistID from artists')
|
||||
|
||||
if not headphones.LASTFM_USERNAME:
|
||||
return
|
||||
|
||||
else:
|
||||
username = headphones.LASTFM_USERNAME
|
||||
|
||||
url = 'http://ws.audioscrobbler.com/2.0/?method=library.getartists&limit=10000&api_key=%s&user=%s' % (api_key, username)
|
||||
data = urllib.urlopen(url).read()
|
||||
d = minidom.parseString(data)
|
||||
artists = d.getElementsByTagName("artist")
|
||||
|
||||
artistlist = []
|
||||
|
||||
for artist in artists:
|
||||
mbidnode = artist.getElementsByTagName("mbid")[0].childNodes
|
||||
if not headphones.LASTFM_USERNAME:
|
||||
return
|
||||
|
||||
else:
|
||||
username = headphones.LASTFM_USERNAME
|
||||
|
||||
url = 'http://ws.audioscrobbler.com/2.0/?method=library.getartists&limit=10000&api_key=%s&user=%s' % (api_key, username)
|
||||
data = urllib.urlopen(url).read()
|
||||
d = minidom.parseString(data)
|
||||
artists = d.getElementsByTagName("artist")
|
||||
|
||||
artistlist = []
|
||||
|
||||
for artist in artists:
|
||||
mbidnode = artist.getElementsByTagName("mbid")[0].childNodes
|
||||
|
||||
for node in mbidnode:
|
||||
artist_mbid = node.data
|
||||
|
||||
try:
|
||||
if not any(artist_mbid in x for x in results):
|
||||
artistlist.append(artist_mbid)
|
||||
except:
|
||||
continue
|
||||
|
||||
from headphones import importer
|
||||
|
||||
for artistid in artistlist:
|
||||
importer.addArtisttoDB(artistid)
|
||||
|
||||
for node in mbidnode:
|
||||
artist_mbid = node.data
|
||||
|
||||
try:
|
||||
if not any(artist_mbid in x for x in results):
|
||||
artistlist.append(artist_mbid)
|
||||
except:
|
||||
continue
|
||||
|
||||
from headphones import importer
|
||||
|
||||
for artistid in artistlist:
|
||||
importer.addArtisttoDB(artistid)
|
||||
|
||||
def getAlbumDescription(rgid, artist, album):
|
||||
|
||||
myDB = db.DBConnection()
|
||||
result = myDB.select('SELECT Summary from descriptions WHERE ReleaseGroupID=?', [rgid])
|
||||
|
||||
if result:
|
||||
return
|
||||
|
||||
params = { "method": 'album.getInfo',
|
||||
"api_key": api_key,
|
||||
|
||||
myDB = db.DBConnection()
|
||||
result = myDB.select('SELECT Summary from descriptions WHERE ReleaseGroupID=?', [rgid])
|
||||
|
||||
if result:
|
||||
return
|
||||
|
||||
params = { "method": 'album.getInfo',
|
||||
"api_key": api_key,
|
||||
"artist": artist.encode('utf-8'),
|
||||
"album": album.encode('utf-8')
|
||||
}
|
||||
|
||||
searchURL = 'http://ws.audioscrobbler.com/2.0/?' + urllib.urlencode(params)
|
||||
data = urllib.urlopen(searchURL).read()
|
||||
|
||||
if data == '<?xml version="1.0" encoding="utf-8"?><lfm status="failed"><error code="6">Album not found</error></lfm>':
|
||||
return
|
||||
|
||||
try:
|
||||
d = minidom.parseString(data)
|
||||
searchURL = 'http://ws.audioscrobbler.com/2.0/?' + urllib.urlencode(params)
|
||||
data = urllib.urlopen(searchURL).read()
|
||||
|
||||
if data == '<?xml version="1.0" encoding="utf-8"?><lfm status="failed"><error code="6">Album not found</error></lfm>':
|
||||
return
|
||||
|
||||
try:
|
||||
d = minidom.parseString(data)
|
||||
|
||||
albuminfo = d.getElementsByTagName("album")
|
||||
|
||||
for item in albuminfo:
|
||||
summarynode = item.getElementsByTagName("summary")[0].childNodes
|
||||
contentnode = item.getElementsByTagName("content")[0].childNodes
|
||||
for node in summarynode:
|
||||
summary = node.data
|
||||
for node in contentnode:
|
||||
content = node.data
|
||||
|
||||
controlValueDict = {'ReleaseGroupID': rgid}
|
||||
newValueDict = {'Summary': summary,
|
||||
'Content': content}
|
||||
myDB.upsert("descriptions", newValueDict, controlValueDict)
|
||||
|
||||
except:
|
||||
return
|
||||
albuminfo = d.getElementsByTagName("album")
|
||||
|
||||
for item in albuminfo:
|
||||
summarynode = item.getElementsByTagName("summary")[0].childNodes
|
||||
contentnode = item.getElementsByTagName("content")[0].childNodes
|
||||
for node in summarynode:
|
||||
summary = node.data
|
||||
for node in contentnode:
|
||||
content = node.data
|
||||
|
||||
controlValueDict = {'ReleaseGroupID': rgid}
|
||||
newValueDict = {'Summary': summary,
|
||||
'Content': content}
|
||||
myDB.upsert("descriptions", newValueDict, controlValueDict)
|
||||
|
||||
except:
|
||||
return
|
||||
|
||||
def getAlbumDescriptionOld(rgid, releaselist):
|
||||
"""
|
||||
This was a dumb way to do it - going to just use artist & album name but keeping this here
|
||||
because I may use it to fetch and cache album art
|
||||
"""
|
||||
"""
|
||||
This was a dumb way to do it - going to just use artist & album name but keeping this here
|
||||
because I may use it to fetch and cache album art
|
||||
"""
|
||||
|
||||
myDB = db.DBConnection()
|
||||
result = myDB.select('SELECT Summary from descriptions WHERE ReleaseGroupID=?', [rgid])
|
||||
|
||||
if result:
|
||||
return
|
||||
|
||||
for release in releaselist:
|
||||
|
||||
mbid = release['releaseid']
|
||||
url = 'http://ws.audioscrobbler.com/2.0/?method=album.getInfo&mbid=%s&api_key=%s' % (mbid, api_key)
|
||||
data = urllib.urlopen(url).read()
|
||||
|
||||
if data == '<?xml version="1.0" encoding="utf-8"?><lfm status="failed"><error code="6">Album not found</error></lfm>':
|
||||
continue
|
||||
|
||||
try:
|
||||
d = minidom.parseString(data)
|
||||
|
||||
albuminfo = d.getElementsByTagName("album")
|
||||
|
||||
for item in albuminfo:
|
||||
summarynode = item.getElementsByTagName("summary")[0].childNodes
|
||||
contentnode = item.getElementsByTagName("content")[0].childNodes
|
||||
for node in summarynode:
|
||||
summary = node.data
|
||||
for node in contentnode:
|
||||
content = node.data
|
||||
|
||||
controlValueDict = {'ReleaseGroupID': rgid}
|
||||
newValueDict = {'ReleaseID': mbid,
|
||||
'Summary': summary,
|
||||
'Content': content}
|
||||
myDB.upsert("descriptions", newValueDict, controlValueDict)
|
||||
break
|
||||
|
||||
except:
|
||||
continue
|
||||
|
||||
|
||||
myDB = db.DBConnection()
|
||||
result = myDB.select('SELECT Summary from descriptions WHERE ReleaseGroupID=?', [rgid])
|
||||
|
||||
if result:
|
||||
return
|
||||
|
||||
for release in releaselist:
|
||||
|
||||
mbid = release['releaseid']
|
||||
url = 'http://ws.audioscrobbler.com/2.0/?method=album.getInfo&mbid=%s&api_key=%s' % (mbid, api_key)
|
||||
data = urllib.urlopen(url).read()
|
||||
|
||||
if data == '<?xml version="1.0" encoding="utf-8"?><lfm status="failed"><error code="6">Album not found</error></lfm>':
|
||||
continue
|
||||
|
||||
try:
|
||||
d = minidom.parseString(data)
|
||||
|
||||
albuminfo = d.getElementsByTagName("album")
|
||||
|
||||
for item in albuminfo:
|
||||
summarynode = item.getElementsByTagName("summary")[0].childNodes
|
||||
contentnode = item.getElementsByTagName("content")[0].childNodes
|
||||
for node in summarynode:
|
||||
summary = node.data
|
||||
for node in contentnode:
|
||||
content = node.data
|
||||
|
||||
controlValueDict = {'ReleaseGroupID': rgid}
|
||||
newValueDict = {'ReleaseID': mbid,
|
||||
'Summary': summary,
|
||||
'Content': content}
|
||||
myDB.upsert("descriptions", newValueDict, controlValueDict)
|
||||
break
|
||||
|
||||
except:
|
||||
continue
|
||||
|
||||
|
||||
|
||||
@@ -1,3 +1,18 @@
|
||||
# This file is part of Headphones.
|
||||
#
|
||||
# Headphones 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.
|
||||
#
|
||||
# Headphones 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 Headphones. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import os
|
||||
import glob
|
||||
|
||||
@@ -8,212 +23,212 @@ from headphones import db, logger, helpers, importer
|
||||
|
||||
def libraryScan(dir=None):
|
||||
|
||||
if not dir:
|
||||
dir = headphones.MUSIC_DIR
|
||||
|
||||
try:
|
||||
dir = str(dir)
|
||||
except UnicodeEncodeError:
|
||||
dir = unicode(dir).encode('unicode_escape')
|
||||
|
||||
if not os.path.isdir(dir):
|
||||
logger.warn('Cannot find directory: %s. Not scanning' % dir)
|
||||
return
|
||||
if not dir:
|
||||
dir = headphones.MUSIC_DIR
|
||||
|
||||
try:
|
||||
dir = str(dir)
|
||||
except UnicodeEncodeError:
|
||||
dir = unicode(dir).encode('unicode_escape')
|
||||
|
||||
if not os.path.isdir(dir):
|
||||
logger.warn('Cannot find directory: %s. Not scanning' % dir)
|
||||
return
|
||||
|
||||
myDB = db.DBConnection()
|
||||
|
||||
# Clean up bad filepaths
|
||||
tracks = myDB.select('SELECT Location, TrackID from tracks WHERE Location IS NOT NULL')
|
||||
|
||||
for track in tracks:
|
||||
if not os.path.isfile(track['Location'].encode(headphones.SYS_ENCODING)):
|
||||
myDB.action('UPDATE tracks SET Location=?, BitRate=?, Format=? WHERE TrackID=?', [None, None, None, track['TrackID']])
|
||||
myDB = db.DBConnection()
|
||||
|
||||
# Clean up bad filepaths
|
||||
tracks = myDB.select('SELECT Location, TrackID from tracks WHERE Location IS NOT NULL')
|
||||
|
||||
for track in tracks:
|
||||
if not os.path.isfile(track['Location'].encode(headphones.SYS_ENCODING)):
|
||||
myDB.action('UPDATE tracks SET Location=?, BitRate=?, Format=? WHERE TrackID=?', [None, None, None, track['TrackID']])
|
||||
|
||||
logger.info('Scanning music directory: %s' % dir)
|
||||
logger.info('Scanning music directory: %s' % dir)
|
||||
|
||||
new_artists = []
|
||||
bitrates = []
|
||||
new_artists = []
|
||||
bitrates = []
|
||||
|
||||
myDB.action('DELETE from have')
|
||||
|
||||
for r,d,f in os.walk(dir):
|
||||
for files in f:
|
||||
# MEDIA_FORMATS = music file extensions, e.g. mp3, flac, etc
|
||||
if any(files.lower().endswith('.' + x.lower()) for x in headphones.MEDIA_FORMATS):
|
||||
myDB.action('DELETE from have')
|
||||
|
||||
for r,d,f in os.walk(dir):
|
||||
for files in f:
|
||||
# MEDIA_FORMATS = music file extensions, e.g. mp3, flac, etc
|
||||
if any(files.lower().endswith('.' + x.lower()) for x in headphones.MEDIA_FORMATS):
|
||||
|
||||
song = os.path.join(r, files)
|
||||
file = unicode(os.path.join(r, files), headphones.SYS_ENCODING, errors='replace')
|
||||
song = os.path.join(r, files)
|
||||
file = unicode(os.path.join(r, files), headphones.SYS_ENCODING, errors='replace')
|
||||
|
||||
# Try to read the metadata
|
||||
try:
|
||||
f = MediaFile(song)
|
||||
# Try to read the metadata
|
||||
try:
|
||||
f = MediaFile(song)
|
||||
|
||||
except:
|
||||
logger.error('Cannot read file: ' + file)
|
||||
continue
|
||||
|
||||
# Grab the bitrates for the auto detect bit rate option
|
||||
if f.bitrate:
|
||||
bitrates.append(f.bitrate)
|
||||
|
||||
# Try to find a match based on artist/album/tracktitle
|
||||
if f.albumartist:
|
||||
f_artist = f.albumartist
|
||||
elif f.artist:
|
||||
f_artist = f.artist
|
||||
else:
|
||||
continue
|
||||
|
||||
if f_artist and f.album and f.title:
|
||||
except:
|
||||
logger.error('Cannot read file: ' + file)
|
||||
continue
|
||||
|
||||
# Grab the bitrates for the auto detect bit rate option
|
||||
if f.bitrate:
|
||||
bitrates.append(f.bitrate)
|
||||
|
||||
# Try to find a match based on artist/album/tracktitle
|
||||
if f.albumartist:
|
||||
f_artist = f.albumartist
|
||||
elif f.artist:
|
||||
f_artist = f.artist
|
||||
else:
|
||||
continue
|
||||
|
||||
if f_artist and f.album and f.title:
|
||||
|
||||
track = myDB.action('SELECT TrackID from tracks WHERE CleanName LIKE ?', [helpers.cleanName(f_artist +' '+f.album+' '+f.title)]).fetchone()
|
||||
|
||||
if not track:
|
||||
track = myDB.action('SELECT TrackID from tracks WHERE ArtistName LIKE ? AND AlbumTitle LIKE ? AND TrackTitle LIKE ?', [f_artist, f.album, f.title]).fetchone()
|
||||
|
||||
if track:
|
||||
myDB.action('UPDATE tracks SET Location=?, BitRate=?, Format=? WHERE TrackID=?', [file, f.bitrate, f.format, track['TrackID']])
|
||||
continue
|
||||
|
||||
# Try to match on mbid if available and we couldn't find a match based on metadata
|
||||
if f.mb_trackid:
|
||||
track = myDB.action('SELECT TrackID from tracks WHERE CleanName LIKE ?', [helpers.cleanName(f_artist +' '+f.album+' '+f.title)]).fetchone()
|
||||
|
||||
if not track:
|
||||
track = myDB.action('SELECT TrackID from tracks WHERE ArtistName LIKE ? AND AlbumTitle LIKE ? AND TrackTitle LIKE ?', [f_artist, f.album, f.title]).fetchone()
|
||||
|
||||
if track:
|
||||
myDB.action('UPDATE tracks SET Location=?, BitRate=?, Format=? WHERE TrackID=?', [file, f.bitrate, f.format, track['TrackID']])
|
||||
continue
|
||||
|
||||
# Try to match on mbid if available and we couldn't find a match based on metadata
|
||||
if f.mb_trackid:
|
||||
|
||||
# Wondering if theres a better way to do this -> do one thing if the row exists,
|
||||
# do something else if it doesn't
|
||||
track = myDB.action('SELECT TrackID from tracks WHERE TrackID=?', [f.mb_trackid]).fetchone()
|
||||
|
||||
if track:
|
||||
myDB.action('UPDATE tracks SET Location=?, BitRate=?, Format=? WHERE TrackID=?', [file, f.bitrate, f.format, track['TrackID']])
|
||||
continue
|
||||
|
||||
# if we can't find a match in the database on a track level, it might be a new artist or it might be on a non-mb release
|
||||
new_artists.append(f_artist)
|
||||
|
||||
# The have table will become the new database for unmatched tracks (i.e. tracks with no associated links in the database
|
||||
myDB.action('INSERT INTO have (ArtistName, AlbumTitle, TrackNumber, TrackTitle, TrackLength, BitRate, Genre, Date, TrackID, Location, CleanName, Format) VALUES( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', [f_artist, f.album, f.track, f.title, f.length, f.bitrate, f.genre, f.date, f.mb_trackid, file, helpers.cleanName(f_artist+' '+f.album+' '+f.title), f.format])
|
||||
# Wondering if theres a better way to do this -> do one thing if the row exists,
|
||||
# do something else if it doesn't
|
||||
track = myDB.action('SELECT TrackID from tracks WHERE TrackID=?', [f.mb_trackid]).fetchone()
|
||||
|
||||
if track:
|
||||
myDB.action('UPDATE tracks SET Location=?, BitRate=?, Format=? WHERE TrackID=?', [file, f.bitrate, f.format, track['TrackID']])
|
||||
continue
|
||||
|
||||
# if we can't find a match in the database on a track level, it might be a new artist or it might be on a non-mb release
|
||||
new_artists.append(f_artist)
|
||||
|
||||
# The have table will become the new database for unmatched tracks (i.e. tracks with no associated links in the database
|
||||
myDB.action('INSERT INTO have (ArtistName, AlbumTitle, TrackNumber, TrackTitle, TrackLength, BitRate, Genre, Date, TrackID, Location, CleanName, Format) VALUES( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', [f_artist, f.album, f.track, f.title, f.length, f.bitrate, f.genre, f.date, f.mb_trackid, file, helpers.cleanName(f_artist+' '+f.album+' '+f.title), f.format])
|
||||
|
||||
logger.info('Completed scanning of directory: %s' % dir)
|
||||
logger.info('Checking filepaths to see if we can find any matches')
|
||||
logger.info('Completed scanning of directory: %s' % dir)
|
||||
logger.info('Checking filepaths to see if we can find any matches')
|
||||
|
||||
# Now check empty file paths to see if we can find a match based on their folder format
|
||||
tracks = myDB.select('SELECT * from tracks WHERE Location IS NULL')
|
||||
for track in tracks:
|
||||
|
||||
release = myDB.action('SELECT * from albums WHERE AlbumID=?', [track['AlbumID']]).fetchone()
|
||||
# Now check empty file paths to see if we can find a match based on their folder format
|
||||
tracks = myDB.select('SELECT * from tracks WHERE Location IS NULL')
|
||||
for track in tracks:
|
||||
|
||||
release = myDB.action('SELECT * from albums WHERE AlbumID=?', [track['AlbumID']]).fetchone()
|
||||
|
||||
try:
|
||||
year = release['ReleaseDate'][:4]
|
||||
except TypeError:
|
||||
year = ''
|
||||
|
||||
artist = release['ArtistName'].replace('/', '_')
|
||||
album = release['AlbumTitle'].replace('/', '_')
|
||||
releasetype = release['Type'].replace('/', '_')
|
||||
|
||||
if release['ArtistName'].startswith('The '):
|
||||
sortname = release['ArtistName'][4:]
|
||||
else:
|
||||
sortname = release['ArtistName']
|
||||
|
||||
if sortname.isdigit():
|
||||
firstchar = '0-9'
|
||||
else:
|
||||
firstchar = sortname[0]
|
||||
try:
|
||||
year = release['ReleaseDate'][:4]
|
||||
except TypeError:
|
||||
year = ''
|
||||
|
||||
artist = release['ArtistName'].replace('/', '_')
|
||||
album = release['AlbumTitle'].replace('/', '_')
|
||||
releasetype = release['Type'].replace('/', '_')
|
||||
|
||||
if release['ArtistName'].startswith('The '):
|
||||
sortname = release['ArtistName'][4:]
|
||||
else:
|
||||
sortname = release['ArtistName']
|
||||
|
||||
if sortname.isdigit():
|
||||
firstchar = '0-9'
|
||||
else:
|
||||
firstchar = sortname[0]
|
||||
|
||||
|
||||
albumvalues = { '$Artist': artist,
|
||||
'$Album': album,
|
||||
'$Year': year,
|
||||
'$Type': releasetype,
|
||||
'$First': firstchar,
|
||||
'$artist': artist.lower(),
|
||||
'$album': album.lower(),
|
||||
'$year': year,
|
||||
'$type': releasetype.lower(),
|
||||
'$first': firstchar.lower()
|
||||
}
|
||||
|
||||
|
||||
folder = helpers.replace_all(headphones.FOLDER_FORMAT, albumvalues)
|
||||
folder = folder.replace('./', '_/').replace(':','_').replace('?','_')
|
||||
|
||||
if folder.endswith('.'):
|
||||
folder = folder.replace(folder[len(folder)-1], '_')
|
||||
|
||||
albumvalues = { '$Artist': artist,
|
||||
'$Album': album,
|
||||
'$Year': year,
|
||||
'$Type': releasetype,
|
||||
'$First': firstchar,
|
||||
'$artist': artist.lower(),
|
||||
'$album': album.lower(),
|
||||
'$year': year,
|
||||
'$type': releasetype.lower(),
|
||||
'$first': firstchar.lower()
|
||||
}
|
||||
|
||||
|
||||
folder = helpers.replace_all(headphones.FOLDER_FORMAT, albumvalues)
|
||||
folder = folder.replace('./', '_/').replace(':','_').replace('?','_')
|
||||
|
||||
if folder.endswith('.'):
|
||||
folder = folder.replace(folder[len(folder)-1], '_')
|
||||
|
||||
if not track['TrackNumber']:
|
||||
tracknumber = ''
|
||||
else:
|
||||
tracknumber = '%02d' % track['TrackNumber']
|
||||
|
||||
title = track['TrackTitle']
|
||||
|
||||
trackvalues = { '$Track': tracknumber,
|
||||
'$Title': title,
|
||||
'$Artist': release['ArtistName'],
|
||||
'$Album': release['AlbumTitle'],
|
||||
'$Year': year,
|
||||
'$track': tracknumber,
|
||||
'$title': title.lower(),
|
||||
'$artist': release['ArtistName'].lower(),
|
||||
'$album': release['AlbumTitle'].lower(),
|
||||
'$year': year
|
||||
}
|
||||
|
||||
new_file_name = helpers.replace_all(headphones.FILE_FORMAT, trackvalues).replace('/','_') + '.*'
|
||||
|
||||
new_file_name = new_file_name.replace('?','_').replace(':', '_')
|
||||
|
||||
full_path_to_file = os.path.normpath(os.path.join(headphones.MUSIC_DIR, folder, new_file_name)).encode(headphones.SYS_ENCODING, 'replace')
|
||||
if not track['TrackNumber']:
|
||||
tracknumber = ''
|
||||
else:
|
||||
tracknumber = '%02d' % track['TrackNumber']
|
||||
|
||||
title = track['TrackTitle']
|
||||
|
||||
trackvalues = { '$Track': tracknumber,
|
||||
'$Title': title,
|
||||
'$Artist': release['ArtistName'],
|
||||
'$Album': release['AlbumTitle'],
|
||||
'$Year': year,
|
||||
'$track': tracknumber,
|
||||
'$title': title.lower(),
|
||||
'$artist': release['ArtistName'].lower(),
|
||||
'$album': release['AlbumTitle'].lower(),
|
||||
'$year': year
|
||||
}
|
||||
|
||||
new_file_name = helpers.replace_all(headphones.FILE_FORMAT, trackvalues).replace('/','_') + '.*'
|
||||
|
||||
new_file_name = new_file_name.replace('?','_').replace(':', '_')
|
||||
|
||||
full_path_to_file = os.path.normpath(os.path.join(headphones.MUSIC_DIR, folder, new_file_name)).encode(headphones.SYS_ENCODING, 'replace')
|
||||
|
||||
match = glob.glob(full_path_to_file)
|
||||
|
||||
if match:
|
||||
match = glob.glob(full_path_to_file)
|
||||
|
||||
if match:
|
||||
|
||||
logger.info('Found a match: %s. Writing MBID to metadata' % match[0])
|
||||
|
||||
unipath = unicode(match[0], headphones.SYS_ENCODING, errors='replace')
|
||||
logger.info('Found a match: %s. Writing MBID to metadata' % match[0])
|
||||
|
||||
unipath = unicode(match[0], headphones.SYS_ENCODING, errors='replace')
|
||||
|
||||
myDB.action('UPDATE tracks SET Location=? WHERE TrackID=?', [unipath, track['TrackID']])
|
||||
myDB.action('DELETE from have WHERE Location=?', [unipath])
|
||||
|
||||
# Try to insert the appropriate track id so we don't have to keep doing this
|
||||
try:
|
||||
f = MediaFile(match[0])
|
||||
f.mb_trackid = track['TrackID']
|
||||
f.save()
|
||||
myDB.action('UPDATE tracks SET BitRate=?, Format=? WHERE TrackID=?', [f.bitrate, f.format, track['TrackID']])
|
||||
myDB.action('UPDATE tracks SET Location=? WHERE TrackID=?', [unipath, track['TrackID']])
|
||||
myDB.action('DELETE from have WHERE Location=?', [unipath])
|
||||
|
||||
# Try to insert the appropriate track id so we don't have to keep doing this
|
||||
try:
|
||||
f = MediaFile(match[0])
|
||||
f.mb_trackid = track['TrackID']
|
||||
f.save()
|
||||
myDB.action('UPDATE tracks SET BitRate=?, Format=? WHERE TrackID=?', [f.bitrate, f.format, track['TrackID']])
|
||||
|
||||
logger.debug('Wrote mbid to track: %s' % match[0])
|
||||
logger.debug('Wrote mbid to track: %s' % match[0])
|
||||
|
||||
except:
|
||||
logger.error('Error embedding track id into: %s' % match[0])
|
||||
continue
|
||||
except:
|
||||
logger.error('Error embedding track id into: %s' % match[0])
|
||||
continue
|
||||
|
||||
logger.info('Done checking empty filepaths')
|
||||
logger.info('Done syncing library with directory: %s' % dir)
|
||||
|
||||
# Clean up the new artist list
|
||||
unique_artists = {}.fromkeys(new_artists).keys()
|
||||
current_artists = myDB.select('SELECT ArtistName, ArtistID from artists')
|
||||
|
||||
artist_list = [f for f in unique_artists if f.lower() not in [x[0].lower() for x in current_artists]]
|
||||
|
||||
# Update track counts
|
||||
logger.info('Updating track counts')
|
||||
logger.info('Done checking empty filepaths')
|
||||
logger.info('Done syncing library with directory: %s' % dir)
|
||||
|
||||
# Clean up the new artist list
|
||||
unique_artists = {}.fromkeys(new_artists).keys()
|
||||
current_artists = myDB.select('SELECT ArtistName, ArtistID from artists')
|
||||
|
||||
artist_list = [f for f in unique_artists if f.lower() not in [x[0].lower() for x in current_artists]]
|
||||
|
||||
# Update track counts
|
||||
logger.info('Updating track counts')
|
||||
|
||||
for artist in current_artists:
|
||||
havetracks = len(myDB.select('SELECT TrackTitle from tracks WHERE ArtistID like ? AND Location IS NOT NULL', [artist['ArtistID']])) + len(myDB.select('SELECT TrackTitle from have WHERE ArtistName like ?', [artist['ArtistName']]))
|
||||
myDB.action('UPDATE artists SET HaveTracks=? WHERE ArtistID=?', [havetracks, artist['ArtistID']])
|
||||
|
||||
logger.info('Found %i new artists' % len(artist_list))
|
||||
for artist in current_artists:
|
||||
havetracks = len(myDB.select('SELECT TrackTitle from tracks WHERE ArtistID like ? AND Location IS NOT NULL', [artist['ArtistID']])) + len(myDB.select('SELECT TrackTitle from have WHERE ArtistName like ?', [artist['ArtistName']]))
|
||||
myDB.action('UPDATE artists SET HaveTracks=? WHERE ArtistID=?', [havetracks, artist['ArtistID']])
|
||||
|
||||
logger.info('Found %i new artists' % len(artist_list))
|
||||
|
||||
if len(artist_list):
|
||||
if headphones.ADD_ARTISTS:
|
||||
logger.info('Importing %i new artists' % len(artist_list))
|
||||
importer.artistlist_to_mbids(artist_list)
|
||||
else:
|
||||
logger.info('To add these artists, go to Manage->Manage New Artists')
|
||||
headphones.NEW_ARTISTS = artist_list
|
||||
|
||||
if headphones.DETECT_BITRATE:
|
||||
headphones.PREFERRED_BITRATE = sum(bitrates)/len(bitrates)/1000
|
||||
if len(artist_list):
|
||||
if headphones.ADD_ARTISTS:
|
||||
logger.info('Importing %i new artists' % len(artist_list))
|
||||
importer.artistlist_to_mbids(artist_list)
|
||||
else:
|
||||
logger.info('To add these artists, go to Manage->Manage New Artists')
|
||||
headphones.NEW_ARTISTS = artist_list
|
||||
|
||||
if headphones.DETECT_BITRATE:
|
||||
headphones.PREFERRED_BITRATE = sum(bitrates)/len(bitrates)/1000
|
||||
|
||||
@@ -1,3 +1,18 @@
|
||||
# This file is part of Headphones.
|
||||
#
|
||||
# Headphones 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.
|
||||
#
|
||||
# Headphones 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 Headphones. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import os
|
||||
import threading
|
||||
import logging
|
||||
@@ -13,69 +28,69 @@ MAX_FILES = 5
|
||||
# Simple rotating log handler that uses RotatingFileHandler
|
||||
class RotatingLogger(object):
|
||||
|
||||
def __init__(self, filename, max_size, max_files):
|
||||
|
||||
self.filename = filename
|
||||
self.max_size = max_size
|
||||
self.max_files = max_files
|
||||
|
||||
|
||||
def initLogger(self, verbose=1):
|
||||
|
||||
l = logging.getLogger('headphones')
|
||||
l.setLevel(logging.DEBUG)
|
||||
|
||||
self.filename = os.path.join(headphones.LOG_DIR, self.filename)
|
||||
|
||||
filehandler = handlers.RotatingFileHandler(self.filename, maxBytes=self.max_size, backupCount=self.max_files)
|
||||
filehandler.setLevel(logging.DEBUG)
|
||||
|
||||
fileformatter = logging.Formatter('%(asctime)s - %(levelname)-7s :: %(message)s', '%d-%b-%Y %H:%M:%S')
|
||||
|
||||
filehandler.setFormatter(fileformatter)
|
||||
l.addHandler(filehandler)
|
||||
|
||||
if verbose:
|
||||
consolehandler = logging.StreamHandler()
|
||||
if verbose == 1:
|
||||
consolehandler.setLevel(logging.INFO)
|
||||
if verbose == 2:
|
||||
consolehandler.setLevel(logging.DEBUG)
|
||||
consoleformatter = logging.Formatter('%(asctime)s - %(levelname)s :: %(message)s', '%d-%b-%Y %H:%M:%S')
|
||||
consolehandler.setFormatter(consoleformatter)
|
||||
l.addHandler(consolehandler)
|
||||
|
||||
def log(self, message, level):
|
||||
def __init__(self, filename, max_size, max_files):
|
||||
|
||||
self.filename = filename
|
||||
self.max_size = max_size
|
||||
self.max_files = max_files
|
||||
|
||||
|
||||
def initLogger(self, verbose=1):
|
||||
|
||||
l = logging.getLogger('headphones')
|
||||
l.setLevel(logging.DEBUG)
|
||||
|
||||
self.filename = os.path.join(headphones.LOG_DIR, self.filename)
|
||||
|
||||
filehandler = handlers.RotatingFileHandler(self.filename, maxBytes=self.max_size, backupCount=self.max_files)
|
||||
filehandler.setLevel(logging.DEBUG)
|
||||
|
||||
fileformatter = logging.Formatter('%(asctime)s - %(levelname)-7s :: %(message)s', '%d-%b-%Y %H:%M:%S')
|
||||
|
||||
filehandler.setFormatter(fileformatter)
|
||||
l.addHandler(filehandler)
|
||||
|
||||
if verbose:
|
||||
consolehandler = logging.StreamHandler()
|
||||
if verbose == 1:
|
||||
consolehandler.setLevel(logging.INFO)
|
||||
if verbose == 2:
|
||||
consolehandler.setLevel(logging.DEBUG)
|
||||
consoleformatter = logging.Formatter('%(asctime)s - %(levelname)s :: %(message)s', '%d-%b-%Y %H:%M:%S')
|
||||
consolehandler.setFormatter(consoleformatter)
|
||||
l.addHandler(consolehandler)
|
||||
|
||||
def log(self, message, level):
|
||||
|
||||
logger = logging.getLogger('headphones')
|
||||
|
||||
threadname = threading.currentThread().getName()
|
||||
|
||||
if level != 'DEBUG':
|
||||
headphones.LOG_LIST.insert(0, (helpers.now(), message, level, threadname))
|
||||
|
||||
message = threadname + ' : ' + message
|
||||
logger = logging.getLogger('headphones')
|
||||
|
||||
threadname = threading.currentThread().getName()
|
||||
|
||||
if level != 'DEBUG':
|
||||
headphones.LOG_LIST.insert(0, (helpers.now(), message, level, threadname))
|
||||
|
||||
message = threadname + ' : ' + message
|
||||
|
||||
if level == 'DEBUG':
|
||||
logger.debug(message)
|
||||
elif level == 'INFO':
|
||||
logger.info(message)
|
||||
elif level == 'WARNING':
|
||||
logger.warn(message)
|
||||
else:
|
||||
logger.error(message)
|
||||
if level == 'DEBUG':
|
||||
logger.debug(message)
|
||||
elif level == 'INFO':
|
||||
logger.info(message)
|
||||
elif level == 'WARNING':
|
||||
logger.warn(message)
|
||||
else:
|
||||
logger.error(message)
|
||||
|
||||
headphones_log = RotatingLogger('headphones.log', MAX_SIZE, MAX_FILES)
|
||||
|
||||
def debug(message):
|
||||
headphones_log.log(message, level='DEBUG')
|
||||
headphones_log.log(message, level='DEBUG')
|
||||
|
||||
def info(message):
|
||||
headphones_log.log(message, level='INFO')
|
||||
|
||||
headphones_log.log(message, level='INFO')
|
||||
|
||||
def warn(message):
|
||||
headphones_log.log(message, level='WARNING')
|
||||
|
||||
headphones_log.log(message, level='WARNING')
|
||||
|
||||
def error(message):
|
||||
headphones_log.log(message, level='ERROR')
|
||||
|
||||
headphones_log.log(message, level='ERROR')
|
||||
|
||||
|
||||
@@ -1,3 +1,18 @@
|
||||
# This file is part of Headphones.
|
||||
#
|
||||
# Headphones 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.
|
||||
#
|
||||
# Headphones 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 Headphones. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import re
|
||||
import urllib
|
||||
from xml.dom import minidom
|
||||
@@ -7,53 +22,53 @@ from headphones import logger
|
||||
|
||||
def getLyrics(artist, song):
|
||||
|
||||
params = { "artist": artist.encode('utf-8'),
|
||||
"song": song.encode('utf-8'),
|
||||
"fmt": 'xml'
|
||||
params = { "artist": artist.encode('utf-8'),
|
||||
"song": song.encode('utf-8'),
|
||||
"fmt": 'xml'
|
||||
}
|
||||
|
||||
searchURL = 'http://lyrics.wikia.com/api.php?' + urllib.urlencode(params)
|
||||
|
||||
try:
|
||||
data = urllib.urlopen(searchURL).read()
|
||||
except Exception, e:
|
||||
logger.warn('Error opening: %s. Error: %s' % (searchURL, e))
|
||||
return
|
||||
|
||||
try:
|
||||
parseddata = minidom.parseString(data)
|
||||
except Exception, e:
|
||||
logger.warn('Error parsing data from url: %s. Error: %s' % (searchURL, e))
|
||||
return
|
||||
|
||||
url = parseddata.getElementsByTagName("url")
|
||||
|
||||
if url:
|
||||
lyricsurl = url[0].firstChild.nodeValue
|
||||
else:
|
||||
logger.info('No lyrics found for %s - %s' % (artist, song))
|
||||
return
|
||||
|
||||
try:
|
||||
lyricspage = urllib.urlopen(lyricsurl).read()
|
||||
except Exception, e:
|
||||
logger.warn('Error fetching lyrics from: %s. Error: %s' % (lyricsurl, e))
|
||||
return
|
||||
|
||||
m = re.compile('''<div class='lyricbox'><div class='rtMatcher'>.*?</div>(.*?)<!--''').search(lyricspage)
|
||||
|
||||
if not m:
|
||||
m = re.compile('''<div class='lyricbox'><span style="padding:1em"><a href="/Category:Instrumental" title="Instrumental">''').search(lyricspage)
|
||||
if m:
|
||||
return u'(Instrumental)'
|
||||
else:
|
||||
logger.warn('Cannot find lyrics on: %s' % lyricsurl)
|
||||
return
|
||||
|
||||
lyrics = convert_html_entities(m.group(1)).replace('<br />', '\n')
|
||||
lyrics = re.sub('<.*?>', '', lyrics)
|
||||
|
||||
return lyrics
|
||||
searchURL = 'http://lyrics.wikia.com/api.php?' + urllib.urlencode(params)
|
||||
|
||||
try:
|
||||
data = urllib.urlopen(searchURL).read()
|
||||
except Exception, e:
|
||||
logger.warn('Error opening: %s. Error: %s' % (searchURL, e))
|
||||
return
|
||||
|
||||
try:
|
||||
parseddata = minidom.parseString(data)
|
||||
except Exception, e:
|
||||
logger.warn('Error parsing data from url: %s. Error: %s' % (searchURL, e))
|
||||
return
|
||||
|
||||
url = parseddata.getElementsByTagName("url")
|
||||
|
||||
if url:
|
||||
lyricsurl = url[0].firstChild.nodeValue
|
||||
else:
|
||||
logger.info('No lyrics found for %s - %s' % (artist, song))
|
||||
return
|
||||
|
||||
try:
|
||||
lyricspage = urllib.urlopen(lyricsurl).read()
|
||||
except Exception, e:
|
||||
logger.warn('Error fetching lyrics from: %s. Error: %s' % (lyricsurl, e))
|
||||
return
|
||||
|
||||
m = re.compile('''<div class='lyricbox'><div class='rtMatcher'>.*?</div>(.*?)<!--''').search(lyricspage)
|
||||
|
||||
if not m:
|
||||
m = re.compile('''<div class='lyricbox'><span style="padding:1em"><a href="/Category:Instrumental" title="Instrumental">''').search(lyricspage)
|
||||
if m:
|
||||
return u'(Instrumental)'
|
||||
else:
|
||||
logger.warn('Cannot find lyrics on: %s' % lyricsurl)
|
||||
return
|
||||
|
||||
lyrics = convert_html_entities(m.group(1)).replace('<br />', '\n')
|
||||
lyrics = re.sub('<.*?>', '', lyrics)
|
||||
|
||||
return lyrics
|
||||
|
||||
def convert_html_entities(s):
|
||||
matches = re.findall("&#\d+;", s)
|
||||
@@ -77,4 +92,4 @@ def convert_html_entities(s):
|
||||
if htmlentitydefs.name2codepoint.has_key(name):
|
||||
s = s.replace(hit, unichr(htmlentitydefs.name2codepoint[name]))
|
||||
s = s.replace(amp, "&")
|
||||
return s
|
||||
return s
|
||||
|
||||
@@ -1,3 +1,18 @@
|
||||
# This file is part of Headphones.
|
||||
#
|
||||
# Headphones 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.
|
||||
#
|
||||
# Headphones 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 Headphones. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from __future__ import with_statement
|
||||
|
||||
import time
|
||||
@@ -52,10 +67,10 @@ def startmb(forcemb=False):
|
||||
|
||||
# Add headphones credentials
|
||||
if headphones.MIRROR == "headphones":
|
||||
if not mbuser and mbpass:
|
||||
logger.warn("No username or password set for VIP server")
|
||||
if not mbuser and mbpass:
|
||||
logger.warn("No username or password set for VIP server")
|
||||
else:
|
||||
musicbrainzngs.hpauth(mbuser,mbpass)
|
||||
musicbrainzngs.hpauth(mbuser,mbpass)
|
||||
|
||||
# Don't really need to return q anymore since ngs, but maybe we can return an 'initialized=True' instead?
|
||||
q = musicbrainzngs
|
||||
@@ -224,7 +239,7 @@ def getArtist(artistid, extrasonly=False):
|
||||
includeExtras = False
|
||||
|
||||
if includeExtras or headphones.INCLUDE_EXTRAS:
|
||||
includes = ["single", "ep", "compilation", "soundtrack", "live", "remix"]
|
||||
includes = ["single", "ep", "compilation", "soundtrack", "live", "remix", "spokenword", "audiobook"]
|
||||
for include in includes:
|
||||
|
||||
artist = None
|
||||
|
||||
@@ -1,3 +1,18 @@
|
||||
# This file is part of Headphones.
|
||||
#
|
||||
# Headphones 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.
|
||||
#
|
||||
# Headphones 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 Headphones. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import os
|
||||
import headphones
|
||||
import shutil
|
||||
@@ -13,124 +28,124 @@ except ImportError:
|
||||
import lib.argparse as argparse
|
||||
|
||||
def encode(albumPath):
|
||||
tempDirEncode=os.path.join(albumPath,"temp")
|
||||
musicFiles=[]
|
||||
musicFinalFiles=[]
|
||||
musicTempFiles=[]
|
||||
encoder =""
|
||||
startAlbumTime=time.time()
|
||||
ifencoded=0
|
||||
|
||||
if not os.path.exists(tempDirEncode):
|
||||
os.mkdir(tempDirEncode)
|
||||
else:
|
||||
shutil.rmtree(tempDirEncode)
|
||||
time.sleep(1)
|
||||
os.mkdir(tempDirEncode)
|
||||
|
||||
for r,d,f in os.walk(albumPath):
|
||||
for music in f:
|
||||
if any(music.lower().endswith('.' + x.lower()) for x in headphones.MEDIA_FORMATS):
|
||||
if (headphones.ENCODERLOSSLESS):
|
||||
if (music.lower().endswith('.flac')):
|
||||
musicFiles.append(os.path.join(r, music))
|
||||
musicTemp = os.path.normpath(os.path.splitext(music)[0]+'.'+headphones.ENCODEROUTPUTFORMAT).encode(headphones.SYS_ENCODING)
|
||||
musicTempFiles.append(os.path.join(tempDirEncode, musicTemp))
|
||||
else:
|
||||
logger.warn('Music "%s" is already encoded' % (music))
|
||||
else:
|
||||
musicFiles.append(os.path.join(r, music))
|
||||
musicTemp = os.path.normpath(os.path.splitext(music)[0]+'.'+headphones.ENCODEROUTPUTFORMAT).encode(headphones.SYS_ENCODING)
|
||||
musicTempFiles.append(os.path.join(tempDirEncode, musicTemp))
|
||||
|
||||
if headphones.ENCODER=='lame':
|
||||
encoder=os.path.join(headphones.ENCODERFOLDER,'lame')
|
||||
elif headphones.ENCODER=='ffmpeg':
|
||||
encoder=os.path.join(headphones.ENCODERFOLDER,'ffmpeg')
|
||||
i=0
|
||||
for music in musicFiles:
|
||||
infoMusic=MediaFile(music)
|
||||
if headphones.ENCODER == 'lame':
|
||||
if not any(music.lower().endswith('.' + x) for x in ["mp3", "wav"]):
|
||||
logger.warn('Lame cant encode "%s" format for "%s", use ffmpeg' % (os.path.splitext(music)[1],music))
|
||||
else:
|
||||
if (music.lower().endswith('.mp3') and (infoMusic.bitrate/1000<=headphones.BITRATE)):
|
||||
logger.warn('Music "%s" has bitrate<="%skbit" will not be reencoded' % (music,headphones.BITRATE))
|
||||
else:
|
||||
command(encoder,music,musicTempFiles[i],albumPath)
|
||||
ifencoded=1
|
||||
else:
|
||||
if headphones.ENCODEROUTPUTFORMAT=='ogg':
|
||||
if music.lower().endswith('.ogg'):
|
||||
logger.warn('Can not reencode .ogg music "%s"' % (music))
|
||||
else:
|
||||
command(encoder,music,musicTempFiles[i],albumPath)
|
||||
ifencoded=1
|
||||
elif (headphones.ENCODEROUTPUTFORMAT=='mp3' or headphones.ENCODEROUTPUTFORMAT=='m4a'):
|
||||
if (music.lower().endswith('.'+headphones.ENCODEROUTPUTFORMAT) and (infoMusic.bitrate/1000<=headphones.BITRATE)):
|
||||
logger.warn('Music "%s" has bitrate<="%skbit" will not be reencoded' % (music,headphones.BITRATE))
|
||||
else:
|
||||
command(encoder,music,musicTempFiles[i],albumPath)
|
||||
ifencoded=1
|
||||
i=i+1
|
||||
|
||||
shutil.rmtree(tempDirEncode)
|
||||
time.sleep(1)
|
||||
for r,d,f in os.walk(albumPath):
|
||||
for music in f:
|
||||
if any(music.lower().endswith('.' + x.lower()) for x in headphones.MEDIA_FORMATS):
|
||||
musicFinalFiles.append(os.path.join(r, music))
|
||||
|
||||
if ifencoded==0:
|
||||
logger.info('Encoding for folder "%s" is not needed' % (albumPath))
|
||||
|
||||
return musicFinalFiles
|
||||
|
||||
tempDirEncode=os.path.join(albumPath,"temp")
|
||||
musicFiles=[]
|
||||
musicFinalFiles=[]
|
||||
musicTempFiles=[]
|
||||
encoder =""
|
||||
startAlbumTime=time.time()
|
||||
ifencoded=0
|
||||
|
||||
if not os.path.exists(tempDirEncode):
|
||||
os.mkdir(tempDirEncode)
|
||||
else:
|
||||
shutil.rmtree(tempDirEncode)
|
||||
time.sleep(1)
|
||||
os.mkdir(tempDirEncode)
|
||||
|
||||
for r,d,f in os.walk(albumPath):
|
||||
for music in f:
|
||||
if any(music.lower().endswith('.' + x.lower()) for x in headphones.MEDIA_FORMATS):
|
||||
if (headphones.ENCODERLOSSLESS):
|
||||
if (music.lower().endswith('.flac')):
|
||||
musicFiles.append(os.path.join(r, music))
|
||||
musicTemp = os.path.normpath(os.path.splitext(music)[0]+'.'+headphones.ENCODEROUTPUTFORMAT).encode(headphones.SYS_ENCODING)
|
||||
musicTempFiles.append(os.path.join(tempDirEncode, musicTemp))
|
||||
else:
|
||||
logger.debug('Music "%s" is already encoded' % (music))
|
||||
else:
|
||||
musicFiles.append(os.path.join(r, music))
|
||||
musicTemp = os.path.normpath(os.path.splitext(music)[0]+'.'+headphones.ENCODEROUTPUTFORMAT).encode(headphones.SYS_ENCODING)
|
||||
musicTempFiles.append(os.path.join(tempDirEncode, musicTemp))
|
||||
|
||||
if headphones.ENCODER=='lame':
|
||||
encoder=os.path.join(headphones.ENCODERFOLDER,'lame')
|
||||
elif headphones.ENCODER=='ffmpeg':
|
||||
encoder=os.path.join(headphones.ENCODERFOLDER,'ffmpeg')
|
||||
i=0
|
||||
for music in musicFiles:
|
||||
infoMusic=MediaFile(music)
|
||||
if headphones.ENCODER == 'lame':
|
||||
if not any(music.lower().endswith('.' + x) for x in ["mp3", "wav"]):
|
||||
logger.warn('Lame cant encode "%s" format for "%s", use ffmpeg' % (os.path.splitext(music)[1],music))
|
||||
else:
|
||||
if (music.lower().endswith('.mp3') and (infoMusic.bitrate/1000<=headphones.BITRATE)):
|
||||
logger.info('Music "%s" has bitrate<="%skbit" will not be reencoded' % (music,headphones.BITRATE))
|
||||
else:
|
||||
command(encoder,music,musicTempFiles[i],albumPath)
|
||||
ifencoded=1
|
||||
else:
|
||||
if headphones.ENCODEROUTPUTFORMAT=='ogg':
|
||||
if music.lower().endswith('.ogg'):
|
||||
logger.warn('Can not reencode .ogg music "%s"' % (music))
|
||||
else:
|
||||
command(encoder,music,musicTempFiles[i],albumPath)
|
||||
ifencoded=1
|
||||
elif (headphones.ENCODEROUTPUTFORMAT=='mp3' or headphones.ENCODEROUTPUTFORMAT=='m4a'):
|
||||
if (music.lower().endswith('.'+headphones.ENCODEROUTPUTFORMAT) and (infoMusic.bitrate/1000<=headphones.BITRATE)):
|
||||
logger.info('Music "%s" has bitrate<="%skbit" will not be reencoded' % (music,headphones.BITRATE))
|
||||
else:
|
||||
command(encoder,music,musicTempFiles[i],albumPath)
|
||||
ifencoded=1
|
||||
i=i+1
|
||||
|
||||
shutil.rmtree(tempDirEncode)
|
||||
time.sleep(1)
|
||||
for r,d,f in os.walk(albumPath):
|
||||
for music in f:
|
||||
if any(music.lower().endswith('.' + x.lower()) for x in headphones.MEDIA_FORMATS):
|
||||
musicFinalFiles.append(os.path.join(r, music))
|
||||
|
||||
if ifencoded==0:
|
||||
logger.info('Encoding for folder "%s" is not needed' % (albumPath))
|
||||
|
||||
return musicFinalFiles
|
||||
|
||||
def command(encoder,musicSource,musicDest,albumPath):
|
||||
return_code=1
|
||||
cmd=''
|
||||
startMusicTime=time.time()
|
||||
if headphones.ENCODER == 'lame':
|
||||
if headphones.ADVANCEDENCODER =='':
|
||||
cmd=encoder + ' -h'
|
||||
if headphones.ENCODERVBRCBR=='cbr':
|
||||
cmd=cmd+ ' --resample ' + str(headphones.SAMPLINGFREQUENCY) + ' -b ' + str(headphones.BITRATE)
|
||||
elif headphones.ENCODERVBRCBR=='vbr':
|
||||
cmd=cmd+' -V'+str(headphones.ENCODERQUALITY)
|
||||
cmd=cmd+ ' ' + headphones.ADVANCEDENCODER
|
||||
else:
|
||||
cmd=cmd+' '+ headphones.ADVANCEDENCODER
|
||||
cmd=cmd+ ' "' + musicSource + '"'
|
||||
cmd=cmd+ ' "' + musicDest +'"'
|
||||
|
||||
elif headphones.ENCODER == 'ffmpeg':
|
||||
cmd=encoder+ ' -i'
|
||||
cmd=cmd+ ' "' + musicSource + '"'
|
||||
if headphones.ADVANCEDENCODER =='':
|
||||
if headphones.ENCODEROUTPUTFORMAT=='ogg':
|
||||
cmd=cmd+ ' -acodec libvorbis'
|
||||
if headphones.ENCODEROUTPUTFORMAT=='m4a':
|
||||
cmd=cmd+ ' -strict experimental'
|
||||
if headphones.ENCODERVBRCBR=='cbr':
|
||||
cmd=cmd+ ' -ar ' + str(headphones.SAMPLINGFREQUENCY) + ' -ab ' + str(headphones.BITRATE) + 'k'
|
||||
elif headphones.ENCODERVBRCBR=='vbr':
|
||||
cmd=cmd+' -aq ' + str(headphones.ENCODERQUALITY)
|
||||
cmd=cmd+ ' -y -ac 2 -vn'
|
||||
else:
|
||||
cmd=cmd+' '+ headphones.ADVANCEDENCODER
|
||||
cmd=cmd+ ' "' + musicDest + '"'
|
||||
print cmd
|
||||
time.sleep(10)
|
||||
return_code = call(cmd, shell=True)
|
||||
if (return_code==0) and (os.path.exists(musicDest)):
|
||||
os.remove(musicSource)
|
||||
shutil.move(musicDest,albumPath)
|
||||
logger.info('Music "%s" encoded in %s' % (musicSource,getTimeEncode(startMusicTime)))
|
||||
|
||||
return_code=1
|
||||
cmd=''
|
||||
startMusicTime=time.time()
|
||||
if headphones.ENCODER == 'lame':
|
||||
if headphones.ADVANCEDENCODER =='':
|
||||
cmd=encoder + ' -h'
|
||||
if headphones.ENCODERVBRCBR=='cbr':
|
||||
cmd=cmd+ ' --resample ' + str(headphones.SAMPLINGFREQUENCY) + ' -b ' + str(headphones.BITRATE)
|
||||
elif headphones.ENCODERVBRCBR=='vbr':
|
||||
cmd=cmd+' -V'+str(headphones.ENCODERQUALITY)
|
||||
cmd=cmd+ ' ' + headphones.ADVANCEDENCODER
|
||||
else:
|
||||
cmd=cmd+' '+ headphones.ADVANCEDENCODER
|
||||
cmd=cmd+ ' "' + musicSource + '"'
|
||||
cmd=cmd+ ' "' + musicDest +'"'
|
||||
|
||||
elif headphones.ENCODER == 'ffmpeg':
|
||||
cmd=encoder+ ' -i'
|
||||
cmd=cmd+ ' "' + musicSource + '"'
|
||||
if headphones.ADVANCEDENCODER =='':
|
||||
if headphones.ENCODEROUTPUTFORMAT=='ogg':
|
||||
cmd=cmd+ ' -acodec libvorbis'
|
||||
if headphones.ENCODEROUTPUTFORMAT=='m4a':
|
||||
cmd=cmd+ ' -strict experimental'
|
||||
if headphones.ENCODERVBRCBR=='cbr':
|
||||
cmd=cmd+ ' -ar ' + str(headphones.SAMPLINGFREQUENCY) + ' -ab ' + str(headphones.BITRATE) + 'k'
|
||||
elif headphones.ENCODERVBRCBR=='vbr':
|
||||
cmd=cmd+' -aq ' + str(headphones.ENCODERQUALITY)
|
||||
cmd=cmd+ ' -y -ac 2 -vn'
|
||||
else:
|
||||
cmd=cmd+' '+ headphones.ADVANCEDENCODER
|
||||
cmd=cmd+ ' "' + musicDest + '"'
|
||||
print cmd
|
||||
time.sleep(10)
|
||||
return_code = call(cmd, shell=True)
|
||||
if (return_code==0) and (os.path.exists(musicDest)):
|
||||
os.remove(musicSource)
|
||||
shutil.move(musicDest,albumPath)
|
||||
logger.info('Music "%s" encoded in %s' % (musicSource,getTimeEncode(startMusicTime)))
|
||||
|
||||
def getTimeEncode(start):
|
||||
seconds =int(time.time()-start)
|
||||
hours = seconds / 3600
|
||||
seconds -= 3600*hours
|
||||
minutes = seconds / 60
|
||||
seconds -= 60*minutes
|
||||
return "%02d:%02d:%02d" % (hours, minutes, seconds)
|
||||
seconds =int(time.time()-start)
|
||||
hours = seconds / 3600
|
||||
seconds -= 3600*hours
|
||||
minutes = seconds / 60
|
||||
seconds -= 60*minutes
|
||||
return "%02d:%02d:%02d" % (hours, minutes, seconds)
|
||||
|
||||
@@ -1,3 +1,18 @@
|
||||
# This file is part of Headphones.
|
||||
#
|
||||
# Headphones 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.
|
||||
#
|
||||
# Headphones 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 Headphones. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
from headphones import logger
|
||||
import base64
|
||||
import cherrypy
|
||||
@@ -64,110 +79,110 @@ class PROWL:
|
||||
|
||||
class XBMC:
|
||||
|
||||
def __init__(self):
|
||||
|
||||
self.hosts = headphones.XBMC_HOST
|
||||
self.username = headphones.XBMC_USERNAME
|
||||
self.password = headphones.XBMC_PASSWORD
|
||||
|
||||
def _send(self, command):
|
||||
|
||||
hosts = [x.strip() for x in self.hosts.split(',')]
|
||||
username = self.username
|
||||
password = self.password
|
||||
|
||||
url_command = urllib.urlencode(command)
|
||||
|
||||
for host in hosts:
|
||||
|
||||
url = host + '/xbmcCmds/xbmcHttp/?' + url_command
|
||||
|
||||
req = urllib2.Request(url)
|
||||
|
||||
if password:
|
||||
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
|
||||
req.add_header("Authorization", "Basic %s" % base64string)
|
||||
|
||||
logger.info('XBMC url: %s' % url)
|
||||
|
||||
try:
|
||||
handle = urllib2.urlopen(req)
|
||||
except Exception, e:
|
||||
logger.warn('Error opening XBMC url: ' % e)
|
||||
return
|
||||
|
||||
response = handle.read().decode(headphones.SYS_ENCODING)
|
||||
|
||||
return response
|
||||
def __init__(self):
|
||||
|
||||
def update(self):
|
||||
|
||||
# From what I read you can't update the music library on a per directory or per path basis
|
||||
# so need to update the whole thing
|
||||
|
||||
updatecommand = {'command': 'ExecBuiltIn', 'parameter': 'XBMC.updatelibrary(music)'}
|
||||
|
||||
logger.info('Sending library update command to XBMC')
|
||||
request = self._send(updatecommand)
|
||||
|
||||
if not request:
|
||||
logger.warn('Error sending update request to XBMC')
|
||||
|
||||
def notify(self, artist, album, albumartpath):
|
||||
|
||||
header = "Headphones"
|
||||
message = "%s - %s added to your library" % (artist, album)
|
||||
time = "3000" # in ms
|
||||
|
||||
|
||||
notification = header + "," + message + "," + time + "," + albumartpath
|
||||
|
||||
notifycommand = {'command': 'ExecBuiltIn', 'parameter': 'Notification(' + notification + ')' }
|
||||
|
||||
logger.info('Sending notification command to XMBC')
|
||||
request = self._send(notifycommand)
|
||||
|
||||
if not request:
|
||||
logger.warn('Error sending notification request to XBMC')
|
||||
|
||||
self.hosts = headphones.XBMC_HOST
|
||||
self.username = headphones.XBMC_USERNAME
|
||||
self.password = headphones.XBMC_PASSWORD
|
||||
|
||||
def _send(self, command):
|
||||
|
||||
hosts = [x.strip() for x in self.hosts.split(',')]
|
||||
username = self.username
|
||||
password = self.password
|
||||
|
||||
url_command = urllib.urlencode(command)
|
||||
|
||||
for host in hosts:
|
||||
|
||||
url = host + '/xbmcCmds/xbmcHttp/?' + url_command
|
||||
|
||||
req = urllib2.Request(url)
|
||||
|
||||
if password:
|
||||
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
|
||||
req.add_header("Authorization", "Basic %s" % base64string)
|
||||
|
||||
logger.info('XBMC url: %s' % url)
|
||||
|
||||
try:
|
||||
handle = urllib2.urlopen(req)
|
||||
except Exception, e:
|
||||
logger.warn('Error opening XBMC url: ' % e)
|
||||
return
|
||||
|
||||
response = handle.read().decode(headphones.SYS_ENCODING)
|
||||
|
||||
return response
|
||||
|
||||
def update(self):
|
||||
|
||||
# From what I read you can't update the music library on a per directory or per path basis
|
||||
# so need to update the whole thing
|
||||
|
||||
updatecommand = {'command': 'ExecBuiltIn', 'parameter': 'XBMC.updatelibrary(music)'}
|
||||
|
||||
logger.info('Sending library update command to XBMC')
|
||||
request = self._send(updatecommand)
|
||||
|
||||
if not request:
|
||||
logger.warn('Error sending update request to XBMC')
|
||||
|
||||
def notify(self, artist, album, albumartpath):
|
||||
|
||||
header = "Headphones"
|
||||
message = "%s - %s added to your library" % (artist, album)
|
||||
time = "3000" # in ms
|
||||
|
||||
|
||||
notification = header + "," + message + "," + time + "," + albumartpath
|
||||
|
||||
notifycommand = {'command': 'ExecBuiltIn', 'parameter': 'Notification(' + notification + ')' }
|
||||
|
||||
logger.info('Sending notification command to XMBC')
|
||||
request = self._send(notifycommand)
|
||||
|
||||
if not request:
|
||||
logger.warn('Error sending notification request to XBMC')
|
||||
|
||||
class NMA:
|
||||
|
||||
def __init__(self):
|
||||
|
||||
self.apikey = headphones.NMA_APIKEY
|
||||
self.priority = headphones.NMA_PRIORITY
|
||||
|
||||
def _send(self, data):
|
||||
|
||||
url_data = urllib.urlencode(data)
|
||||
url = 'https://www.notifymyandroid.com/publicapi/notify'
|
||||
|
||||
req = urllib2.Request(url, url_data)
|
||||
def __init__(self):
|
||||
|
||||
self.apikey = headphones.NMA_APIKEY
|
||||
self.priority = headphones.NMA_PRIORITY
|
||||
|
||||
def _send(self, data):
|
||||
|
||||
url_data = urllib.urlencode(data)
|
||||
url = 'https://www.notifymyandroid.com/publicapi/notify'
|
||||
|
||||
req = urllib2.Request(url, url_data)
|
||||
|
||||
try:
|
||||
handle = urllib2.urlopen(req)
|
||||
except Exception, e:
|
||||
logger.warn('Error opening NotifyMyAndroid url: ' % e)
|
||||
return
|
||||
try:
|
||||
handle = urllib2.urlopen(req)
|
||||
except Exception, e:
|
||||
logger.warn('Error opening NotifyMyAndroid url: ' % e)
|
||||
return
|
||||
|
||||
response = handle.read().decode(headphones.SYS_ENCODING)
|
||||
|
||||
return response
|
||||
|
||||
def notify(self, artist, album):
|
||||
|
||||
apikey = self.apikey
|
||||
priority = self.priority
|
||||
|
||||
event = artist + ' - ' + album + ' complete!'
|
||||
|
||||
description = "Headphones has downloaded and postprocessed: " + artist + ' [' + album + ']'
|
||||
|
||||
data = { 'apikey': apikey, 'application':'Headphones', 'event': event, 'description': description, 'priority': priority}
|
||||
response = handle.read().decode(headphones.SYS_ENCODING)
|
||||
|
||||
return response
|
||||
|
||||
def notify(self, artist, album):
|
||||
|
||||
apikey = self.apikey
|
||||
priority = self.priority
|
||||
|
||||
event = artist + ' - ' + album + ' complete!'
|
||||
|
||||
description = "Headphones has downloaded and postprocessed: " + artist + ' [' + album + ']'
|
||||
|
||||
data = { 'apikey': apikey, 'application':'Headphones', 'event': event, 'description': description, 'priority': priority}
|
||||
|
||||
logger.info('Sending notification request to NotifyMyAndroid')
|
||||
request = self._send(data)
|
||||
|
||||
if not request:
|
||||
logger.warn('Error sending notification request to NotifyMyAndroid')
|
||||
|
||||
logger.info('Sending notification request to NotifyMyAndroid')
|
||||
request = self._send(data)
|
||||
|
||||
if not request:
|
||||
logger.warn('Error sending notification request to NotifyMyAndroid')
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,19 +1,21 @@
|
||||
# This file is part of Sick Beard.
|
||||
# This file is part of Headphones.
|
||||
#
|
||||
# Sick Beard 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.
|
||||
# Headphones 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.
|
||||
#
|
||||
# Sick Beard 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.
|
||||
# Headphones 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with Headphones. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
#####################################
|
||||
## Stolen from Sick-Beard's sab.py ##
|
||||
#####################################
|
||||
|
||||
import urllib, httplib
|
||||
import datetime
|
||||
@@ -66,7 +68,7 @@ def sendNZB(nzb):
|
||||
multiPartParams = {"nzbfile": (nzb.name+".nzb", nzb.extraInfo[0])}
|
||||
|
||||
if not headphones.SAB_HOST.startswith('http'):
|
||||
headphones.SAB_HOST = 'http://' + headphones.SAB_HOST
|
||||
headphones.SAB_HOST = 'http://' + headphones.SAB_HOST
|
||||
|
||||
if headphones.SAB_HOST.endswith('/'):
|
||||
headphones.SAB_HOST = headphones.SAB_HOST[0:len(headphones.SAB_HOST)-1]
|
||||
|
||||
@@ -1,3 +1,18 @@
|
||||
# This file is part of Headphones.
|
||||
#
|
||||
# Headphones 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.
|
||||
#
|
||||
# Headphones 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 Headphones. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import urllib, urllib2, urlparse
|
||||
import lib.feedparser as feedparser
|
||||
from xml.dom import minidom
|
||||
@@ -11,6 +26,8 @@ import string
|
||||
import headphones, exceptions
|
||||
from headphones import logger, db, helpers, classes, sab
|
||||
|
||||
import lib.bencode as bencode
|
||||
|
||||
class NewzbinDownloader(urllib.FancyURLopener):
|
||||
|
||||
def __init__(self):
|
||||
@@ -100,9 +117,9 @@ def searchNZB(albumid=None, new=False, losslessOnly=False):
|
||||
myDB = db.DBConnection()
|
||||
|
||||
if albumid:
|
||||
results = myDB.select('SELECT ArtistName, AlbumTitle, AlbumID, ReleaseDate from albums WHERE AlbumID=?', [albumid])
|
||||
results = myDB.select('SELECT ArtistName, AlbumTitle, AlbumID, ReleaseDate, Type from albums WHERE AlbumID=?', [albumid])
|
||||
else:
|
||||
results = myDB.select('SELECT ArtistName, AlbumTitle, AlbumID, ReleaseDate from albums WHERE Status="Wanted" OR Status="Wanted Lossless"')
|
||||
results = myDB.select('SELECT ArtistName, AlbumTitle, AlbumID, ReleaseDate, Type from albums WHERE Status="Wanted" OR Status="Wanted Lossless"')
|
||||
new = True
|
||||
|
||||
for albums in results:
|
||||
@@ -126,9 +143,9 @@ def searchNZB(albumid=None, new=False, losslessOnly=False):
|
||||
if albums[0] in albums[1] or len(albums[0]) < 4 or len(albums[1]) < 4:
|
||||
term = cleanartist + ' ' + cleanalbum + ' ' + year
|
||||
elif albums[0] == 'Various Artists':
|
||||
term = cleanalbum + ' ' + year
|
||||
term = cleanalbum + ' ' + year
|
||||
else:
|
||||
term = cleanartist + ' ' + cleanalbum
|
||||
term = cleanartist + ' ' + cleanalbum
|
||||
|
||||
# Replace bad characters in the term and unicode it
|
||||
term = re.sub('[\.\-\/]', ' ', term).encode('utf-8')
|
||||
@@ -147,12 +164,17 @@ def searchNZB(albumid=None, new=False, losslessOnly=False):
|
||||
else:
|
||||
categories = "22"
|
||||
|
||||
# Search Audiobooks
|
||||
if albums['Type'] == "Other":
|
||||
categories = "49"
|
||||
logger.info("Album type is audiobook/spokenword. Using audiobook category")
|
||||
|
||||
# For some reason NZBMatrix is erroring out/timing out when the term starts with a "The" right now
|
||||
# so we'll strip it out for the time being. This may get fixed on their end, it may not, but
|
||||
# hopefully this will fix it for now. If you notice anything else it gets stuck on, please post it
|
||||
# on Github so it can be added
|
||||
if term.lower().startswith("the "):
|
||||
term = term[4:]
|
||||
term = term[4:]
|
||||
|
||||
|
||||
params = { "page": "download",
|
||||
@@ -169,26 +191,26 @@ def searchNZB(albumid=None, new=False, losslessOnly=False):
|
||||
searchURL = "http://rss.nzbmatrix.com/rss.php?" + urllib.urlencode(params)
|
||||
logger.info(u'Parsing results from <a href="%s">NZBMatrix</a>' % searchURL)
|
||||
try:
|
||||
data = urllib2.urlopen(searchURL, timeout=20).read()
|
||||
data = urllib2.urlopen(searchURL, timeout=20).read()
|
||||
except urllib2.URLError, e:
|
||||
logger.warn('Error fetching data from NZBMatrix: %s' % e)
|
||||
data = False
|
||||
|
||||
logger.warn('Error fetching data from NZBMatrix: %s' % e)
|
||||
data = False
|
||||
|
||||
if data:
|
||||
|
||||
d = feedparser.parse(data)
|
||||
|
||||
for item in d.entries:
|
||||
try:
|
||||
url = item.link
|
||||
title = item.title
|
||||
size = int(item.links[1]['length'])
|
||||
|
||||
resultlist.append((title, size, url, provider))
|
||||
logger.info('Found %s. Size: %s' % (title, helpers.bytes_to_mb(size)))
|
||||
|
||||
except AttributeError, e:
|
||||
logger.info(u"No results found from NZBMatrix for %s" % term)
|
||||
d = feedparser.parse(data)
|
||||
|
||||
for item in d.entries:
|
||||
try:
|
||||
url = item.link
|
||||
title = item.title
|
||||
size = int(item.links[1]['length'])
|
||||
|
||||
resultlist.append((title, size, url, provider))
|
||||
logger.info('Found %s. Size: %s' % (title, helpers.bytes_to_mb(size)))
|
||||
|
||||
except AttributeError, e:
|
||||
logger.info(u"No results found from NZBMatrix for %s" % term)
|
||||
|
||||
if headphones.NEWZNAB:
|
||||
provider = "newznab"
|
||||
@@ -197,7 +219,11 @@ def searchNZB(albumid=None, new=False, losslessOnly=False):
|
||||
elif headphones.PREFERRED_QUALITY:
|
||||
categories = "3040,3010"
|
||||
else:
|
||||
categories = "3010"
|
||||
categories = "3010"
|
||||
|
||||
if albums['Type'] == 'Other':
|
||||
categories = "3030"
|
||||
logger.info("Album type is audiobook/spokenword. Using audiobook category")
|
||||
|
||||
params = { "t": "search",
|
||||
"apikey": headphones.NEWZNAB_APIKEY,
|
||||
@@ -211,31 +237,31 @@ def searchNZB(albumid=None, new=False, losslessOnly=False):
|
||||
logger.info(u'Parsing results from <a href="%s">%s</a>' % (searchURL, headphones.NEWZNAB_HOST))
|
||||
|
||||
try:
|
||||
data = urllib2.urlopen(searchURL, timeout=20).read()
|
||||
data = urllib2.urlopen(searchURL, timeout=20).read()
|
||||
except urllib2.URLError, e:
|
||||
logger.warn('Error fetching data from %s: %s' % (headphones.NEWZNAB_HOST, e))
|
||||
data = False
|
||||
|
||||
logger.warn('Error fetching data from %s: %s' % (headphones.NEWZNAB_HOST, e))
|
||||
data = False
|
||||
|
||||
if data:
|
||||
|
||||
d = feedparser.parse(data)
|
||||
|
||||
if not len(d.entries):
|
||||
logger.info(u"No results found from %s for %s" % (headphones.NEWZNAB_HOST, term))
|
||||
pass
|
||||
|
||||
else:
|
||||
for item in d.entries:
|
||||
try:
|
||||
url = item.link
|
||||
title = item.title
|
||||
size = int(item.links[1]['length'])
|
||||
|
||||
resultlist.append((title, size, url, provider))
|
||||
logger.info('Found %s. Size: %s' % (title, helpers.bytes_to_mb(size)))
|
||||
|
||||
except Exception, e:
|
||||
logger.error(u"An unknown error occured trying to parse the feed: %s" % e)
|
||||
|
||||
d = feedparser.parse(data)
|
||||
|
||||
if not len(d.entries):
|
||||
logger.info(u"No results found from %s for %s" % (headphones.NEWZNAB_HOST, term))
|
||||
pass
|
||||
|
||||
else:
|
||||
for item in d.entries:
|
||||
try:
|
||||
url = item.link
|
||||
title = item.title
|
||||
size = int(item.links[1]['length'])
|
||||
|
||||
resultlist.append((title, size, url, provider))
|
||||
logger.info('Found %s. Size: %s' % (title, helpers.bytes_to_mb(size)))
|
||||
|
||||
except Exception, e:
|
||||
logger.error(u"An unknown error occured trying to parse the feed: %s" % e)
|
||||
|
||||
if headphones.NZBSORG:
|
||||
provider = "nzbsorg"
|
||||
@@ -244,7 +270,11 @@ def searchNZB(albumid=None, new=False, losslessOnly=False):
|
||||
elif headphones.PREFERRED_QUALITY:
|
||||
categories = "3040,3010"
|
||||
else:
|
||||
categories = "3010"
|
||||
categories = "3010"
|
||||
|
||||
if albums['Type'] == 'Other':
|
||||
categories = "3030"
|
||||
logger.info("Album type is audiobook/spokenword. Using audiobook category")
|
||||
|
||||
params = { "t": "search",
|
||||
"apikey": headphones.NZBSORG_HASH,
|
||||
@@ -258,31 +288,31 @@ def searchNZB(albumid=None, new=False, losslessOnly=False):
|
||||
logger.info(u'Parsing results from <a href="%s">nzbs.org</a>' % searchURL)
|
||||
|
||||
try:
|
||||
data = urllib2.urlopen(searchURL, timeout=20).read()
|
||||
data = urllib2.urlopen(searchURL, timeout=20).read()
|
||||
except urllib2.URLError, e:
|
||||
logger.warn('Error fetching data from nzbs.org: %s' % e)
|
||||
data = False
|
||||
|
||||
logger.warn('Error fetching data from nzbs.org: %s' % e)
|
||||
data = False
|
||||
|
||||
if data:
|
||||
|
||||
d = feedparser.parse(data)
|
||||
|
||||
if not len(d.entries):
|
||||
logger.info(u"No results found from nzbs.org for %s" % term)
|
||||
pass
|
||||
|
||||
else:
|
||||
for item in d.entries:
|
||||
try:
|
||||
url = item.link
|
||||
title = item.title
|
||||
size = int(item.links[1]['length'])
|
||||
|
||||
resultlist.append((title, size, url, provider))
|
||||
logger.info('Found %s. Size: %s' % (title, helpers.bytes_to_mb(size)))
|
||||
|
||||
except Exception, e:
|
||||
logger.error(u"An unknown error occured trying to parse the feed: %s" % e)
|
||||
|
||||
d = feedparser.parse(data)
|
||||
|
||||
if not len(d.entries):
|
||||
logger.info(u"No results found from nzbs.org for %s" % term)
|
||||
pass
|
||||
|
||||
else:
|
||||
for item in d.entries:
|
||||
try:
|
||||
url = item.link
|
||||
title = item.title
|
||||
size = int(item.links[1]['length'])
|
||||
|
||||
resultlist.append((title, size, url, provider))
|
||||
logger.info('Found %s. Size: %s' % (title, helpers.bytes_to_mb(size)))
|
||||
|
||||
except Exception, e:
|
||||
logger.error(u"An unknown error occured trying to parse the feed: %s" % e)
|
||||
|
||||
if headphones.NEWZBIN:
|
||||
provider = "newzbin"
|
||||
@@ -297,12 +327,17 @@ def searchNZB(albumid=None, new=False, losslessOnly=False):
|
||||
categories = "7" #music
|
||||
format = "8" #mp3
|
||||
|
||||
if albums['Type'] == 'Other':
|
||||
categories = "13"
|
||||
format = "16"
|
||||
logger.info("Album type is audiobook/spokenword. Using audiobook category")
|
||||
|
||||
params = {
|
||||
"fpn": "p",
|
||||
'u_nfo_posts_only': 0,
|
||||
'u_url_posts_only': 0,
|
||||
'u_comment_posts_only': 0,
|
||||
'u_show_passworded': 0,
|
||||
'u_url_posts_only': 0,
|
||||
'u_comment_posts_only': 0,
|
||||
'u_show_passworded': 0,
|
||||
"searchaction": "Search",
|
||||
#"dl": 1,
|
||||
"category": categories,
|
||||
@@ -403,28 +438,28 @@ def searchNZB(albumid=None, new=False, losslessOnly=False):
|
||||
|
||||
if new:
|
||||
|
||||
while True:
|
||||
|
||||
if len(nzblist):
|
||||
|
||||
alreadydownloaded = myDB.select('SELECT * from snatched WHERE URL=?', [nzblist[0][2]])
|
||||
|
||||
if len(alreadydownloaded):
|
||||
logger.info('%s has already been downloaded. Skipping.' % nzblist[0][0])
|
||||
nzblist.pop(0)
|
||||
|
||||
else:
|
||||
break
|
||||
else:
|
||||
logger.info('No more results found for %s' % term)
|
||||
return "none"
|
||||
while True:
|
||||
|
||||
if len(nzblist):
|
||||
|
||||
alreadydownloaded = myDB.select('SELECT * from snatched WHERE URL=?', [nzblist[0][2]])
|
||||
|
||||
if len(alreadydownloaded):
|
||||
logger.info('%s has already been downloaded. Skipping.' % nzblist[0][0])
|
||||
nzblist.pop(0)
|
||||
|
||||
else:
|
||||
break
|
||||
else:
|
||||
logger.info('No more results found for %s' % term)
|
||||
return "none"
|
||||
|
||||
logger.info(u"Pre-processing result")
|
||||
|
||||
(data, bestqual) = preprocess(nzblist)
|
||||
|
||||
if data and bestqual:
|
||||
logger.info(u'Found best result: <a href="%s">%s</a> - %s' % (bestqual[2], bestqual[0], helpers.bytes_to_mb(bestqual[1])))
|
||||
logger.info(u'Found best result: <a href="%s">%s</a> - %s' % (bestqual[2], bestqual[0], helpers.bytes_to_mb(bestqual[1])))
|
||||
nzb_folder_name = '%s - %s [%s]' % (helpers.latinToAscii(albums[0]).encode('UTF-8').replace('/', '_'), helpers.latinToAscii(albums[1]).encode('UTF-8').replace('/', '_'), year)
|
||||
if headphones.SAB_HOST and not headphones.BLACKHOLE:
|
||||
|
||||
@@ -455,9 +490,9 @@ def searchNZB(albumid=None, new=False, losslessOnly=False):
|
||||
|
||||
|
||||
def verifyresult(title, artistterm, term):
|
||||
|
||||
title = re.sub('[\.\-\/\_]', ' ', title)
|
||||
|
||||
|
||||
title = re.sub('[\.\-\/\_]', ' ', title)
|
||||
|
||||
#if artistterm != 'Various Artists':
|
||||
#
|
||||
# if not re.search('^' + re.escape(artistterm), title, re.IGNORECASE):
|
||||
@@ -472,23 +507,23 @@ def verifyresult(title, artistterm, term):
|
||||
|
||||
#another attempt to weed out substrings. We don't want "Vol III" when we were looking for "Vol II"
|
||||
|
||||
tokens = re.split('\W', term, re.IGNORECASE | re.UNICODE)
|
||||
for token in tokens:
|
||||
tokens = re.split('\W', term, re.IGNORECASE | re.UNICODE)
|
||||
for token in tokens:
|
||||
|
||||
if not token:
|
||||
continue
|
||||
if token == 'Various' or token == 'Artists' or token == 'VA':
|
||||
continue
|
||||
if not re.search('(?:\W|^)+' + token + '(?:\W|$)+', title, re.IGNORECASE | re.UNICODE):
|
||||
cleantoken = ''.join(c for c in token if c not in string.punctuation)
|
||||
if not not re.search('(?:\W|^)+' + cleantoken + '(?:\W|$)+', title, re.IGNORECASE | re.UNICODE):
|
||||
dic = {'!':'i', '$':'s'}
|
||||
dumbtoken = helpers.replace_all(token, dic)
|
||||
if not not re.search('(?:\W|^)+' + dumbtoken + '(?:\W|$)+', title, re.IGNORECASE | re.UNICODE):
|
||||
logger.info("Removed from results: " + title + " (missing tokens: " + token + " and " + cleantoken + ")")
|
||||
return False
|
||||
|
||||
return True
|
||||
if not token:
|
||||
continue
|
||||
if token == 'Various' or token == 'Artists' or token == 'VA':
|
||||
continue
|
||||
if not re.search('(?:\W|^)+' + token + '(?:\W|$)+', title, re.IGNORECASE | re.UNICODE):
|
||||
cleantoken = ''.join(c for c in token if c not in string.punctuation)
|
||||
if not not re.search('(?:\W|^)+' + cleantoken + '(?:\W|$)+', title, re.IGNORECASE | re.UNICODE):
|
||||
dic = {'!':'i', '$':'s'}
|
||||
dumbtoken = helpers.replace_all(token, dic)
|
||||
if not not re.search('(?:\W|^)+' + dumbtoken + '(?:\W|$)+', title, re.IGNORECASE | re.UNICODE):
|
||||
logger.info("Removed from results: " + title + " (missing tokens: " + token + " and " + cleantoken + ")")
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def getresultNZB(result):
|
||||
|
||||
@@ -521,7 +556,7 @@ def preprocess(resultlist):
|
||||
usenet_retention = 2000
|
||||
else:
|
||||
usenet_retention = int(headphones.USENET_RETENTION)
|
||||
|
||||
|
||||
for result in resultlist:
|
||||
nzb = getresultNZB(result)
|
||||
if nzb:
|
||||
@@ -581,9 +616,9 @@ def searchTorrent(albumid=None, new=False, losslessOnly=False):
|
||||
if albums[0] in albums[1] or len(albums[0]) < 4 or len(albums[1]) < 4:
|
||||
term = cleanartist + ' ' + cleanalbum + ' ' + year
|
||||
elif albums[0] == 'Various Artists':
|
||||
term = cleanalbum + ' ' + year
|
||||
term = cleanalbum + ' ' + year
|
||||
else:
|
||||
term = cleanartist + ' ' + cleanalbum
|
||||
term = cleanartist + ' ' + cleanalbum
|
||||
|
||||
# Replace bad characters in the term and unicode it
|
||||
term = re.sub('[\.\-\/]', ' ', term).encode('utf-8')
|
||||
@@ -619,51 +654,51 @@ def searchTorrent(albumid=None, new=False, losslessOnly=False):
|
||||
searchURL = providerurl + "/?%s" % urllib.urlencode(params)
|
||||
|
||||
try:
|
||||
data = urllib2.urlopen(searchURL, timeout=20).read()
|
||||
data = urllib2.urlopen(searchURL, timeout=20).read()
|
||||
except urllib2.URLError, e:
|
||||
logger.warn('Error fetching data from %s: %s' % (provider, e))
|
||||
data = False
|
||||
logger.warn('Error fetching data from %s: %s' % (provider, e))
|
||||
data = False
|
||||
|
||||
if data:
|
||||
|
||||
d = feedparser.parse(data)
|
||||
if not len(d.entries):
|
||||
logger.info(u"No results found from %s for %s" % (provider, term))
|
||||
pass
|
||||
|
||||
else:
|
||||
for item in d.entries:
|
||||
try:
|
||||
rightformat = True
|
||||
title = item.title
|
||||
seeders = item.seeds
|
||||
url = item.links[1]['url']
|
||||
size = int(item.links[1]['length'])
|
||||
try:
|
||||
if format == "2":
|
||||
request = urllib2.Request(url)
|
||||
request.add_header('Accept-encoding', 'gzip')
|
||||
response = urllib2.urlopen(request)
|
||||
if response.info().get('Content-Encoding') == 'gzip':
|
||||
buf = StringIO( response.read())
|
||||
f = gzip.GzipFile(fileobj=buf)
|
||||
torrent = f.read()
|
||||
else:
|
||||
torrent = response.read()
|
||||
if int(torrent.find(".mp3")) > 0 and int(torrent.find(".flac")) < 1:
|
||||
rightformat = False
|
||||
except Exception, e:
|
||||
rightformat = False
|
||||
if rightformat == True and size < maxsize and minimumseeders < int(seeders):
|
||||
resultlist.append((title, size, url, provider))
|
||||
logger.info('Found %s. Size: %s' % (title, helpers.bytes_to_mb(size)))
|
||||
else:
|
||||
logger.info('%s is larger than the maxsize, the wrong format or has to little seeders for this category, skipping. (Size: %i bytes, Seeders: %i, Format: %s)' % (title, size, int(seeders), rightformat))
|
||||
|
||||
except Exception, e:
|
||||
logger.error(u"An unknown error occured in the KAT parser: %s" % e)
|
||||
|
||||
|
||||
d = feedparser.parse(data)
|
||||
if not len(d.entries):
|
||||
logger.info(u"No results found from %s for %s" % (provider, term))
|
||||
pass
|
||||
|
||||
else:
|
||||
for item in d.entries:
|
||||
try:
|
||||
rightformat = True
|
||||
title = item.title
|
||||
seeders = item.seeds
|
||||
url = item.links[1]['url']
|
||||
size = int(item.links[1]['length'])
|
||||
try:
|
||||
if format == "2":
|
||||
request = urllib2.Request(url)
|
||||
request.add_header('Accept-encoding', 'gzip')
|
||||
request.add_header('Referer', 'http://kat.ph/')
|
||||
response = urllib2.urlopen(request)
|
||||
if response.info().get('Content-Encoding') == 'gzip':
|
||||
buf = StringIO( response.read())
|
||||
f = gzip.GzipFile(fileobj=buf)
|
||||
torrent = f.read()
|
||||
else:
|
||||
torrent = response.read()
|
||||
if int(torrent.find(".mp3")) > 0 and int(torrent.find(".flac")) < 1:
|
||||
rightformat = False
|
||||
except Exception, e:
|
||||
rightformat = False
|
||||
if rightformat == True and size < maxsize and minimumseeders < int(seeders):
|
||||
resultlist.append((title, size, url, provider))
|
||||
logger.info('Found %s. Size: %s' % (title, helpers.bytes_to_mb(size)))
|
||||
else:
|
||||
logger.info('%s is larger than the maxsize, the wrong format or has to little seeders for this category, skipping. (Size: %i bytes, Seeders: %i, Format: %s)' % (title, size, int(seeders), rightformat))
|
||||
|
||||
except Exception, e:
|
||||
logger.error(u"An unknown error occured in the KAT parser: %s" % e)
|
||||
|
||||
if headphones.ISOHUNT:
|
||||
provider = "ISOhunt"
|
||||
providerurl = url_fix("http://isohunt.com/js/rss/" + term)
|
||||
@@ -687,54 +722,54 @@ def searchTorrent(albumid=None, new=False, losslessOnly=False):
|
||||
searchURL = providerurl + "?%s" % urllib.urlencode(params)
|
||||
|
||||
try:
|
||||
data = urllib2.urlopen(searchURL, timeout=20).read()
|
||||
data = urllib2.urlopen(searchURL, timeout=20).read()
|
||||
except urllib2.URLError, e:
|
||||
logger.warn('Error fetching data from %s: %s' % (provider, e))
|
||||
data = False
|
||||
logger.warn('Error fetching data from %s: %s' % (provider, e))
|
||||
data = False
|
||||
|
||||
if data:
|
||||
|
||||
d = feedparser.parse(data)
|
||||
if not len(d.entries):
|
||||
logger.info(u"No results found from %s for %s" % (provider, term))
|
||||
pass
|
||||
|
||||
else:
|
||||
for item in d.entries:
|
||||
try:
|
||||
rightformat = True
|
||||
title = re.sub(r"(?<= \[)(.+)(?=\])","",item.title)
|
||||
title = title.replace("[]","")
|
||||
sxstart = item.description.find("Seeds: ") + 7
|
||||
seeds = ""
|
||||
while item.description[sxstart:sxstart + 1] != " ":
|
||||
seeds = seeds + item.description[sxstart:sxstart + 1]
|
||||
sxstart = sxstart + 1
|
||||
url = item.links[1]['url']
|
||||
size = int(item.links[1]['length'])
|
||||
try:
|
||||
if format == "2":
|
||||
request = urllib2.Request(url)
|
||||
request.add_header('Accept-encoding', 'gzip')
|
||||
response = urllib2.urlopen(request)
|
||||
if response.info().get('Content-Encoding') == 'gzip':
|
||||
buf = StringIO( response.read())
|
||||
f = gzip.GzipFile(fileobj=buf)
|
||||
torrent = f.read()
|
||||
else:
|
||||
torrent = response.read()
|
||||
if int(torrent.find(".mp3")) > 0 and int(torrent.find(".flac")) < 1:
|
||||
rightformat = False
|
||||
except Exception, e:
|
||||
rightformat = False
|
||||
if rightformat == True and size < maxsize and minimumseeders < seeds:
|
||||
resultlist.append((title, size, url, provider))
|
||||
logger.info('Found %s. Size: %s' % (title, helpers.bytes_to_mb(size)))
|
||||
else:
|
||||
logger.info('%s is larger than the maxsize, the wrong format or has to little seeders for this category, skipping. (Size: %i bytes, Seeders: %i, Format: %s)' % (title, size, int(seeds), rightformat))
|
||||
|
||||
except Exception, e:
|
||||
logger.error(u"An unknown error occured in the ISOhunt parser: %s" % e)
|
||||
|
||||
d = feedparser.parse(data)
|
||||
if not len(d.entries):
|
||||
logger.info(u"No results found from %s for %s" % (provider, term))
|
||||
pass
|
||||
|
||||
else:
|
||||
for item in d.entries:
|
||||
try:
|
||||
rightformat = True
|
||||
title = re.sub(r"(?<= \[)(.+)(?=\])","",item.title)
|
||||
title = title.replace("[]","")
|
||||
sxstart = item.description.find("Seeds: ") + 7
|
||||
seeds = ""
|
||||
while item.description[sxstart:sxstart + 1] != " ":
|
||||
seeds = seeds + item.description[sxstart:sxstart + 1]
|
||||
sxstart = sxstart + 1
|
||||
url = item.links[1]['url']
|
||||
size = int(item.links[1]['length'])
|
||||
try:
|
||||
if format == "2":
|
||||
request = urllib2.Request(url)
|
||||
request.add_header('Accept-encoding', 'gzip')
|
||||
response = urllib2.urlopen(request)
|
||||
if response.info().get('Content-Encoding') == 'gzip':
|
||||
buf = StringIO( response.read())
|
||||
f = gzip.GzipFile(fileobj=buf)
|
||||
torrent = f.read()
|
||||
else:
|
||||
torrent = response.read()
|
||||
if int(torrent.find(".mp3")) > 0 and int(torrent.find(".flac")) < 1:
|
||||
rightformat = False
|
||||
except Exception, e:
|
||||
rightformat = False
|
||||
if rightformat == True and size < maxsize and minimumseeders < seeds:
|
||||
resultlist.append((title, size, url, provider))
|
||||
logger.info('Found %s. Size: %s' % (title, helpers.bytes_to_mb(size)))
|
||||
else:
|
||||
logger.info('%s is larger than the maxsize, the wrong format or has to little seeders for this category, skipping. (Size: %i bytes, Seeders: %i, Format: %s)' % (title, size, int(seeds), rightformat))
|
||||
|
||||
except Exception, e:
|
||||
logger.error(u"An unknown error occured in the ISOhunt parser: %s" % e)
|
||||
|
||||
if headphones.MININOVA:
|
||||
provider = "Mininova"
|
||||
@@ -755,53 +790,53 @@ def searchTorrent(albumid=None, new=False, losslessOnly=False):
|
||||
searchURL = providerurl
|
||||
|
||||
try:
|
||||
data = urllib2.urlopen(searchURL, timeout=20).read()
|
||||
data = urllib2.urlopen(searchURL, timeout=20).read()
|
||||
except urllib2.URLError, e:
|
||||
logger.warn('Error fetching data from %s: %s' % (provider, e))
|
||||
data = False
|
||||
logger.warn('Error fetching data from %s: %s' % (provider, e))
|
||||
data = False
|
||||
|
||||
if data:
|
||||
|
||||
d = feedparser.parse(data)
|
||||
if not len(d.entries):
|
||||
logger.info(u"No results found from %s for %s" % (provider, term))
|
||||
pass
|
||||
|
||||
else:
|
||||
for item in d.entries:
|
||||
try:
|
||||
rightformat = True
|
||||
title = item.title
|
||||
sxstart = item.description.find("Ratio: ") + 7
|
||||
seeds = ""
|
||||
while item.description[sxstart:sxstart + 1] != " ":
|
||||
seeds = seeds + item.description[sxstart:sxstart + 1]
|
||||
sxstart = sxstart + 1
|
||||
url = item.links[1]['url']
|
||||
size = int(item.links[1]['length'])
|
||||
try:
|
||||
if format == "2":
|
||||
request = urllib2.Request(url)
|
||||
request.add_header('Accept-encoding', 'gzip')
|
||||
response = urllib2.urlopen(request)
|
||||
if response.info().get('Content-Encoding') == 'gzip':
|
||||
buf = StringIO( response.read())
|
||||
f = gzip.GzipFile(fileobj=buf)
|
||||
torrent = f.read()
|
||||
else:
|
||||
torrent = response.read()
|
||||
if int(torrent.find(".mp3")) > 0 and int(torrent.find(".flac")) < 1:
|
||||
rightformat = False
|
||||
except Exception, e:
|
||||
rightformat = False
|
||||
if rightformat == True and size < maxsize and minimumseeders < seeds:
|
||||
resultlist.append((title, size, url, provider))
|
||||
logger.info('Found %s. Size: %s' % (title, helpers.bytes_to_mb(size)))
|
||||
else:
|
||||
logger.info('%s is larger than the maxsize, the wrong format or has to little seeders for this category, skipping. (Size: %i bytes, Seeders: %i, Format: %s)' % (title, size, int(seeds), rightformat))
|
||||
|
||||
except Exception, e:
|
||||
logger.error(u"An unknown error occured in the MiniNova Parser: %s" % e)
|
||||
|
||||
d = feedparser.parse(data)
|
||||
if not len(d.entries):
|
||||
logger.info(u"No results found from %s for %s" % (provider, term))
|
||||
pass
|
||||
|
||||
else:
|
||||
for item in d.entries:
|
||||
try:
|
||||
rightformat = True
|
||||
title = item.title
|
||||
sxstart = item.description.find("Ratio: ") + 7
|
||||
seeds = ""
|
||||
while item.description[sxstart:sxstart + 1] != " ":
|
||||
seeds = seeds + item.description[sxstart:sxstart + 1]
|
||||
sxstart = sxstart + 1
|
||||
url = item.links[1]['url']
|
||||
size = int(item.links[1]['length'])
|
||||
try:
|
||||
if format == "2":
|
||||
request = urllib2.Request(url)
|
||||
request.add_header('Accept-encoding', 'gzip')
|
||||
response = urllib2.urlopen(request)
|
||||
if response.info().get('Content-Encoding') == 'gzip':
|
||||
buf = StringIO( response.read())
|
||||
f = gzip.GzipFile(fileobj=buf)
|
||||
torrent = f.read()
|
||||
else:
|
||||
torrent = response.read()
|
||||
if int(torrent.find(".mp3")) > 0 and int(torrent.find(".flac")) < 1:
|
||||
rightformat = False
|
||||
except Exception, e:
|
||||
rightformat = False
|
||||
if rightformat == True and size < maxsize and minimumseeders < seeds:
|
||||
resultlist.append((title, size, url, provider))
|
||||
logger.info('Found %s. Size: %s' % (title, helpers.bytes_to_mb(size)))
|
||||
else:
|
||||
logger.info('%s is larger than the maxsize, the wrong format or has to little seeders for this category, skipping. (Size: %i bytes, Seeders: %i, Format: %s)' % (title, size, int(seeds), rightformat))
|
||||
|
||||
except Exception, e:
|
||||
logger.error(u"An unknown error occured in the MiniNova Parser: %s" % e)
|
||||
|
||||
|
||||
|
||||
@@ -847,28 +882,28 @@ def searchTorrent(albumid=None, new=False, losslessOnly=False):
|
||||
|
||||
if new:
|
||||
|
||||
while True:
|
||||
|
||||
if len(torrentlist):
|
||||
|
||||
alreadydownloaded = myDB.select('SELECT * from snatched WHERE URL=?', [torrentlist[0][2]])
|
||||
|
||||
if len(alreadydownloaded):
|
||||
logger.info('%s has already been downloaded. Skipping.' % torrentlist[0][0])
|
||||
torrentlist.pop(0)
|
||||
|
||||
else:
|
||||
break
|
||||
else:
|
||||
logger.info('No more results found for %s' % term)
|
||||
return
|
||||
while True:
|
||||
|
||||
if len(torrentlist):
|
||||
|
||||
alreadydownloaded = myDB.select('SELECT * from snatched WHERE URL=?', [torrentlist[0][2]])
|
||||
|
||||
if len(alreadydownloaded):
|
||||
logger.info('%s has already been downloaded. Skipping.' % torrentlist[0][0])
|
||||
torrentlist.pop(0)
|
||||
|
||||
else:
|
||||
break
|
||||
else:
|
||||
logger.info('No more results found for %s' % term)
|
||||
return
|
||||
|
||||
logger.info(u"Pre-processing result")
|
||||
|
||||
(data, bestqual) = preprocesstorrent(torrentlist)
|
||||
|
||||
if data and bestqual:
|
||||
logger.info(u'Found best result: <a href="%s">%s</a> - %s' % (bestqual[2], bestqual[0], helpers.bytes_to_mb(bestqual[1])))
|
||||
logger.info(u'Found best result: <a href="%s">%s</a> - %s' % (bestqual[2], bestqual[0], helpers.bytes_to_mb(bestqual[1])))
|
||||
torrent_folder_name = '%s - %s [%s]' % (helpers.latinToAscii(albums[0]).encode('UTF-8').replace('/', '_'), helpers.latinToAscii(albums[1]).encode('UTF-8').replace('/', '_'), year)
|
||||
if headphones.TORRENTBLACKHOLE_DIR == "sendtracker":
|
||||
|
||||
@@ -879,15 +914,17 @@ def searchTorrent(albumid=None, new=False, losslessOnly=False):
|
||||
|
||||
elif headphones.TORRENTBLACKHOLE_DIR != "":
|
||||
|
||||
# Get torrent name from .torrent, this is usually used by the torrent client as the folder name
|
||||
|
||||
torrent_name = torrent_folder_name + '.torrent'
|
||||
download_path = os.path.join(headphones.TORRENTBLACKHOLE_DIR, torrent_name)
|
||||
try:
|
||||
f = open(download_path, 'wb')
|
||||
f.write(data)
|
||||
f.close()
|
||||
logger.info('File saved to: %s' % torrent_name)
|
||||
torrent_file = open(download_path, 'rb').read()
|
||||
torrent_info = bencode.bdecode(torrent_file)
|
||||
torrent_folder_name = torrent_info['info'].get('name','')
|
||||
logger.info('Torrent folder name: %s' % torrent_folder_name)
|
||||
except Exception, e:
|
||||
logger.error('Couldn\'t write Torrent file: %s' % e)
|
||||
logger.error('Couldn\'t get name from Torrent file: %s' % e)
|
||||
break
|
||||
|
||||
myDB.action('UPDATE albums SET status = "Snatched" WHERE AlbumID=?', [albums[2]])
|
||||
@@ -896,30 +933,26 @@ def searchTorrent(albumid=None, new=False, losslessOnly=False):
|
||||
def preprocesstorrent(resultlist):
|
||||
selresult = ""
|
||||
for result in resultlist:
|
||||
try:
|
||||
if selresult == "":
|
||||
selresult = result
|
||||
request = urllib2.Request(result[2])
|
||||
request.add_header('Accept-encoding', 'gzip')
|
||||
response = urllib2.urlopen(request)
|
||||
if response.info().get('Content-Encoding') == 'gzip':
|
||||
buf = StringIO( response.read())
|
||||
f = gzip.GzipFile(fileobj=buf)
|
||||
torrent = f.read()
|
||||
else:
|
||||
torrent = response.read()
|
||||
elif int(selresult[1]) < int(result[1]):
|
||||
selresult = result
|
||||
request = urllib2.Request(result[2])
|
||||
request.add_header('Accept-encoding', 'gzip')
|
||||
response = urllib2.urlopen(request)
|
||||
if response.info().get('Content-Encoding') == 'gzip':
|
||||
buf = StringIO( response.read())
|
||||
f = gzip.GzipFile(fileobj=buf)
|
||||
torrent = f.read()
|
||||
else:
|
||||
torrent = response.read()
|
||||
except ExpatError:
|
||||
logger.error('Unable to torrent file. Skipping.')
|
||||
continue
|
||||
if selresult == "":
|
||||
selresult = result
|
||||
elif int(selresult[1]) < int(result[1]): # if size is lower than new result replace previous selected result (bigger size = better quality?)
|
||||
selresult = result
|
||||
|
||||
try:
|
||||
request = urllib2.Request(selresult[2])
|
||||
request.add_header('Accept-encoding', 'gzip')
|
||||
|
||||
if selresult[3] == 'Kick Ass Torrent':
|
||||
request.add_header('Referer', 'http://kat.ph/')
|
||||
|
||||
response = urllib2.urlopen(request)
|
||||
if response.info().get('Content-Encoding') == 'gzip':
|
||||
buf = StringIO(response.read())
|
||||
f = gzip.GzipFile(fileobj=buf)
|
||||
torrent = f.read()
|
||||
else:
|
||||
torrent = response.read()
|
||||
except ExpatError:
|
||||
logger.error('Unable to torrent %s' % selresult[2])
|
||||
|
||||
return torrent, selresult
|
||||
|
||||
@@ -1,440 +0,0 @@
|
||||
from headphones import db
|
||||
|
||||
_header = '''
|
||||
<html>
|
||||
<head>
|
||||
<title>Headphones</title>
|
||||
<link rel="stylesheet" type="text/css" href="css/style.css" />
|
||||
<link rel="icon" type="image/x-icon" href="images/favicon.ico" />
|
||||
<link rel="apple-touch-icon" href="images/headphoneslogo.png" />
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">'''
|
||||
|
||||
_shutdownheader = '''
|
||||
<html>
|
||||
<head>
|
||||
<title>Headphones</title>
|
||||
<link rel="stylesheet" type="text/css" href="css/style.css" />
|
||||
<link rel="icon" type="image/x-icon" href="images/favicon.ico" />
|
||||
<link rel="apple-touch-icon" href="images/headphoneslogo.png" />
|
||||
<meta http-equiv="refresh" content="%s;url=index">
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">'''
|
||||
|
||||
_logobar = '''
|
||||
<div class="logo"><a href="home"><img src="images/headphoneslogo.png" border="0">headphones</a></div>
|
||||
<div class="search"><form action="findArtist" method="GET">
|
||||
<input type="text" value="Add an artist" onfocus="if
|
||||
(this.value==this.defaultValue) this.value='';" name="name" />
|
||||
<input type="submit" /></form></div><br />
|
||||
'''
|
||||
|
||||
_nav = '''<div class="nav">
|
||||
<a href="home">HOME</a>
|
||||
<a href="upcoming">UPCOMING</a>
|
||||
<a href="extras">EXTRAS</a>
|
||||
<a href="manage">MANAGE</a>
|
||||
<a href="history">HISTORY</a>
|
||||
<a href="logs">LOGS</a>
|
||||
<a href="config">SETTINGS</a>
|
||||
<div style="float:right">
|
||||
<a href="restart" title="Restart"><img src="images/restart.png" height="15px" width="15px" border="0"></a>
|
||||
<a href="shutdown" title="Shutdown"><img src="images/shutdown.png" height="15px" width="15px" border="0"></a>
|
||||
</div>
|
||||
</div>'''
|
||||
|
||||
_footer = '''
|
||||
</div><div class="footer"><br /><div class="center"><form action="https://www.paypal.com/cgi-bin/webscr" method="post">
|
||||
<input type="hidden" name="cmd" value="_s-xclick">
|
||||
<input type="hidden" name="hosted_button_id" value="93FFC6WDV97QS">
|
||||
<input type="image" src="https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
|
||||
<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
|
||||
</form><br /><div class="version">Version: %s</div>
|
||||
</div></div>
|
||||
</body>
|
||||
</html>'''
|
||||
|
||||
configform = form = '''
|
||||
<br>
|
||||
<center>
|
||||
<div class="smalltext">
|
||||
<a href="#web_interface" >Web Interface</a> |
|
||||
<a href="#download" class="smalltext">Download Settings</a> |
|
||||
<a href="#providers" class="smalltext">Search Providers</a> |
|
||||
<a href="#post_processing" class="smalltext">Quality & Post Processing</a> |
|
||||
<a href="#advanced_settings" class="smalltext">Advanced Settings</a>
|
||||
</div>
|
||||
</center>
|
||||
<div class="table">
|
||||
<div class="config">
|
||||
<form action="configUpdate" method="post">
|
||||
<a name="web_interface"><h1><u>Web Interface</u></h1></a>
|
||||
|
||||
<table class="configtable" summary="Web Interface">
|
||||
<tr>
|
||||
<td>
|
||||
<p>
|
||||
HTTP Host: <br><br>
|
||||
<input type="text" name="http_host" value="%s" size="30" maxlength="40"><br>
|
||||
<i class="smalltext">i.e. localhost or 0.0.0.0</i>
|
||||
</p>
|
||||
</td>
|
||||
<td>
|
||||
<p>
|
||||
HTTP Username: <br><br>
|
||||
<input type="text" name="http_username" value="%s" size="30" maxlength="40">
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
<p>
|
||||
HTTP Port: <br><br>
|
||||
<input type="text" name="http_port" value="%s" size="20" maxlength="40">
|
||||
</p>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
<p>
|
||||
HTTP Password: <br><br>
|
||||
<input type="password" name="http_password" value="%s" size="30" maxlength="40">
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
<p>Launch Browser on Startup:<input type="checkbox" name="launch_browser" value="1" %s /></p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<a name="download"><h1><u>Download Settings</u></h1></a>
|
||||
|
||||
<table class="configtable" summary="Download Settings">
|
||||
<tr>
|
||||
<td>
|
||||
<p>SABnzbd Host:</p><input type="text" name="sab_host" value="%s" size="30" maxlength="40"><br>
|
||||
|
||||
<i class="smalltext">usually localhost:8080</i>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
<p>SABnzbd Username:</p><input type="text" name="sab_username" value="%s" size="20" maxlength="40">
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
<br>
|
||||
|
||||
<p>SABnzbd API:</p><input type="text" name="sab_apikey" value="%s" size="46" maxlength="40">
|
||||
</td>
|
||||
|
||||
<td>
|
||||
<br>
|
||||
|
||||
<p>SABnzbd Password:</p><input type="password" name="sab_password" value="%s" size="20" maxlength="40">
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
<br>
|
||||
|
||||
<p>SABnzbd Category:</p><input type="text" name="sab_category" value="%s" size="20" maxlength="40">
|
||||
</td>
|
||||
|
||||
<td>
|
||||
<br>
|
||||
|
||||
<p>Music Download Directory:</p><input type="text" name="download_dir" value="%s" size="60"><br>
|
||||
|
||||
<i class="smalltext">Full path to the directory where SAB downloads your music<br>
|
||||
i.e. /Users/name/Downloads/music</i>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
<br>
|
||||
|
||||
<p>Use Black Hole:</p><input type="checkbox" name="blackhole" value=1 %s />
|
||||
</td>
|
||||
|
||||
<td>
|
||||
<br>
|
||||
|
||||
<p>Black Hole Directory:</p><input type="text" name="blackhole_dir" value="%s" size="60"><br>
|
||||
|
||||
<i class="smalltext">Folder your Download program watches for NZBs</i>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
<br>
|
||||
|
||||
<p>Usenet Retention:</p><input type="text" name="usenet_retention" value="%s" size="20" maxlength="40">
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<a name="providers"><h1><u>Search Providers</u></h1></a>
|
||||
|
||||
<table class="configtable" summary="Search Providers">
|
||||
<tr>
|
||||
<td>
|
||||
<p>NZBMatrix: <input type="checkbox" name="nzbmatrix" value="1" %s /></p>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
<p>
|
||||
NZBMatrix Username: <br>
|
||||
<input type="text" name="nzbmatrix_username" value="%s" size="30" maxlength="40">
|
||||
</p>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
<p>
|
||||
NZBMatrix API: <br>
|
||||
<input type="text" name="nzbmatrix_apikey" value="%s" size="46" maxlength="40">
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
<br>
|
||||
|
||||
<p>Newznab: <input type="checkbox" name="newznab" value="1" %s /></p>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
<br>
|
||||
|
||||
<p>
|
||||
Newznab Host:<br>
|
||||
<input type="text" name="newznab_host" value="%s" size="30" maxlength="40"><br>
|
||||
<i class="smalltext">i.e. http://nzb.su</i>
|
||||
</p>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
<br>
|
||||
|
||||
<p>
|
||||
Newznab API:<br>
|
||||
<input type="text" name="newznab_apikey" value="%s" size="46" maxlength="40">
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
<br>
|
||||
|
||||
<p>NZBs.org:<input type="checkbox" name="nzbsorg" value="1" %s /></p>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
<br>
|
||||
|
||||
<p>
|
||||
NZBs.org UID:<br>
|
||||
<input type="text" name="nzbsorg_uid" value="%s" size="30" maxlength="40">
|
||||
</p>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
<br>
|
||||
|
||||
<p>
|
||||
NZBs.org Hash:<br>
|
||||
<input type="text" name="nzbsorg_hash" value="%s" size="46" maxlength="40">
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
<br>
|
||||
|
||||
<p>Newzbin:<input type="checkbox" name="newzbin" value="1" %s /></p>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
<br>
|
||||
|
||||
<p>
|
||||
Newzbin UID:<br>
|
||||
<input type="text" name="newzbin_uid" value="%s" size="30" maxlength="40">
|
||||
</p>
|
||||
</td>
|
||||
|
||||
<td>
|
||||
<br>
|
||||
|
||||
<p>
|
||||
Newzbin Password:<br>
|
||||
<input type="text" name="newzbin_password" value="%s" size="46" maxlength="40">
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<a name="post_processing"><h1><u>Quality & Post Processing</u></h1></a>
|
||||
|
||||
<table class="configtable" summary="Quality & Post Processing">
|
||||
<tr>
|
||||
<td>
|
||||
<b>Album Quality:</b>
|
||||
<p>
|
||||
<input type="radio" name="preferred_quality" value="0" %s />Highest Quality excluding Lossless<br /><br />
|
||||
<input type="radio" name="preferred_quality" value="1" %s />Highest Quality including Lossless<br /><br />
|
||||
<input type="radio" name="preferred_quality" value="3" %s />Lossless Only<br /><br />
|
||||
<input type="radio" name="preferred_quality" value="2" %s />Preferred Bitrate:
|
||||
<input type="text" name="preferred_bitrate" value="%s" size="5" maxlength="5" />kbps <br>
|
||||
<i class="smalltext2"><input type="checkbox" name="detect_bitrate" value="1" %s />Auto-Detect Preferred Bitrate </i>
|
||||
</p>
|
||||
</td>
|
||||
<td>
|
||||
<b>Post-Processing:</b>
|
||||
<p>
|
||||
<input type="checkbox" name="move_files" value="1" %s />Move downloads to Destination Folder<br />
|
||||
<input type="checkbox" name="rename_files" value="1" %s />Rename files<br>
|
||||
<input type="checkbox" name="correct_metadata" value="1" %s />Correct metadata<br>
|
||||
<input type="checkbox" name="cleanup_files" value="1" %s />Delete leftover files (.m3u, .nfo, .sfv, .nzb, etc.)<br>
|
||||
<input type="checkbox" name="add_album_art" value="1" %s>Add album art as 'folder.jpg' to album folder<br>
|
||||
<input type="checkbox" name="embed_album_art" value="1" %s>Embed album art in each file
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
<br>
|
||||
|
||||
<p><b>Path to Destination folder</b>:<br><input type="text" name="destination_dir" value="%s" size="60">
|
||||
<br>
|
||||
<i class="smalltext">i.e. /Users/name/Music/iTunes or /Volumes/share/music</i>
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<a name="advanced_settings"><h1><u>Advanced Settings</u></h1></a>
|
||||
|
||||
<table class="configtable" summary="Advanced Settings">
|
||||
<tr>
|
||||
<td>
|
||||
<b>Renaming Options:</b>
|
||||
<br>
|
||||
|
||||
<p><b>Folder Format</b>:<br><input type="text" name="folder_format" value="%s" size="60">
|
||||
<br>
|
||||
<i class="smalltext">Use: artist, album, year and first (first letter in artist name)<br />
|
||||
E.g.: first/artist/album [year] = G/Girl Talk/All Day [2010]</i>
|
||||
</p>
|
||||
|
||||
<p><b>File Format</b>:<br><input type="text" name="file_format" value="%s" size="60">
|
||||
<br>
|
||||
<i class="smalltext">Use: tracknumber, title, artist, album and year</i>
|
||||
</p>
|
||||
</td>
|
||||
<td>
|
||||
<b>Miscellaneous:</b>
|
||||
<p>
|
||||
<input type="checkbox" name="include_extras" value="1" %s />Automatically Include Extras When Adding an Artist<br />
|
||||
<i class="smalltext">Extras includes: EPs, Compilations, Live Albums, Remix Albums and Singles</i>
|
||||
</p>
|
||||
<p><b>Log Directory</b>:<br><input type="text" name="log_dir" value="%s" size="60">
|
||||
</p>
|
||||
</td>
|
||||
<td>
|
||||
<b>Prowl Notification:</b>
|
||||
<p>
|
||||
<input type="checkbox" name="prowl_enabled" value="1" %s />Enabled?
|
||||
</p>
|
||||
<p>
|
||||
<i class="smalltext">API key:</i>
|
||||
<input type="text" name="prowl_keys" value="%s" size="50">
|
||||
</p>
|
||||
<p>
|
||||
<input type="checkbox" name="prowl_onsnatch" value="1" %s />Notify on snatch?</p>
|
||||
<p><b>Priority (-2,-1,0,1 or 2):</b><input type="text" name="prowl_priority" value="%s" size="5">
|
||||
</p>
|
||||
</td>
|
||||
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
|
||||
<p class="center"><input type="submit" value="Save Changes"><br>
|
||||
(Web Interface changes require a restart to take effect)</p>
|
||||
</form>
|
||||
</div>
|
||||
</div>'''
|
||||
|
||||
|
||||
def displayAlbums(ArtistID, Type=None):
|
||||
|
||||
myDB = db.DBConnection()
|
||||
|
||||
results = myDB.select('SELECT AlbumTitle, ReleaseDate, AlbumID, Status, ArtistName, AlbumASIN from albums WHERE ArtistID=? AND Type=? order by ReleaseDate DESC', [ArtistID, Type])
|
||||
|
||||
if not len(results):
|
||||
return
|
||||
|
||||
typeheadings = {'Album' : 'Official Albums',
|
||||
'Compilation': 'Compilations',
|
||||
'EP': 'EPs',
|
||||
'Live': 'Live Albums',
|
||||
'Remix': 'Remixes',
|
||||
'Single': 'Singles'}
|
||||
|
||||
page = ['''<p class="mediumcentered">%s</p>
|
||||
<table border="0" cellpadding="3">
|
||||
<tr>
|
||||
<th align="left" width="30"></th>
|
||||
<th align="left" width="120">Album Name</th>
|
||||
<th align="center" width="100">Release Date</th>
|
||||
<th align="center" width="180">Status</th>
|
||||
<th align="center">Have</th>
|
||||
</tr>''' % typeheadings[Type]]
|
||||
i = 0
|
||||
while i < len(results):
|
||||
totaltracks = len(myDB.select('SELECT TrackTitle from tracks WHERE AlbumID=?', [results[i][2]]))
|
||||
havetracks = len(myDB.select('SELECT TrackTitle from have WHERE ArtistName like ? AND AlbumTitle like ?', [results[i][4], results[i][0]]))
|
||||
try:
|
||||
percent = (havetracks*100)/totaltracks
|
||||
if percent > 100:
|
||||
percent = 100
|
||||
except ZeroDivisionError:
|
||||
percent = 100
|
||||
if results[i][3] == 'Skipped':
|
||||
newStatus = '''%s [<A class="external" href="queueAlbum?AlbumID=%s&ArtistID=%s">want</a>]''' % (results[i][3], results[i][2], ArtistID)
|
||||
elif results[i][3] == 'Wanted':
|
||||
newStatus = '''<b>%s</b>[<A class="external" href="unqueueAlbum?AlbumID=%s&ArtistID=%s">skip</a>]''' % (results[i][3], results[i][2], ArtistID)
|
||||
elif results[i][3] == 'Downloaded':
|
||||
newStatus = '''<b>%s</b>[<A class="external" href="queueAlbum?AlbumID=%s&ArtistID=%s">retry</a>][<A class="external" href="queueAlbum?AlbumID=%s&ArtistID=%s&new=True">new</a>]''' % (results[i][3], results[i][2], ArtistID, results[i][2], ArtistID)
|
||||
elif results[i][3] == 'Snatched':
|
||||
newStatus = '''<b>%s</b>[<A class="external" href="queueAlbum?AlbumID=%s&ArtistID=%s">retry</a>][<A class="external" href="queueAlbum?AlbumID=%s&ArtistID=%s&new=True">new</a>]''' % (results[i][3], results[i][2], ArtistID, results[i][2], ArtistID)
|
||||
else:
|
||||
newStatus = '%s' % (results[i][3])
|
||||
page.append('''<tr>
|
||||
<td align="left">
|
||||
<td align="left" width="240"><a href="albumPage?AlbumID=%s">%s</a>
|
||||
(<A class="external" href="http://musicbrainz.org/release-group/%s.html">link</a>)</td>
|
||||
<td align="center" width="160">%s</td>
|
||||
<td align="center">%s</td>
|
||||
<td><div class="progress-container"><div style="width: %s%%"><div class="smalltext3">%s/%s</div></div></div></td>
|
||||
</tr>''' % (results[i][5], results[i][2], results[i][0], results[i][2], results[i][1], newStatus, percent, havetracks, totaltracks))
|
||||
i = i+1
|
||||
page.append('</table><br />')
|
||||
|
||||
return ''.join(page)
|
||||
@@ -1,18 +1,33 @@
|
||||
# This file is part of Headphones.
|
||||
#
|
||||
# Headphones 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.
|
||||
#
|
||||
# Headphones 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 Headphones. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import headphones
|
||||
|
||||
from headphones import logger, db, importer
|
||||
|
||||
def dbUpdate():
|
||||
|
||||
myDB = db.DBConnection()
|
||||
myDB = db.DBConnection()
|
||||
|
||||
activeartists = myDB.select('SELECT ArtistID, ArtistName from artists WHERE Status="Active" or Status="Loading" order by LastUpdated ASC')
|
||||
activeartists = myDB.select('SELECT ArtistID, ArtistName from artists WHERE Status="Active" or Status="Loading" order by LastUpdated ASC')
|
||||
|
||||
logger.info('Starting update for %i active artists' % len(activeartists))
|
||||
|
||||
for artist in activeartists:
|
||||
|
||||
artistid = artist[0]
|
||||
importer.addArtisttoDB(artistid)
|
||||
|
||||
logger.info('Update complete')
|
||||
logger.info('Starting update for %i active artists' % len(activeartists))
|
||||
|
||||
for artist in activeartists:
|
||||
|
||||
artistid = artist[0]
|
||||
importer.addArtisttoDB(artistid)
|
||||
|
||||
logger.info('Update complete')
|
||||
|
||||
@@ -1,3 +1,18 @@
|
||||
# This file is part of Headphones.
|
||||
#
|
||||
# Headphones 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.
|
||||
#
|
||||
# Headphones 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 Headphones. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import platform, subprocess, re, os, urllib2, tarfile
|
||||
|
||||
import headphones
|
||||
@@ -10,205 +25,205 @@ branch = "master"
|
||||
|
||||
def runGit(args):
|
||||
|
||||
if headphones.GIT_PATH:
|
||||
git_locations = ['"'+headphones.GIT_PATH+'"']
|
||||
else:
|
||||
git_locations = ['git']
|
||||
|
||||
if platform.system().lower() == 'darwin':
|
||||
git_locations.append('/usr/local/git/bin/git')
|
||||
|
||||
|
||||
output = err = None
|
||||
|
||||
for cur_git in git_locations:
|
||||
|
||||
cmd = cur_git+' '+args
|
||||
|
||||
try:
|
||||
logger.debug('Trying to execute: "' + cmd + '" with shell in ' + headphones.PROG_DIR)
|
||||
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, cwd=headphones.PROG_DIR)
|
||||
output, err = p.communicate()
|
||||
logger.debug('Git output: ' + output)
|
||||
except OSError:
|
||||
logger.debug('Command ' + cmd + ' didn\'t work, couldn\'t find git')
|
||||
continue
|
||||
|
||||
if 'not found' in output or "not recognized as an internal or external command" in output:
|
||||
logger.debug('Unable to find git with command ' + cmd)
|
||||
output = None
|
||||
elif 'fatal:' in output or err:
|
||||
logger.error('Git returned bad info. Are you sure this is a git installation?')
|
||||
output = None
|
||||
elif output:
|
||||
break
|
||||
|
||||
return (output, err)
|
||||
|
||||
if headphones.GIT_PATH:
|
||||
git_locations = ['"'+headphones.GIT_PATH+'"']
|
||||
else:
|
||||
git_locations = ['git']
|
||||
|
||||
if platform.system().lower() == 'darwin':
|
||||
git_locations.append('/usr/local/git/bin/git')
|
||||
|
||||
|
||||
output = err = None
|
||||
|
||||
for cur_git in git_locations:
|
||||
|
||||
cmd = cur_git+' '+args
|
||||
|
||||
try:
|
||||
logger.debug('Trying to execute: "' + cmd + '" with shell in ' + headphones.PROG_DIR)
|
||||
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, cwd=headphones.PROG_DIR)
|
||||
output, err = p.communicate()
|
||||
logger.debug('Git output: ' + output)
|
||||
except OSError:
|
||||
logger.debug('Command ' + cmd + ' didn\'t work, couldn\'t find git')
|
||||
continue
|
||||
|
||||
if 'not found' in output or "not recognized as an internal or external command" in output:
|
||||
logger.debug('Unable to find git with command ' + cmd)
|
||||
output = None
|
||||
elif 'fatal:' in output or err:
|
||||
logger.error('Git returned bad info. Are you sure this is a git installation?')
|
||||
output = None
|
||||
elif output:
|
||||
break
|
||||
|
||||
return (output, err)
|
||||
|
||||
def getVersion():
|
||||
|
||||
if version.HEADPHONES_VERSION.startswith('build '):
|
||||
|
||||
headphones.INSTALL_TYPE = 'win'
|
||||
|
||||
# Don't have a way to update exe yet, but don't want to set VERSION to None
|
||||
return 'Windows Install'
|
||||
|
||||
elif os.path.isdir(os.path.join(headphones.PROG_DIR, '.git')):
|
||||
|
||||
headphones.INSTALL_TYPE = 'git'
|
||||
output, err = runGit('rev-parse HEAD')
|
||||
|
||||
if not output:
|
||||
logger.error('Couldn\'t find latest installed version.')
|
||||
return None
|
||||
|
||||
cur_commit_hash = output.strip()
|
||||
|
||||
if not re.match('^[a-z0-9]+$', cur_commit_hash):
|
||||
logger.error('Output doesn\'t look like a hash, not using it')
|
||||
return None
|
||||
|
||||
return cur_commit_hash
|
||||
|
||||
else:
|
||||
|
||||
headphones.INSTALL_TYPE = 'source'
|
||||
|
||||
version_file = os.path.join(headphones.PROG_DIR, 'version.txt')
|
||||
|
||||
if not os.path.isfile(version_file):
|
||||
return None
|
||||
|
||||
fp = open(version_file, 'r')
|
||||
current_version = fp.read().strip(' \n\r')
|
||||
fp.close()
|
||||
|
||||
if current_version:
|
||||
return current_version
|
||||
else:
|
||||
return None
|
||||
|
||||
if version.HEADPHONES_VERSION.startswith('win32build'):
|
||||
|
||||
headphones.INSTALL_TYPE = 'win'
|
||||
|
||||
# Don't have a way to update exe yet, but don't want to set VERSION to None
|
||||
return 'Windows Install'
|
||||
|
||||
elif os.path.isdir(os.path.join(headphones.PROG_DIR, '.git')):
|
||||
|
||||
headphones.INSTALL_TYPE = 'git'
|
||||
output, err = runGit('rev-parse HEAD')
|
||||
|
||||
if not output:
|
||||
logger.error('Couldn\'t find latest installed version.')
|
||||
return None
|
||||
|
||||
cur_commit_hash = output.strip()
|
||||
|
||||
if not re.match('^[a-z0-9]+$', cur_commit_hash):
|
||||
logger.error('Output doesn\'t look like a hash, not using it')
|
||||
return None
|
||||
|
||||
return cur_commit_hash
|
||||
|
||||
else:
|
||||
|
||||
headphones.INSTALL_TYPE = 'source'
|
||||
|
||||
version_file = os.path.join(headphones.PROG_DIR, 'version.txt')
|
||||
|
||||
if not os.path.isfile(version_file):
|
||||
return None
|
||||
|
||||
fp = open(version_file, 'r')
|
||||
current_version = fp.read().strip(' \n\r')
|
||||
fp.close()
|
||||
|
||||
if current_version:
|
||||
return current_version
|
||||
else:
|
||||
return None
|
||||
|
||||
def checkGithub():
|
||||
|
||||
# Get the latest commit available from github
|
||||
url = 'https://api.github.com/repos/%s/headphones/commits/%s' % (user, branch)
|
||||
logger.info ('Retrieving latest version information from github')
|
||||
try:
|
||||
result = urllib2.urlopen(url).read()
|
||||
git = simplejson.JSONDecoder().decode(result)
|
||||
headphones.LATEST_VERSION = git['sha']
|
||||
except:
|
||||
logger.warn('Could not get the latest commit from github')
|
||||
headphones.COMMITS_BEHIND = 0
|
||||
return headphones.CURRENT_VERSION
|
||||
|
||||
# See how many commits behind we are
|
||||
if headphones.CURRENT_VERSION:
|
||||
logger.info('Comparing currently installed version with latest github version')
|
||||
url = 'https://api.github.com/repos/%s/headphones/compare/%s...%s' % (user, headphones.CURRENT_VERSION, headphones.LATEST_VERSION)
|
||||
|
||||
try:
|
||||
result = urllib2.urlopen(url).read()
|
||||
git = simplejson.JSONDecoder().decode(result)
|
||||
headphones.COMMITS_BEHIND = git['total_commits']
|
||||
except:
|
||||
logger.warn('Could not get commits behind from github')
|
||||
headphones.COMMITS_BEHIND = 0
|
||||
return headphones.CURRENT_VERSION
|
||||
|
||||
if headphones.COMMITS_BEHIND >= 1:
|
||||
logger.info('New version is available. You are %s commits behind' % headphones.COMMITS_BEHIND)
|
||||
elif headphones.COMMITS_BEHIND == 0:
|
||||
logger.info('Headphones is up to date')
|
||||
elif headphones.COMMITS_BEHIND == -1:
|
||||
logger.info('You are running an unknown version of Headphones. Run the updater to identify your version')
|
||||
|
||||
else:
|
||||
logger.info('You are running an unknown version of Headphones. Run the updater to identify your version')
|
||||
|
||||
return headphones.LATEST_VERSION
|
||||
|
||||
# Get the latest commit available from github
|
||||
url = 'https://api.github.com/repos/%s/headphones/commits/%s' % (user, branch)
|
||||
logger.info ('Retrieving latest version information from github')
|
||||
try:
|
||||
result = urllib2.urlopen(url).read()
|
||||
git = simplejson.JSONDecoder().decode(result)
|
||||
headphones.LATEST_VERSION = git['sha']
|
||||
except:
|
||||
logger.warn('Could not get the latest commit from github')
|
||||
headphones.COMMITS_BEHIND = 0
|
||||
return headphones.CURRENT_VERSION
|
||||
|
||||
# See how many commits behind we are
|
||||
if headphones.CURRENT_VERSION:
|
||||
logger.info('Comparing currently installed version with latest github version')
|
||||
url = 'https://api.github.com/repos/%s/headphones/compare/%s...%s' % (user, headphones.CURRENT_VERSION, headphones.LATEST_VERSION)
|
||||
|
||||
try:
|
||||
result = urllib2.urlopen(url).read()
|
||||
git = simplejson.JSONDecoder().decode(result)
|
||||
headphones.COMMITS_BEHIND = git['total_commits']
|
||||
except:
|
||||
logger.warn('Could not get commits behind from github')
|
||||
headphones.COMMITS_BEHIND = 0
|
||||
return headphones.CURRENT_VERSION
|
||||
|
||||
if headphones.COMMITS_BEHIND >= 1:
|
||||
logger.info('New version is available. You are %s commits behind' % headphones.COMMITS_BEHIND)
|
||||
elif headphones.COMMITS_BEHIND == 0:
|
||||
logger.info('Headphones is up to date')
|
||||
elif headphones.COMMITS_BEHIND == -1:
|
||||
logger.info('You are running an unknown version of Headphones. Run the updater to identify your version')
|
||||
|
||||
else:
|
||||
logger.info('You are running an unknown version of Headphones. Run the updater to identify your version')
|
||||
|
||||
return headphones.LATEST_VERSION
|
||||
|
||||
def update():
|
||||
|
||||
|
||||
if headphones.INSTALL_TYPE == 'win':
|
||||
|
||||
logger.info('Windows .exe updating not supported yet.')
|
||||
pass
|
||||
|
||||
|
||||
if headphones.INSTALL_TYPE == 'win':
|
||||
|
||||
logger.info('Windows .exe updating not supported yet.')
|
||||
pass
|
||||
|
||||
|
||||
elif headphones.INSTALL_TYPE == 'git':
|
||||
|
||||
output, err = runGit('pull origin ' + version.HEADPHONES_VERSION)
|
||||
|
||||
if not output:
|
||||
logger.error('Couldn\'t download latest version')
|
||||
|
||||
for line in output.split('\n'):
|
||||
|
||||
if 'Already up-to-date.' in line:
|
||||
logger.info('No update available, not updating')
|
||||
logger.info('Output: ' + str(output))
|
||||
elif line.endswith('Aborting.'):
|
||||
logger.error('Unable to update from git: '+line)
|
||||
logger.info('Output: ' + str(output))
|
||||
|
||||
else:
|
||||
|
||||
tar_download_url = 'https://github.com/%s/headphones/tarball/%s' % (user, branch)
|
||||
update_dir = os.path.join(headphones.PROG_DIR, 'update')
|
||||
version_path = os.path.join(headphones.PROG_DIR, 'version.txt')
|
||||
|
||||
try:
|
||||
logger.info('Downloading update from: '+tar_download_url)
|
||||
data = urllib2.urlopen(tar_download_url)
|
||||
except (IOError, URLError):
|
||||
logger.error("Unable to retrieve new version from "+tar_download_url+", can't update")
|
||||
return
|
||||
|
||||
download_name = data.geturl().split('/')[-1]
|
||||
|
||||
tar_download_path = os.path.join(headphones.PROG_DIR, download_name)
|
||||
|
||||
# Save tar to disk
|
||||
f = open(tar_download_path, 'wb')
|
||||
f.write(data.read())
|
||||
f.close()
|
||||
|
||||
# Extract the tar to update folder
|
||||
logger.info('Extracing file' + tar_download_path)
|
||||
tar = tarfile.open(tar_download_path)
|
||||
tar.extractall(update_dir)
|
||||
tar.close()
|
||||
|
||||
# Delete the tar.gz
|
||||
logger.info('Deleting file' + tar_download_path)
|
||||
os.remove(tar_download_path)
|
||||
|
||||
# Find update dir name
|
||||
update_dir_contents = [x for x in os.listdir(update_dir) if os.path.isdir(os.path.join(update_dir, x))]
|
||||
if len(update_dir_contents) != 1:
|
||||
logger.error(u"Invalid update data, update failed: "+str(update_dir_contents))
|
||||
return
|
||||
content_dir = os.path.join(update_dir, update_dir_contents[0])
|
||||
|
||||
# walk temp folder and move files to main folder
|
||||
for dirname, dirnames, filenames in os.walk(content_dir):
|
||||
dirname = dirname[len(content_dir)+1:]
|
||||
for curfile in filenames:
|
||||
old_path = os.path.join(content_dir, dirname, curfile)
|
||||
new_path = os.path.join(headphones.PROG_DIR, dirname, curfile)
|
||||
|
||||
if os.path.isfile(new_path):
|
||||
os.remove(new_path)
|
||||
os.renames(old_path, new_path)
|
||||
|
||||
# Update version.txt
|
||||
try:
|
||||
ver_file = open(version_path, 'w')
|
||||
ver_file.write(headphones.LATEST_VERSION)
|
||||
ver_file.close()
|
||||
except IOError, e:
|
||||
logger.error(u"Unable to write current version to version.txt, update not complete: "+ex(e))
|
||||
return
|
||||
elif headphones.INSTALL_TYPE == 'git':
|
||||
|
||||
output, err = runGit('pull origin ' + version.HEADPHONES_VERSION)
|
||||
|
||||
if not output:
|
||||
logger.error('Couldn\'t download latest version')
|
||||
|
||||
for line in output.split('\n'):
|
||||
|
||||
if 'Already up-to-date.' in line:
|
||||
logger.info('No update available, not updating')
|
||||
logger.info('Output: ' + str(output))
|
||||
elif line.endswith('Aborting.'):
|
||||
logger.error('Unable to update from git: '+line)
|
||||
logger.info('Output: ' + str(output))
|
||||
|
||||
else:
|
||||
|
||||
tar_download_url = 'https://github.com/%s/headphones/tarball/%s' % (user, branch)
|
||||
update_dir = os.path.join(headphones.PROG_DIR, 'update')
|
||||
version_path = os.path.join(headphones.PROG_DIR, 'version.txt')
|
||||
|
||||
try:
|
||||
logger.info('Downloading update from: '+tar_download_url)
|
||||
data = urllib2.urlopen(tar_download_url)
|
||||
except (IOError, URLError):
|
||||
logger.error("Unable to retrieve new version from "+tar_download_url+", can't update")
|
||||
return
|
||||
|
||||
download_name = data.geturl().split('/')[-1]
|
||||
|
||||
tar_download_path = os.path.join(headphones.PROG_DIR, download_name)
|
||||
|
||||
# Save tar to disk
|
||||
f = open(tar_download_path, 'wb')
|
||||
f.write(data.read())
|
||||
f.close()
|
||||
|
||||
# Extract the tar to update folder
|
||||
logger.info('Extracing file' + tar_download_path)
|
||||
tar = tarfile.open(tar_download_path)
|
||||
tar.extractall(update_dir)
|
||||
tar.close()
|
||||
|
||||
# Delete the tar.gz
|
||||
logger.info('Deleting file' + tar_download_path)
|
||||
os.remove(tar_download_path)
|
||||
|
||||
# Find update dir name
|
||||
update_dir_contents = [x for x in os.listdir(update_dir) if os.path.isdir(os.path.join(update_dir, x))]
|
||||
if len(update_dir_contents) != 1:
|
||||
logger.error(u"Invalid update data, update failed: "+str(update_dir_contents))
|
||||
return
|
||||
content_dir = os.path.join(update_dir, update_dir_contents[0])
|
||||
|
||||
# walk temp folder and move files to main folder
|
||||
for dirname, dirnames, filenames in os.walk(content_dir):
|
||||
dirname = dirname[len(content_dir)+1:]
|
||||
for curfile in filenames:
|
||||
old_path = os.path.join(content_dir, dirname, curfile)
|
||||
new_path = os.path.join(headphones.PROG_DIR, dirname, curfile)
|
||||
|
||||
if os.path.isfile(new_path):
|
||||
os.remove(new_path)
|
||||
os.renames(old_path, new_path)
|
||||
|
||||
# Update version.txt
|
||||
try:
|
||||
ver_file = open(version_path, 'w')
|
||||
ver_file.write(headphones.LATEST_VERSION)
|
||||
ver_file.close()
|
||||
except IOError, e:
|
||||
logger.error(u"Unable to write current version to version.txt, update not complete: "+ex(e))
|
||||
return
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,3 +1,18 @@
|
||||
# This file is part of Headphones.
|
||||
#
|
||||
# Headphones 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.
|
||||
#
|
||||
# Headphones 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 Headphones. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
@@ -10,16 +25,16 @@ from headphones.webserve import WebInterface
|
||||
def initialize(options={}):
|
||||
|
||||
|
||||
cherrypy.config.update({
|
||||
'log.screen': False,
|
||||
'server.thread_pool': 10,
|
||||
'server.socket_port': options['http_port'],
|
||||
'server.socket_host': options['http_host'],
|
||||
'engine.autoreload_on': False,
|
||||
})
|
||||
cherrypy.config.update({
|
||||
'log.screen': False,
|
||||
'server.thread_pool': 10,
|
||||
'server.socket_port': options['http_port'],
|
||||
'server.socket_host': options['http_host'],
|
||||
'engine.autoreload_on': False,
|
||||
})
|
||||
|
||||
conf = {
|
||||
'/': {
|
||||
conf = {
|
||||
'/': {
|
||||
'tools.staticdir.root': os.path.join(headphones.PROG_DIR, 'data')
|
||||
},
|
||||
'/interfaces':{
|
||||
@@ -39,32 +54,36 @@ def initialize(options={}):
|
||||
'tools.staticdir.dir': "js"
|
||||
},
|
||||
'/favicon.ico':{
|
||||
'tools.staticfile.on': True,
|
||||
'tools.staticfile.filename': "images/favicon.ico"
|
||||
'tools.staticfile.on': True,
|
||||
'tools.staticfile.filename': "images/favicon.ico"
|
||||
},
|
||||
'/cache':{
|
||||
'tools.staticdir.on': True,
|
||||
'tools.staticdir.dir': headphones.CACHE_DIR
|
||||
}
|
||||
}
|
||||
|
||||
if options['http_password'] != "":
|
||||
conf['/'].update({
|
||||
'tools.auth_basic.on': True,
|
||||
'tools.auth_basic.realm': 'Headphones',
|
||||
'tools.auth_basic.checkpassword': cherrypy.lib.auth_basic.checkpassword_dict(
|
||||
{options['http_username']:options['http_password']})
|
||||
})
|
||||
|
||||
if options['http_password'] != "":
|
||||
conf['/'].update({
|
||||
'tools.auth_basic.on': True,
|
||||
'tools.auth_basic.realm': 'Headphones',
|
||||
'tools.auth_basic.checkpassword': cherrypy.lib.auth_basic.checkpassword_dict(
|
||||
{options['http_username']:options['http_password']})
|
||||
})
|
||||
|
||||
|
||||
# Prevent time-outs
|
||||
cherrypy.engine.timeout_monitor.unsubscribe()
|
||||
|
||||
cherrypy.tree.mount(WebInterface(), options['http_root'], config = conf)
|
||||
|
||||
try:
|
||||
cherrypy.process.servers.check_port(options['http_host'], options['http_port'])
|
||||
cherrypy.server.start()
|
||||
except IOError:
|
||||
print 'Failed to start on port: %i. Is something else running?' % (options['http_port'])
|
||||
sys.exit(0)
|
||||
|
||||
cherrypy.server.wait()
|
||||
|
||||
|
||||
# Prevent time-outs
|
||||
cherrypy.engine.timeout_monitor.unsubscribe()
|
||||
|
||||
cherrypy.tree.mount(WebInterface(), options['http_root'], config = conf)
|
||||
|
||||
try:
|
||||
cherrypy.process.servers.check_port(options['http_host'], options['http_port'])
|
||||
cherrypy.server.start()
|
||||
except IOError:
|
||||
print 'Failed to start on port: %i. Is something else running?' % (options['http_port'])
|
||||
sys.exit(0)
|
||||
|
||||
cherrypy.server.wait()
|
||||
|
||||
|
||||
|
||||
66
init.fedora.centos.systemd
Normal file
66
init.fedora.centos.systemd
Normal file
@@ -0,0 +1,66 @@
|
||||
# Headphones - Automatic music downloader for SABnzbd
|
||||
#
|
||||
# Service Unit file for systemd system manager
|
||||
#
|
||||
# INSTALLATION NOTES
|
||||
#
|
||||
# 1. Rename this file as you want, ensuring that it ends in .service
|
||||
# e.g. 'headphones.service'
|
||||
#
|
||||
# 2. Adjust configuration settings as required. More details in the
|
||||
# "CONFIGURATION NOTES" section shown below.
|
||||
#
|
||||
# 3. Copy this file into your systemd service unit directory, which is
|
||||
# often '/lib/systemd/system'.
|
||||
#
|
||||
# 4. Create any files/directories that you specified back in step #2.
|
||||
# e.g. '/etc/headphones/headphones.ini'
|
||||
# '/home/sabnzbd/.headphones'
|
||||
#
|
||||
# 5. Enable boot-time autostart with the following commands:
|
||||
# systemctl daemon-reload
|
||||
# systemctl enable headphones.service
|
||||
#
|
||||
# 6. Start now with the following command:
|
||||
# systemctl start headphones.service
|
||||
#
|
||||
# 7. If troubleshooting startup-errors, start by checking permissions
|
||||
# and ownership on the files/directories that you created in step #4.
|
||||
#
|
||||
#
|
||||
# CONFIGURATION NOTES
|
||||
#
|
||||
# - The example settings in this file assume that:
|
||||
# 1. You will run Headphones as user/group: sabnzbd.sabnzbd
|
||||
# 2. You will either have Headphones installed as a subdirectory
|
||||
# under '~sabnzbd', or that you will have a symlink under
|
||||
# '~/sabnzbd' pointing to your Headphones install dir.
|
||||
# 3. Your Headphones data directory and configuration file will be
|
||||
# in separate locations from your Headphones install dir, to
|
||||
# simplify updates.
|
||||
#
|
||||
# - Option names (e.g. ExecStart=, Type=) appear to be case-sensitive)
|
||||
#
|
||||
# - Adjust ExecStart= to point to:
|
||||
# 1. Your Headphones executable,
|
||||
# 2. Your config file (recommended is to put it somewhere in /etc)
|
||||
# 3. Your datadir (recommended is to NOT put it in your Headphones exec dir)
|
||||
#
|
||||
# - Adjust User= and Group= to the user/group you want Headphones to run as.
|
||||
#
|
||||
# - WantedBy= specifies which target (i.e. runlevel) to start Headphones for.
|
||||
# multi-user.target equates to runlevel 3 (multi-user text mode)
|
||||
# graphical.target equates to runlevel 5 (multi-user X11 graphical mode)
|
||||
|
||||
[Unit]
|
||||
Description=Headphones - Automatic music downloader for SABnzbd
|
||||
|
||||
[Service]
|
||||
ExecStart=/home/sabnzbd/headphones/Headphones.py --daemon --config /etc/headphones/headphones.ini --datadir /home/sabnzbd/.headphones --nolaunch --quiet
|
||||
GuessMainPID=no
|
||||
Type=forking
|
||||
User=sabnzbd
|
||||
Group=sabnzbd
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
131
lib/bencode.py
Normal file
131
lib/bencode.py
Normal file
@@ -0,0 +1,131 @@
|
||||
# Got this from here: https://gist.github.com/1126793
|
||||
|
||||
# The contents of this file are subject to the Python Software Foundation
|
||||
# License Version 2.3 (the License). You may not copy or use this file, in
|
||||
# either source code or executable form, except in compliance with the License.
|
||||
# You may obtain a copy of the License at http://www.python.org/license.
|
||||
#
|
||||
# Software distributed under the License is distributed on an AS IS basis,
|
||||
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
|
||||
# for the specific language governing rights and limitations under the
|
||||
# License.
|
||||
|
||||
# Written by Petru Paler
|
||||
|
||||
# Minor modifications made by Andrew Resch to replace the BTFailure errors with Exceptions
|
||||
|
||||
def decode_int(x, f):
|
||||
f += 1
|
||||
newf = x.index('e', f)
|
||||
n = int(x[f:newf])
|
||||
if x[f] == '-':
|
||||
if x[f + 1] == '0':
|
||||
raise ValueError
|
||||
elif x[f] == '0' and newf != f+1:
|
||||
raise ValueError
|
||||
return (n, newf+1)
|
||||
|
||||
def decode_string(x, f):
|
||||
colon = x.index(':', f)
|
||||
n = int(x[f:colon])
|
||||
if x[f] == '0' and colon != f+1:
|
||||
raise ValueError
|
||||
colon += 1
|
||||
return (x[colon:colon+n], colon+n)
|
||||
|
||||
def decode_list(x, f):
|
||||
r, f = [], f+1
|
||||
while x[f] != 'e':
|
||||
v, f = decode_func[x[f]](x, f)
|
||||
r.append(v)
|
||||
return (r, f + 1)
|
||||
|
||||
def decode_dict(x, f):
|
||||
r, f = {}, f+1
|
||||
while x[f] != 'e':
|
||||
k, f = decode_string(x, f)
|
||||
r[k], f = decode_func[x[f]](x, f)
|
||||
return (r, f + 1)
|
||||
|
||||
decode_func = {}
|
||||
decode_func['l'] = decode_list
|
||||
decode_func['d'] = decode_dict
|
||||
decode_func['i'] = decode_int
|
||||
decode_func['0'] = decode_string
|
||||
decode_func['1'] = decode_string
|
||||
decode_func['2'] = decode_string
|
||||
decode_func['3'] = decode_string
|
||||
decode_func['4'] = decode_string
|
||||
decode_func['5'] = decode_string
|
||||
decode_func['6'] = decode_string
|
||||
decode_func['7'] = decode_string
|
||||
decode_func['8'] = decode_string
|
||||
decode_func['9'] = decode_string
|
||||
|
||||
def bdecode(x):
|
||||
try:
|
||||
r, l = decode_func[x[0]](x, 0)
|
||||
except (IndexError, KeyError, ValueError):
|
||||
raise Exception("not a valid bencoded string")
|
||||
|
||||
return r
|
||||
|
||||
from types import StringType, IntType, LongType, DictType, ListType, TupleType
|
||||
|
||||
|
||||
class Bencached(object):
|
||||
|
||||
__slots__ = ['bencoded']
|
||||
|
||||
def __init__(self, s):
|
||||
self.bencoded = s
|
||||
|
||||
def encode_bencached(x,r):
|
||||
r.append(x.bencoded)
|
||||
|
||||
def encode_int(x, r):
|
||||
r.extend(('i', str(x), 'e'))
|
||||
|
||||
def encode_bool(x, r):
|
||||
if x:
|
||||
encode_int(1, r)
|
||||
else:
|
||||
encode_int(0, r)
|
||||
|
||||
def encode_string(x, r):
|
||||
r.extend((str(len(x)), ':', x))
|
||||
|
||||
def encode_list(x, r):
|
||||
r.append('l')
|
||||
for i in x:
|
||||
encode_func[type(i)](i, r)
|
||||
r.append('e')
|
||||
|
||||
def encode_dict(x,r):
|
||||
r.append('d')
|
||||
ilist = x.items()
|
||||
ilist.sort()
|
||||
for k, v in ilist:
|
||||
r.extend((str(len(k)), ':', k))
|
||||
encode_func[type(v)](v, r)
|
||||
r.append('e')
|
||||
|
||||
encode_func = {}
|
||||
encode_func[Bencached] = encode_bencached
|
||||
encode_func[IntType] = encode_int
|
||||
encode_func[LongType] = encode_int
|
||||
encode_func[StringType] = encode_string
|
||||
encode_func[ListType] = encode_list
|
||||
encode_func[TupleType] = encode_list
|
||||
encode_func[DictType] = encode_dict
|
||||
|
||||
try:
|
||||
from types import BooleanType
|
||||
encode_func[BooleanType] = encode_bool
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
def bencode(x):
|
||||
r = []
|
||||
encode_func[type(x)](x, r)
|
||||
return ''.join(r)
|
||||
Reference in New Issue
Block a user