GithubHelp home page GithubHelp logo

fuzeman / trakt.py Goto Github PK

View Code? Open in Web Editor NEW
149.0 17.0 34.0 1.08 MB

Python interface for the Trakt.tv API

Home Page: http://traktpy.readthedocs.org

License: MIT License

Python 100.00%
python trakt api-client

trakt.py's Introduction

trakt.py

image

image

image

image

Python interface for the Trakt.tv API.

Install

pip install trakt.py

Examples

Configure the client

from trakt import Trakt


Trakt.configuration.defaults.client(
    id='<client-id>',
    secret='<client-secret>'
)

Scrobble an episode

show = {
    'title': 'Community',
    'year': 2009
}

episode = {
    'season': 5,
    'number': 13
}

# Send "start" event
Trakt['scrobble'].start(
    show=show,
    episode=episode,

    progress=1
)

# [...] (watching episode)

# Send "stop" event (scrobble)
Trakt['scrobble'].stop(
    show=show,
    episode=episode,

    progress=93
)

Add a movie to your collection

Trakt['sync/collection'].add({
    'movies': [
        {
            'title': "Twelve Monkeys",
            'year': 1995,

            'ids': {
                'imdb': "tt0114746"
            }
        }
    ]
})

Retrieve shows that a user has watched

# `watched` = {<key>: <Show>} dictionary
watched = Trakt['sync/watched'].movies()

for key, show in watched.items():
    print '%s (%s)' % (show.title, show.year)

License

The MIT License (MIT)

Copyright (c) 2014 Dean Gardiner

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

trakt.py's People

Contributors

fuzeman avatar jannon avatar lalitmaganti avatar lhuriguen avatar meisnate12 avatar mza921 avatar omaralvarez avatar razzeee avatar ruinernin avatar shad7 avatar sharkykh avatar snagytx avatar stevenvdschoot avatar

Stargazers

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

Watchers

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

trakt.py's Issues

transparent trakt call

could you add a possibility for transparent trakt calls for functions that are not supported?
e.g. collection=Trakt['shows/'+showID+'/progress/collection']

maybe it is already possible but your interface-machine is too complicated for me to understand properly! :-/

Exception not caught

I'm trying to auth and haven't set exceptions to true.
When I'm offline and try to auth I still get an error:

00:43:26 T:3964   ERROR: EXCEPTION Thrown (PythonToCppException) : -->Python callback/script returned the following error<--
                                             - NOTE: IGNORING THIS CAN LEAD TO MEMORY LEAKS!
                                            Error Type: <class 'requests.exceptions.ConnectionError'>
                                            Error Contents: ('Connection aborted.', gaierror(11001, 'getaddrinfo failed'))
                                            Traceback (most recent call last):
                                              File "C:\Users\razze\AppData\Roaming\Kodi\addons\script.trakt\default.py", line 15, in <module>
                                                traktService().run()
                                              File "C:\Users\razze\AppData\Roaming\Kodi\addons\script.trakt\service.py", line 104, in run
                                                globals.traktapi = traktAPI()
                                              File "C:\Users\razze\AppData\Roaming\Kodi\addons\script.trakt\traktapi.py", line 35, in __init__
                                                self.getToken()
                                              File "C:\Users\razze\AppData\Roaming\Kodi\addons\script.trakt\traktapi.py", line 60, in getToken
                                                auth = Trakt['auth'].login(getSetting('username'), getSetting('password'))
                                              File "C:\Users\razze\AppData\Roaming\Kodi\addons\script.trakt\trakt\interfaces\auth.py", line 10, in login
                                                'password': password
                                              File "C:\Users\razze\AppData\Roaming\Kodi\addons\script.trakt\trakt\core\http.py", line 89, in post
                                                return self.request('POST', path, params, data, **kwargs)
                                              File "C:\Users\razze\AppData\Roaming\Kodi\addons\script.trakt\trakt\core\http.py", line 66, in request
                                                response = self.session.send(prepared, timeout=timeout)
                                              File "C:\Users\razze\AppData\Roaming\Kodi\addons\script.module.requests\lib\requests\sessions.py", line 569, in send
                                                r = adapter.send(request, **kwargs)
                                              File "C:\Users\razze\AppData\Roaming\Kodi\addons\script.module.requests\lib\requests\adapters.py", line 407, in send
                                                raise ConnectionError(err, request=request)
                                            ConnectionError: ('Connection aborted.', gaierror(11001, 'getaddrinfo failed'))
                                            -->End of Python script error report<--

Implement users/id/watchlist and users/id/collection

It would be fine, if there will be implemented more methods from /users/ API. I am not sure, if every endpoint should have its own issue, or it is possible to merge them into one issue. I would like to replace my custom trakt library with trakt.py and I am still missing some functions:

users/*/watchlist - now there is only sync/watchlist that is for authenticated users only. It will be fine if anyone (friends&following) will be able to see watch on my/their watchlist

more useful methods: users//collection, users//watched, users//history, users//ratings

Not working

from trakt import Trakt
Traceback (most recent call last):
File "", line 1, in
File "build/bdist.linux-x86_64/egg/trakt/init.py", line 1, in
File "build/bdist.linux-x86_64/egg/trakt/client.py", line 1, in
ImportError: No module named core.configuration

Grabbing error codes?

Hey everybody,

is there a way we can get the error from the library? As far as I've seen it only adds it to the logfile, no luck with try etc.

Cheers

Show watched progression

Hi,

First, love your work.
The implementation is really easy to use, and the code in itself is very neat ! :)

Would it be possible to implement, in the show interface, the functionnality to get the watched progress ?

The function in itself wouldn't be difficult to code, I think, the part I'm not confortable with is the description of the object.
Now there isn't any object usable for this that I've found.
The response object of the API look like the seasons object in your code, but not quite it...

Wrong logging of errors

I'm getting errors in the logfile which should not be errors

17:44:20 T:5692   ERROR: [script.trakt] "POST /scrobble/stop HTTP/1.1" 201 None

Might be happening for all Success states other than 200?

Special Season episodes

  File "/home/vagrant/tvrenamer/.tox/cover34/lib/python3.4/site-packages/trakt/interfaces/shows/__init__.py", line 56, in episode
    self.get_data(response, **kwargs)
  File "/home/vagrant/tvrenamer/.tox/cover34/lib/python3.4/site-packages/trakt/mapper/summary.py", line 120, in episode
    pk, keys = cls.get_ids('episode', i_episode)
  File "/home/vagrant/tvrenamer/.tox/cover34/lib/python3.4/site-packages/trakt/mapper/core/base.py", line 63, in get_ids
    item.get('season') or parent.pk,
AttributeError: 'NoneType' object has no attribute 'pk'

The existing code:

        if media == 'episode':
            keys.insert(0, (
                item.get('season') or parent.pk,
                item.get('number')
            ))

The value returned from item.get('season') is 0, but parent is None.

ReadTimeout Error

from trakt import Trakt
/usr/local/lib/python2.7/dist-packages/arrow/arrow.py:28: DeprecationWarning: Arrow will drop support for Python 2.7 and 3.5 in the upcoming v1.0.0 release. Please upgrade to Python 3.6+ to continue receiving updates for Arrow.
DeprecationWarning,
Traceback (most recent call last):
File "", line 1, in
File "/usr/local/lib/python2.7/dist-packages/trakt/init.py", line 3, in
from trakt.client import TraktClient
File "/usr/local/lib/python2.7/dist-packages/trakt/client.py", line 5, in
from trakt.core.http import HttpClient
File "/usr/local/lib/python2.7/dist-packages/trakt/core/http.py", line 13, in
from requests.packages.urllib3.exceptions import ReadTimeoutError
ImportError: cannot import name ReadTimeoutError

What am I missing here???

thanks!!

More list/watchlist methods

So there is an watchlist method, but nothing to add to it?
Also what about getting all custom lists and getting the items of them?

Extended Info in watchlists

Hey,

I can't seem to find a way to get extended information from Trakt['sync/watchlist'].movies(extended='full').
On Trakt.tv's API 'Get watchlist' is said to have the extended info option.

http://docs.trakt.apiary.io/reference/sync/get-watchlist/get-watchlist

It also states that you can have the API sort the items for you, then send them to you, but I can't seem find the way to do that in trakt.py.
It appears the API doesn't handle that (tried testing using Apiary)
Posted in the Trakt API G+ community

Sorting for watchlist isn't an option, I misread the API docs, see https://plus.google.com/u/0/106638395660757564216/posts/THrT7croDVQ

Am I missing something here, or is it just not implemented?

Traceback (most recent call last):
  File "C:\Project\.venv\lib\site-packages\tornado\web.py", line 1509, in _execute
    result = method(*self.path_args, **self.path_kwargs)
  File "main.py", line 102, in get
    return dispatcher()
  File "main.py", line 125, in watchlist
    watchlist = TraktAPI.get_movies_watchlist()
  File "C:\Project\trakt_api.py", line 57, in get_movies_watchlist
    watchlist = Trakt['sync/watchlist'].movies(extended='full', pagination=True, per_page=100)
  File "C:\Project\.venv\lib\site-packages\trakt\interfaces\base\__init__.py", line 22, in wrap
    return func(*args, **kwargs)
  File "C:\Project\.venv\lib\site-packages\trakt\interfaces\sync\core\mixins.py", line 61, in movies
    **kwargs
  File "C:\Project\.venv\lib\site-packages\trakt\interfaces\sync\watchlist.py", line 26, in get
    **kwargs
  File "C:\Project\.venv\lib\site-packages\trakt\interfaces\base\__init__.py", line 22, in wrap
    return func(*args, **kwargs)
  File "C:\Project\.venv\lib\site-packages\trakt\interfaces\sync\core\mixins.py", line 32, in get
    items = self.get_data(response, **kwargs)
TypeError: get_data() got an unexpected keyword argument 'extended'

Documentation missing some big points

Hey there,

seems to me like there are some calls missing from documentation, can't firgure out how to get a movie or show by id.
Rating examples would be apreciated too.

Thanks

oAuth must be provided

So I'm not using oAuth for kodi, but I get these messages in the log file here and there.

19:38:56 T:11220   DEBUG: [script.trakt] requests.packages.urllib3.connectionpool: "POST /scrobble/start HTTP/1.1" 520 None
19:38:56 T:11220 WARNING: [script.trakt] trakt.core.http: Continue retry since status is 520, waiting 5 seconds
19:39:01 T:11220 WARNING: [script.trakt] trakt.core.http: Retry # 1
19:39:01 T:11220   DEBUG: [script.trakt] requests.packages.urllib3.connectionpool: "POST /scrobble/start HTTP/1.1" 401 None
19:39:01 T:11220   DEBUG: [script.trakt] trakt.interfaces.base: response returned content-type: 'text/html', falling back to raw data
19:39:01 T:11220 WARNING: [script.trakt] trakt.interfaces.base: request failed: Unauthorized - "OAuth must be provided" (code: 401)

Documentation Improvements

  • Simplify API navigation in the documentation site
  • Write documentation for objects
  • Write documentation for interfaces
  • Write documentation for other modules
  • Write quickstart guide, with basic library overview

to_info is not creating valid json

The dates seem to be datetime objects, would be nice if these could be strings.

Here is an example:

            {
                'plays': None,
                'collected_at': datetime.datetime(2014,
                5,
                18,
                23,
                12,
                10),
                'collected': 1,
                'watched': 0,
                'number': 19,
                'ids': {

                }
            },

Rate limiting

FYI, just got the following email from Trakt

As of October 27, 2020, we’re enforcing rate limiting for all API apps. You’ve created a Trakt API app, and we wanted to let you know directly. If you have any questions, please continue the discussion in the GitHub API project.

WHY ARE RATE LIMITS BEING ENFORCED?
Over the past several months, Trakt performance has been negatively impacted by a huge increase in API traffic and poorly coded apps. In order to stabilize the API and increase performance for everyone, we’re turning on rate limiting. The Trakt API is free to use, and rate limiting will help us keep it that way.

WHAT UPDATES DOES MY APP NEED?
Your app will need to handle the 429 HTTP status code and headers that are sent when the rate limit is exceeded. This might be built into your API library, or you might need to customize your code to handle it. The API docs have more details.

WHAT ARE THE LIMITS?
/sync/history/* 2 calls every second
All API methods 1,000 calls every 5 minutes

All limits are per user.

MOVING FORWARD
We plan on adjusting limits until we find a balance of good performance with minimal app impact. The goal is to prevent API abuse, but allow users to use apps normally. We’ll keep the API docs updated with the current rate limits.
If you have any questions, please continue the discussion in the GitHub API project.

It would be awesome if this client helped throttle API calls when a 429 response is received

Continue previous session

Hello,

Is it possible to continue from a previously authorized session?

I'm currently doing an oauth authentication, but I can't really figure out how I would save and reuse the token the next time I run my script so I don't have to go through the whole auth process again.

Is this even possible with this library?

How do I add an episode/movie to history with `watched_at='released'`?

I'm struggling to decipher how to use this library from the API docs.

I had to dig into the examples module just to find out how to authenticate, and copy/paste the examples.helpers.authenticate function somewhere locally to do it. Not sure why this helper isn't included in the main package, and mentioned in the README which only configures the client?

But that's a side issue. Now that I'm authenticated, I'm looking for a way to "add" a "play" to my trakt history, specifically with watched_at='released'. I don't see any examples for Trakt['sync/history'].add() in the examples package.

After getting an episode that I want to add (as e), I tried the following:

In [25]: Trakt['sync/history'].add({'shows': [{'ids': {'trakt': e.id}}]})                                                                                   
Out[25]: 
{'added': {'movies': 0, 'episodes': 0},
 'not_found': {'movies': [],
  'shows': [{'ids': {'trakt': 5885625430}}],
  'seasons': [],
  'episodes': [],
  'people': []}}

It says zero episodes added. So I tried:

In [31]: Trakt['sync/history'].add({'shows': [e.to_dict()]})                                                                                                
Out[31]: 
{'added': {'movies': 0, 'episodes': 24},
 'not_found': {'movies': [],
  'shows': [],
  'seasons': [],
  'episodes': [],
  'people': []}}

This says 24 epsodes added, but no corresponding play for the single episode I tried to add is showing up at trakt.tv.

Ideally, what I want to do is loop over my existing history and replace all duplicate and non-release plays with a single play at release.

Thanks.

Add id lookup to library

I'm still using multiple custom calls outside of trakt.py to make my script work. Would be nice to get them over to the new one.
It starts here https://github.com/Razzeee/script.trakt/blob/dev/traktapi.py#L361

TypeError: argument of type 'NoneType' is not iterable

  File "/home/vagrant/tvrenamer/.tox/cover34/lib/python3.4/site-packages/trakt/interfaces/shows/__init__.py", line 56, in episode
    self.get_data(response)
  File "/home/vagrant/tvrenamer/.tox/cover34/lib/python3.4/site-packages/trakt/mapper/summary.py", line 101, in episode
    if 'episode' in item:
TypeError: argument of type 'NoneType' is not iterable
requests.packages.urllib3.connectionpool: DEBUG: "GET /search?query=Firefly&type=show HTTP/1.1" 200 None
requests.packages.urllib3.connectionpool: DEBUG: "GET /shows/1428/seasons/5/episodes/1 HTTP/1.1" 404 None
trakt.interfaces.base: DEBUG: response returned content-type: 'text/html', falling back to raw data
trakt.interfaces.base: WARNING: request failed: Not Found - "method exists, but no record found" (code: 404)

Because the status code is 404, and exceptions are turned off it seems, it will return None

        # Return `None` if we encountered an error, return response data
        if error:
            return None
    @classmethod
    def episode(cls, client, item, **kwargs):
        if 'episode' in item:
            i_episode = item['episode']
        else:
            i_episode = item

Because the check for the string episode in item, and because it is None, the TypeError is being raised.

Watchlist get all

it appears to me that watchlist unlike watched & collection has paging
watchlist = Trakt['sync/watchlist'].movies()

is there a way to get all watchlist items without paging?

Insecure platform warning

Any chance, to get this fixed? Or do I need to do something to the requests package?

22:47:12 T:11192 ERROR: C:\Users\razze\AppData\Roaming\Kodi\addons\script.module.requests\lib\requests\packages\urllib3\util\ssl_.py:79: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.

"Images" is None when using extended=full

Been testing out trakt.py and came across this scenario.

Trakt.configuration.defaults.app(id="xxxx")
Trakt.configuration.defaults.client(
    id="xxxx",
    secret="xxxx",
)

for show in Trakt["movies"].trending(extended="full"):
    pprint(vars(show))

Seems like images is always populated with None on this endpoint. Is this expected?

Implement friends and following for users

It is possible to retrieve the friends and following of a give user? The methods from trakt API: /users/id/friends /users/id/following

I would like to implement list of friends I follow to be able to see their lists and watched history.

Thanks

Implement lists/trending and lists/popular

Hello, thanks for merging and improving my previous commits.

I almost forgot about these useful methods that I used in my kodi plugin - to allow user to browse through trending and popular lists.

The usage sholud be like
Trakt['lists'].popular()
Trakt['lists'].trending()

I tried to implement it, but I cannot figure out, how to attach user to List object, because I lost in some circular import of UserMapper in List class.

Another issue with List is that interface Users
Trakt['users'].likes('lists') is returning CustomLists, but lists in users/*/like are "public" lists. The returned CustomList contains only "username" field but to retrieve the lists it is necessary to use users's slug id and also List id/slug. And I think it is not a good idea to have .add delete methods on lists that do not belong to the current authenticated user. And actions like likelist or unlike should be available on List rather than CusomList.

Thanks

Issues with Trakt

Can't seem to figured out what's going on, has put me through hell and back trying to work out what the issues are, had to delete me entire data base and start fresh thinking it would fix it but still having issues.

Can't get the addon to work at the end of any show or movie, won't let me rate an item, will only pop up and allow Kodi to mark as watched when going to the very end of the file.

Talked with Razee and he believes the issue is with this side of things. Is there something going on with the plugin right now ??

Check if we can default to TLS 1.2

Had a user report this:

trakt/script.trakt#333 (comment)

Seems that's a certificate issue.
I fix it changing your 3.1.8 version file "~/.kodi/addons/script.module.trakt/lib/trakt/core/http.py"
The actual line:

        self.session.mount('https://', HTTPSAdapter(ssl_version=ssl.PROTOCOL_TLSv1, **self.adapter_kwargs))

by this one:

        self.session.mount('https://', HTTPSAdapter(ssl_version=ssl.PROTOCOL_TLSv1_2, **self.adapter_kwargs))

And works. Certificate on the autorization page acepts TLS v 1.2 and fails (at least for me) with TLS v 1.0

Feel free to double check it and add it to yor version if you like.

Regards

watched attribute always None in Episode

Hi,

I want to know if a given episode has already been watched. Even with extended='full', the Episode.is_watched is always None or 0 (but I can confirm that the episode is marked as watched in the trakt web interface).

I tried with both Trakt['search'].lookup(trakt_id, service='trakt', extended='full') and Trakt['shows'].episode(slug, seasonnumber, episodenumber, extended='full')

Am I doing something wrong there ?

thanks

New API Methods

Hey fuzeman, do you mind adding the methods named here to your module? They are needed for the official kodi trakt addon to make manual ratings to work. For more info see my comment in the script.trakt repository: trakt/script.trakt#183 (comment)

Installation error

$ pip --no-cache-dir install 'trakt.py>=2.5.0'
Collecting trakt.py>=2.5.0
  Downloading trakt.py-2.5.0.zip (51kB)
    100% |████████████████████████████████| 53kB 1.2MB/s
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 20, in <module>
      File "/tmp/pip-build-0BRffG/trakt.py/setup.py", line 1, in <module>
        from trakt import __version__
      File "trakt/__init__.py", line 3, in <module>
        from trakt.client import TraktClient, __version__
      File "trakt/client.py", line 1, in <module>
        from trakt.core.configuration import ConfigurationManager
      File "trakt/core/configuration.py", line 1, in <module>
        from trakt.core.context_collection import ContextCollection
      File "trakt/core/context_collection.py", line 4, in <module>
        from six.moves import _thread as thread
    ImportError: No module named six.moves

When using a virtualenv or an environment that does not already include the required libraries will fail because setup.py has to import trakt which will fail to find the dependency.

Recommend Projects

  • React photo React

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

  • Vue.js photo Vue.js

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

  • Typescript photo Typescript

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

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

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

Recommend Topics

  • javascript

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

  • web

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

  • server

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

  • Machine learning

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

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

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

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.