shareUserPermission.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from django.core import serializers
  4. import traceback, simplejson as json
  5. from django.views.generic.base import View
  6. from django.core.exceptions import FieldError
  7. from django.views.decorators.csrf import csrf_exempt
  8. from django.utils.decorators import method_decorator
  9. from Model.models import Device_User, Device_Info, Role
  10. from Service.CommonService import CommonService
  11. from Object.ResponseObject import ResponseObject
  12. from Object.TokenObject import TokenObject
  13. class searchUserView(View):
  14. @method_decorator(csrf_exempt)
  15. def dispatch(self, *args, **kwargs):
  16. return super(searchUserView, self).dispatch(*args, **kwargs)
  17. def post(self, request, *args, **kwargs):
  18. request.encoding = 'utf-8'
  19. fieldDict = request.POST
  20. return self.searchUser(fieldDict, args, kwargs)
  21. def get(self, request, *args, **kwargs):
  22. request.encoding = 'gb2312'
  23. fieldDict = request.GET
  24. return self.searchUser(fieldDict, args, kwargs)
  25. def searchUserSQL(self, fieldDict, response, *args, **kwargs):
  26. exact = fieldDict.get('exact', True)
  27. if exact == '0' or exact == 'False':
  28. exact = False
  29. else:
  30. exact = True
  31. if 'exact' in fieldDict.keys():
  32. fieldDict.pop('exact')
  33. try:
  34. if exact == 'True' or exact == 1:
  35. User = Device_User.objects.filter(**fieldDict).order_by('-data_joined')
  36. elif exact == 'False' or exact == 0:
  37. if 'username' in fieldDict.keys():
  38. User = Device_User.objects.filter(username=fieldDict.get('username',
  39. None)).order_by('-data_joined')
  40. elif 'userEmail' in fieldDict.keys():
  41. User = Device_User.objects.filter(userEmail=fieldDict.get('userEmail',
  42. None)).order_by('-data_joined')
  43. elif 'userID' in fieldDict.keys():
  44. User = Device_User.objects.filter(userID=fieldDict.get('userID',
  45. None)).order_by('-data_joined')
  46. else:
  47. User = Device_User.objects.filter(**fieldDict).order_by('-data_joined')
  48. else:
  49. User = Device_User.objects.filter(**fieldDict).order_by('-data_joined')
  50. except FieldError:
  51. return response.json(502)
  52. except Exception as e:
  53. errorInfo = traceback.format_exc()
  54. print('查询数据库错误: %s' % errorInfo)
  55. return response.json(500, {'details': repr(e)})
  56. else:
  57. if User:
  58. ddUser = User[0].device_info_set.all()
  59. sqlJSON = serializers.serialize('json', User)
  60. sqlList = json.loads(sqlJSON)
  61. if ddUser:
  62. sqlJSON1 = serializers.serialize('json', ddUser)
  63. sqlList1 = json.loads(sqlJSON1)
  64. device_Info_dict = {}
  65. device_Info_list = []
  66. for eachJson1 in sqlList1:
  67. device_Info_dict['primaryUserID'] = eachJson1['fields']['primaryUserID']
  68. device_Info_dict['Type'] = eachJson1['fields']['Type']
  69. device_Info_dict['UID'] = eachJson1['fields']['UID']
  70. device_Info_dict['pk'] = eachJson1['pk']
  71. device_Info_dict['NickName'] = eachJson1['fields']['NickName']
  72. device_Info_dict['View_Password'] = eachJson1['fields']['View_Password']
  73. device_Info_dict['View_Account'] = eachJson1['fields']['View_Account']
  74. device_Info_dict['Online'] = eachJson1['fields']['Online']
  75. device_Info_dict['EventNotification'] = eachJson1['fields']['EventNotification']
  76. device_Info_dict['ChannelIndex'] = eachJson1['fields']['ChannelIndex']
  77. device_Info_dict['EventNotification'] = eachJson1['fields']['EventNotification']
  78. device_Info_dict['NotificationMode'] = eachJson1['fields']['NotificationMode']
  79. device_Info_list.append(device_Info_dict)
  80. device_Info_dict = {}
  81. sqlList[0]['device_info'] = device_Info_list
  82. sqlDict = dict(zip(["datas"], [sqlList]))
  83. return response.json(0, sqlDict)
  84. else:
  85. return response.json(102)
  86. def searchUserPCSQL(self, fieldDict, response):
  87. try:
  88. page = int(fieldDict['page'])
  89. line = int(fieldDict['line'])
  90. fieldDict.pop('page')
  91. fieldDict.pop('line')
  92. fieldDict.pop('type')
  93. if len(fieldDict) > 0:
  94. searchCondition = CommonService.get_kwargs(data=fieldDict)
  95. device_user_queryset = Device_User.objects.filter(**searchCondition).order_by('-data_joined')
  96. else:
  97. device_user_queryset = Device_User.objects.all().order_by('-data_joined')
  98. except FieldError:
  99. return response.json(502)
  100. except Exception as e:
  101. errorInfo = traceback.format_exc()
  102. print('查询数据库错误: %s' % errorInfo)
  103. return response.json(500, {"details": repr(e)})
  104. else:
  105. if device_user_queryset:
  106. device_user_count = device_user_queryset.count()
  107. device_user_res = device_user_queryset[(page - 1) * line:page * line]
  108. sqlDict = CommonService.qs_to_dict(device_user_res)
  109. for k, v in enumerate(sqlDict["datas"]):
  110. for val in device_user_res:
  111. if v['pk'] == val.userID:
  112. device_info_query_set = val.device_info_set.all()
  113. device_info_list = CommonService.qs_to_dict(device_info_query_set)
  114. # device_user关联到device_info
  115. sqlDict["datas"][k]['device_info'] = device_info_list
  116. if len(v['fields']['role']) > 0:
  117. role_query_set = Role.objects.get(rid=v['fields']['role'][0])
  118. sqlDict["datas"][k]['fields']['role'].append(role_query_set.roleName)
  119. sqlDict['count'] = device_user_count
  120. return response.json(0, sqlDict)
  121. else:
  122. return response.json(0, {"datas": ""})
  123. def searchUser(self, fieldDict, *args, **kwargs):
  124. response = ResponseObject()
  125. token = fieldDict.get('token', None)
  126. if token != None:
  127. tko = TokenObject(token)
  128. tko.valid()
  129. response.lang = tko.lang
  130. if tko.code == 0:
  131. fieldDict = fieldDict.dict()
  132. fieldDict.pop('token')
  133. type = fieldDict.get('type', None)
  134. if type == 'PC':
  135. return self.searchUserPCSQL(fieldDict, response)
  136. else:
  137. return self.searchUserSQL(fieldDict, response, args, kwargs)
  138. else:
  139. return response.json(tko.code)
  140. else:
  141. return response.json(444)
  142. class shareUserEquipmentView(View):
  143. @method_decorator(csrf_exempt)
  144. def dispatch(self, *args, **kwargs):
  145. return super(shareUserEquipmentView, self).dispatch(*args, **kwargs)
  146. def post(self, request, *args, **kwargs):
  147. request.encoding = 'utf-8'
  148. queryDict = request.POST
  149. return self.shareUser(queryDict, args, kwargs)
  150. def get(self, request, *args, **kwargs):
  151. request.encoding = 'gb2312'
  152. queryDict = request.GET
  153. return self.shareUser(queryDict, args, kwargs)
  154. def shareUser(self, queryDict, *args, **kwargs):
  155. token = queryDict.get('token', None)
  156. GuestID = queryDict.get('guestID', None)
  157. content = queryDict.get('content', None)
  158. sharedAll = queryDict.get('sharedAll', False)
  159. if sharedAll in ('1', '0'):
  160. sharedAll = bool(int(sharedAll))
  161. elif sharedAll in ('true', 'false'):
  162. if sharedAll == 'true':
  163. sharedAll = 1
  164. else:
  165. sharedAll = 0
  166. response = ResponseObject()
  167. if token != None and GuestID != None:
  168. tko = TokenObject(token)
  169. tko.valid()
  170. response.lang = tko.lang
  171. if tko.code == 0:
  172. MasterID = tko.userID
  173. if sharedAll and MasterID != None:
  174. return self.shareUserSQL(MasterID, GuestID, True, response, args, kwargs)
  175. if content != None and MasterID != None:
  176. return self.shareUserSQL(MasterID, GuestID, False, response, args, content=content)
  177. else:
  178. return response.json(804)
  179. else:
  180. return response.json(tko.code)
  181. else:
  182. return response.json(800)
  183. def shareUserSQL(self, MasterID, GuestID, sharedAll, response, *args, **kwargs):
  184. try:
  185. Guest = Device_User.objects.filter(userID=GuestID).order_by('-data_joined')
  186. Master = Device_Info.objects.filter(userID_id=MasterID).order_by('-data_joined')
  187. except Exception as e:
  188. errorInfo = traceback.format_exc()
  189. print('查询数据库错误: %s' % errorInfo)
  190. return response.json(500, {"details": repr(e)})
  191. else:
  192. if Master:
  193. if Guest:
  194. querysetList = []
  195. dictLen = 0
  196. if sharedAll:
  197. for equipment in Master:
  198. eqDict = equipment.model_to_dict(exclude=['id', 'data_joined', 'primaryUserID'])
  199. shareEquipment = Device_Info.objects.filter(userID_id=GuestID, primaryUserID= \
  200. MasterID, UID=eqDict.get('UID', None)).order_by('-data_joined')
  201. if shareEquipment:
  202. dictLen += 1
  203. continue
  204. else:
  205. eqDict['primaryUserID'] = eqDict.pop('userID')
  206. eqDict['isShare'] = True
  207. eqDict['userID_id'] = GuestID
  208. eqDict['id'] = CommonService.getUserID(getUser=False)
  209. querysetList.append(Device_Info(**eqDict))
  210. else:
  211. content = kwargs.get('content', None)
  212. if content != None:
  213. contentDict = json.loads(content)
  214. uidlist = UID = contentDict.get('UID', None)
  215. print(uidlist)
  216. for equipment in Master:
  217. eqDict = equipment.model_to_dict(exclude=['id', 'data_joined', 'primaryUserID'])
  218. if eqDict['UID'] in uidlist:
  219. UID.remove(eqDict['UID'])
  220. shareEquipment = Device_Info.objects.filter(userID_id=GuestID, primaryUserID= \
  221. MasterID, UID=eqDict.get('UID', None)).order_by('-data_joined')
  222. if shareEquipment:
  223. dictLen += 1
  224. else:
  225. eqDict['primaryUserID'] = eqDict.pop('userID')
  226. eqDict['isShare'] = True
  227. eqDict['userID_id'] = GuestID
  228. eqDict['id'] = CommonService.getUserID(getUser=False)
  229. querysetList.append(Device_Info(**eqDict))
  230. else:
  231. continue
  232. if len(querysetList) == 0:
  233. if sharedAll:
  234. return response.json(160)
  235. else:
  236. if len(UID) > 0:
  237. return response.json(160, {'error_UID': UID})
  238. else:
  239. return response.json(160)
  240. else:
  241. try:
  242. equipmentCount = Device_Info.objects.bulk_create(querysetList)
  243. except Exception as e:
  244. errorInfo = traceback.format_exc()
  245. print('添加数据库记录错误: %s' % errorInfo)
  246. return response.json(500, {"details": repr(e)})
  247. else:
  248. if dictLen > 0:
  249. return response.json(0, {
  250. 'Shared': dictLen,
  251. 'Sharing': len(querysetList),
  252. 'errormsg': u'A part of the equipment has been shared!',
  253. })
  254. else:
  255. if sharedAll:
  256. return response.json(0, {
  257. 'Sharing': len(querysetList)
  258. })
  259. else:
  260. if len(UID) > 0:
  261. return response.json(0, {
  262. 'error_UID': UID,
  263. 'Sharing': len(querysetList),
  264. })
  265. else:
  266. return response.json(0, {
  267. 'Sharing': len(querysetList),
  268. })
  269. else:
  270. return response.json(113)
  271. else:
  272. return response.json(172)
  273. class unsharedUserEquipmentView(View):
  274. @method_decorator(csrf_exempt)
  275. def dispatch(self, *args, **kwargs):
  276. return super(unsharedUserEquipmentView, self).dispatch(*args, **kwargs)
  277. def post(self, request, *args, **kwargs):
  278. request.encoding = 'utf-8'
  279. queryset = request.POST
  280. return self.unsharedUserEquipment(queryset, args, kwargs)
  281. def get(self, request, *args, **kwargs):
  282. request.encoding = 'gb2312'
  283. queryset = request.GET
  284. return self.unsharedUserEquipment(queryset, args, kwargs)
  285. def unsharedUserEquipment(self, queryset, *args, **kwargs):
  286. token = queryset.get('token', None)
  287. GuestID = queryset.get('guestID', None)
  288. content = queryset.get('content', None)
  289. unsharedAll = queryset.get('unsharedAll', False)
  290. response = ResponseObject()
  291. if unsharedAll in ('1', '0'):
  292. unsharedAll = bool(int(unsharedAll))
  293. elif unsharedAll in ('true', 'false'):
  294. if unsharedAll == 'true':
  295. unsharedAll = 1
  296. else:
  297. unsharedAll = 0
  298. if token != None and GuestID != None and len(GuestID) > 0:
  299. tko = TokenObject(token)
  300. tko.valid()
  301. response.lang = tko.lang
  302. if tko.code == 0:
  303. MasterID = tko.userID
  304. if unsharedAll and MasterID != None:
  305. return self.unsharedUserEquipmentSQL(MasterID, GuestID, True, response, args, kwargs)
  306. else:
  307. if content != None and MasterID != None:
  308. return self.unsharedUserEquipmentSQL(MasterID, GuestID, False, response, args, content=content)
  309. else:
  310. return response.json(805)
  311. else:
  312. return response.json(tko.code)
  313. else:
  314. return response.json(800)
  315. def unsharedUserEquipmentSQL(self, MasterID, GuestID, unsharedAll, response, *args, **kwargs):
  316. if unsharedAll:
  317. try:
  318. equipmentCount = Device_Info.objects.filter(userID_id=GuestID, primaryUserID=MasterID).delete()
  319. except Exception as e:
  320. errorInfo = traceback.format_exc()
  321. print('删除设备更新数据库错误: %s' % errorInfo)
  322. return response.json(171, {"details": repr(e)})
  323. else:
  324. return response.json(0, {'removeCount': equipmentCount[0]})
  325. else:
  326. content = kwargs.get('content', None)
  327. if content != None:
  328. removeCount = 0
  329. errorRemove = []
  330. errorUID = []
  331. contentDict = json.loads(content)
  332. uidlist = contentDict.get('UID', None)
  333. for index in range(len(uidlist)):
  334. uid = uidlist[index]
  335. try:
  336. equipment = Device_Info.objects.filter(userID_id=GuestID, primaryUserID=MasterID, UID=uid)
  337. if equipment:
  338. equipmentCount = equipment.delete()
  339. else:
  340. errorUID.append(uid)
  341. continue
  342. except Exception as e:
  343. errorInfo = traceback.format_exc()
  344. print('查询数据库错误: %s' % errorInfo)
  345. errorRemove.append(uid)
  346. continue
  347. else:
  348. removeCount += equipmentCount[0]
  349. if len(errorRemove) > 0:
  350. return response.json(171, {
  351. 'removeCount': removeCount,
  352. 'error_UID': errorRemove,
  353. })
  354. else:
  355. if len(errorUID) > 0:
  356. return response.json(173, {
  357. 'removeCount': removeCount,
  358. 'error_UID': errorUID,
  359. })
  360. else:
  361. return response.json(0, {
  362. 'removeCount': removeCount
  363. })