-
Notifications
You must be signed in to change notification settings - Fork 13
/
xupload.py
177 lines (153 loc) · 6.63 KB
/
xupload.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
import aiohttp
import aiofiles
import asyncio
import os
class Xupload(object):
PROXY_SOCKET = ""
_QUERY_TIMEOUT = 60 * 60
_CHUNK_SIZE = 4 << 20
def __init__(self, upload_url, file_path, workers=1, headers=None, progress=None):
if not os.path.exists(file_path):
raise IOError("[Errno 2] No such file or directory: '%s'" % file_path)
self._url = upload_url
self._file_path = file_path
self._file_size = os.stat(self._file_path).st_size
self._workers = int(max(1, min(workers, self._file_size / self._CHUNK_SIZE, 8)))
self._headers = headers if isinstance(headers,dict) else {}
self._progress = progress
self._chunk_size = self._file_size / self._workers
self._chunk_size = (
int(self._chunk_size / int(self._chunk_size / self._CHUNK_SIZE))
if int(self._chunk_size / self._CHUNK_SIZE) > 0
else int(self._chunk_size)
)
self._session = None
self._clients = []
self._tasks = []
chunks = int(round(self._file_size / self._chunk_size / self._workers))
for index in range(self._workers):
start = index * self._chunk_size * chunks
end = (
self._file_size - 1
if index == self._workers - 1
else ((index + 1) * self._chunk_size * chunks) - 1
)
self._clients.append({
'start': start,
'offset': start,
'end': end,
'size': 0,
'sent': 0
})
def start(self):
loop = asyncio.get_event_loop()
result = loop.run_until_complete(self._run())
loop.run_until_complete(asyncio.sleep(0.250))
loop.close()
return result
async def _prepare_handle(self, client):
async with aiofiles.open(self._file_path, "rb") as file:
client['size'] = min(self._chunk_size, client['end'] - client['offset'] + 1)
client['data'] = await self._get_file_chunk(file, client['size'], client['offset'])
client['headers'] = {
**self._headers,
**{
'Accept': '*/*',
'Content-Type': 'application/octet-stream',
'Content-Disposition': 'attachment; filename="{}"'.format(
os.path.basename(self._file_path)
),
'Content-Range': 'bytes {}-{}/{}'.format(
client['offset'],
client['offset'] + client['size'] - 1,
self._file_size
)
}
}
self._tasks.append(
asyncio.ensure_future(self._post_chunk(self._url, client))
)
async def _run(self):
self._session = aiohttp.ClientSession(
timeout=aiohttp.ClientTimeout(total=self._QUERY_TIMEOUT),
connector=aiohttp.TCPConnector(limit=self._workers)
)
if self._progress:
self._progress(0, self._file_size)
async with self._session:
for client in self._clients:
await self._prepare_handle(client)
while len(self._tasks) > 0:
await asyncio.sleep(0.3)
for task in self._tasks:
if task.done():
self._tasks.remove(task)
result = task.result()
exception = task.exception()
if result['status'] == 200:
if self._progress:
self._progress(self._file_size, self._file_size)
return result["content"]
if result['status'] in (202, 416):
client = self._get_client_from_request(result['request_info'])
client['sent'] += client['size']
if self._progress:
sent = 0
for c in self._clients:
sent += c['sent']
self._progress(min(sent,self._file_size), self._file_size)
ranges = []
range_header = result['headers'].get('Range').split('/')
if len(range_header) > 0:
ranges = [r.split('-') for r in range_header[0].split(',')]
for r_start, r_end in [[int(i), int(j)] for i,j in ranges]:
if client['start'] >= r_start and client['start'] < r_end:
if client['end'] <= r_end:
break
if (r_end - client['start'] + 1) % self._chunk_size == 0:
client['offset'] = r_end + 1
await self._prepare_handle(client)
break
elif 'content' in result and 'error' in result['content']:
return result['content']
if exception:
raise DailymotionXuploadError(str(exception))
def _get_client_from_request(self, request_info):
for client in self._clients:
if client['headers']['Content-Range'] == request_info.headers['Content-Range']:
return client
@staticmethod
def print_progress(current, total):
"""
Example of function which prints the percentage of progression
:param current: current bytes sent
:param total: total bytes
:return: None
"""
percent = int(min((current * 100) / total, 100))
print(
"[{}{}] {}%\r".format(
"*" * int(percent), " " * (100 - int(percent)), percent
),
flush=True,
end="",
)
async def _post_chunk(self, url, client):
async with self._session.post(
url,
data=client["data"],
headers=client["headers"],
proxy=self.PROXY_SOCKET,
expect100=True,
) as resp:
return {
"status": resp.status,
"headers": resp.headers,
"content": await resp.json(),
"request_info": resp.request_info,
}
async def _get_file_chunk(self, file, chunk_length, chunk_start=0):
await file.seek(chunk_start)
return await file.read(chunk_length)
class DailymotionXuploadError(Exception):
pass