diff options
author | mrDoctorWho <mrdoctorwho@gmail.com> | 2014-02-16 10:11:11 +0400 |
---|---|---|
committer | mrDoctorWho <mrdoctorwho@gmail.com> | 2014-02-16 10:11:11 +0400 |
commit | 33360c5e5ae220435c7928459177ca341316dcb4 (patch) | |
tree | 6fd2719522afa21b75f6813c67f1366b2ff2fd13 /library | |
parent | cc9fd58a88c5ef201d4a87b6f9b09a1ed4208b1f (diff) |
Testing longPoll.
Diffstat (limited to 'library')
-rw-r--r-- | library/stext.py | 9 | ||||
-rw-r--r-- | library/vkApi.py | 50 | ||||
-rw-r--r-- | library/xmpp/dispatcher.py | 13 | ||||
-rw-r--r-- | library/xmpp/transports.py | 61 |
4 files changed, 83 insertions, 50 deletions
diff --git a/library/stext.py b/library/stext.py index 4772240..aba88cb 100644 --- a/library/stext.py +++ b/library/stext.py @@ -14,10 +14,11 @@ def rFile(name): def _(what): name = "%s/locales/locale.%s" % (path, locale) - what = what.replace("\n", "\L") + what = what.replace("\n", "\\n") if locale != "en" and os.path.exists(name): - data = rFile(name) - for line in data.splitlines(): + data = file(name).readlines() + for line in data: if line.startswith(what): what = line.split("=")[1] - return what.replace("\L", "\n")
\ No newline at end of file + break + return what.replace("\\n", "\n")
\ No newline at end of file diff --git a/library/vkApi.py b/library/vkApi.py index 08e6d6e..1adf417 100644 --- a/library/vkApi.py +++ b/library/vkApi.py @@ -1,11 +1,11 @@ # coding: utf-8 # © simpleApps CodingTeam, 2013 — 2014. -import time, ssl, urllib, urllib2, cookielib +import time, ssl, socket, urllib, urllib2, cookielib import logging, json, webtools logger = logging.getLogger("vk4xmpp") - +socket.setdefaulttimeout(30) # we should waste all time. def attemptTo(maxRetries, resultType, *errors): """ @@ -24,7 +24,7 @@ def attemptTo(maxRetries, resultType, *errors): while retries < maxRetries: try: data = func(*args, **kwargs) - except errors, exc: + except errors as exc: retries += 1 time.sleep(0.2) else: @@ -49,13 +49,13 @@ class RequestProcessor(object): headers = {"User-agent": "Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:21.0)" " Gecko/20130309 Firefox/21.0", "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", - "Accept-Language": "ru-RU, utf-8" - } + "Accept-Language": "ru-RU, utf-8"} + def __init__(self): self.cookieJar = cookielib.CookieJar() self.cookieProcessor = urllib2.HTTPCookieProcessor(self.cookieJar) self.open = urllib2.build_opener(self.cookieProcessor).open - self.open.im_func.func_defaults = (None, 4) + self.open.im_func.func_defaults = (None, 30) def getCookie(self, name): for cookie in self.cookieJar: @@ -69,20 +69,25 @@ class RequestProcessor(object): request = urllib2.Request(url, data, headers) return request - @attemptTo(5, dict, urllib2.URLError, ssl.SSLError) + @attemptTo(5, tuple, urllib2.URLError, ssl.SSLError, socket.timeout) def post(self, url, data = {}): resp = self.open(self.request(url, data)) body = resp.read() return (body, resp) - @attemptTo(5, dict, urllib2.URLError, ssl.SSLError) + @attemptTo(5, tuple, urllib2.URLError, ssl.SSLError, socket.timeout) def get(self, url, query = {}): if query: - url += "/?%s" % urllib.urlencode(query) + url += "?%s" % urllib.urlencode(query) resp = self.open(self.request(url)) body = resp.read() return (body, resp) + def getOpener(self, url, query = {}): + if query: + url += "?%s" % urllib.urlencode(query) + return self.open(self.request(url)) + class APIBinding: def __init__(self, number, password = None, token = None, app_id = 3789129, @@ -107,8 +112,7 @@ class APIBinding: values = {"act": "login", "utf8": "1", # check if it needed "email": self.number, - "pass": self.password - } + "pass": self.password} body, response = self.RIP.post(url, values) remixSID = self.RIP.getCookie("remixsid") @@ -123,7 +127,7 @@ class APIBinding: if "security_check" in response.url: # This code should be rewritten! Users from another countries can have problems because of it! - Hash = webtools.regexp(r"security_check.*?hash: '(.*?)'\};", body)[0] + hash = webtools.regexp(r"security_check.*?hash: '(.*?)'\};", body)[0] code = self.number[2:-2] if len(self.number) == 12: if not self.number.startswith("+"): @@ -137,9 +141,8 @@ class APIBinding: "al": "1", "al_page": "3", "code": code, - "hash": Hash, - "to": "" - } + "hash": hash, + "to": ""} post = self.RIP.post("https://vk.com/login.php", values) body, response = post if response and not body.split("<!>")[4] == "4": @@ -157,13 +160,12 @@ class APIBinding: return data def confirmThisApp(self): - url = "https://oauth.vk.com/authorize" + url = "https://oauth.vk.com/authorize/" values = {"display": "mobile", "scope": self.scope, "client_id": self.app_id, "response_type": "token", - "redirect_uri": "https://oauth.vk.com/blank.html" - } + "redirect_uri": "https://oauth.vk.com/blank.html"} token = None body, response = self.RIP.get(url, values) @@ -226,10 +228,12 @@ class APIBinding: return self.method(method, values) elif eCode == 5: # auth failed raise VkApiError("Logged out") - if eCode == 7: + elif eCode == 7: # not allowed raise NotAllowed() - elif eCode == 9: + elif eCode == 9: # ???? return {} + elif eCode == 10: # internal server error + raise InternalServerError() if eCode == 14: # captcha if "captcha_sid" in error: self.captcha = {"sid": error["captcha_sid"], "img": error["captcha_img"]} @@ -244,6 +248,8 @@ class APIBinding: class NetworkNotFound(Exception): ## maybe network is unreachable or vk is down (same as 10 jan 2014) pass +class LongPollError(Exception): + pass class VkApiError(Exception): pass @@ -253,6 +259,10 @@ class AuthError(VkApiError): pass +class InternalServerError(VkApiError): + pass + + class CaptchaNeeded(VkApiError): pass diff --git a/library/xmpp/dispatcher.py b/library/xmpp/dispatcher.py index fb6710c..8df49e0 100644 --- a/library/xmpp/dispatcher.py +++ b/library/xmpp/dispatcher.py @@ -151,15 +151,10 @@ class Dispatcher(PlugIn): handler(self)
if self._pendingExceptions:
e = self._pendingExceptions.pop()
- raise e[0](e[1]).with_traceback(e[2])
- conn = self._owner.Connection
- recv, send = select([conn._sock], [conn._sock] if conn._send_queue else [], [], timeout)[:2]
- if send:
- while conn._send_queue:
- conn.send_now(conn._send_queue.pop(0))
- if recv:
+ raise e[0], e[1], e[2]
+ if self._owner.Connection.pending_data(timeout):
try:
- data = conn.receive()
+ data = self._owner.Connection.receive()
except IOError:
return None
try:
@@ -168,7 +163,7 @@ class Dispatcher(PlugIn): pass
if self._pendingExceptions:
e = self._pendingExceptions.pop()
- raise e[0](e[1]).with_traceback(e[2])
+ raise e[0], e[1], e[2]
if data:
return len(data)
return "0"
diff --git a/library/xmpp/transports.py b/library/xmpp/transports.py index 47aa50d..f34f8a7 100644 --- a/library/xmpp/transports.py +++ b/library/xmpp/transports.py @@ -31,6 +31,8 @@ import sys import socket
if sys.hexversion >= 0x20600F0:
import ssl
+import thread
+import time
from . import dispatcher
from base64 import encodestring
@@ -49,7 +51,33 @@ DATA_RECEIVED = 'DATA RECEIVED' DATA_SENT = 'DATA SENT'
DBG_CONNECT_PROXY = 'CONNECTproxy'
-BUFLEN = 1024
+BUFLEN = 2024
+SEND_INTERVAL = 0
+
+class SendSemaphore(object):
+
+ def __init__(self):
+ self.__lock = thread.allocate_lock()
+ self.__released = 0
+ self.interval = SEND_INTERVAL
+
+ def set_inteval(self, interval):
+ self.interval = interval
+
+ def acquire(self, blocking=1):
+ rc = self.__lock.acquire(blocking)
+ if blocking and self.interval and time.time() - self.__released < self.interval:
+ time.sleep(self.interval)
+ return rc
+
+ __enter__ = acquire
+
+ def release(self):
+ self.__released = time.time()
+ self.__lock.release()
+
+ def __exit__(self, *args):
+ self.release()
class error:
"""
@@ -80,9 +108,10 @@ class TCPsocket(PlugIn): """
PlugIn.__init__(self)
self.DBG_LINE = "socket"
- self._exported_methods = [self.send, self.disconnect]
+ self.__queue = SendSemaphore()
+ self.set_send_interval = self.__queue.set_inteval
+ self._exported_methods = [self.send, self.disconnect, self.set_send_interval]
self._server, self.use_srv = server, use_srv
- self._send_queue = []
def srv_lookup(self, server):
"""
@@ -221,9 +250,6 @@ class TCPsocket(PlugIn): return data
def send(self, data):
- self._send_queue.append(data)
-
- def send_now(self, data, timeout=0.002):
"""
Writes raw outgoing data. Blocks until done.
If supplied data is unicode string, encodes it to utf-8 before send.
@@ -232,17 +258,18 @@ class TCPsocket(PlugIn): data = data.encode("utf-8")
elif not isinstance(data, str):
data = ustr(data).encode("utf-8")
- try:
- self._send(data)
- except Exception:
- self.DEBUG("Socket error while sending data.", "error")
- self._owner.disconnected()
- else:
- if not data.strip():
- data = repr(data)
- self.DEBUG(data, "sent")
- if hasattr(self._owner, "Dispatcher"):
- self._owner.Dispatcher.Event("", DATA_SENT, data)
+ with self.__queue:
+ try:
+ self._send(data)
+ except Exception:
+ self.DEBUG("Socket error while sending data.", "error")
+ self._owner.disconnected()
+ else:
+ if not data.strip():
+ data = repr(data)
+ self.DEBUG(data, "sent")
+ if hasattr(self._owner, "Dispatcher"):
+ self._owner.Dispatcher.Event("", DATA_SENT, data)
def pending_data(self, timeout=0):
"""
|