def device_status(request): # define default response response = { "error": "", "data": "" } # return if GET request if request.method == 'GET': response['error'] = { 'no' : 'err0', 'msg': 'sorry no gets' } return json_response_from(response) # params checking if not (request.POST.has_key('device_id') and request.POST.has_key('status_type') \ and request.POST.has_key('status_value')): response['error'] = { 'no' : 'err1', 'msg': 'missing mandatory params' } return json_response_from(response) # if not (request.POST['status_type'] == "O" and request.POST['status_value'] == "3" \ # and request.POST.has_key('build_version')): # response['error'] = { # 'no' : 'err1', # 'msg': 'missing mandatory params' # } # return json_response_from(response) # data check try: dev = Device.objects.get(meid=request.POST['device_id']) #Heartbeat if request.POST['status_type'] == "H": heartbeat = HeartbeatStatus( dev = dev, status_value = request.POST['status_value'], build_version = request.POST['build_version'], latitude = request.POST['latitude'], longitude = request.POST['longitude'], timestamp = datetime.now() ) heartbeat.save() #OTA 1: download completed, 2: signal before a phone goes into recovery, 3: build_version # if request.POST['status_type'] == "O": # ota = OtaStatus() # ota.dev = dev # ota.status_value = request.POST['status_value'] # ota.timestamp = datetime.now() # if request.POST['status_value'] == "3": # ota.build_version = request.POST['build_version'] # ota.save() # device does not exist except Device.DoesNotExist: response['err'] = { 'no' : 'err1', 'msg': 'invalid device' } return json_response_from(response) # device response['data'] = dev.meid return json_response_from(response)
def create_or_update_device(request): # define default response response = {"error": "", "data": ""} # return if GET request if request.method == 'GET': response['error'] = {'no': 'err0', 'msg': 'sorry no gets'} return json_response_from(response) # get params from POST params = request.POST # error checking if (params['device_id'] == "" or params['reg_id'] == "" or params['phone_no'] == ""): response['error'] = {'no': 'err1', 'msg': 'missing mandatory params'} # get device device = Device.objects.filter(meid=params['device_id']) # if device exists, update if device.count() == 1: device = device[0] # email #if ('email' in params and device.email != params['email']): # device.email = params['email'] # reg_id if ('reg_id' in params and device.reg_id != params['reg_id']): device.reg_id = params['reg_id'] # update if ('update_interval' in params and device.update_interval != params['update_interval']): device.update_interval = params['update_interval'] device.save() # device does not exist, insert else: device = Device( meid=params['device_id'], # email = "*****@*****.**", #params['email'] reg_id=params['reg_id'], active="E") device.save() # create monitor interval in StatusMonitor class # statusmonitor = StatusMonitor( # name = 'monitorInterval', # value = '10', # units = 'min') # statusmonitor.save() deviceprofile = DeviceProfile() #deviceprofile.statusmonitor.add(statusmonitor) deviceprofile.dev = device if params['device_id'].startswith('A0000', 0, 5): deviceprofile.phone_no = params['phone_no'] deviceprofile.save() # device response['data'] = device # render json response return json_response_from(response)
def device_status(request): # define default response response = {"error": "", "data": ""} # return if GET request if request.method == 'GET': response['error'] = {'no': 'err0', 'msg': 'sorry no gets'} return json_response_from(response) # params checking if not (request.POST.has_key('device_id') and request.POST.has_key('status_type') \ and request.POST.has_key('status_value')): response['error'] = {'no': 'err1', 'msg': 'missing mandatory params'} return json_response_from(response) # if not (request.POST['status_type'] == "O" and request.POST['status_value'] == "3" \ # and request.POST.has_key('build_version')): # response['error'] = { # 'no' : 'err1', # 'msg': 'missing mandatory params' # } # return json_response_from(response) # data check try: dev = Device.objects.get(meid=request.POST['device_id']) #Heartbeat if request.POST['status_type'] == "H": heartbeat = HeartbeatStatus( dev=dev, status_value=request.POST['status_value'], build_version=request.POST['build_version'], latitude=request.POST['latitude'], longitude=request.POST['longitude'], timestamp=datetime.now()) heartbeat.save() #OTA 1: download completed, 2: signal before a phone goes into recovery, 3: build_version # if request.POST['status_type'] == "O": # ota = OtaStatus() # ota.dev = dev # ota.status_value = request.POST['status_value'] # ota.timestamp = datetime.now() # if request.POST['status_value'] == "3": # ota.build_version = request.POST['build_version'] # ota.save() # device does not exist except Device.DoesNotExist: response['err'] = {'no': 'err1', 'msg': 'invalid device'} return json_response_from(response) # device response['data'] = dev.meid return json_response_from(response)
def show(request, Id, Type): # define default response response = { "err": "", "data": "" } # get transaction using userId or transId # get transactionDevapp using tid trans_list = {} if Type == "1": for o in Transaction.objects.filter(id=Id).values('id', 'user_id'): trans_list[o['id']] = o['user_id'] id = Id else: for o in Transaction.objects.filter(user=Id).values('id', 'user_id'): trans_list[o['id']] = o['user_id'] id = User.objects.get(id=Id) transdevapps = TransactionDevApp.objects.filter(tid__in=trans_list.keys()) return render_to_response( 'transaction/show.html', { 'id' : id, 'transdevapps': transdevapps }, context_instance=RequestContext(request) ) return json_response_from(response)
def show(request, deviceId, logFilename): user = request.user # define default response response = {"err": "", "data": ""} if is_valid_device(user, deviceId): # get device device = Device.objects.filter(id=deviceId) # if device exists, update if device.count() == 1: # generate file name filename = os.path.join(RAW_LOG_ROOT, device[0].meid, logFilename + ".log") if os.path.isfile(filename): # open log file Logfile = open(filename, 'r+') # read file Logdata = Logfile.read() # render respone return render_to_response( 'device/log.html', { 'device': device[0], 'logFilename': logFilename, 'Logdata': Logdata }, context_instance=RequestContext(request)) #the file does not exist else: response['err'] = {'no': 'err2', 'msg': 'No such log file'} #device does not exist else: response['err'] = {'no': 'err1', 'msg': 'invalid device'} return json_response_from(response) else: return HttpResponseRedirect('/')
def show(request, appId): userprofile = UserProfile.objects.get(user=request.user) # define default response response = { "err": "", "data": "" } # get application devs = {} try: app = Application.objects.get(id=appId) # application exists for o in DeviceApplication.objects.filter(app=app): for dev in Device.objects.filter(id=o.dev.id): devs[dev] = dev return render_to_response( 'application/show.html', { 'userprofile': userprofile, 'app' : app, 'devs': devs }, context_instance=RequestContext(request) ) # application does not exist except Application.DoesNotExist: response['err'] = { 'no' : 'err1', 'msg': 'invalid application' } return json_response_from(response)
def edit(request, deviceId): user = request.user # define default response response = { "err": "", "data": "" } #check deviceId to control accesses if is_valid_device(user, deviceId): # get device try: device = Device.objects.get(id=deviceId) # device exists return render_to_response( 'device/edit.html', { 'device': device }, context_instance=RequestContext(request) ) # device does not exist except Device.DoesNotExist: response['err'] = { 'no' : 'err1', 'msg': 'invalid device' } return json_response_from(response) else: return HttpResponseRedirect('/')
def profile(request): experiments = {} # define default response response = {"err": "", "data": ""} try: # get UserProfile with user foreignkey userprofile = UserProfile.objects.get(user=request.user) if userprofile.user_type == 'A': #get all devices devprofiles = DeviceProfile.objects.all() #get Experiment details if experimenter if(userprofile.user_type== 'E'): experiments = Experiment.objects.filter(user=request.user) return render_to_response( 'users/profile.html', { 'userprofile' : userprofile, 'experiments': experiments }, context_instance=RequestContext(request) ) # User does not exist except UserProfile.DoesNotExist: response['err'] = { 'no' : 'err1', 'msg': 'invalid user' } return json_response_from(response)
def create_or_update_device(request): # define default response response = { "error": "", "data": "" } # return if GET request if request.method == 'GET': response['error'] = { 'no' : 'err0', 'msg': 'sorry no gets' } return json_response_from(response) # get params from POST params = request.POST # error checking if (params['device_id'] == "" or params['reg_id'] == ""): response['error'] = { 'no' : 'err1', 'msg': 'missing mandatory params' } # get device device = Device.objects.filter(id=params['device_id']) # if device exists, update if device.count() == 1: device = device[0] # email if ('email' in params and device.email != params['email']): device.email = params['email'] # reg_id if ('reg_id' in params and device.reg_id != params['reg_id']): device.reg_id = params['reg_id'] # update if ('update_interval' in params and device.update_interval != params['update_interval']): device.update_interval = params['update_interval'] # device does not exist, insert else: device = Device( id = params['device_id'], email = "*****@*****.**", #params['email'] reg_id = params['reg_id'] ) # save device device.save() # device response['data'] = device # render json response return json_response_from(response)
def approve_experiment(modeladmin, request, queryset): for obj in queryset: # define default response response = {"err": "", "data": ""} # return if GET request if request.method == 'GET': response['err'] = {'no': 'err0', 'msg': 'sorry no gets'} return HttpResponseRedirect('/error/') dev_ids = obj.dev.all() app_ids = obj.app.all() transact = Transaction() transact.eid = obj transact.user = User.objects.get(id__in=obj.user.all) transact.total = len(dev_ids) * len(app_ids) transact.progress = 0 #Check Data Validation for dev_id in dev_ids: for app_id in app_ids: #check FailureAlready(F1) if DeviceApplication.objects.filter(dev=dev_id).filter(app=app_id): response['err'] = { 'no': 'err1', 'msg': 'The application is already installed' } return json_response_from(response) #insert the data from POST method for dev_id in dev_ids: for app_id in app_ids: transact.save() t_id = transact.id trndevapp = TransactionDevApp() trndevapp.tid = Transaction.objects.get(id=t_id) trndevapp.dev = dev_id trndevapp.app = app_id trndevapp.action = 'I' trndevapp.result = "N" # N is N/A trndevapp.save() Device.objects.filter(id=dev_id.id).update(active="D") msg = "new_manifest" for dev_id in dev_ids: Device.objects.get(id=dev_id.id).send_message( payload=json({"message": msg})) eprofile = ExperimentProfile.objects.get(experiment=obj) eprofile.starttime = datetime.now() print obj.period endtime = datetime.now() + timedelta(int(obj.period)) print endtime eprofile.endtime = endtime eprofile.save() queryset.update(active=1)
def show_tag(request, deviceId): # define default response response = { "err": "", "data": "" } # get device try: device = Device.objects.get(id=deviceId) # device exists # get log data list from deviceId directory path = os.path.join(RAW_LOG_ROOT, device[0].meid) # empty filelist = {} try: os.chdir(path) filelist = os.listdir(".") sort_nicely(filelist) Tagdata = '' for file in filelist: filename = os.path.join(RAW_LOG_ROOT, device[0].meid, file) Logfile = open(filename, 'r+') for line in Logfile: #Logdata = Logfile.readline() #Two ways to find with string and without string if re.search(request.POST['tagName'], line): if not request.POST.has_key('anti'): Tagdata += line else: if request.POST.has_key('anti'): Tagdata += line # render respone return render_to_response( 'device/filter.html', { 'device': device[0], 'TagName': request.POST['tagName'], 'Tagdata': Tagdata }, context_instance=RequestContext(request) ) Logfile.close() Tagfile.close() except OSError, e: if e.errno != errno.EEXIST: response['err'] = { 'no' : 'err2', 'msg': 'cannot change dir' } # device does not exist except Device.DoesNotExist: response['err'] = { 'no' : 'err1', 'msg': 'invalid device' } return json_response_from(response)
def download_manifest(request, deviceId): # define default response response = { "error": "", "data": "" } try: #if device exists dev = Device.objects.get(meid=deviceId) app_list = {} apps = {} tags = {} services = {} # get apps of particular device deviceprofile = DeviceProfile.objects.get(dev=dev) # services = deviceprofile.services.all() for o in TransactionDevApp.objects.filter(dev=dev).filter(result="N").values('app', 'action'): # get list of apps to download for app in Application.objects.filter(id=o['app']): if o['action'] == "I": apps[app.id] = {"app_object": app, "app_status": "install"} else: apps[app.id] = {"app_object": app, "app_status": "uninstall"} #get tag names from experiments # for dev in Experiment.dev.all(): # print dev.meid # for device in deviceprofile.group.all(): # for experiment in Experiment.objects.filter(=group.id): # tags[group.id] = experiment.tag return render( request, 'manifest/success.xml', { 'deviceId' : deviceId, 'deviceprofile' : deviceprofile, 'status_monitor_update_value' : dev.update_interval, 'apps' : apps, 'tags' : tags }, content_type="application/xml" ) # device does not exist except Device.DoesNotExist : return render( request, 'manifest/fail.xml', { 'no' : 'err1' , 'msg': 'invalid device' }, content_type="application/xml" ) return json_response_from(response)
def download_manifest(request, deviceId): # define default response response = {"error": "", "data": ""} try: #if device exists dev = Device.objects.get(meid=deviceId) app_list = {} apps = {} tags = {} services = {} # get apps of particular device deviceprofile = DeviceProfile.objects.get(dev=dev) # services = deviceprofile.services.all() for o in TransactionDevApp.objects.filter(dev=dev).filter( result="N").values('app', 'action'): # get list of apps to download for app in Application.objects.filter(id=o['app']): if o['action'] == "I": apps[app.id] = {"app_object": app, "app_status": "install"} else: apps[app.id] = { "app_object": app, "app_status": "uninstall" } #get tag names from experiments # for dev in Experiment.dev.all(): # print dev.meid # for device in deviceprofile.group.all(): # for experiment in Experiment.objects.filter(=group.id): # tags[group.id] = experiment.tag return render(request, 'manifest/success.xml', { 'deviceId': deviceId, 'deviceprofile': deviceprofile, 'status_monitor_update_value': dev.update_interval, 'apps': apps, 'tags': tags }, content_type="application/xml") # device does not exist except Device.DoesNotExist: return render(request, 'manifest/fail.xml', { 'no': 'err1', 'msg': 'invalid device' }, content_type="application/xml") return json_response_from(response)
def approve_experiment(modeladmin, request, queryset): for obj in queryset: # define default response response = {"err": "", "data": ""} # return if GET request if request.method == "GET": response["err"] = {"no": "err0", "msg": "sorry no gets"} return HttpResponseRedirect("/error/") dev_ids = obj.dev.all() app_ids = obj.app.all() transact = Transaction() transact.eid = obj transact.user = User.objects.get(id__in=obj.user.all) transact.total = len(dev_ids) * len(app_ids) transact.progress = 0 # Check Data Validation for dev_id in dev_ids: for app_id in app_ids: # check FailureAlready(F1) if DeviceApplication.objects.filter(dev=dev_id).filter(app=app_id): response["err"] = {"no": "err1", "msg": "The application is already installed"} return json_response_from(response) # insert the data from POST method for dev_id in dev_ids: for app_id in app_ids: transact.save() t_id = transact.id trndevapp = TransactionDevApp() trndevapp.tid = Transaction.objects.get(id=t_id) trndevapp.dev = dev_id trndevapp.app = app_id trndevapp.action = "I" trndevapp.result = "N" # N is N/A trndevapp.save() Device.objects.filter(id=dev_id.id).update(active="D") msg = "new_manifest" for dev_id in dev_ids: Device.objects.get(id=dev_id.id).send_message(payload=json({"message": msg})) eprofile = ExperimentProfile.objects.get(experiment=obj) eprofile.starttime = datetime.now() print obj.period endtime = datetime.now() + timedelta(int(obj.period)) print endtime eprofile.endtime = endtime eprofile.save() queryset.update(active=1)
def upload_log(request, deviceId): # return if GET request if request.method == 'GET': return HttpResponse( "Sorry Bub", content_type='text/plain' ) # define default response response = {"err": "", "data": ""} # Verify Filename is coming in post if ("filename" in request.POST): now = datetime.now() #filename = os.path.join(RAW_LOG_ROOT, deviceId, str(int(time.time())) + ".log") #filename = os.path.join(RAW_LOG_ROOT, deviceId, request.POST['filename']) filename = os.path.join(RAW_LOG_ROOT, deviceId, str(int(now.strftime("%Y%m%d%H%M"))) + ".log") filedir = os.path.dirname(filename) # create folder for user if it doesn`t exist try: print "trying to create dir" + str(filedir) os.mkdir(filedir) except OSError, e: if e.errno != errno.EEXIST: print "some problem in creating dir" response['err'] = { 'no' : 'err1', 'msg': 'cannot create dir, failed upload' } raise # get file handle fileHandle = open(filename, 'wb+') # write it out for chunk in request.FILES['file'].chunks(): fileHandle.write(chunk) # close file handle fileHandle.close() try: dev = Device.objects.get(meid=deviceId) DeviceProfile.objects.filter(dev=dev).update(last_log=now) # success msg response['data'] = "done" # device does not exist except Device.DoesNotExist: response['err'] = { 'no' : 'err1', 'msg': 'invalid device' } return json_response_from(response)
def c2dm(request, deviceId): # define default response response = {"err": "", "data": ""} # return if GET request if request.method == 'GET': response['err'] = {'no': 'err0', 'msg': 'sorry no gets'} else: msg = request.POST['c2dm_msg'] # get device try: dev = Device.objects.get(id=deviceId) # msg = "new_manifest" #TODO: Implement other messages. response = dev.send_message(payload=json({"message": msg})) except Device.DoesNotExist: response['err'] = {'no': 'err1', 'msg': 'invalid device'} return json_response_from(response)
def show_tag(request, deviceId): # define default response response = {"err": "", "data": ""} # get device try: device = Device.objects.get(id=deviceId) # device exists # get log data list from deviceId directory path = os.path.join(RAW_LOG_ROOT, device[0].meid) # empty filelist = {} try: os.chdir(path) filelist = os.listdir(".") sort_nicely(filelist) Tagdata = '' for file in filelist: filename = os.path.join(RAW_LOG_ROOT, device[0].meid, file) Logfile = open(filename, 'r+') for line in Logfile: #Logdata = Logfile.readline() #Two ways to find with string and without string if re.search(request.POST['tagName'], line): if not request.POST.has_key('anti'): Tagdata += line else: if request.POST.has_key('anti'): Tagdata += line # render respone return render_to_response('device/filter.html', { 'device': device[0], 'TagName': request.POST['tagName'], 'Tagdata': Tagdata }, context_instance=RequestContext(request)) Logfile.close() Tagfile.close() except OSError, e: if e.errno != errno.EEXIST: response['err'] = {'no': 'err2', 'msg': 'cannot change dir'} # device does not exist except Device.DoesNotExist: response['err'] = {'no': 'err1', 'msg': 'invalid device'} return json_response_from(response)
def edit(request, userId): # define default response response = { "err": "", "data": "" } try: # get UserProfile with user foreignkey userprofile = UserProfile.objects.get(user=userId) return render_to_response( 'users/edit.html', { 'userprofile' : userprofile}, context_instance=RequestContext(request) ) # User does not exist except Device.DoesNotExist: response['err'] = { 'no' : 'err1', 'msg': 'invalid user' } return json_response_from(response)
def edit(request, deviceId): user = request.user # define default response response = {"err": "", "data": ""} #check deviceId to control accesses if is_valid_device(user, deviceId): # get device try: device = Device.objects.get(id=deviceId) # device exists return render_to_response('device/edit.html', {'device': device}, context_instance=RequestContext(request)) # device does not exist except Device.DoesNotExist: response['err'] = {'no': 'err1', 'msg': 'invalid device'} return json_response_from(response) else: return HttpResponseRedirect('/')
def upload_log(request, deviceId): # return if GET request if request.method == 'GET': return HttpResponse("Sorry Bub", content_type='text/plain') # define default response response = {"err": "", "data": ""} # Verify Filename is coming in post if ("filename" in request.POST): now = datetime.now() #filename = os.path.join(RAW_LOG_ROOT, deviceId, str(int(time.time())) + ".log") #filename = os.path.join(RAW_LOG_ROOT, deviceId, request.POST['filename']) filename = os.path.join(RAW_LOG_ROOT, deviceId, str(int(now.strftime("%Y%m%d%H%M"))) + ".log") filedir = os.path.dirname(filename) # create folder for user if it doesn`t exist try: print "trying to create dir" + str(filedir) os.mkdir(filedir) except OSError, e: if e.errno != errno.EEXIST: print "some problem in creating dir" response['err'] = { 'no': 'err1', 'msg': 'cannot create dir, failed upload' } raise # get file handle fileHandle = open(filename, 'wb+') # write it out for chunk in request.FILES['file'].chunks(): fileHandle.write(chunk) # close file handle fileHandle.close() try: dev = Device.objects.get(meid=deviceId) DeviceProfile.objects.filter(dev=dev).update(last_log=now) # success msg response['data'] = "done" # device does not exist except Device.DoesNotExist: response['err'] = {'no': 'err1', 'msg': 'invalid device'} return json_response_from(response)
def show(request, deviceId, logFilename): user = request.user # define default response response = { "err": "", "data": "" } if is_valid_device(user, deviceId): # get device device = Device.objects.filter(id=deviceId) # if device exists, update if device.count() == 1: # generate file name filename = os.path.join(RAW_LOG_ROOT, device[0].meid, logFilename + ".log") if os.path.isfile(filename): # open log file Logfile = open(filename, 'r+') # read file Logdata = Logfile.read() # render respone return render_to_response( 'device/log.html', { 'device': device[0], 'logFilename': logFilename, 'Logdata': Logdata }, context_instance=RequestContext(request) ) #the file does not exist else: response['err'] = { 'no' : 'err2', 'msg': 'No such log file' } #device does not exist else: response['err'] = { 'no' : 'err1', 'msg': 'invalid device' } return json_response_from(response) else: return HttpResponseRedirect('/')
def show(request, appId): # define default response response = {"err": "", "data": ""} # get application devs = {} try: app = Application.objects.get(id=appId) # application exists for o in DeviceApplication.objects.filter(app=app): for dev in Device.objects.filter(id=o.dev.id): devs[dev] = dev return render_to_response('application/show.html', { 'app': app, 'devs': devs }, context_instance=RequestContext(request)) # application does not exist except Application.DoesNotExist: response['err'] = {'no': 'err1', 'msg': 'invalid application'} return json_response_from(response)
def update(request, userId): # define default response response = { "err": "", "data": "" } # return if GET request if request.method == 'GET': response['err'] = { 'no' : 'err0', 'msg': 'sorry no gets' } return HttpResponseRedirect('/error/') # get params from POST params = request.POST try: # get UserProfile with user foreignkey userprofile = UserProfile.objects.get(user=userId) user = User.objects.get(id=userId) # User First Name if ('fname' in params and userprofile.user.first_name != params['fname']): user.first_name = params['fname'] # User Last Name if ('lname' in params and userprofile.user.last_name != params['lname']): user.last_name = params['lname'] # User email, not device email if ('email' in params and userprofile.user.email != params['email']): user.email = params['email'] # ub_id if ('ub_id' in params and userprofile.ub_id != params['ub_id']): userprofile.ub_id = params['ub_id'] # save User and UserProfile user.save() userprofile.save() # redirect to /accounts/profile/userId return HttpResponseRedirect('/accounts/profile/' + userId) # User does not exist except Device.DoesNotExist: response['err'] = { 'no' : 'err1', 'msg': 'invalid user' } return json_response_from(response)
def download_manifest(request, deviceId): # define default response response = { "error": "", "data": "" } try: #if device exists dev = Device.objects.get(id=deviceId) app_list = {} apps = {} # get apps of particular device for o in TransactionDevApp.objects.filter(dev=dev.id).filter(result="N").values('app', 'action'): # get list of apps to download for app in Application.objects.filter(id=o['app']): if o['action'] == "I": apps[app.id] = {"app_object": app, "app_status": "install"} else: apps[app.id] = {"app_object": app, "app_status": "uninstall"} return render( request, 'manifest/success.xml', { 'deviceId' : deviceId , 'status_monitor_update_value' : dev.update_interval , 'apps' : apps }, content_type="application/xml" ) # device does not exist except Device.DoesNotExist : return render( request, 'manifest/fail.xml', { 'no' : 'err1' , 'msg': 'invalid device' }, content_type="application/xml" ) return json_response_from(response)
def show(request, Id, Type): # define default response response = {"err": "", "data": ""} # get transaction using userId or transId # get transactionDevapp using tid trans_list = {} if Type == "1": for o in Transaction.objects.filter(id=Id).values('id', 'user_id'): trans_list[o['id']] = o['user_id'] id = Id else: for o in Transaction.objects.filter(user=Id).values('id', 'user_id'): trans_list[o['id']] = o['user_id'] id = User.objects.get(id=Id) transdevapps = TransactionDevApp.objects.filter(tid__in=trans_list.keys()) return render_to_response('transaction/show.html', { 'id': id, 'transdevapps': transdevapps }, context_instance=RequestContext(request)) return json_response_from(response)
def c2dm(request, deviceId): # define default response response = { "err": "", "data": "" } # return if GET request if request.method == 'GET': response['err'] = { 'no' : 'err0', 'msg': 'sorry no gets' } else: msg = request.POST['c2dm_msg'] # get device try: dev = Device.objects.get(id=deviceId) # msg = "new_manifest" #TODO: Implement other messages. response = dev.send_message(payload=json({"message": msg})) except Device.DoesNotExist: response['err'] = { 'no' : 'err1', 'msg': 'invalid device' } return json_response_from(response)
def download_manifest(request, deviceId): # define default response response = {"error": "", "data": ""} try: #if device exists dev = Device.objects.get(id=deviceId) app_list = {} apps = {} # get apps of particular device for o in TransactionDevApp.objects.filter(dev=dev.id).filter( result="N").values('app', 'action'): # get list of apps to download for app in Application.objects.filter(id=o['app']): if o['action'] == "I": apps[app.id] = {"app_object": app, "app_status": "install"} else: apps[app.id] = { "app_object": app, "app_status": "uninstall" } return render(request, 'manifest/success.xml', { 'deviceId': deviceId, 'status_monitor_update_value': dev.update_interval, 'apps': apps }, content_type="application/xml") # device does not exist except Device.DoesNotExist: return render(request, 'manifest/fail.xml', { 'no': 'err1', 'msg': 'invalid device' }, content_type="application/xml") return json_response_from(response)
def insert_or_update_deviceapplication(request): # define default response response = { "error": "", "data": "" } # return if GET request if request.method == 'GET': response['error'] = { 'no' : 'err0', 'msg': 'sorry no gets' } return json_response_from(response) # params checking if not (request.POST.has_key('dev_id') and request.POST.has_key('app_id') \ and request.POST.has_key('action') and request.POST.has_key('result')): response['error'] = { 'no' : 'err1', 'msg': 'missing mandatory params' } return json_response_from(response) app_ids = request.POST.getlist('app_id') actions = request.POST.getlist('action') results = request.POST.getlist('result') num = 0 # data check try: dev = Device.objects.get(meid=request.POST['dev_id']) for app_id in app_ids: try: app = Application.objects.get(id=app_id) #if result is Success if results[num] == "S": #if action is install if actions[num] == "I": devapp = DeviceApplication() if DeviceApplication.objects.filter(dev=dev).filter(app=app): response['err'] = { 'no' : 'err1', 'msg': 'has the information already' } return json_response_from(response) devapp.app = app devapp.dev = dev devapp.save() else: #if action is uninstall try: devapp = DeviceApplication.objects.filter(dev=dev).filter(app=app) devapp.delete() # deviceapplication does not exist except DeviceApplication.DoesNotExist: response['err'] = { 'no' : 'err1', 'msg': 'invalid deviceapplication' } return json_response_from(response) #update the result in TransactionDevApp table #update the status in Transaction #TODO: improve this logic try: # for i in TransactionDevApp.objects.filter(dev=dev).filter(app=app).filter(action=actions[num]).filter(result="N"): for i in TransactionDevApp.objects.filter(dev=dev).filter(app=app).filter(result="N"): count = TransactionDevApp.objects.filter(id=i.id).update(result=results[num], end=datetime.now()) trans = Transaction.objects.get(id=i.tid.id) if trans.total == trans.progress + count: trans.end = datetime.now() trans.progress += count #progress/ total trans.save() if not TransactionDevApp.objects.filter(dev=dev).filter(result="N"): Device.objects.filter(id=dev).update(active="E") # Application.objects.filter(id=app).update(active="E") # TransactionDevApp does not exist except TransactionDevApp.DoesNotExist: response['err'] = { 'no' : 'err1', 'msg': 'invalid TransactionDevApp' } return json_response_from(response) num = num + 1 # application does not exist except Application.DoesNotExist: response['err'] = { 'no' : 'err1', 'msg': 'invalid application' } return json_response_from(response) # device does not exist except Device.DoesNotExist: response['err'] = { 'no' : 'err1', 'msg': 'invalid device' } return json_response_from(response) return json_response_from(response)
def status(request, deviceId, statusType): user = request.user # define default response response = { "err": "", "data": "" } #check deviceId to control accesses if is_valid_device(user, deviceId): # get device try: device = Device.objects.get(id=deviceId) # device exists # get log data list from deviceId directory path = os.path.join(RAW_LOG_ROOT, device.meid) # empty filelist = {} tagName = '' if statusType == '1': tagName = 'Battery_level' #tagName = 'Battery level' elif statusType == '2': tagName = 'Location_Latitude' #tagName = 'Location: Latitude' else: tagName = 'Signal_Strength' #tagName = 'Signal Strength' try: os.chdir(path) filelist = os.listdir(".") sort_nicely(filelist) Tagdata = '' for file in filelist: filename = os.path.join(RAW_LOG_ROOT, device.meid, file) Logfile = open(filename, 'r+') for line in Logfile: #Logdata = Logfile.readline() if re.search(tagName, line): temp = line.split() Tagdata += ' [ ' + temp[0] + ' ' + temp[1] + ' ] ' if statusType == '1': Tagdata += 'Battery Level: ' + temp[7] + '\n' elif statusType == '2': Tagdata += 'GPS Latitude: ' + temp[7] + ', Longitude: ' + temp[9] + ', Accuracy: ' + temp[11] + '\n' else: Tagdata += 'Signal Strengh: ' + temp[7] + ', asu: ' + temp[9] + '\n' # render respone return render_to_response( 'device/status.html', { 'device': device, 'TagName': tagName, 'Tagdata': Tagdata }, context_instance=RequestContext(request) ) Logfile.close() Tagfile.close() except OSError, e: if e.errno != errno.EEXIST: response['err'] = { 'no' : 'err1', 'msg': 'cannot change dir' } # device does not exist except Device.DoesNotExist: response['err'] = { 'no' : 'err1', 'msg': 'invalid device' } return json_response_from(response) else: return HttpResponseRedirect('/')
return render_to_response( 'device/show.html', { 'device': dev, 'apps': apps, 'unapps': unapps, 'filelist': filelist, 'userprofile': userprofile, # 'group': userprofile.group }, context_instance=RequestContext(request)) # device does not exist except Device.DoesNotExist: response['err'] = {'no': 'err1', 'msg': 'invalid device'} return json_response_from(response) else: return HttpResponseRedirect('/') """ Edit Device Form [GET] @date 02/08/2012 @param String deviceId @author Micheal """ @login_required
def create_or_update_device(request): # define default response response = { "error": "", "data": "" } # return if GET request if request.method == 'GET': response['error'] = { 'no' : 'err0', 'msg': 'sorry no gets' } return json_response_from(response) # get params from POST params = request.POST # error checking if (params['device_id'] == "" or params['reg_id'] == "" or params['phone_no'] == ""): response['error'] = { 'no' : 'err1', 'msg': 'missing mandatory params' } # get device device = Device.objects.filter(meid=params['device_id']) # if device exists, update if device.count() == 1: device = device[0] # email #if ('email' in params and device.email != params['email']): # device.email = params['email'] # reg_id if ('reg_id' in params and device.reg_id != params['reg_id']): device.reg_id = params['reg_id'] # update if ('update_interval' in params and device.update_interval != params['update_interval']): device.update_interval = params['update_interval'] device.save() # device does not exist, insert else: device = Device( meid = params['device_id'], # email = "*****@*****.**", #params['email'] reg_id = params['reg_id'], active = "E" ) device.save() # create monitor interval in StatusMonitor class # statusmonitor = StatusMonitor( # name = 'monitorInterval', # value = '10', # units = 'min') # statusmonitor.save() deviceprofile = DeviceProfile() #deviceprofile.statusmonitor.add(statusmonitor) deviceprofile.dev = device if params['device_id'].startswith('A0000', 0, 5): deviceprofile.phone_no = params['phone_no'] deviceprofile.save() # device response['data'] = device # render json response return json_response_from(response)
'apps' : apps, 'unapps' : unapps, 'filelist' : filelist, 'userprofile': userprofile, # 'group': userprofile.group }, context_instance=RequestContext(request) ) # device does not exist except Device.DoesNotExist: response['err'] = { 'no' : 'err1', 'msg': 'invalid device' } return json_response_from(response) else: return HttpResponseRedirect('/') """ Edit Device Form [GET] @date 02/08/2012 @param String deviceId @author Micheal """ @login_required def edit(request, deviceId): user = request.user # define default response
def insert_or_update_deviceapplication(request): # define default response response = {"error": "", "data": ""} # return if GET request if request.method == 'GET': response['error'] = {'no': 'err0', 'msg': 'sorry no gets'} return json_response_from(response) # params checking if not (request.POST.has_key('dev_id') and request.POST.has_key('app_id') \ and request.POST.has_key('action') and request.POST.has_key('result')): response['error'] = {'no': 'err1', 'msg': 'missing mandatory params'} return json_response_from(response) app_ids = request.POST.getlist('app_id') actions = request.POST.getlist('action') results = request.POST.getlist('result') num = 0 # data check try: dev = Device.objects.get(meid=request.POST['dev_id']) for app_id in app_ids: try: app = Application.objects.get(id=app_id) #if result is Success if results[num] == "S": #if action is install if actions[num] == "I": devapp = DeviceApplication() if DeviceApplication.objects.filter(dev=dev).filter( app=app): response['err'] = { 'no': 'err1', 'msg': 'has the information already' } return json_response_from(response) devapp.app = app devapp.dev = dev devapp.save() else: #if action is uninstall try: devapp = DeviceApplication.objects.filter( dev=dev).filter(app=app) devapp.delete() # deviceapplication does not exist except DeviceApplication.DoesNotExist: response['err'] = { 'no': 'err1', 'msg': 'invalid deviceapplication' } return json_response_from(response) #update the result in TransactionDevApp table #update the status in Transaction #TODO: improve this logic try: # for i in TransactionDevApp.objects.filter(dev=dev).filter(app=app).filter(action=actions[num]).filter(result="N"): for i in TransactionDevApp.objects.filter(dev=dev).filter( app=app).filter(result="N"): count = TransactionDevApp.objects.filter( id=i.id).update(result=results[num], end=datetime.now()) trans = Transaction.objects.get(id=i.tid.id) if trans.total == trans.progress + count: trans.end = datetime.now() trans.progress += count #progress/ total trans.save() if not TransactionDevApp.objects.filter( dev=dev).filter(result="N"): Device.objects.filter(id=dev).update(active="E") # Application.objects.filter(id=app).update(active="E") # TransactionDevApp does not exist except TransactionDevApp.DoesNotExist: response['err'] = { 'no': 'err1', 'msg': 'invalid TransactionDevApp' } return json_response_from(response) num = num + 1 # application does not exist except Application.DoesNotExist: response['err'] = {'no': 'err1', 'msg': 'invalid application'} return json_response_from(response) # device does not exist except Device.DoesNotExist: response['err'] = {'no': 'err1', 'msg': 'invalid device'} return json_response_from(response) return json_response_from(response)
def create(request): # define default response response = { "err": "", "data": "" } # return if GET request if request.method == 'GET': response['err'] = { 'no' : 'err0', 'msg': 'sorry no gets' } return HttpResponseRedirect('/error/') # params checking if not (request.POST.has_key('dev') and request.POST.has_key('app') \ and request.POST.has_key('action')): response['error'] = { 'no' : 'err1', 'msg': 'missing mandatory params' } return json_response_from(response) dev_ids = request.POST.getlist('dev') app_ids = request.POST.getlist('app') transact = Transaction() transact.user = User.objects.get(id=request.POST['user']) transact.total = len(dev_ids) * len(app_ids) transact.progress = 0 #transact.end = null #Check Data Validation for dev_id in dev_ids: for app_id in app_ids: #check FailureAlready(F1) if DeviceApplication.objects.filter(dev=dev_id).filter(app=app_id): if request.POST['action'] == "I": response['err'] = { 'no' : 'err1', 'msg': 'The application is already installed' } return json_response_from(response) #check FailureNoSuchApplication(F2) else: if request.POST['action'] == "U": response['err'] = { 'no' : 'err1', 'msg': 'The phone does not have the application to uninstall' } return json_response_from(response) #insert the data from POST method for dev_id in dev_ids: for app_id in app_ids: transact.save() t_id = transact.id trndevapp = TransactionDevApp() trndevapp.tid = Transaction.objects.get(id=t_id) trndevapp.dev = Device.objects.get(id=dev_id) trndevapp.app = Application.objects.get(id=app_id) trndevapp.action = request.POST['action'] trndevapp.result = "N" # N is N/A trndevapp.save() Device.objects.filter(id=dev_id).update(active="D") # Application.objects.filter(id=app_id).update(active="D") #send "new_manifest" message to phones via C2DM msg = "new_manifest" for dev_id in dev_ids: Device.objects.get(id=dev_id).send_message(payload=json({"message": msg})) return HttpResponseRedirect('/transaction/' + str(t_id) + '/1/') return json_response_from(response)
def status(request, deviceId, statusType): user = request.user # define default response response = {"err": "", "data": ""} #check deviceId to control accesses if is_valid_device(user, deviceId): # get device try: device = Device.objects.get(id=deviceId) # device exists # get log data list from deviceId directory path = os.path.join(RAW_LOG_ROOT, device.meid) # empty filelist = {} tagName = '' if statusType == '1': tagName = 'Battery_level' #tagName = 'Battery level' elif statusType == '2': tagName = 'Location_Latitude' #tagName = 'Location: Latitude' else: tagName = 'Signal_Strength' #tagName = 'Signal Strength' try: os.chdir(path) filelist = os.listdir(".") sort_nicely(filelist) Tagdata = '' for file in filelist: filename = os.path.join(RAW_LOG_ROOT, device.meid, file) Logfile = open(filename, 'r+') for line in Logfile: #Logdata = Logfile.readline() if re.search(tagName, line): temp = line.split() Tagdata += ' [ ' + temp[0] + ' ' + temp[1] + ' ] ' if statusType == '1': Tagdata += 'Battery Level: ' + temp[7] + '\n' elif statusType == '2': Tagdata += 'GPS Latitude: ' + temp[ 7] + ', Longitude: ' + temp[ 9] + ', Accuracy: ' + temp[11] + '\n' else: Tagdata += 'Signal Strengh: ' + temp[ 7] + ', asu: ' + temp[9] + '\n' # render respone return render_to_response( 'device/status.html', { 'device': device, 'TagName': tagName, 'Tagdata': Tagdata }, context_instance=RequestContext(request)) Logfile.close() Tagfile.close() except OSError, e: if e.errno != errno.EEXIST: response['err'] = { 'no': 'err1', 'msg': 'cannot change dir' } # device does not exist except Device.DoesNotExist: response['err'] = {'no': 'err1', 'msg': 'invalid device'} return json_response_from(response) else: return HttpResponseRedirect('/')
def create(request): # define default response response = {"err": "", "data": ""} # return if GET request if request.method == 'GET': response['err'] = {'no': 'err0', 'msg': 'sorry no gets'} return HttpResponseRedirect('/error/') # params checking if not (request.POST.has_key('dev') and request.POST.has_key('app') \ and request.POST.has_key('action')): response['error'] = {'no': 'err1', 'msg': 'missing mandatory params'} return json_response_from(response) dev_ids = request.POST.getlist('dev') app_ids = request.POST.getlist('app') transact = Transaction() transact.user = User.objects.get(id=request.POST['user']) transact.total = len(dev_ids) * len(app_ids) transact.progress = 0 #transact.end = null #Check Data Validation for dev_id in dev_ids: for app_id in app_ids: #check FailureAlready(F1) if DeviceApplication.objects.filter(dev=dev_id).filter(app=app_id): if request.POST['action'] == "I": response['err'] = { 'no': 'err1', 'msg': 'The application is already installed' } return json_response_from(response) #check FailureNoSuchApplication(F2) else: if request.POST['action'] == "U": response['err'] = { 'no': 'err1', 'msg': 'The phone does not have the application to uninstall' } return json_response_from(response) #insert the data from POST method for dev_id in dev_ids: for app_id in app_ids: transact.save() t_id = transact.id trndevapp = TransactionDevApp() trndevapp.tid = Transaction.objects.get(id=t_id) trndevapp.dev = Device.objects.get(id=dev_id) trndevapp.app = Application.objects.get(id=app_id) trndevapp.action = request.POST['action'] trndevapp.result = "N" # N is N/A trndevapp.save() Device.objects.filter(id=dev_id).update(active="D") # Application.objects.filter(id=app_id).update(active="D") #send "new_manifest" message to phones via C2DM msg = "new_manifest" for dev_id in dev_ids: Device.objects.get(id=dev_id).send_message( payload=json({"message": msg})) return HttpResponseRedirect('/transaction/' + str(t_id) + '/1/') return json_response_from(response)