move sys.argv hack to tubelib/youtube
[enigma2-plugins.git] / tubelib / src / youtube / ThreadedRequest.py
1 from Tools.Log import Log
2 from twisted.internet import threads, reactor
3 from threading import Lock
4
5 class ThreadedRequest(object):
6         # Pythons HttpConnection (used by googles python client api) is not thread safe
7         # We have to use locking to ensure serialized requests
8         _lock = Lock()
9
10         def __init__(self, query, callback, subquery=None):
11                 self._canceled = False
12                 self._callback = callback
13                 self._query = query
14                 self._subquery = subquery
15                 threads.deferToThread(self._doQuery)
16
17         def _doQuery(self):
18                 self._lock.acquire()
19                 try:
20                         data = self._query.execute()
21                         if self._subquery:
22                                 query = self._subquery(data)
23                                 data = query.execute()
24                         self._onResult(True, data)
25                 except Exception as e:
26                         Log.w(e)
27                         self._onResult(False, e)
28                 self._lock.release()
29
30         def _onResult(self, success, data):
31                 reactor.callFromThread(self._finish, success, data)
32
33         def _finish(self, success, data):
34                 if self._canceled:
35                         return
36                 self._callback(success, data)
37
38         def cancel(self):
39                 self._canceled = True