Пример #1
0
def send_push(request, udid):
    device = None
    if udid:
        try:
            device = Device.objects.get(udid=udid)
        except Device.DoesNotExist:
            raise Http404
    else:
        raise Http404

    push.push_notification(device)
    return HttpResponse('OK')
Пример #2
0
def send_push(request, udid):
    device = None
    if udid:
        try:
            device = Device.objects.get(udid=udid)
        except Device.DoesNotExist:
            raise Http404
    else:
        raise Http404

    push.push_notification(device)
    return HttpResponse('OK')
Пример #3
0
def application_list(request, udid):
    device = None
    if udid:
        try:
            device = Device.objects.get(udid=udid)
        except Device.DoesNotExist:
            raise Http404
    else:
        raise Http404

    DeviceCommand.NewInstalledApplicationList(device)
    push.push_notification(device)

    return HttpResponse('OK')
Пример #4
0
def device_information(request, udid):
    device = None
    if udid:
        try:
            device = Device.objects.get(udid=udid)
        except Device.DoesNotExist:
            raise Http404
    else:
        raise Http404

    DeviceCommand.NewDeviceInformation(device)

    push.push_notification(device)
    return HttpResponse('OK')
Пример #5
0
def application_list(request, udid):
    device = None
    if udid:
        try:
            device = Device.objects.get(udid=udid)
        except Device.DoesNotExist:
            raise Http404
    else:
        raise Http404

    DeviceCommand.NewInstalledApplicationList(device)
    push.push_notification(device)

    return HttpResponse('OK')
Пример #6
0
def device_information(request, udid):
    device = None
    if udid:
        try:
            device = Device.objects.get(udid=udid)
        except Device.DoesNotExist:
            raise Http404
    else:
        raise Http404

    DeviceCommand.NewDeviceInformation(device)

    push.push_notification(device)
    return HttpResponse('OK')
Пример #7
0
def build_system_configuration_profile(device, install=False):
    # Configuration Profiles are only valid on OS X.
    if device.os != Device.OSX:
        return

    plist = {}
    plist['PayloadDisplayName'] = 'System Device Configuration'
    plist['PayloadDescription'] = 'Managed Preferences for Device'
    plist[
        'PayloadIdentifier'] = settings.MANAGED_PROFILE_IDENTIFIER + '.ManagedPreferences'
    plist['PayloadOrganization'] = settings.ORGANIZATION
    plist['PayloadRemovalDisallowed'] = False
    plist['PayloadVersion'] = 1
    plist['PayloadType'] = 'Configuration'
    plist['PayloadScope'] = 'System'
    plist['PayloadUUID'] = str(uuid.uuid4())

    plist['PayloadContent'] = []
    apps = build_custom_preference_profile(device)
    for app in apps:
        payload = {}
        payload['PayloadEnabled'] = True
        payload['PayloadType'] = 'com.apple.ManagedClient.preferences'
        payload['PayloadUUID'] = str(uuid.uuid4())
        payload['PayloadIdentifier'] = plist[
            'PayloadIdentifier'] + '.alacarte.customsettings.' + payload[
                'PayloadUUID']
        payload['PayloadVerison'] = 1
        payload['PayloadContent'] = {app: apps[app]}
        plist['PayloadContent'].append(payload)

    if DeviceProfile.objects.filter(
            device=device, identifier=plist['PayloadIdentifier']).count() == 0:
        profile = DeviceProfile(device=device)
    else:
        profile = DeviceProfile.objects.get(
            device=device, identifier=plist['PayloadIdentifier'])
    profile.name = plist['PayloadDisplayName']
    profile.identifier = plist['PayloadIdentifier']
    profile.uuid = plist['PayloadUUID']

    profile.payload = plistlib.writePlistToString(plist)

    profile.save()

    if install == True:
        DeviceCommand.InstallProfile(device, profile)
        push.push_notification(device)
Пример #8
0
def build_system_configuration_profile(device, install = False):
    # Configuration Profiles are only valid on OS X.
    if device.os != Device.OSX:
        return

    plist = { }
    plist['PayloadDisplayName'] = 'System Device Configuration'
    plist['PayloadDescription'] = 'Managed Preferences for Device'
    plist['PayloadIdentifier'] = settings.MANAGED_PROFILE_IDENTIFIER + '.ManagedPreferences'
    plist['PayloadOrganization'] = settings.ORGANIZATION
    plist['PayloadRemovalDisallowed'] = False
    plist['PayloadVersion'] = 1
    plist['PayloadType'] = 'Configuration'
    plist['PayloadScope'] = 'System'
    plist['PayloadUUID'] = str(uuid.uuid4())

    plist['PayloadContent'] = [ ]
    apps = build_custom_preference_profile(device)
    for app in apps:
        payload = { }
        payload['PayloadEnabled'] = True
        payload['PayloadType'] = 'com.apple.ManagedClient.preferences'
        payload['PayloadUUID'] = str(uuid.uuid4())
        payload['PayloadIdentifier'] = plist['PayloadIdentifier'] + '.alacarte.customsettings.' + payload['PayloadUUID']
        payload['PayloadVerison'] = 1
        payload['PayloadContent'] = { app: apps[app] }
        plist['PayloadContent'].append(payload)

    if DeviceProfile.objects.filter(device=device, identifier=plist['PayloadIdentifier']).count() == 0:
        profile = DeviceProfile(device=device)
    else:
        profile = DeviceProfile.objects.get(device=device, identifier=plist['PayloadIdentifier'])
    profile.name = plist['PayloadDisplayName']
    profile.identifier = plist['PayloadIdentifier']
    profile.uuid = plist['PayloadUUID']

    profile.payload = plistlib.writePlistToString(plist)

    profile.save()

    if install == True:
        DeviceCommand.InstallProfile(device, profile)
        push.push_notification(device)
Пример #9
0
 def on_status(self, status):
     try:
         say("Detected flash...")
         if configuration.is_following(status.user.screen_name):
             say("...from a relevant source!")
             url = None
             if 'urls' in status.entities and len(status.entities['urls']) > 0:
                 url = status.entities['urls'][0]["expanded_url"]
             flash = generate_flash(status.text,
                                    url,
                                    configuration.get_name(status.user.screen_name),
                                    status.id,
                                    status.created_at,
                                    configuration.get_channel(status.user.screen_name)
                                    )
             push_flash(flash)
             push.push_notification(flash)
             ok("Detected and pushed flash: " + str(flash))
         else:
             say("...from an irrelevant source.")
     except Exception as e:
         error("Encountered an exception while processing a flash: " + str(e))
     return True
Пример #10
0
def checkin(request):
    logger = logging.getLogger('django')
    logger.debug('WWW Query: %s', request.body)

    if settings.USE_CERTIFICATE == True:
        # Get the certificate fingerprint
        try:
            bio = BIO.MemoryBuffer(base64.b64decode(request.META['HTTP_MDM_SIGNATURE']))
            p7 = SMIME.PKCS7(m2.pkcs7_read_bio_der(bio._ptr()), 1)
            stk = X509.X509_Stack()
            sk3 = p7.get0_signers(stk)
            cert = sk3.pop()
            fingerprint = cert.get_fingerprint('md5')
            if len(fingerprint) == 31:
                fingerprint = '0' + fingerprint
        except:
            fingerprint = None

        logger.debug('Fingerprint: %s', fingerprint)
        # If no certificate supplied, permission denied.
        if fingerprint == None and settings.REQUIRE_CERTIFICATE == True:
            return HttpResponseForbidden()

        # If no certificate found, permission denied.
        certificate = Certificate.objects.filter(md5=fingerprint).first()
        if certificate == None and settings.REQUIRE_CERTIFICATE == True:
            return HttpResponseForbidden()

        # If certificate does not match device, permission denied.
        # TODO
    else:
        certificate = None

    # Prepare handling of checkin request and response commands.
    responseData = plistlib.writePlistToString(dict())
    standard_commands.initialize()

    try:
        plist = plistlib.readPlistFromString(request.body)
    except:
        plist = dict()

    if 'MessageType' in plist:
        if plist['MessageType'] == 'Authenticate':
            if 'UserID' in plist:
                return HttpResponseBadRequest('User binding not currently supported')

            device = Device.objects.filter(udid=plist['UDID']).first()
            if device == None:
                device = Device(udid=plist['UDID'], push_topic=plist['Topic'])
            device.last_checkin = datetime.now()
            device.last_notification = datetime.now()
            device.save()
            if certificate != None:
                certificate.device = device
                certificate.save()

            try:
                group = DeviceGroup.objects.filter(uuid=settings.DEFAULT_DEVICE_GROUP).first()
                group.devices.add(device)
                group.save()
            except:
                pass

        elif plist['MessageType'] == 'TokenUpdate':
            if 'UserID' in plist:
                return HttpResponseBadRequest('User binding not currently supported')

            device = Device.objects.get(udid=plist['UDID'])
            device.push_topic = plist['Topic']
            device.push_token = plist['Token'].asBase64(maxlinelength=8000)
            device.push_magic = plist['PushMagic']
            device.last_checkin = datetime.now()
            device.save()

            DeviceCommand.NewDeviceInformation(device)
            DeviceCommand.NewProfileList(device)
            DeviceCommand.NewInstalledApplicationList(device)
            push.push_notification(device)
        elif plist['MessageType'] == 'CheckOut':
            if 'UserID' in plist:
                return HttpResponseBadRequest('User binding not currently supported')

            Device.objects.get(udid=plist['UDID']).delete()
        else:
            print 'Unknown message type: ' + plist['MessageType']
            print plist
    elif 'Status' in plist:
        responseData = ''

        # Update device checkin time
        device = Device.objects.get(udid=plist['UDID'])
        device.last_checkin = datetime.now()
        device.save()

        # Update device location if it has been 15 minutes since last.
        since = datetime.now() - timedelta(minutes=15)
        location = DeviceCheckin.objects.filter(device=device).order_by('-end_date').first()
        if location and location.ip == request.META['REMOTE_ADDR']:
            location.end_date = datetime.now()
            location.save()
        else:
            location = DeviceCheckin(device=device)
            location.start_date = datetime.now()
            location.end_date = datetime.now()
            location.ip = request.META['REMOTE_ADDR']
            loc = geo.geocode(request.META['REMOTE_ADDR'])
            location.latitude = loc['latitude']
            location.longitude = loc['longitude']
            location.country_code = loc['country_code']
            location.region_code = loc['region_code']
            location.city = loc['city']
            if 'country_name' in loc:
                location.country_name = loc['country_name']
            if 'region_name' in loc:
                location.region_name = loc['region_name']
            location.save()

        if plist['Status'] == 'Acknowledged':
            cmd = DeviceCommand.objects.get(uuid=plist['CommandUUID'])
            cmd.status = DeviceCommand.SUCCESS
            cmd.date_completed = datetime.now()
            cmd.save()
            commands.handleCommandResponse(cmd, plist)
        elif plist['Status'] == 'Error' or plist['Status'] == 'CommandFormatError':
            cmd = DeviceCommand.objects.get(uuid=plist['CommandUUID'])
            cmd.status = DeviceCommand.FAILED
            cmd.date_completed = datetime.now()
            cmd.save()
        elif plist['Status'] == 'NotNow':
            cmd = DeviceCommand.objects.get(uuid=plist['CommandUUID'])
            cmd.status = DeviceCommand.PENDING
            cmd.attempts = 0
            cmd.save()

        if plist['Status'] == 'Idle' or plist['Status'] == 'Acknowledged':
            # Look for the next command, mark as failed if too many attempts.
            cmd = DeviceCommand.objects.filter(device=device, status__in=[DeviceCommand.PENDING, DeviceCommand.RUNNING]).first()
            while cmd and cmd.attempts >= 3:
                cmd.status = DeviceCommand.FAILED
                cmd.save()
                cmd = DeviceCommand.objects.filter(device=device, status__in=[DeviceCommand.PENDING, DeviceCommand.RUNNING]).first()

            # Run the next command.
            if cmd:
                data = commands.dataForCommand(cmd)
                responseData = plistlib.writePlistToString(data)
                cmd.status = DeviceCommand.RUNNING
                cmd.attempts += 1
                cmd.save()

    logger.debug('WWW Result: %s', responseData)

    response = HttpResponse(responseData, content_type = 'application/xml; charset=UTF-8')
    response['Content-Length'] = len(responseData)
    return response
Пример #11
0
def monitor_detail_api(request, udid):
    device = None
    if udid:
        try:
            device = Device.objects.get(udid=udid)
        except Device.DoesNotExist:
            raise Http404
    else:
        raise Http404

    if request.method == 'GET':
        data = request.GET
    else:
        data = request.POST

    result = { }
    if 'command' not in data:
        result['status'] = 'ERROR'
        result['error'] = 'Invalid request'
        return HttpResponse(json.dumps(result))

    if data['command'] == 'CommandHistory':
        commands = DeviceCommand.objects.filter(device=device)
        result['objects'] = [ ]
        for cmd in commands:
            obj = {
                'name': cmd.name,
                'status': cmd.get_status_display(),
                'date_requested': cmd.date_requested.strftime("%m/%d/%Y %l:%M%p"),
                'date_requested_sort': cmd.date_requested.strftime("%s"),
            }
            if cmd.date_completed:
                obj['date_completed'] = cmd.date_completed.strftime("%m/%d/%Y %l:%M%p")
                obj['date_completed_sort'] = cmd.date_completed.strftime("%s")
            else:
                obj['date_completed'] = ''
                obj['date_completed_sort'] = -1
       
            result['objects'].append(obj)

        result['status'] = 'OK'
    elif data['command'] == 'InstalledProfiles':
        profiles = ProfileInventoryItem.objects.filter(device=device)
        result['objects'] = [ ]
        for profile in profiles:
            managed = profile.identifier[:len(settings.MANAGED_PROFILE_IDENTIFIER)] == settings.MANAGED_PROFILE_IDENTIFIER
            uptodate = False
            if managed:
                p = DeviceProfile.objects.filter(device=device, identifier=profile.identifier).first()
                if p and p.uuid == profile.uuid:
                    uptodate = True

            result['objects'].append({
                'name': profile.name,
                'description': profile.description,
                'identifier': profile.identifier,
                'uuid': profile.uuid,
                'managed': managed,
                'uptodate': uptodate,
            })
        result['status'] = 'OK'
    elif data['command'] == 'LocationHistory':
        checkins = DeviceCheckin.objects.filter(device=device)
        result['objects'] = [ ]
        for checkin in checkins:
            result['objects'].append({
                'start_date': checkin.start_date.strftime("%m/%d/%Y %l:%M%p"),
                'start_date_sort': checkin.start_date.strftime("%s"),
                'end_date': checkin.end_date.strftime("%m/%d/%Y %l:%M%p"),
                'end_date_sort': checkin.end_date.strftime("%s"),
                'ip': checkin.ip,
                'latitude': checkin.latitude,
                'longitude': checkin.longitude,
                'city': checkin.city,
                'region': checkin.region_code,
                'country': checkin.country_code,
            })
        result['status'] = 'OK'
    elif data['command'] == 'InstallProfile':
        profile = DeviceProfile.objects.filter(device=device, identifier=data['identifier']).first()
        if profile:
            DeviceCommand.InstallProfile(device, profile)
            push.push_notification(device)
            result['status'] = 'OK'
        else:
            result['status'] = 'ERROR'
            result['error'] = 'Invalid profile specified.'

    return HttpResponse(json.dumps(result))
Пример #12
0
def get_pages(cnt = 1, ignore = True, push = False):
    global col_Errors, col_Items
    global prefix_url
    global max_try

    last_page, coding = get_last_page()
    if int(last_page) == 0: #判断获取最后一页是否出错
        log.log_prn('Get', 'get_last_page error', 'ERROR')
        return

    log.log_prn('Get', 'Get last page num : %d' % int(last_page), 'NORMAL')

    temp_last_page = last_page

    circle_count = 1

    while cnt <= int(temp_last_page):
        log.log_prn("Get", "---------------------------------------", "NORMAL")
        log.log_prn("Get", "Getting page %d data ..." % cnt, "NORMAL")

        page_infos = get_single_page(cnt, coding)
        if page_infos == None:#因为数量不匹配,错误
            db.insert_one_doc(col_Errors, cnt)

        #插入db的item数量
        insert_count = 0

        #404 requests.get返回码错误
        #400 requests.get无响应
        if 404 == page_infos['return_code'] or 400 == page_infos['return_code']:
            log.log_prn('Get', 'get_page return_code %d, times %d, page_url %s' % (page_infos['return_code'], circle_count ,prefix_url + str(cnt)), 'ERROR')
            op_time.delay(2, 1)
            if circle_count < max_try:#设定抓取出错次数,超过则跳过,并存入db
                circle_count = circle_count + 1
                continue #这里直接进入下一次循环,但是页面并没有改变,下一次还是抓取此次页面
            else:
                circle_count = 1
                cnt = cnt + 1
                log.log_prn('Get', 'Fail to get the page %s' % prefix_url + str(cnt), 'ERROR')

                #!!!待存入error db,如何来定位?
                db.insert_one_doc(col_Errors, cnt)

        elif 200 == page_infos['return_code']:
            #!!!循环得到的数据,查看数据库中是否存在,如果存在则break
            insert_data = [] #插入数据库的item
            for item in page_infos["data"]:
                if db.find_one_doc(col_Items, item['id']) != 0:#数据库中存在
                    log.log_prn("Get", "Item %d already exist." % int(item['id']), "WARN")
                else:
                    insert_count = insert_count+1
                    db.insert_one_doc(col_Items, item)
                    insert_data.append(item) #记录插入数据库的数据
                    log.log_prn("Get", "Item %d insert in Collection Items" % int(item['id']), "NROMAL")

            if insert_count == 0 and True == ignore:#如果本页面中Item插入数据库的数量=0,则认为该页面以及其后面的页面都已经在数据库存在
                log.log_prn("Get", "ignore False.Page %d items have already inserted in db, aboart this scan" % cnt, "NORMAL")
                log.flush_log()
                break #后续循环退出

            if not push_notification(insert_data):
                log.log_prn("Get", "Push items failed. Page %d" % cnt, "ERROR")

            cnt = cnt + 1
            circle_count = 1

        log.log_prn("Get", "Insert %d items to Col_items" % insert_count, "NORMAL")
        log.flush_log()
        op_time.delay(3, 1)
    return None
Пример #13
0
def checkin(request):
    logger = logging.getLogger('django')
    logger.debug('WWW Query: %s', request.body)

    if settings.USE_CERTIFICATE == True:
        # Get the certificate fingerprint
        try:
            bio = BIO.MemoryBuffer(
                base64.b64decode(request.META['HTTP_MDM_SIGNATURE']))
            p7 = SMIME.PKCS7(m2.pkcs7_read_bio_der(bio._ptr()), 1)
            stk = X509.X509_Stack()
            sk3 = p7.get0_signers(stk)
            cert = sk3.pop()
            fingerprint = cert.get_fingerprint('md5')
            if len(fingerprint) == 31:
                fingerprint = '0' + fingerprint
        except:
            fingerprint = None

        logger.debug('Fingerprint: %s', fingerprint)
        # If no certificate supplied, permission denied.
        if fingerprint == None and settings.REQUIRE_CERTIFICATE == True:
            return HttpResponseForbidden()

        # If no certificate found, permission denied.
        certificate = Certificate.objects.filter(md5=fingerprint).first()
        if certificate == None and settings.REQUIRE_CERTIFICATE == True:
            return HttpResponseForbidden()

        # If certificate does not match device, permission denied.
        # TODO
    else:
        certificate = None

    # Prepare handling of checkin request and response commands.
    responseData = plistlib.writePlistToString(dict())
    standard_commands.initialize()

    try:
        plist = plistlib.readPlistFromString(request.body)
    except:
        plist = dict()

    if 'MessageType' in plist:
        if plist['MessageType'] == 'Authenticate':
            if 'UserID' in plist:
                return HttpResponseBadRequest(
                    'User binding not currently supported')

            device = Device.objects.filter(udid=plist['UDID']).first()
            if device == None:
                device = Device(udid=plist['UDID'], push_topic=plist['Topic'])
            device.last_checkin = datetime.now()
            device.last_notification = datetime.now()
            device.save()
            if certificate != None:
                certificate.device = device
                certificate.save()

            try:
                group = DeviceGroup.objects.filter(
                    uuid=settings.DEFAULT_DEVICE_GROUP).first()
                group.devices.add(device)
                group.save()
            except:
                pass

        elif plist['MessageType'] == 'TokenUpdate':
            if 'UserID' in plist:
                return HttpResponseBadRequest(
                    'User binding not currently supported')

            device = Device.objects.get(udid=plist['UDID'])
            device.push_topic = plist['Topic']
            device.push_token = plist['Token'].asBase64(maxlinelength=8000)
            device.push_magic = plist['PushMagic']
            device.last_checkin = datetime.now()
            device.save()

            DeviceCommand.NewDeviceInformation(device)
            DeviceCommand.NewProfileList(device)
            DeviceCommand.NewInstalledApplicationList(device)
            push.push_notification(device)
        elif plist['MessageType'] == 'CheckOut':
            if 'UserID' in plist:
                return HttpResponseBadRequest(
                    'User binding not currently supported')

            Device.objects.get(udid=plist['UDID']).delete()
        else:
            print 'Unknown message type: ' + plist['MessageType']
            print plist
    elif 'Status' in plist:
        responseData = ''

        # Update device checkin time
        device = Device.objects.get(udid=plist['UDID'])
        device.last_checkin = datetime.now()
        device.save()

        # Update device location if it has been 15 minutes since last.
        since = datetime.now() - timedelta(minutes=15)
        location = DeviceCheckin.objects.filter(
            device=device).order_by('-end_date').first()
        if location and location.ip == request.META['REMOTE_ADDR']:
            location.end_date = datetime.now()
            location.save()
        else:
            location = DeviceCheckin(device=device)
            location.start_date = datetime.now()
            location.end_date = datetime.now()
            location.ip = request.META['REMOTE_ADDR']
            loc = geo.geocode(request.META['REMOTE_ADDR'])
            location.latitude = loc['latitude']
            location.longitude = loc['longitude']
            location.country_code = loc['country_code']
            location.region_code = loc['region_code']
            location.city = loc['city']
            if 'country_name' in loc:
                location.country_name = loc['country_name']
            if 'region_name' in loc:
                location.region_name = loc['region_name']
            location.save()

        if plist['Status'] == 'Acknowledged':
            cmd = DeviceCommand.objects.get(uuid=plist['CommandUUID'])
            cmd.status = DeviceCommand.SUCCESS
            cmd.date_completed = datetime.now()
            cmd.save()
            commands.handleCommandResponse(cmd, plist)
        elif plist['Status'] == 'Error' or plist[
                'Status'] == 'CommandFormatError':
            cmd = DeviceCommand.objects.get(uuid=plist['CommandUUID'])
            cmd.status = DeviceCommand.FAILED
            cmd.date_completed = datetime.now()
            cmd.save()
        elif plist['Status'] == 'NotNow':
            cmd = DeviceCommand.objects.get(uuid=plist['CommandUUID'])
            cmd.status = DeviceCommand.PENDING
            cmd.attempts = 0
            cmd.save()

        if plist['Status'] == 'Idle' or plist['Status'] == 'Acknowledged':
            # Look for the next command, mark as failed if too many attempts.
            cmd = DeviceCommand.objects.filter(
                device=device,
                status__in=[DeviceCommand.PENDING,
                            DeviceCommand.RUNNING]).first()
            while cmd and cmd.attempts >= 3:
                cmd.status = DeviceCommand.FAILED
                cmd.save()
                cmd = DeviceCommand.objects.filter(
                    device=device,
                    status__in=[DeviceCommand.PENDING,
                                DeviceCommand.RUNNING]).first()

            # Run the next command.
            if cmd:
                data = commands.dataForCommand(cmd)
                responseData = plistlib.writePlistToString(data)
                cmd.status = DeviceCommand.RUNNING
                cmd.attempts += 1
                cmd.save()

    logger.debug('WWW Result: %s', responseData)

    response = HttpResponse(responseData,
                            content_type='application/xml; charset=UTF-8')
    response['Content-Length'] = len(responseData)
    return response
Пример #14
0
def monitor_detail_api(request, udid):
    device = None
    if udid:
        try:
            device = Device.objects.get(udid=udid)
        except Device.DoesNotExist:
            raise Http404
    else:
        raise Http404

    if request.method == 'GET':
        data = request.GET
    else:
        data = request.POST

    result = {}
    if 'command' not in data:
        result['status'] = 'ERROR'
        result['error'] = 'Invalid request'
        return HttpResponse(json.dumps(result))

    if data['command'] == 'CommandHistory':
        commands = DeviceCommand.objects.filter(device=device)
        result['objects'] = []
        for cmd in commands:
            obj = {
                'name': cmd.name,
                'status': cmd.get_status_display(),
                'date_requested':
                cmd.date_requested.strftime("%m/%d/%Y %l:%M%p"),
                'date_requested_sort': cmd.date_requested.strftime("%s"),
            }
            if cmd.date_completed:
                obj['date_completed'] = cmd.date_completed.strftime(
                    "%m/%d/%Y %l:%M%p")
                obj['date_completed_sort'] = cmd.date_completed.strftime("%s")
            else:
                obj['date_completed'] = ''
                obj['date_completed_sort'] = -1

            result['objects'].append(obj)

        result['status'] = 'OK'
    elif data['command'] == 'InstalledProfiles':
        profiles = ProfileInventoryItem.objects.filter(device=device)
        result['objects'] = []
        for profile in profiles:
            managed = profile.identifier[:len(
                settings.MANAGED_PROFILE_IDENTIFIER
            )] == settings.MANAGED_PROFILE_IDENTIFIER
            uptodate = False
            if managed:
                p = DeviceProfile.objects.filter(
                    device=device, identifier=profile.identifier).first()
                if p and p.uuid == profile.uuid:
                    uptodate = True

            result['objects'].append({
                'name': profile.name,
                'description': profile.description,
                'identifier': profile.identifier,
                'uuid': profile.uuid,
                'managed': managed,
                'uptodate': uptodate,
            })
        result['status'] = 'OK'
    elif data['command'] == 'LocationHistory':
        checkins = DeviceCheckin.objects.filter(device=device)
        result['objects'] = []
        for checkin in checkins:
            result['objects'].append({
                'start_date':
                checkin.start_date.strftime("%m/%d/%Y %l:%M%p"),
                'start_date_sort':
                checkin.start_date.strftime("%s"),
                'end_date':
                checkin.end_date.strftime("%m/%d/%Y %l:%M%p"),
                'end_date_sort':
                checkin.end_date.strftime("%s"),
                'ip':
                checkin.ip,
                'latitude':
                checkin.latitude,
                'longitude':
                checkin.longitude,
                'city':
                checkin.city,
                'region':
                checkin.region_code,
                'country':
                checkin.country_code,
            })
        result['status'] = 'OK'
    elif data['command'] == 'InstallProfile':
        profile = DeviceProfile.objects.filter(
            device=device, identifier=data['identifier']).first()
        if profile:
            DeviceCommand.InstallProfile(device, profile)
            push.push_notification(device)
            result['status'] = 'OK'
        else:
            result['status'] = 'ERROR'
            result['error'] = 'Invalid profile specified.'

    return HttpResponse(json.dumps(result))