-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmanage.py
250 lines (207 loc) · 7.71 KB
/
manage.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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
#coding:utf-8
'''
Created on 2016年11月3日
@author: 肖雄
'''
import downloader
from log import logger
from auth import LoginWanpan
import os
import tool
import requests
import pcs
import config
import sys
import re
import urllib
import getopt
def login(username, password=None):
'''
登录模块:
1.先用username查询是否有保存的cookies和bdstoken
2.如果有则用cookies和bdstoken登录
3.以上步骤失败则采取用户名和密码登录
返回值:
errno, req, bdstoken,
errno 为0,代表登录成功, 为1代表登录失败
req 为会话请求
bdstoken 登录凭证
'''
login_wanpan = LoginWanpan()
path_cookies = './session_saved/' + username + '_cookies'
path_token = './session_saved/' + username + '_token'
if os.path.exists(path_cookies) and os.path.exists(path_token):
cookies = tool.load_cookies_from_lwp(path_cookies)
token = tool.load_auth(path_token)
if cookies and token:
req = requests.Session()
req.cookies = cookies
bdstoken = login_wanpan.get_bdstoken(req)
if bdstoken:
logger.info(u'cookies 和 token有效')
return 0, req, bdstoken
else:
logger.info(u'cookies 或者 token无效')
if os.path.exists(path_cookies):
os.remove(path_cookies)
if os.path.exists(path_token):
os.remove(path_token)
if password:
return login_wanpan.run(username, password)
else:
return 1, None, None
else:
logger.info(u'cookies 或者 token 文件缺失或损坏')
if os.path.exists(path_cookies):
os.remove(path_cookies)
if os.path.exists(path_token):
os.remove(path_token)
if password:
return login_wanpan.run(username, password)
else:
return 1, None, None
else:
logger.info(u'没有登录记录')
if os.path.exists(path_cookies):
os.remove(path_cookies)
if os.path.exists(path_token):
os.remove(path_token)
if password:
return login_wanpan.run(username, password)
else:
return 1, None, None
def phelp():
print u"""
Welcome to yundownload!
quit----------------------退出程序
cd [路径]------------------切换目录
ls -----------------------展示当前目录文件
pwd-----------------------打印当前目录
down [文件名] [下载路径]-----------下载文件至本地
?-------------------------打印此帮助信息
"""
def usage_login():
print 'Usage: manage.py -u username '
print '-p --password=password'
print '-h --help'
sys.exit(0)
def download(req, now_path, *cmd):
cmd = cmd[0] #* 变成了一个元组
if len(cmd) < 2 or len(cmd) > 3:
print cmd
print u'参数错误 down 文件名 保存目录(默认当前目录) '
return
if len(cmd) == 2:
dirname = ur'./下载/'
else:
dirname = cmd[2]
filename = cmd[1]
'''
以上参数已经是unicode编码
'''
filename = filename.encode('utf-8')
dirname = dirname.encode('utf-8')
now_path = now_path.encode('utf-8')
'''下载链接需要用utf-8编码'''
url = 'http://pcs.baidu.com/rest/2.0/pcs/file?path=' + urllib.quote(now_path + filename) + '&method=download&app_id=266719'
loading = downloader.DownLoader(req, url, dirname.decode('utf-8'), filename.decode('utf-8'))
loading.run()
return
def main():
if not os.path.exists('./session_saved'):
os.makedirs('session_saved')
if not len(sys.argv[1:]):
usage_login()
try:
opts, args = getopt.getopt(sys.argv[1:], 'hu:p:', ['help', 'username', 'password'])
except getopt.GetoptError, reason:
logger.error(reason.message)
usage_login()
username = None
password = None
for o,a in opts:
if o in ('-h', '--help'):
usage_login()
elif o in ('-u', '--username'):
username = a
elif o in ('-p', '--password'):
password = a
else:
assert False, 'Unhandled Option'
if username:
if password:
error, req, bdstoken = login(username, password)
else:
error, req, bdstoken = login(username)
else:
print 'no username'
usage_login()
while error == 1:
print u'登录失败,请重试!'
username = raw_input(u'请输入用户名'.encode(sys.stdin.encoding))
password = raw_input(u'请输入密码'.encode(sys.stdin.encoding))
error, req, bdstoken = login(username, password)
now_path = u'/'
error, content = pcs.list_dir(req, bdstoken=bdstoken, headers=config.DEFAULT_HEADERS, path=now_path) #初始环境置为根目录
while True:
catalogs = pcs.get_catalogs(content)
cmd = raw_input('[#'+now_path.encode(sys.stdout.encoding)+']>>') # 终端提示符
cmd = cmd.strip() # 去掉两端空格
cmd = cmd.decode(sys.stdin.encoding)
if '' == cmd:
continue
if 'quit' == cmd: # 键入"quit"退出程序
print 'quit'
break
cmd = re.split(r'\s+', cmd) # 分离命令生成列表
print cmd
if 'cd' == cmd[0]:
temp = now_path
temp_content = content
if cmd[1] == r'..': # 返回上一级目录
try:
now_path = now_path[:-1]
now_path = now_path[:now_path.rfind(r'/')+1]
error, content = pcs.list_dir(req, bdstoken=bdstoken, headers=config.DEFAULT_HEADERS, path=now_path)
if error is not 0:
now_path = temp
content = temp_content
print 'No such file or directory'
except:
now_path = temp
content = temp_content
print 'No such file or directory'
else:
#print catalogs
if cmd[1] in catalogs: # 进入特定目录
try:
now_path = now_path + cmd[1] + '/' #注意这里,加了/
print now_path
error, content = pcs.list_dir(req, bdstoken=bdstoken, headers=config.DEFAULT_HEADERS, path=now_path)
print error
if error is not 0:
now_path = temp
content = temp_content
print '222 No such file or directory'
except Exception, e:
logger.error(e.message)
now_path = temp
content = temp_content
print '333 No such file or directory'
else:
print '444 No such file or directory'
elif 'ls' == cmd[0]:
if catalogs:
for catalog in catalogs:
print catalog
elif 'pwd' == cmd[0]:
print now_path
elif 'down' == cmd[0]:
download(req, now_path, cmd)
elif '?' == cmd[0]:
phelp()
else:
print 'command not found'
phelp()
if __name__ == '__main__':
main()