-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathservice.py
2276 lines (2131 loc) · 106 KB
/
service.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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
'''
XBMCLocalProxy 0.1
Copyright 2011 Torben Gerkensmeyer
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.
'''
from __future__ import unicode_literals
import io
import sys
from urllib import parse
from urllib import request
from urllib import response
import http.cookiejar as cookielib
import html.entities as htmlentitydefs
from datetime import datetime
import base64
import uuid
import re
import time
import socket
import gzip
import json
import xbmc,xbmcaddon,xbmcvfs
try:
xbmc.translatePath = xbmcvfs.translatePath
except AttributeError:
pass
from threading import Semaphore
import os
import mimetypes
import shutil
import lib.comm as comm
from traceback import format_exc
from socketserver import ThreadingMixIn
from http.server import HTTPServer, BaseHTTPRequestHandler
from cgi import parse_header, parse_multipart
from Cryptodome import Random
from Cryptodome.Hash import MD5
from Cryptodome.Hash import SHA1
from Cryptodome.Cipher import PKCS1_OAEP, PKCS1_v1_5
from Cryptodome.PublicKey import RSA
__cwd__=os.path.dirname(__file__)
__lib__ = xbmc.translatePath( os.path.join( __cwd__, 'lib' ) )
sys.path.append (__lib__)
from pyhtml import *
defaultUserAgent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 115Browser/27.0.3.7'
_cookiestr=''
def encode_obj(in_obj):
def encode_list(in_list):
out_list = []
for el in in_list:
out_list.append(encode_obj(el))
return out_list
def encode_dict(in_dict):
out_dict = {}
for k, v in in_dict.items():
out_dict[k] = encode_obj(v)
return out_dict
if isinstance(in_obj, str):
return comm.ensure_binary(in_obj)
elif isinstance(in_obj, list):
return encode_list(in_obj)
elif isinstance(in_obj, tuple):
return tuple(encode_list(in_obj))
elif isinstance(in_obj, dict):
return encode_dict(in_obj)
return in_obj
class SmartRedirectHandler(request.HTTPRedirectHandler):
def http_error_301(self, req, fp, code, msg, headers):
result = request.HTTPRedirectHandler.http_error_301(
self, req, fp, code, msg, headers)
#result.status = code
return result
def http_error_302(self, req, fp, code, msg, headers):
result = request.HTTPRedirectHandler.http_error_302(
self, req, fp, code, msg, headers)
#result.status = code
return result
class PassRedirectHandler(request.HTTPRedirectHandler):
def http_error_301(self, req, fp, code, msg, headers):
infourl = response.addinfourl(fp, headers, req.get_full_url())
infourl.status = code
infourl.code = code
return infourl
def http_error_302(self, req, fp, code, msg, headers):
infourl = response.addinfourl(fp, headers, req.get_full_url())
infourl.status = code
infourl.code = code
return infourl
class api_115(object):
downcookie=''
def __init__(self, cookstr):
if cookstr=='0':
cookstr=_cookiestr
#xbmc.log(cookstr,level=xbmc.LOGERROR)
self.headers = {
'User-Agent': defaultUserAgent,
'Accept-encoding': 'gzip,deflate',
'Cookie': cookstr,
}
self.user_id=None
self.user_key=None
if self.get_userkey() is False:
xbmc.log(msg='Get userkey info failed!',level=xbmc.LOGERROR)
def urlopen(self,url, data=None,referer=None,binary=False, **args):
#url=url
reponse=''
for i in range(1,5):
try:
headers=self.headers.copy()
if 'userAgent' in args:
headers['User-Agent']=args['userAgent']
del args['userAgent']
req = request.Request(url,headers = headers)
if referer:
req.add_header('Referer', referer)
opener = request.build_opener(SmartRedirectHandler)
if data:
if type(data) == str:
data=data.encode()
rsp = opener.open(req, data=data, timeout=15)
else:
rsp = opener.open(req, timeout=15)
if rsp.info().get('Content-Encoding') == 'gzip':
reponse = gzip.GzipFile(fileobj=io.BytesIO(rsp.read())).read()
else:
reponse = rsp.read()
if not binary:
reponse=comm.ensure_text(reponse)
#xbmc.log(msg=str(rsp.headers),level=xbmc.LOGERROR)
self.downcookie=''
for key,value in rsp.headers.items():
if key.lower()=='set-cookie':
downcookies = re.findall(r'(?:[0-9abcdef]{20,}|acw_tc)\s*\x3D\s*[0-9abcdef]{20,}', value, re.DOTALL | re.MULTILINE)
for downcook in downcookies:
self.downcookie+=downcook+';'
rsp.close()
break
except Exception as e:
xbmc.log(msg=format_exc(),level=xbmc.LOGERROR)
return reponse
def jsonload(self,data):
try:
data= data.replace('\n','').replace('\r','')
data=json.loads(data[data.index('{'):])
return data
except:
return {'state':False,'error':'jsonload error'}
def gettaglist(self):
data=self.urlopen('https://webapi.115.com/label/list?user_id=&offset=0&limit=11500&sort=create_time&order=desc')
return json.loads(data[data.index('{'):])
def settag(self,fid,tag):
data = parse.urlencode({'fid': fid,'file_label':tag})
try:
data=self.urlopen('http://web.api.115.com/files/edit',data=data)
data= self.fetch(data).replace('\n','').replace('\r','')
data=json.loads(data[data.index('{'):])
return data['state']
except:
return False
def getfilelist(self,cid,offset,pageitem,star,sorttype,sortasc,typefilter='0',nf='0',search_value=''):
try:
if search_value!='' and search_value!='0':
file_label=''
match=re.search(r'^tag\s*(?P<tag>[0-9]{10,})$',search_value)
if match:
file_label=match.group('tag')
if file_label:
data=parse.urlencode({'file_label': file_label,'cid':cid,'aid':'1','limit':str(pageitem),
'o':sorttype,'asc':sortasc,'offset':str(offset),'format':'json','date':'','pick_code':'','type':typefilter,'source':''})
else:
data=parse.urlencode({'search_value': search_value,'cid':cid,'aid':'1','limit':str(pageitem),
'o':sorttype,'asc':sortasc,'offset':str(offset),'format':'json','date':'','pick_code':'','type':typefilter,'source':''})
data=self.urlopen('http://web.api.115.com/files/search?'+data)
else:
self.urlopen('https://webapi.115.com/files/order',data=parse.urlencode(encode_obj({'file_id':cid,'user_order':sorttype,'user_asc':sortasc,'fc_mix':'1'})))
data = parse.urlencode(encode_obj({'aid': '1','cid':cid,'limit':pageitem,'offset':offset,'type':typefilter,'star':star,'natsort':'1','fc_mix':'1',
'o':sorttype,'asc':sortasc,'nf':nf,'show_dir':'1','format':'json','_':str(int(time.time()))}))
if sorttype=='file_name':
data=self.urlopen('http://aps.115.com/natsort/files.php?'+data)
else:
data=self.urlopen('http://webapi.115.com/files?'+data)
return json.loads(data[data.index('{'):])
except:
xbmc.log(msg=format_exc(),level=xbmc.LOGERROR)
def getpc(self,fid):
try:
data=self.urlopen('http://web.api.115.com/category/get?aid=1&cid='+fid)
data= json.loads(data[data.index('{'):])
return data['pick_code']
except Exception as errno:
xbmc.log(msg=format_exc(),level=xbmc.LOGERROR)
return ''
def getsubtitle(self,pc):
try:
data=self.urlopen('http://webapi.115.com/movies/subtitle?pickcode=%s'%(pc))
data=json.loads(data[data.index('{'):])
if data['state']:
return data['data']['list']
except Exception as errno:
xbmc.log(msg=format_exc(),level=xbmc.LOGERROR)
def createdir(self,pid,cname):
data = parse.urlencode({'pid': pid,'cname':cname})
try:
data=self.urlopen('http://web.api.115.com/files/add',data=data)
data= json.loads(data[data.index('{'):])
return data['cid']
except Exception as errno:
xbmc.log(msg=format_exc(),level=xbmc.LOGERROR)
return ''
def copy(self,fid,cid):
data = parse.urlencode({'fid': fid,'pid':cid})
try:
data=self.urlopen('http://web.api.115.com/files/copy',data=data)
data= json.loads(data[data.index('{'):])
return data['state']
except Exception as errno:
xbmc.log(msg=format_exc(),level=xbmc.LOGERROR)
return False
def rename(self,fid,newname):
data = parse.urlencode({'fid': fid,'file_name':newname})
try:
data=self.urlopen('http://web.api.115.com/files/edit',data=data)
data= json.loads(data[data.index('{'):])
return data['state']
except Exception as errno:
xbmc.log(msg=format_exc(),level=xbmc.LOGERROR)
return False
def batchrename(self,namedict):
newnames={}
for key,value in namedict.items():
newnames['files_new_name[%s]'%key]=value
data = parse.urlencode(newnames)
try:
data=self.urlopen('https://webapi.115.com/files/batch_rename',data=data)
data= json.loads(data[data.index('{'):])
return data['state']
except Exception as errno:
xbmc.log(msg=format_exc(),level=xbmc.LOGERROR)
return False
def batchcidrename(self,cid,oldnewnames):
namedict={}
files=[]
self.getallfiles(cid,files)
for f in files:
if f['n'] in oldnewnames:
namedict[f['fid']]=oldnewnames[f['n']]
self.batchrename(namedict)
def getallfiles(self,cid,files):
data=self.getfilelist(cid=cid,offset=0,pageitem=1150,star='0',sorttype='user_utime',sortasc='0')
if 'data' in data:
resp = data['data']
for d in resp:
if 'fid' in d:
files.append(d)
elif 'pid' in d:
cid=d['cid']
self.getallfiles(cid,files)
def countfiles(self,cid):
try:
data=self.urlopen('https://webapi.115.com/category/get?cid=%s'%(cid))
data= json.loads(data[data.index('{'):])
return int(data['count'])
except Exception as errno:
xbmc.log(msg=format_exc(),level=xbmc.LOGERROR)
def pathdeep(self,cid):
try:
data=self.urlopen('https://webapi.115.com/category/get?cid=%s'%(cid))
data= json.loads(data[data.index('{'):])
return int(len(data['paths']))
except Exception as errno:
xbmc.log(msg=format_exc(),level=xbmc.LOGERROR)
def delete(self,fids):
data={'pid':0}
i=0
for fid in fids:
data['fid['+str(i)+']']=fid
i+=1
data = parse.urlencode(data)
try:
data=self.urlopen('http://web.api.115.com/rb/delete',data=data)
data= json.loads(data[data.index('{'):])
return data['state']
except Exception as errno:
xbmc.log(msg=format_exc(),level=xbmc.LOGERROR)
return ''
def get_userkey(self):
try:
data=self.urlopen('http://proapi.115.com/app/uploadinfo')
data= json.loads(data[data.index('{'):])
self.user_id=str(data['user_id'])
self.user_key=str(data['userkey']).upper()
except Exception as errno:
xbmc.log(msg=format_exc(),level=xbmc.LOGERROR)
return False
def get_preid(self,pc):
try:
file_url=self.getfiledownloadurl(pc)
xbmc.log(msg='file_url:'+file_url,level=xbmc.LOGERROR)
filedownloadurl=downcookie=''
if file_url.find('|')>0:
filedownloadurl,downcookie=file_url.split('|')
else:
filedownloadurle=file_url
reqheaders={}
reqheaders['User-Agent']=defaultUserAgent
reqheaders['Referer']='https://115.com/?cid=0&offset=0&mode=wangpan'
reqheaders['Cookie']=self.headers['Cookie']+';'+downcookie+';'
reqheaders['Range']='bytes=0-131071';
req = request.Request(filedownloadurl, headers=reqheaders)
response=None
preid=''
opener = request.build_opener(SmartRedirectHandler)
rsp = opener.open(req, timeout=15)
if rsp.info().get('Content-Encoding') == 'gzip':
reponse = gzip.GzipFile(fileobj=io.BytesIO(rsp.read())).read()
else:
reponse = rsp.read()
sha = SHA1.new()
sha.update(bytes(reponse))
preid = sha.hexdigest()
return preid.upper()
except Exception as errno:
xbmc.log(msg=format_exc(),level=xbmc.LOGERROR)
return ''
def import_file_with_sha1(self,preid,fileid,filesize,filename,cid,tm):
target='U_1_'+str(cid)
#tm=str(int(time.time()))+'000'
#tm='16649927390000'
xbmc.log(msg="tm:"+tm,level=xbmc.LOGERROR)
sha=SHA1.new()
sha.update( str.encode(self.user_id+fileid+ fileid +target+'0'))
s1 = sha.hexdigest()
xbmc.log(msg="s1:"+s1,level=xbmc.LOGERROR)
s2=self.user_key+s1+"000000"
sha=SHA1.new()
sha.update(str.encode(s2))
sig=sha.hexdigest().upper()
xbmc.log(msg="sig:"+sig,level=xbmc.LOGERROR)
useridmd5 = MD5.new()
useridmd5.update(self.user_id.encode())
struidmd5=useridmd5.hexdigest()
xbmc.log(msg="useridmd5:"+struidmd5,level=xbmc.LOGERROR)
tokenmd5 = MD5.new()
appVersion = "25.2.0"
tokenstr = "Qclm8MGWUv59TnrR0XPg" +fileid +str(filesize)+ preid + self.user_id + tm + struidmd5 +appVersion;
tokenmd5.update(tokenstr.encode())
token=tokenmd5.hexdigest()
xbmc.log(msg="token:"+token,level=xbmc.LOGERROR)
url=("http://uplb.115.com/3.0/initupload.php?rt=0&topupload=0&isp=0&appid=0&appversion=%s&format=json&sig=%s&token=%s&t=%s")%(appVersion,sig,token,tm)
postData=('preid=%s&fileid=%s&quickid=%s&app_ver=%s&filename=%s&filesize=%s&exif=&target=%s&userid=%s')%(preid,fileid,fileid,appVersion,filename,filesize,target,self.user_id)
try:
data=self.urlopen(url,data=postData)
data= json.loads(data[data.index('{'):])
if data['status']==2 and data['statuscode']==0:
return True
else:
xbmc.log(msg=filename+' upload failed.',level=xbmc.LOGERROR)
return False
except Exception as errno:
xbmc.log(msg=format_exc(),level=xbmc.LOGERROR)
return False
def exportfid(self,name,length,sha1,pc):
fidsha1=''
try:
preid=self.get_preid(pc)
fidsha1='115://'+name+'|'+length+'|'+sha1+'|'+preid;
except Exception as e:
xbmc.log(msg=format_exc(),level=xbmc.LOGERROR)
return fidsha1
def exportcid(self,outlist,cid,pathdeep=0):
data=self.getfilelist(cid=cid,offset=0,pageitem=1150,star='0',sorttype='user_utime',sortasc='0')
paths=''
pathlist=[]
if 'path' in data:
for item in data['path']:
pathlist.append(item['name'])
if len(pathlist)>=pathdeep:
pathlist=pathlist[pathdeep:]
paths='|'.join(pathlist)
if 'data' in data:
resp = data['data']
for d in resp:
if 'fid' in d:
fidsha1=self.exportfid(d['n'],str(d['s']),d['sha'],d['pc'])
if paths!='':
fidsha1=fidsha1+'|'+paths
outlist.append(fidsha1)
elif 'pid' in d:
cid=d['cid']
self.exportcid(outlist,cid,pathdeep)
def url_is_alive(self,url):
try:
rspcode=0
req = request.Request(url,headers = self.headers)
req.get_method = lambda : 'HEAD'
req.add_header('keep_alive','false')
opener = request.build_opener(SmartRedirectHandler)
rsp = opener.open(req, timeout=15)
rspcode=str(rsp.code)
rsp.close()
return rspcode=='200'
except:
xbmc.log(msg=format_exc(),level=xbmc.LOGERROR)
return False
def notecatelist(self):
data=self.urlopen('https://note.115.com/?ct=note&ac=cate&has_picknews=1')
return self.jsonload(data)
def noteaddcate(self,cname):
data = parse.urlencode(encode_obj({'cname': cname,'up_key':'tn__%d_0'%(int(time.time()))}))
data=self.urlopen('https://note.115.com/?ct=note&ac=addcate',data=data)
return self.jsonload(data)
def notegetcateid(self,cname):
cid=0
data=self.notecatelist()
if data['state'] and data['data']:
for cate in data['data']:
if cate['cname']==cname:
cid=int(cate['cid'])
break
if cid==0:
data = self.noteaddcate(cname)
if data['state']:
cid=int(data['data']['cid'])
return cid
def notesave(self,cid,nid,title,content):
data = parse.urlencode(encode_obj({'cid': cid,'nid':nid,'subject':title,'content':content,'is_html':0,'toc_ids':''}))
data = self.urlopen('https://note.115.com/?ct=note&ac=save',data=data)
return self.jsonload(data)
def notelist(self,cid,start):
data = parse.urlencode(encode_obj({'ct':'note','page_size':90,'has_picknews':1,'cid': cid,'keyword':'','start':start,'_':int(time.time())}))
data = self.urlopen('https://note.115.com/?'+data)
return self.jsonload(data)
def notedelete(self,nid):
data = parse.urlencode(encode_obj({'nid': nid}))
data = self.urlopen('https://note.115.com/?ct=note&ac=delete',data=data)
return self.jsonload(data)
def notedetail(self,nid):
data = parse.urlencode(encode_obj({'ct': 'note','nid':nid,'ac':'detail'}))
data = self.urlopen('https://note.115.com/?'+data)
return self.jsonload(data)
def notegetcontent(self,cname,notetitle):
content=''
cid=self.notegetcateid(cname)
data=self.notelist(cid=cid,start=0)
nid=0
if data['state'] and data['data']:
for note in data['data']:
if note['title']==notetitle:
nid=int(note['nid'])
break
if nid:
data = self.notedetail(nid)
if data['state']:
content=data['data']['content']
return content
def notegetpcurl(self,pc):
content=''
cid=self.notegetcateid('pickcodeurl')
data=self.notelist(cid=cid,start=0)
nid=0
nidolds=''
if data['state'] and data['data']:
for note in data['data']:
#xbmc.log(msg='zzzzz: %s %s %d %d'%(pc,note['title'],int(time.time()) , int(note['update_time'])),level=xbmc.LOGERROR)
if (int(time.time()) - int(note['update_time']))>6*3600:
nidolds+=note['nid']+','
else:
if note['title']==pc:
nid=int(note['nid'])
break
if nidolds:
self.notedelete(nidolds)
if nid:
data = self.notedetail(nid)
if data['state']:
content=data['data']['content']
return content
def notesavecontent(self,cname,notetitle,content):
state=False
cid=self.notegetcateid(cname)
data=self.notelist(cid=cid,start=0)
nid=0
if data['state'] and data['data']:
for note in data['data']:
if note['title']==notetitle:
nid=int(note['nid'])
break
data = self.notesave(cid=cid,nid=nid,title=notetitle,content=content)
state = data['state']
return state
def notedeleteolds(self,cname):
state=False
cid=self.notegetcateid(cname)
data=self.notelist(cid=cid,start=90)
nids=''
if data['state'] and data['data']:
for note in data['data']:
nids=nids+note['nid']+','
if nids:
data = self.notedelete(nid=nids)
state = data['state']
return state
g_kts = [240, 229, 105, 174, 191, 220, 191, 138, 26, 69, 232, 190, 125, 166, 115, 184, 222, 143, 231, 196, 69, 218, 134, 196, 155, 100, 139, 20, 106, 180, 241, 170, 56, 1, 53, 158, 38, 105, 44, 134, 0, 107, 79, 165, 54, 52, 98, 166, 42, 150, 104, 24, 242, 74, 253, 189, 107, 151, 143, 77, 143, 137, 19, 183, 108, 142, 147, 237, 14, 13, 72, 62, 215, 47, 136, 216, 254, 254, 126, 134, 80, 149, 79, 209, 235, 131, 38, 52, 219, 102, 123, 156, 126, 157, 122, 129, 50, 234, 182, 51, 222, 58, 169, 89, 52, 102, 59, 170, 186, 129, 96, 72, 185, 213, 129, 156, 248, 108, 132, 119, 255, 84, 120, 38, 95, 190, 232, 30, 54, 159, 52, 128, 92, 69, 44, 155, 118, 213, 27, 143, 204, 195, 184, 245]
g_key_s = [0x29, 0x23, 0x21, 0x5E]
g_key_l = [120, 6, 173, 76, 51, 134, 93, 24, 76, 1, 63, 70]
def m115_getkey(self,length,key):
if key != '':
results = []
for i in range(length):
v1=(key[i] + self.g_kts[length * i])&(0xff)
v2=self.g_kts[length * (length - 1 - i)]
results.append(v1^v2)
return results
if length == 12:
return self.g_key_l
else:
return self.g_key_s
def xor115_enc(self, src, srclen, key, keylen):
ret = []
mod4 = srclen % 4
for i in range(mod4):
ret.append(src[i] ^ key[i % keylen])
for i in range(srclen-mod4):
ret.append(src[i+mod4] ^ key[i % keylen])
return ret
def m115_sym_encode(self,src, srclen, key1, key2):
#plugin.log.error('%d %d %d %d %d %d...%d %d'%(src[0],src[1],src[2],src[3],src[4],src[5],src[30],src[31]))
k1 = self.m115_getkey(4, key1)
#plugin.log.error(len(k1))
#plugin.log.error('%d %d ...%d %d'%(k1[0],k1[1],k1[2],k1[3]))
k2 = self.m115_getkey(12, key2)
#plugin.log.error(len(k2))
#plugin.log.error('%d %d ...%d %d'%(k2[0],k2[1],k2[10],k2[11]))
ret = self.xor115_enc(src, srclen, k1, 4)
ret.reverse();
ret = self.xor115_enc(ret, srclen, k2, 12)
#plugin.log.error(len(ret))
#plugin.log.error('%d %d %d %d %d %d...%d %d'%(ret[0],ret[1],ret[2],ret[3],ret[4],ret[5],ret[30],ret[31]))
return ret;
def m115_sym_decode(self,src, srclen, key1, key2):
k1 = self.m115_getkey(4, key1)
#plugin.log.error('k1:%d %d %d %d'%(k1[0],k1[1],k1[2],k1[3]))
k2 = self.m115_getkey(12, key2)
ssss=0
# for ss in k2:
# plugin.log.error('k2:%d:%d'%(ssss,ss))
# ssss+=1
ret = self.xor115_enc(src, srclen, k2, 12)
ssss=0
# for ss in ret:
# plugin.log.error('ret1:%d:%d'%(ssss,ss))
# ssss+=1
ret.reverse()
ret = self.xor115_enc(ret, srclen, k1, 4)
return ret
n=0x8686980c0f5a24c4b9d43020cd2c22703ff3f450756529058b1cf88f09b8602136477198a6e2683149659bd122c33592fdb5ad47944ad1ea4d36c6b172aad6338c3bb6ac6227502d010993ac967d1aef00f0c8e038de2e4d3bc2ec368af2e9f10a6f1eda4f7262f136420c07c331b871bf139f74f3010e3c4fe57df3afb71683
e=0x10001
def rsa_encrypt(self, bsrc):
pretemp=bytearray(128-len(bsrc))
for i in range(len(pretemp)):
pretemp[i]=0xff
pretemp[0]=0x00
pretemp[1]=0x02
pretemp[len(pretemp)-1]=0x00
pretemp.extend(bsrc)
isrc=int.from_bytes(pretemp,'big')
ienc=pow(isrc,self.e,self.n)
return ienc.to_bytes(128, 'big')
def rsa_decrypt(self,bsrc):
isrc=int.from_bytes(bsrc,'big')
idec=pow(isrc,self.e,self.n)
bdec=idec.to_bytes(128, 'big')
index00=bdec[1:].index(0x00)
return bdec[index00+2:]
def m115_asym_encode(self,src, srclen):
m = 128 - 11
ret = bytearray()
for i in range(int((srclen + m - 1) / m)):
bsrc=bytes(src[i*m:i*m+m])
#plugin.log.error(len(bsrc))
#plugin.log.error('%s %s ...%s %s'%(bsrc[0],bsrc[1],bsrc[30],bsrc[31]))
#rettemp=self.pcipher.encrypt(bsrc)
#rettemp=self.cipher.encrypt(bsrc)
rettemp=self.rsa_encrypt(bsrc)
#plugin.log.error(len(rettemp))
ret.extend(rettemp);
#ret += base64.b64decode(rettemp);
ret = base64.b64encode(ret)
return ret
def m115_asym_decode(self,src, srclen):
m = 128
#plugin.log.error(srclen)
ret = bytearray()
for i in range(int((srclen + m - 1) / m)):
rettemp=bytes(src[i*m:i*m+m])
#dsize = SHA.digest_size
#sentinel = Random.new().read(16+dsize)
#message=self.scipher.decrypt(rettemp,'')
#message=self.cipher.decrypt(rettemp,'')
message=self.rsa_decrypt(rettemp)
#message=self.scipher.decrypt(rettemp,sentinel)
#digest = SHA.new(message[:-dsize]).digest()
#if digest==message[-dsize:]: # Note how we DO NOT look for the sentinel
# plugin.log.error("Encryption was correct.")
#else:
# plugin.log.error("Encryption was not correct.")
ret.extend(message)
#ssss=0
#for ss in ret:
# plugin.log.error('%d:%d'%(ssss,ord(ss)))
# ssss+=1
return ret
def m115_encode(self,src, tm):
#plugin.log.error(src)
key = MD5.new()
#plugin.log.error(b'tm=%s'%tm)
key.update(('!@###@#%sDFDR@#@#'%tm).encode())
bkey = bytearray()
bkey.extend( key.hexdigest().encode())
#plugin.log.error(len(bkey))
#plugin.log.error(key.hexdigest())
#plugin.log.error('%d %d ...%d %d'%(bkey[0],bkey[1],bkey[30],bkey[31]))
bsrc = bytearray()
bsrc.extend(src.encode())
#plugin.log.error(bsrc)
tmp = self.m115_sym_encode(bsrc, len(bsrc),bkey, '')
tmp2 = bkey[0:16]
tmp2.extend(tmp)
#plugin.log.error(len(tmp2))
#plugin.log.error('%d %d %d %d %d %d...%d %d...%d %d'%(tmp2[0],tmp2[1],tmp2[2],tmp2[3],tmp2[4],tmp2[5],tmp2[30],tmp2[31],tmp2[46],tmp2[47]))
return {
'data': self.m115_asym_encode(tmp2, len(tmp2)),'key':key.hexdigest()
}
def m115_decode(self,src, key):
bkey1 = bytearray()
bkey1.extend(key.encode())
#plugin.log.error('%d %d ...%d %d'%(bkey1[0],bkey1[1],bkey1[30],bkey1[31]))
tmp = base64.b64decode(src)
bsrc = bytearray()
bsrc.extend(tmp)
tmp = self.m115_asym_decode(bsrc, len(bsrc))
#plugin.log.error('ch=%s'%len(tmp))
bkey2 = bytearray()
bkey2.extend(tmp[0:16])
#plugin.log.error('key2=%s'%tmp[0:16])
bsrc2 = bytearray()
bsrc2.extend(tmp[16:])
return self.m115_sym_decode(bsrc2, len(tmp) - 16, bkey1,bkey2)
def getfiledownloadurl(self,pc):
result = ''
tm = str((int(int(time.time()))))
data=self.urlopen("https://webapi.115.com/files/download?pickcode="+pc+"&_="+tm)
data= self.jsonload(data)
if data['state']:
result=data['file_url']+'|'+self.downcookie
if not result:
content=self.notegetpcurl(pc=pc)
if content:
result=content
if not result:
pcencode = self.m115_encode((json.dumps({'pickcode': pc})).replace(' ',''),tm)
data=self.urlopen('http://proapi.115.com/app/chrome/downurl?t='+tm,data=parse.urlencode({'data':pcencode['data']}))
jsondata = json.loads(data[data.index('{'):])
if jsondata['state'] != True:
return ''
decodetmp=self.m115_decode(jsondata['data'], pcencode['key'])
bdecode = bytearray()
bdecode.extend(decodetmp)
jsondata = json.loads(bdecode.decode())
jsondata=jsondata[list(jsondata.keys())[0]]
if 'url' in jsondata:
result = jsondata['url']['url']+'|'+self.downcookie
self.notesavecontent(cname='pickcodeurl',notetitle=pc,content=result)
#xbmc.log('url_return '+result,level=xbmc.LOGERROR)
return result
def oldgetfiledownloadurl(self,pc):
bad_server = ''
result = ''
try:
data=self.urlopen('https://webapi.115.com/files/download?pickcode='+pc+'&_='+str(int(time.time())))
data= json.loads(data[data.index('{'):])
if data['state']:
result=data['file_url']
else:
data=self.urlopen('http://proapi.115.com/app/chrome/down?method=get_file_url&pickcode='+pc)
data= json.loads(data[data.index('{'):])
if data['state']:
for value in data['data'].values():
if 'url' in value:
result = value['url']['url']
break
else:
return ''
#xbmc.executebuiltin('XBMC.Notification('%s', '%s', '%s', '%s')' %(result, '', 5000, ''))
return result+'|'+self.downcookie
except Exception as errno:
xbmc.log(msg=format_exc(),level=xbmc.LOGERROR)
return ''
def coversrttovtt(self,srturl):
try:
srtcontent=self.urlopen(srturl)
dictsrt={
'sourceFormat': 'AutoDetect',
'targetFormat': 'Vtt',
'timeShiftBy': '+0.0',
'timeShiftAfter': '0.0',
'writeHours': True,
'vttStartCounter': '',
'maxCharactersPerLine': '',
'input': srtcontent,
}
jsonsrt=json.dumps(dictsrt)
data=parse.urlencode({'tool':'subtitle-subtitle-converter','parameters':jsonsrt})
data=self.urlopen('https://toolslick.com/api/process',data=data)
data= json.loads(data[data.index('{'):])
return data['subtitle']
except Exception as errno:
xbmc.log(msg=format_exc(),level=xbmc.LOGERROR)
return ''
class MyHandler(BaseHTTPRequestHandler):
#文件块读取大小
blockSize=1024*1024*16
#每文件最大访问线程数
accessThreadNum=2
#文件下载地址
fidDownloadurl={}
#文件下载线程计数器
fidSemaphores={}
#文件大小
fileSize={}
def handle(self):
try:
BaseHTTPRequestHandler.handle(self)
except socket.error:
pass
def handle_one_request(self):
try:
self.raw_requestline = self.rfile.readline(65536*1024+1)
if len(self.raw_requestline) > 65536*1024:
self.requestline = ''
self.request_version = ''
self.command = ''
self.send_error(414)
return
if not self.raw_requestline:
self.close_connection = 1
return
if not self.parse_request():
# An error code has been sent, just exit
return
mname = 'do_' + self.command
if not hasattr(self, mname):
self.send_error(501, 'Unsupported method (%r)' % self.command)
return
method = getattr(self, mname)
#xbmc.log('before call do_Get')
method()
#add debug info close
#xbmc.log('after call do_Get')
if not self.wfile.closed:
self.wfile.flush() #actually send the response if not already done.
except socket.timeout as errno:
#a read or a write timed out. Discard this connection
self.log_error('Request timed out: %r', errno)
self.close_connection = 1
return
'''
Serves a HEAD request
'''
def do_HEAD(s):
xbmc.log( 'XBMCLocalProxy: Serving HEAD request...')
s.answer_request(0)
'''
Serves a GET request.
'''
def do_GET(s):
xbmc.log( 'XBMCLocalProxy: Serving GET request...')
s.answer_request(1)
def parse_POST(s):
ctype, pdict = parse_header(s.headers['content-type'])
if ctype == 'multipart/form-data':
postvars = parse_multipart(s.rfile, pdict)
elif ctype == 'application/x-www-form-urlencoded':
length = int(s.headers['content-length'])
postvars = parse.parse_qs(
s.rfile.read(length).decode ('utf-8'),
keep_blank_values=True)
else:
postvars = {}
return postvars
def do_POST(s):
postvars = s.parse_POST()
s.answer_request(1,postvars)
def convert_relative_to_absolute(s,m3u8_content, base_url):
lines = m3u8_content.split('\n')
absolute_lines = []
for line in lines:
if line.startswith('#') or line.strip() == '':
# Skip comments and empty lines
absolute_lines.append(line)
else:
absolute_url = parse.urljoin(base_url, line)
m3uurl='/mp2t?'+parse.urlencode(encode_obj({'url': absolute_url}))
absolute_lines.append(m3uurl)
return '\n'.join(absolute_lines)
def answer_request(s, sendData,postvars={}):
try:
urlsp=parse.urlparse(s.path)
scheme=urlsp.scheme
netloc=urlsp.netloc
request_path=urlsp.path
requestedWith=''
for key in s.headers:
if key.lower()=='x-requested-with':
requestedWith= s.headers[key]
if request_path=='/stop':
sys.exit()
elif request_path=='/version':
s.send_response(200)
s.end_headers()
t = html(
head(
title('WEB115 VERSION'),
link(rel='stylesheet',href='/css/styles.css')
),
body(
xbmcaddon.Addon().getAddonInfo('name')+' is Running',
br(),
'Version: '+xbmcaddon.Addon().getAddonInfo('version')
)
)
s.wfile.write( comm.ensure_binary(t.render()))
elif request_path[0:4]=='/djs':
try:
(url,name)=request_path[5:].split('/')
name=name[:name.index('.json')]
dictvideo={
'encodings':[
{
'name':'h264',
'videoSources':[
{
'resolution':'scode',
'url':parse.unquote_plus(url)
}
]
}
],
'title':name,
'id': 999
}
jsonvideo = json.dumps(dictvideo)
debugstr='''{
'id': 100,
'title': '%s',
'encodings': [{
'name': 'h264',
'videoSources': [{
'resolution': 1080,
'height': 1920,
'width': 3840,
'url': '%s'
}, ]
}
]
}
'''%(name,parse.unquote_plus(url))
s.send_response(200)
#s.send_header('Content-Length', len(jsonvideo))
s.send_header('Content-Length', len(debugstr))
s.send_header('Keep-Alive', 'timeout=5, max=100')
s.send_header('Connection', 'Keep-Alive')
s.send_header('Content-Type', 'application/json')
s.end_headers()
#s.wfile.write(jsonvideo)
s.wfile.write(debugstr)
except Exception as errno:
xbmc.log(msg=format_exc(),level=xbmc.LOGERROR)
elif request_path[0:4]=='/deo':
try:
qs=parse.parse_qs(urlsp.query, keep_blank_values=True)
url=qs.get('url',['0'])[0]
name=qs.get('title',['0'])[0]
mimetype=qs.get('mimetype',['0'])[0]
s.send_response(200)
playhtml='''
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<link rel='stylesheet' type='text/css' href='https://s3.deovr.com/version/1/css/styles.css' />
<title>DEOVR</title>
</head>
<body>
<div>
<deo-video format='LR' angle='180' title='%s' >