The branch, frodo has been updated
       via  eeb18bd7c548469d56417c8a57c682b524e5a829 (commit)
      from  f722b6820d2b2d81f6291cb7bc4a3bac5e2054a5 (commit)

- Log -----------------------------------------------------------------
http://xbmc.git.sourceforge.net/git/gitweb.cgi?p=xbmc/scripts;a=commit;h=eeb18bd7c548469d56417c8a57c682b524e5a829

commit eeb18bd7c548469d56417c8a57c682b524e5a829
Author: Martijn Kaijser <[email protected]>
Date:   Mon Feb 11 19:58:05 2013 +0100

    [script.trakt] 2.0.0

diff --git a/script.trakt/.gitignore b/script.trakt/.gitignore
index 6eaf661..bdeffb2 100644
--- a/script.trakt/.gitignore
+++ b/script.trakt/.gitignore
@@ -1,3 +1,4 @@
 *.pyc
 *.pyo
 .DS*
+.pylint_rc
diff --git a/script.trakt/README.md b/script.trakt/README.md
index 831ccb3..b70a87c 100644
--- a/script.trakt/README.md
+++ b/script.trakt/README.md
@@ -1,17 +1,27 @@
-trakt.tv TV and movie scrobbler for XBMC Eden
-=============================================
+trakt.tv TV and movie scrobbler for XBMC Frodo
+==============================================
 
-Automatically scrobble all TV episodes and movies you are watching to 
trakt.tv! Keep a comprehensive history of everything you've watched and be part 
of a global community of TV and movie enthusiasts. Sign up for a free account 
at http://trakt.tv and get a ton of features including:
+###What is trakt?
 
-* automatically scrobble what you're watching
-* [mobile apps](http://trakt.tv/downloads) for iPhone, iPad, Android, Windows 
Phone, Blackberry, and Symbian
-* share what you're watching (in real time) and rating to facebook, twitter, 
and tumblr
-* use watchlists so you don't forget to what to watch
-* track your media collections and impress your friends
-* create custom [lists](http://trakt.tv/lists) around any topics you choose
-* easily track your TV show progress across all seasons and episodes
-* track your progress against industry lists such as the [IMDb Top 
250](http://trakt.tv/lists/imdb/top-250)
-* discover new shows and movies based on your viewing habits
+Automatically scrobble all TV episodes and movies you are watching to 
trakt.tv! Keep a comprehensive history of everything you've watched and be part 
of a global community of TV and movie enthusiasts. Sign up for a free account 
at [trakt.tv](http://trakt.tv) and get a ton of features:
+
+* Automatically scrobble what you're watching
+* [Mobile apps](http://trakt.tv/downloads) for iPhone, iPad, Android, and 
Windows Phone
+* Share what you're watching (in real time) and rating to facebook, twitter, 
and tumblr
+* Follow your friends and people you're interesed in
+* Use watchlists so you don't forget to what to watch
+* Track your media collections and impress your friends
+* Create custom [lists](http://trakt.tv/lists) around any topics you choose
+* Easily track your TV show progress across all seasons and episodes
+* Track your progress against industry lists such as the [IMDb Top 
250](http://trakt.tv/lists/imdb/top-250)
+* Discover new shows and movies based on your viewing habits
+
+###What can this addon do?
+
+* Automatically scrobble all TV episodes and movies you are watching 
+* Sync your TV episode and movie collections to trakt
+* Auto clean your trakt collection so that it matches up with XBMC
+* Keep watched statuses synced between XBMC and trakt
 
 ###What can be scrobbled?
 
@@ -39,4 +49,4 @@ Remote streaming content will scrobble assuming the metadata 
is correctly set in
 
 ###Thanks
 
-Special thanks to the [trakt 
utilities](https://github.com/Manromen/script.traktutilities) team! This plugin 
is essentially their code with some additions.
\ No newline at end of file
+Special thanks to all who contribute to this plugin! Check the commit history 
and changelog to see these talented developers.
\ No newline at end of file
diff --git a/script.trakt/addon.xml b/script.trakt/addon.xml
index 675d798..9c078e3 100644
--- a/script.trakt/addon.xml
+++ b/script.trakt/addon.xml
@@ -1,28 +1,38 @@
 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<addon id="script.trakt" name="trakt" version="1.0.1" provider-name="trakt.tv">
+<addon id="script.trakt" name="trakt" version="2.0.0" provider-name="trakt.tv">
        <requires>
-               <import addon="xbmc.python" version="2.0"/>
+               <import addon="xbmc.python" version="2.1.0"/>
                <import addon="script.module.simplejson" version="2.0.10"/>
-               <import addon="script.module.myconnpy" version="0.3.2"/>
        </requires>
        <res width="1280" height="720" aspect="16x9" default="true" 
folder="720p" />
-       <extension point="xbmc.service" name="trakt.service" 
library="service.py"/>
+       <extension point="xbmc.service" name="trakt.service" 
library="service.py" start="login" />
+       <extension point="xbmc.python.script" library="sync_exec.py">
+               <provides>executable</provides>
+       </extension>
        <extension point="xbmc.addon.metadata" name="trakt.metadata">
                <language></language>
                <summary lang="en">TV and movie scrobbler for trakt.tv</summary>
-               <description lang="en">Automatically scrobble all TV episodes 
and movies you are watching to trakt.tv! Keep a comprehensive history of 
everything you've watched and be part of a global community of TV and movie 
enthusiasts. Sign up for a free account at http://trakt.tv and get a ton of 
features including:
+               <description lang="en">Automatically scrobble all TV episodes 
and movies you are watching to trakt.tv! Keep a comprehensive history of 
everything you've watched and be part of a global community of TV and movie 
enthusiasts. Sign up for a free account at http://trakt.tv and get a ton of 
features:
+
+- Automatically scrobble what you're watching
+- Mobile apps for iPhone, iPad, Android, and Windows Phone
+- Follow your friends and people you're interesed in
+- Share what you're watching (in real time) and rating to facebook, twitter, 
and tumblr
+- Use watchlists so you don't forget to what to watch
+- Track your media collections and impress your friends
+- Create custom lists around any topics you choose
+- Easily track your TV show progress across all seasons and episodes
+- Track your progress against industry lists such as the IMDb Top 250
+- Discover new shows and movies based on your viewing habits
+
+What can this addon do?
 
-- automatically scrobble what you're watching
-- mobile apps for iPhone, iPad, Android, Windows Phone, Blackberry, and Symbian
-- share what you're watching (in real time) and rating to facebook, twitter, 
and tumblr
-- use watchlists so you don't forget to what to watch
-- track your media collections and impress your friends
-- create custom lists around any topics you choose
-- easily track your TV show progress across all seasons and episodes
-- track your progress against industry lists such as the IMDb Top 250
-- discover new shows and movies based on your viewing habits
+- Automatically scrobble all TV episodes and movies you are watching 
+- Sync your TV episode and movie collections to trakt
+- Auto clean your trakt collection so that it matches up with XBMC
+- Keep watched statuses synced between XBMC and trakt
 
-Special thanks to the trakt utilities team! This plugin is essentially their 
code with a few additions.</description>
+Special thanks to all who contributed to this plugin! Check the commit history 
and changelog to see these talented developers.</description>
                <platform>all</platform>
        </extension>
 </addon>
\ No newline at end of file
diff --git a/script.trakt/changelog.txt b/script.trakt/changelog.txt
index e4eb23a..1abaafe 100644
--- a/script.trakt/changelog.txt
+++ b/script.trakt/changelog.txt
@@ -1,5 +1,16 @@
+version 2.0.0
+  - compatible with Frodo RC3
+  - supports absolute and dvd ordering (mizaki)
+  - sync your TV episode and movie collections to trakt (N3MIS15)
+  - auto clean your trakt collection so that it matches up with XBMC (N3MIS15)
+  - keep watched statuses synced between XBMC and trakt (N3MIS15)
+  - retry the telnet connection to prevent timeouts (sschocke)
+  - fixed authentication issue for incorrect username/password
+  - default to HTTPS on
+  - retry failed API calls (nate1280)
+
 version 1.0.1
-  - code optimization (thanks seadog!)
+  - code optimization (seadog)
   - use tvdb_id for much improved matching and international support
   - hide error notifications during playback
 
@@ -7,4 +18,4 @@ version 1.0.0
   - initial release
   - tv episode and movie scrobbling
   - works with local files and remote streams with correct metadata
-  - tested with XBMC library mode, PleXBMC, Amazon, CBS
\ No newline at end of file
+  - tested with XBMC library mode, PleXBMC, Amazon, CBS
diff --git a/script.trakt/nbconnection.py b/script.trakt/nbconnection.py
index f713f31..ef3d71e 100644
--- a/script.trakt/nbconnection.py
+++ b/script.trakt/nbconnection.py
@@ -20,6 +20,7 @@ class NBConnection():
                self.response = None
                self.responseLock = threading.Lock()
                self.closing = False
+               self.readError = False
 
        def request(self, method, url, body=None, headers={}):
                self.rawConnection.request(method, url, body, headers)
@@ -41,7 +42,15 @@ class NBConnection():
                thread.start_new_thread(NBConnection._run, (self,))
 
        def _run(self):
-               self.response = self.rawConnection.getresponse()
+               print "[trakt] [nbconnection] getresponse start"
+               try:
+                       self.response = self.rawConnection.getresponse()
+               except:
+                       print "[trakt] [nbconnection] Exception"
+                       self.readError = True
+                       self.close()
+               else:
+                       print "[trakt] [nbconnection] response received: " + 
str(self.response.status) + " " + self.response.reason
                self.responseLock.release()
 
        def close(self):
diff --git a/script.trakt/notification_service.py 
b/script.trakt/notification_service.py
index b95e118..339aedc 100644
--- a/script.trakt/notification_service.py
+++ b/script.trakt/notification_service.py
@@ -4,12 +4,16 @@
 import xbmc
 import telnetlib
 import socket
+import time
 
 import simplejson as json
 
 import threading
 from utilities import Debug
 from scrobbler import Scrobbler
+from movie_sync import SyncMovies
+from episode_sync import SyncEpisodes
+from sync_exec import do_sync
 
 class NotificationService(threading.Thread):
        """ Receives XBMC notifications and passes them off as needed """
@@ -34,6 +38,13 @@ class NotificationService(threading.Thread):
                                
self._scrobbler.playbackStarted(notification['params']['data'])
                elif notification['method'] == 'Player.OnPause':
                        self._scrobbler.playbackPaused()
+               elif notification['method'] == 'VideoLibrary.OnScanFinished':
+                       if do_sync('movies'):
+                               movies = SyncMovies(show_progress=False)
+                               movies.Run()
+                       if do_sync('episodes'):
+                               episodes = SyncEpisodes(show_progress=False)
+                               episodes.Run()
                elif notification['method'] == 'System.OnQuit':
                        self._abortRequested = True
 
@@ -63,18 +74,28 @@ class NotificationService(threading.Thread):
                #while xbmc is running
                self._scrobbler = Scrobbler()
                self._scrobbler.start()
-               telnet = telnetlib.Telnet(self.TELNET_ADDRESS, self.TELNET_PORT)
-
                while not (self._abortRequested or xbmc.abortRequested):
                        try:
-                               data = self._readNotification(telnet)
-                       except EOFError:
+                               #try to connect, catch errors and retry every 5 
seconds
                                telnet = telnetlib.Telnet(self.TELNET_ADDRESS, 
self.TELNET_PORT)
-                               self._notificationBuffer = ""
+                               
+                               #if connection succeeds
+                               while not (self._abortRequested or 
xbmc.abortRequested):
+                                       try:
+                                               #read notification data
+                                               data = 
self._readNotification(telnet)
+                                               Debug("[Notification Service] 
message: " + str(data))
+                                               self._forward(data)
+                                       except EOFError:
+                                               #if we end up here, it means 
the connection was lost or reset,
+                                               # so we empty out the buffer, 
and exit this loop, which retries
+                                               # the connection in the outer 
loop
+                                               self._notificationBuffer = ""
+                                               break
+                       except:
+                               time.sleep(5)
                                continue
 
-                       Debug("[Notification Service] message: " + str(data))
-                       self._forward(data)
 
                telnet.close()
                self._scrobbler.abortRequested = True
diff --git a/script.trakt/resources/language/English/strings.xml 
b/script.trakt/resources/language/English/strings.xml
index 8388b17..dd0199d 100644
--- a/script.trakt/resources/language/English/strings.xml
+++ b/script.trakt/resources/language/English/strings.xml
@@ -140,4 +140,51 @@
        <string id="1282">Watched</string>
        <string id="1283">Library</string>
        <string id="1284">Profile</string>
+
+       <!-- Sync Settings -->
+       <string id="1400">Synchronize</string>
+       <string id="1401"></string>
+       <string id="1402">Movies</string>
+       <string id="1403">Add movies to trakt collection</string>
+       <string id="1404">Update trakt movie playcounts</string>
+       <string id="1405">Update XBMC movie playcounts</string>
+       <string id="1406">TV Episodes</string>
+       <string id="1407">Add TV episodes to trakt collection</string>
+       <string id="1408">Update trakt TV episode playcounts</string>
+       <string id="1409">Update XBMC TV episode playcounts</string>
+       <string id="1410">Service</string>
+       <string id="1411">Sync after library updates</string>
+       <string id="1412">Show notifications</string>
+       <string id="1413">Clean trakt movie collection</string>
+       <string id="1414">Clean trakt episode collection</string>
+
+       <!-- Sync Notifications -->
+       <string id="1420">Sync started</string>
+       <string id="1421">Sync complete</string>
+       <string id="1422">Getting movies from XBMC</string>
+       <string id="1423">Getting movie collection from trakt</string>
+       <string id="1424">Getting seen movies from trakt</string>
+       <string id="1425">Checking for XBMC movies that are not on 
trakt</string>
+       <string id="1426">movie(s) will be added to trakt collection</string>
+       <string id="1427">Checking watched movies on trakt</string>
+       <string id="1428">movie(s) playcount will be updated on trakt</string>
+       <string id="1429">Checking if XBMC playcount is up to date</string>
+       <string id="1430">movie(s) playcount will be updated on XBMC</string>
+       <string id="1431">Movie Sync Complete</string>
+       <string id="1432">Getting TV shows from XBMC</string>
+       <string id="1433">Getting episodes from XBMC</string>
+       <string id="1434">Getting episode collection from trakt</string>
+       <string id="1435">Checking for episodes missing from trakt 
collection</string>
+       <string id="1436">shows(s) have episodes added to trakt 
collection</string>
+       <string id="1437">episodes missing</string>
+       <string id="1438">Checking watched episodes on trakt</string>
+       <string id="1439">shows have missing watched status</string>
+       <string id="1440">episodes are being updated</string>
+       <string id="1441">Checking watched episodes on XBMC</string>
+       <string id="1442">Episode Sync Complete</string>
+       <string id="1443">Cleaning trakt movie collection</string>
+       <string id="1444">movie(s) will be removed from trakt 
collection</string>
+       <string id="1445">Cleaning trakt tvshow collection</string>
+       <string id="1446">show(s) will have episodes removed from trakt 
collection</string>
+       <string id="1447">episodes are being removed</string>
 </strings>
\ No newline at end of file
diff --git a/script.trakt/resources/settings.xml 
b/script.trakt/resources/settings.xml
index 2144825..dce7df4 100644
--- a/script.trakt/resources/settings.xml
+++ b/script.trakt/resources/settings.xml
@@ -4,11 +4,28 @@
                <setting id="username" type="text" label="1013" default="" />
                <setting id="password" type="text" option="hidden" label="1014" 
default="" />
                <setting id="debug" type="bool" label="1011" default="true"/>
-               <setting id="https" type="bool" label="1016" default="false"/>
+               <setting id="https" type="bool" label="1016" default="true"/>
        </category>
        <category label="1040"><!-- Scrobbling -->
                <setting id="scrobble_movie" type="bool" label="1041" 
default="true"/>
                <setting id="scrobble_episode" type="bool" label="1042" 
default="true"/>
                <setting id="scrobble_min_view_time" type="slider" label="1043" 
range="0,5,100" default="80"/>
        </category>
+       <category label="1400"><!-- Synchronize -->
+               <setting label="1410" type="lsep"/><!-- Service -->
+               <setting id="sync_on_update" type="bool" label="1411" 
default="false"/>
+               <setting id="show_sync_notifications" type="bool" label="1412" 
default="false"/>
+               <setting type="sep"/>
+               <setting label="1402" type="lsep"/><!-- Movies -->
+               <setting id="add_movies_to_trakt" type="bool" label="1403" 
default="true"/>
+               <setting id="trakt_movie_playcount" type="bool" label="1404" 
default="true"/>
+               <setting id="xbmc_movie_playcount" type="bool" label="1405" 
default="true"/>
+               <setting id="clean_trakt_movies" type="bool" label="1413" 
default="false"/>
+               <setting type="sep"/>
+               <setting label="1406" type="lsep"/><!-- Episodes -->
+               <setting id="add_episodes_to_trakt" type="bool" label="1407" 
default="true"/>
+               <setting id="trakt_episode_playcount" type="bool" label="1408" 
default="true"/>
+               <setting id="xbmc_episode_playcount" type="bool" label="1409" 
default="true"/>
+               <setting id="clean_trakt_episodes" type="bool" label="1414" 
default="false"/>
+       </category>
 </settings>
\ No newline at end of file
diff --git a/script.trakt/scrobbler.py b/script.trakt/scrobbler.py
index 66d59f9..0f30c1e 100644
--- a/script.trakt/scrobbler.py
+++ b/script.trakt/scrobbler.py
@@ -118,7 +118,7 @@ class Scrobbler(threading.Thread):
                elif self.curVideo['type'] == 'episode' and 
scrobbleEpisodeOption == 'true':
                        match = None
                        if 'id' in self.curVideo:
-                               match = 
utilities.getEpisodeDetailsFromXbmc(self.curVideo['id'], ['showtitle', 
'season', 'episode', 'tvshowid'])
+                               match = 
utilities.getEpisodeDetailsFromXbmc(self.curVideo['id'], ['showtitle', 
'season', 'episode', 'tvshowid', 'uniqueid'])
                        elif 'showtitle' in self.curVideoData and 'season' in 
self.curVideoData and 'episode' in self.curVideoData:
                                match = {}
                                match['tvdb_id'] = None
@@ -126,9 +126,10 @@ class Scrobbler(threading.Thread):
                                match['showtitle'] = 
self.curVideoData['showtitle']
                                match['season'] = self.curVideoData['season']
                                match['episode'] = self.curVideoData['episode']
+                               match['uniqueid'] = 
self.curVideoData['uniqueid']['unknown']
                        if match == None:
                                return
-                       response = 
utilities.watchingEpisodeOnTrakt(match['tvdb_id'], match['showtitle'], 
match['year'], match['season'], match['episode'], self.totalTime/60, 
int(100*self.watchedTime/self.totalTime))
+                       response = 
utilities.watchingEpisodeOnTrakt(match['tvdb_id'], match['showtitle'], 
match['year'], match['season'], match['episode'], match['uniqueid']['unknown'], 
self.totalTime/60, int(100*self.watchedTime/self.totalTime))
                        if response != None:
                                Debug("[Scrobbler] Watch response: 
"+str(response))
 
@@ -166,7 +167,7 @@ class Scrobbler(threading.Thread):
                elif self.curVideo['type'] == 'episode' and 
scrobbleEpisodeOption == 'true':
                        match = None
                        if 'id' in self.curVideo:
-                               match = 
utilities.getEpisodeDetailsFromXbmc(self.curVideo['id'], ['showtitle', 
'season', 'episode', 'tvshowid'])
+                               match = 
utilities.getEpisodeDetailsFromXbmc(self.curVideo['id'], ['showtitle', 
'season', 'episode', 'tvshowid', 'uniqueid'])
                        elif 'showtitle' in self.curVideoData and 'season' in 
self.curVideoData and 'episode' in self.curVideoData:
                                match = {}
                                match['tvdb_id'] = None
@@ -174,9 +175,10 @@ class Scrobbler(threading.Thread):
                                match['showtitle'] = 
self.curVideoData['showtitle']
                                match['season'] = self.curVideoData['season']
                                match['episode'] = self.curVideoData['episode']
+                               match['uniqueid'] = 
self.curVideoData['uniqueid']['unknown']
                        if match == None:
                                return
-                       response = 
utilities.scrobbleEpisodeOnTrakt(match['tvdb_id'], match['showtitle'], 
match['year'], match['season'], match['episode'], self.totalTime/60, 
int(100*self.watchedTime/self.totalTime))
+                       response = 
utilities.scrobbleEpisodeOnTrakt(match['tvdb_id'], match['showtitle'], 
match['year'], match['season'], match['episode'], match['uniqueid']['unknown'], 
self.totalTime/60, int(100*self.watchedTime/self.totalTime))
                        if response != None:
                                Debug("[Scrobbler] Scrobble response: 
"+str(response))
 
diff --git a/script.trakt/utilities.py b/script.trakt/utilities.py
index d7cc63d..eaebbc0 100644
--- a/script.trakt/utilities.py
+++ b/script.trakt/utilities.py
@@ -24,8 +24,8 @@ __language__ = __settings__.getLocalizedString
 
 apikey = 'b6135e0f7510a44021fac8c03c36c81a17be35d9'
 
-username = __settings__.getSetting("username")
-pwd = sha.new(__settings__.getSetting("password")).hexdigest()
+username = __settings__.getSetting("username").strip()
+pwd = sha.new(__settings__.getSetting("password").strip()).hexdigest()
 debug = __settings__.getSetting("debug")
 
 def Debug(msg, force = False):
@@ -38,6 +38,19 @@ def Debug(msg, force = False):
 def notification( header, message, time=5000, 
icon=__settings__.getAddonInfo("icon")):
        xbmc.executebuiltin( "XBMC.Notification(%s,%s,%i,%s)" % ( header, 
message, time, icon ) )
 
+def xbmcJsonRequest(params):
+       data = json.dumps(params)
+       request = xbmc.executeJSONRPC(data)
+       response = json.loads(request)
+
+       try:
+               if "result" in response:
+                       return response["result"]
+               return None
+       except KeyError:
+               Debug("[%s] %s" % (params["method"], 
response["error"]["message"]), True)
+               return None
+
 def checkSettings(daemon=False):
        if username == "":
                if daemon:
@@ -65,6 +78,10 @@ def checkSettings(daemon=False):
 
        return True
 
+
+def chunks(l, n):
+       return [l[i:i+n] for i in range(0, len(l), n)]
+
 # get a connection to trakt
 def getTraktConnection():
        https = __settings__.getSetting('https')
@@ -79,6 +96,34 @@ def getTraktConnection():
                return None
        return conn
 
+# json wrapper to make actual json request call, to rety upto 3 times in the 
event of failures.
+def traktJSONWrapper(method, req, args={}, returnStatus=False, anon=False, 
conn=False, silent=True, passVersions=False):
+       response = None
+       
+       # check the method, if not POST or GET, return nothing
+       if not (method == 'POST' or method == 'GET'):
+               Debug("traktJSONWrapper(): Unknown method (%S)." % method)
+               return None
+
+       Debug("traktJSONWrapper(): Starting loop")
+       for i in range(0,3):
+               Debug("traktJSONWrapper(): (%i) Sending JSON API %s %s" % (i, 
method, req.replace("%%API_KEY%%", "")))
+               response = traktJsonRequest(method, req, args, returnStatus, 
anon, conn, silent, passVersions)
+               if xbmc.abortRequested:
+                       Debug("traktJSONWrapper(): (%i) xbmc.abortRequested", i)
+                       break
+               if response == None:
+                       Debug("traktJSONWrapper(): (%i) JSON Response empty", i)
+               if 'status' in response:
+                       Debug("traktJSONWrapper(): (%i) JSON Response '%s'" % 
(i, response['status']))
+                       if response['status'] == 'success':
+                               break
+                       else:
+                               Debug("traktJSONWrapper(): (%i) JSON Error '%s" 
% (i, response['error']))
+               time.sleep(0.1)
+               
+       return response
+
 # make a JSON api request to trakt
 # method: http method (GET or POST)
 # req: REST request (ie 
'/user/library/movies/all.json/%%API_KEY%%/%%USERNAME%%')
@@ -96,6 +141,7 @@ def traktJsonRequest(method, req, args={}, 
returnStatus=False, anon=False, conn=
                conn = getTraktConnection()
                closeConnection = True
        if conn == None:
+               Debug("traktJsonRequest(): Unable to create connection to 
trakt.")
                if returnStatus:
                        data = {}
                        data['status'] = 'failure'
@@ -119,10 +165,11 @@ def traktJsonRequest(method, req, args={}, 
returnStatus=False, anon=False, conn=
                elif method == 'GET':
                        conn.request('GET', req)
                else:
+                       Debug("traktJsonRequest(): Unknown method " + method)
                        return None
-               Debug("json url: "+req)
+               Debug("traktJsonRequest(): "+method+" JSON url: "+req)
        except socket.error:
-               Debug("traktQuery: can't connect to trakt")
+               Debug("traktJsonRequest(): Unable to connect to trakt.")
                if not silent:
                        notification("trakt", __language__(1108).encode( 
"utf-8", "ignore" )) # can't connect to trakt
                if returnStatus:
@@ -136,26 +183,57 @@ def traktJsonRequest(method, req, args={}, 
returnStatus=False, anon=False, conn=
 
        while True:
                if xbmc.abortRequested:
-                       Debug("Broke loop due to abort")
+                       Debug("traktJsonRequest(): Broke loop due to abort.")
                        if returnStatus:
                                data = {}
                                data['status'] = 'failure'
                                data['error'] = 'Abort requested, not waiting 
for response'
                                return data
                        return None
+               if conn.readError:
+                       Debug("traktJsonRequest(): Error reading response.")
+                       if returnStatus:
+                               data = {}
+                               data['status'] = 'failure'
+                               data['error'] = 'Error getting response, read 
error on socket.'
+                               return data
+                       return None
                if conn.hasResult():
+                       Debug("traktJsonRequest(): hasResult()")
                        break
                time.sleep(0.1)
 
+       Debug("traktJsonRequest(): Get response object.")
        response = conn.getResult()
-       raw = response.read()
+       if response == None:
+               Debug("traktJsonRequest(): Response not set.")
+               if returnStatus:
+                       data = {}
+                       data['status'] = 'failure'
+                       data['error'] = 'Error getting response, response not 
set.'
+                       return data
+               return None
+               
+       Debug("traktJsonRequest(): Trying to read response.")
+       try:
+               raw = response.read()
+       except:
+               Debug("traktJsonRequest(): Exception reading response.")
+               if returnStatus:
+                       data = {}
+                       data['status'] = 'failure'
+                       data['error'] = 'Error getting response, exception 
reading response.'
+                       return data
+               return None
+       
        if closeConnection:
                conn.close()
 
        try:
                data = json.loads(raw)
+               Debug("traktJsonRequest(): JSON response: " + str(data))
        except ValueError:
-               Debug("traktQuery: Bad JSON response: "+raw)
+               Debug("traktJsonRequest(): Bad JSON response: " + raw)
                if returnStatus:
                        data = {}
                        data['status'] = 'failure'
@@ -167,7 +245,7 @@ def traktJsonRequest(method, req, args={}, 
returnStatus=False, anon=False, conn=
 
        if 'status' in data:
                if data['status'] == 'failure':
-                       Debug("traktQuery: Error: " + str(data['error']))
+                       Debug("traktJsonRequest(): Error: " + 
str(data['error']))
                        if returnStatus:
                                return data
                        if not silent:
@@ -269,42 +347,60 @@ def getPlaylistLengthFromXBMCPlayer(playerid):
 
 #tell trakt that the user is watching a movie
 def watchingMovieOnTrakt(imdb_id, title, year, duration, percent):
-       response = traktJsonRequest('POST', '/movie/watching/%%API_KEY%%', 
{'imdb_id': imdb_id, 'title': title, 'year': year, 'duration': 
math.ceil(duration), 'progress': math.ceil(percent)}, passVersions=True)
+       Debug("watchingMovieOnTrakt(): Calling traktJSONWrapper()")
+       #response = traktJsonRequest('POST', '/movie/watching/%%API_KEY%%', 
{'imdb_id': imdb_id, 'title': title, 'year': year, 'duration': 
math.ceil(duration), 'progress': math.ceil(percent)}, passVersions=True)
+       response = traktJSONWrapper('POST', '/movie/watching/%%API_KEY%%', 
{'imdb_id': imdb_id, 'title': title, 'year': year, 'duration': 
math.ceil(duration), 'progress': math.ceil(percent)}, passVersions=True)
+       Debug("watchingMovieOnTrakt(): traktJSONWrapper() returned")
        if response == None:
-               Debug("Error in request from 'watchingMovieOnTrakt()'")
+               Debug("watchingMovieOnTrakt(): Error in request")
        return response
 
 #tell trakt that the user is watching an episode
-def watchingEpisodeOnTrakt(tvdb_id, title, year, season, episode, duration, 
percent):
-       response = traktJsonRequest('POST', '/show/watching/%%API_KEY%%', 
{'tvdb_id': tvdb_id, 'title': title, 'year': year, 'season': season, 'episode': 
episode, 'duration': math.ceil(duration), 'progress': math.ceil(percent)}, 
passVersions=True)
+def watchingEpisodeOnTrakt(tvdb_id, title, year, season, episode, uniqueid, 
duration, percent):
+       Debug("watchingEpisodeOnTrakt(): Calling traktJSONWrapper()")
+       #response = traktJsonRequest('POST', '/show/watching/%%API_KEY%%', 
{'tvdb_id': tvdb_id, 'title': title, 'year': year, 'season': season, 'episode': 
episode, 'episode_tvdb_id': uniqueid, 'duration': math.ceil(duration), 
'progress': math.ceil(percent)}, passVersions=True)
+       response = traktJSONWrapper('POST', '/show/watching/%%API_KEY%%', 
{'tvdb_id': tvdb_id, 'title': title, 'year': year, 'season': season, 'episode': 
episode, 'episode_tvdb_id': uniqueid, 'duration': math.ceil(duration), 
'progress': math.ceil(percent)}, passVersions=True)
+       Debug("watchingEpisodeOnTrakt(): traktJSONWrapper() returned")
        if response == None:
-               Debug("Error in request from 'watchingEpisodeOnTrakt()'")
+               Debug("watchingEpisodeOnTrakt(): Error in request")
        return response
 
 #tell trakt that the user has stopped watching a movie
 def cancelWatchingMovieOnTrakt():
-       response = traktJsonRequest('POST', '/movie/cancelwatching/%%API_KEY%%')
+       Debug("cancelWatchingMovieOnTrakt(): Calling traktJSONWrapper()")
+       #response = traktJsonRequest('POST', 
'/movie/cancelwatching/%%API_KEY%%')
+       response = traktJSONWrapper('POST', '/movie/cancelwatching/%%API_KEY%%')
+       Debug("cancelWatchingMovieOnTrakt(): traktJSONWrapper() returned")
        if response == None:
-               Debug("Error in request from 'cancelWatchingMovieOnTrakt()'")
+               Debug("cancelWatchingMovieOnTrakt(): Error in request")
        return response
 
 #tell trakt that the user has stopped an episode
 def cancelWatchingEpisodeOnTrakt():
-       response = traktJsonRequest('POST', '/show/cancelwatching/%%API_KEY%%')
+       Debug("cancelWatchingEpisodeOnTrakt(): Calling traktJSONWrapper()")
+       #response = traktJsonRequest('POST', '/show/cancelwatching/%%API_KEY%%')
+       response = traktJSONWrapper('POST', '/show/cancelwatching/%%API_KEY%%')
+       Debug("cancelWatchingEpisodeOnTrakt(): traktJSONWrapper() returned")
        if response == None:
-               Debug("Error in request from 'cancelWatchingEpisodeOnTrakt()'")
+               Debug("cancelWatchingEpisodeOnTrakt(): Error in request")
        return response
 
 #tell trakt that the user has finished watching an movie
 def scrobbleMovieOnTrakt(imdb_id, title, year, duration, percent):
-       response = traktJsonRequest('POST', '/movie/scrobble/%%API_KEY%%', 
{'imdb_id': imdb_id, 'title': title, 'year': year, 'duration': 
math.ceil(duration), 'progress': math.ceil(percent)}, passVersions=True)
+       Debug("scrobbleMovieOnTrakt(): Calling traktJSONWrapper()")
+       #response = traktJsonRequest('POST', '/movie/scrobble/%%API_KEY%%', 
{'imdb_id': imdb_id, 'title': title, 'year': year, 'duration': 
math.ceil(duration), 'progress': math.ceil(percent)}, passVersions=True)
+       response = traktJSONWrapper('POST', '/movie/scrobble/%%API_KEY%%', 
{'imdb_id': imdb_id, 'title': title, 'year': year, 'duration': 
math.ceil(duration), 'progress': math.ceil(percent)}, passVersions=True)
+       Debug("scrobbleMovieOnTrakt(): traktJSONWrapper() returned")
        if response == None:
-               Debug("Error in request from 'scrobbleMovieOnTrakt()'")
+               Debug("scrobbleMovieOnTrakt(): Error in request")
        return response
 
 #tell trakt that the user has finished watching an episode
-def scrobbleEpisodeOnTrakt(tvdb_id, title, year, season, episode, duration, 
percent):
-       response = traktJsonRequest('POST', '/show/scrobble/%%API_KEY%%', 
{'tvdb_id': tvdb_id, 'title': title, 'year': year, 'season': season, 'episode': 
episode, 'duration': math.ceil(duration), 'progress': math.ceil(percent)}, 
passVersions=True)
+def scrobbleEpisodeOnTrakt(tvdb_id, title, year, season, episode, uniqueid, 
duration, percent):
+       Debug("scrobbleEpisodeOnTrakt(): Calling traktJSONWrapper()")
+       #response = traktJsonRequest('POST', '/show/scrobble/%%API_KEY%%', 
{'tvdb_id': tvdb_id, 'title': title, 'year': year, 'season': season, 'episode': 
episode, 'episode_tvdb_id': uniqueid, 'duration': math.ceil(duration), 
'progress': math.ceil(percent)}, passVersions=True)
+       response = traktJSONWrapper('POST', '/show/scrobble/%%API_KEY%%', 
{'tvdb_id': tvdb_id, 'title': title, 'year': year, 'season': season, 'episode': 
episode, 'episode_tvdb_id': uniqueid, 'duration': math.ceil(duration), 
'progress': math.ceil(percent)}, passVersions=True)
+       Debug("scrobbleEpisodeOnTrakt(): traktJSONWrapper() returned")
        if response == None:
-               Debug("Error in request from 'scrobbleEpisodeOnTrakt()'")
+               Debug("scrobbleEpisodeOnTrakt(): Error in request")
        return response

-----------------------------------------------------------------------

Summary of changes:
 script.trakt/.gitignore                            |    1 +
 script.trakt/README.md                             |   36 +-
 script.trakt/addon.xml                             |   40 ++-
 script.trakt/changelog.txt                         |   15 +-
 script.trakt/episode_sync.py                       |  451 ++++++++++++++++++++
 script.trakt/movie_sync.py                         |  295 +++++++++++++
 script.trakt/nbconnection.py                       |   11 +-
 script.trakt/notification_service.py               |   35 ++-
 .../resources/language/English/strings.xml         |   47 ++
 script.trakt/resources/settings.xml                |   19 +-
 script.trakt/scrobbler.py                          |   10 +-
 script.trakt/sync_exec.py                          |   28 ++
 script.trakt/utilities.py                          |  140 +++++-
 13 files changed, 1063 insertions(+), 65 deletions(-)
 create mode 100644 script.trakt/episode_sync.py
 create mode 100644 script.trakt/movie_sync.py
 create mode 100644 script.trakt/sync_exec.py


hooks/post-receive
-- 
Scripts

------------------------------------------------------------------------------
Free Next-Gen Firewall Hardware Offer
Buy your Sophos next-gen firewall before the end March 2013 
and get the hardware for free! Learn more.
http://p.sf.net/sfu/sophos-d2d-feb
_______________________________________________
Xbmc-addons mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/xbmc-addons

Reply via email to