class ApiUserHandler(APIHandler, BaseHandler):
    def check_xsrf_cookie(self):
        pass

    @schema.validate()
    def post(self):
        try:
            username = self.get_argument('username_guai')
            password = self.get_argument('password_guai')
            user = self.session.query(User).filter(and_(User.username == username, User.password == password)).first()
            if user:
                logging.info(str(username) + 'login success')
                return 'true'
            else:
                logging.info(str(username) + 'login false')
                return 'false'
        except:
            logging.info(str(username) + 'login database_error')
            return 'database_error' class ApiScreenNumber(APIHandler, BaseHandler):
    def check_xsrf_cookie(self):
        pass

    @schema.validate()
    def post(self):
        try:
            device_id = self.get_argument('device_id')
            device = self.session.query(Device).filter(Device.device_id == device_id).first()
            list_data = []
            dict_data = dict()
            if device:
                dict_data['screen_number'] = device.screen_number
                list_data.append(dict_data)
                logging.info("device_id: success" + device_id)
                return list_data
            else:
                dict_data['screen_number'] = '3'
                list_data.append(dict_data)
                logging.info("device_id: success no device" + device_id)
                return list_data
        except:
            logging.info("device_id: database_error" + device_id)
            return 'database_error' class ApiDeviceRegister(APIHandler, BaseHandler):
    def check_xsrf_cookie(self):
        pass

    @schema.validate()
    def post(self):
        try:
            device = self.session.query(Device).filter(Device.device_id == self.get_argument('device_id')).first()
            if device:
                return 'device_already_exists'
            else:
                data = time.strftime("%Y-%m-%d")
                company = self.session.query(Company).filter(Company.code == self.get_argument('company')).first()
                device_data = Device(device_id=self.get_argument('device_id'),
                                     device_id_s=self.get_argument('device_id_s'),
                                     device_name=self.get_argument('device_name'),
                                     ip=self.get_argument('ip'),
                                     port=self.get_argument('port'),
                                     data=data,
                                     model=self.get_argument('model'),
                                     board_model=self.get_argument('board_model'),
                                     screen_size=self.get_argument('screen_size'),
                                     screen_resolution=self.get_argument('screen_resolution'),
                                     screen_number='3',
                                     cpu_model=self.get_argument('cpu_model'),
                                     cpu_num=self.get_argument('cpu_num'),
                                     ram_model=self.get_argument('ram_model'),
                                     ram_size=self.get_argument('ram_size'),
                                     mac_address=self.get_argument('mac_address'),
                                     voltage=self.get_argument('voltage'),
                                     power_consumption=self.get_argument('power_consumption'),
                                     device_position=self.get_argument('device_position'),
                                     company_id=company.id
                                     )
                self.session.add(device_data)
                self.session.commit()
                return 'device_register_ok'
        except:
            return 'database_error' class ApiUserSocketHandler(tornado.websocket.WebSocketHandler):
    # 用户集 字典类型 key为username ，value 为 对应的对象
    user_client_map = {}

    @staticmethod
    def send_to_all_user(self, message):
        for i in ApiUserSocketHandler.user_client_map:
            ApiUserSocketHandler.user_client_map[i].write_message(json.dumps(message))

    @staticmethod
    def send_to_one_user(user_client, message):
        user_client.write_message(json.dumps(message))

    @staticmethod
    def send_to_many_user(user_clients, message):
        for user_client in user_clients:
            user_client.write_message(json.dumps(message))

    def open(self):
        pass

    def on_close(self):
        pass

    def on_message(self, message):
        pass

    def on_pong(self, data):
        logging.info("on_pong: " + data) class ApiDeviceSocketHandler(tornado.websocket.WebSocketHandler):
    # 用户集 字典类型 key为username ，value 为 对应的对象
    device_client_map = {}

    @staticmethod
    def send_to_all_device(self, message):
        for i in ApiDeviceSocketHandler.device_client_map:
            ApiDeviceSocketHandler.device_client_map[i].write_message(json.dumps(message))
            logging.info('send_to_all_device' + str(message))

    @staticmethod
    def send_to_one_device(device_id, message):
        if ApiDeviceSocketHandler.device_client_map.has_key(device_id):
            ApiDeviceSocketHandler.device_client_map[device_id].write_message(json.dumps(message))
            logging.info('send_to_one_device 推送成功' + str(device_id))
        else:
            logging.info('send_to_many_device 推送失败 不在线' + str(device_id))

    @staticmethod
    def send_to_many_device(device_clients, message):
        for device_client in device_clients:
            device_id = device_client.device_id
            if ApiDeviceSocketHandler.device_client_map.has_key(device_id):
                ApiDeviceSocketHandler.device_client_map[device_id].write_message(json.dumps(message))
                logging.info('send_to_many_device 推送成功' + str(device_id))
            else:
                logging.info('send_to_many_device 推送失败 不在线' + str(device_id))

    # send_success
    @staticmethod
    def send_success(self):
        self.write_message(json.dumps([{
            'cmd': 'connect_success',
        }, {
            'form_user': 'system',
            'data': 'open:connect_success',
        }]))

    # websocke第一次连接是调用
    def open(self):
        device_id = str(self.get_argument("device_id"))
        # 发送成功
        ApiDeviceSocketHandler.send_success(self)
        logging.info("device_id: " + device_id + " : connect_success")
        # 添加设备到设备字典中
        ApiDeviceSocketHandler.device_client_map[device_id] = self
        logging.info("device_client_map: " + str(ApiDeviceSocketHandler.device_client_map))
        # 推送资源组数据
        playlist = BaseFunctionHandler.get_res_group_by_device_id(device_id)
        self.write_message(json.dumps(playlist))
        logging.info(device_id + '播放列表推送成功:' + str(json.dumps(playlist)))
        # 推送定时开关机数据
        time_switch = BaseFunctionHandler.get_time_switch(device_id)
        self.write_message(json.dumps(time_switch))
        logging.info(device_id + '定时开关机推送成功:' + str(json.dumps(time_switch)))

    # 获取websocket 数据时调用
    def on_message(self, message):
        if message == 'heart':
            device_id = str(self.get_argument('device_id'))
            logging.info(device_id + ': 心跳连接正常')
        else:
            key, value = message.split("::")
            if key == 'res_data':
                data_list = value.split("||")
                data_dict = dict()
                # 向服务器注册
                for data in data_list:
                    key1, value1 = data.split("__")
                    data_dict[key1] = value1
                logging.info("before服务器注册" + str(data_dict))
                res = BaseFunctionHandler.device_res(self, data_dict)
                logging.info("after服务器注册" + str(res))
                self.write_message(json.dumps([{
                    'cmd': 'res_data',
                }, {
                    'form_user': 'system',
                    'data': res,
                }]))
            else:
                self.write_message(json.dumps([{
                    'cmd': 'error',
                }, {
                    'form_user': 'system',
                    'data': 'key_error',
                }]))

    # 设备断线时调用
    def on_close(self):
        device_id = str(self.get_argument("device_id"))
        del ApiDeviceSocketHandler.device_client_map[device_id]
        logging.info("device_client_map: " + str(ApiDeviceSocketHandler.device_client_map))
        logging.info("device_id:" + device_id + "on_close") class DeviceManageHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        devices = self.session.query(Device).filter(Device.company_id == self.get_secure_cookie('company_id')).all()
        self.render("dev_manage.html", auth_user=self.current_user, devices=devices) class DeviceManageDetailHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        device_id = self.get_argument("device_id")
        err = ''
        device = self.session.query(Device).filter(Device.device_id == device_id).first()
        device_groups = self.session.query(DeviceGroup).filter(DeviceGroup.company_id == self.get_secure_cookie('company_id')).all()
        device_screen_numbers = self.session.query(DeviceScreenNumber).filter().all()
        self.render("dev_manage_detail.html", auth_user=self.current_user, device=device, device_groups=device_groups, device_screen_numbers=device_screen_numbers, err=err)

    @tornado.web.authenticated
    def post(self):
        device_id = self.get_argument('device_id')
        device_name = self.get_argument("device_name")
        ip = self.get_argument("ip")
        device_position = self.get_argument("device_position")
        port = self.get_argument("port")
        device_use = self.get_argument("device_use")
        device_audio = self.get_argument("device_audio")
        screen_number = self.get_argument("screen_number")
        ad_environment = self.get_argument("ad_environment")
        device_group_id = self.get_argument('deviceGroup_id')
        try:
            device = Device(
                    device_id=device_id,
                    device_name=device_name,
                    ip=ip,
                    device_position=device_position,
                    port=port,
                    device_audio=device_audio,
                    screen_number=screen_number,
                    device_use=device_use,
                    ad_environment=ad_environment,
                    deviceGroup_id=device_group_id,
            )
            self.session.merge(device)
            self.session.commit()
            # 新建任务
            my_task = MyTask(
                name='设备信息任务',
                type='device',
                time=time.strftime("%Y-%m-%d %H:%M:%S"),
                user_id=self.get_secure_cookie('user_id'),
                company_id=self.get_secure_cookie('company_id'),
            )
            self.session.add(my_task)
            self.session.commit()
            # 新建任务内容
            data_list = list()
            data_dict = dict()
            data_dict['cmd'] = 'device'
            data_list.append(data_dict)
            data_dict = dict()
            data_dict['device_audio'] = device_audio
            data_dict['screen_number'] = screen_number
            data_list.append(data_dict)
            my_task_content = MyTaskContent(
                device_id=device.device_id,
                from_user=self.get_secure_cookie('username'),
                new_time=time.strftime("%Y-%m-%d %H:%M:%S"),
                send_time=time.strftime("%Y-%m-%d %H:%M:%S"),
                send_data=str(data_list),
                my_task_id=my_task.id
            )
            self.session.add(my_task_content)
            self.session.commit()
            ApiDeviceSocketHandler.send_to_one_device(device_id, data_list)
            self.redirect('/dev/group?device_group_id='+device_group_id)
        except:
            err = '修改失败'
            device = self.session.query(Device).filter(Device.device_id == device_id).first()
            self.render("dev_manage_detail.html", auth_user=self.current_user, device=device, err=err) class DeviceGroupHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        company_id = self.get_secure_cookie('company_id')
        device_group_id = self.get_argument('device_group_id')
        device_groups = self.session.query(DeviceGroup).filter(DeviceGroup.company_id == company_id).all()
        if device_group_id == '':
            device_group = self.session.query(DeviceGroup).filter(DeviceGroup.company_id == company_id).first()
            if device_group:
                device_group_id = device_group.id
                devices = self.session.query(Device).filter(Device.deviceGroup_id == device_group_id).all()
            else:
                devices = ''
        else:
            devices = self.session.query(Device).filter(Device.deviceGroup_id == device_group_id).all()
        self.render("dev_group.html", auth_user=self.current_user, device_groups=device_groups, devices=devices) class DeviceGroupAddHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        msg = ''
        action = '/dev/group/add'
        device_group = DeviceGroup()
        res_groups = self.session.query(ResGroup).filter(ResGroup.company_id == self.get_secure_cookie('company_id')).all()
        device_time_switches = self.session.query(DeviceTimeSwitch).filter(DeviceTimeSwitch.company_id == self.get_secure_cookie('company_id')).all()
        self.render("dev_group_add.html", auth_user=self.current_user, action=action, device_group=device_group, res_groups=res_groups, device_time_switches=device_time_switches,  msg=msg)

    @tornado.web.authenticated
    def post(self):
        name = self.get_argument('name')
        res_group_id = self.get_argument('res_group_id')
        device_time_switch_id = self.get_argument('device_time_switch_id')
        try:
            device_group = DeviceGroup(
                name=name,
                resGroup_id=res_group_id,
                device_time_switch_id=device_time_switch_id,
                company_id=self.get_secure_cookie('company_id'),
            )
            self.session.add(device_group)
            self.session.commit()
            self.redirect('/dev/group?device_group_id=')
        except:
            msg = '设备组新增失败'
            action = '/dev/group/add'
            device_group = DeviceGroup()
            self.render("dev_group_add.html", auth_user=self.current_user, action=action, device_group=device_group, msg=msg) class DeviceGroupDeleteHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        device_group_id = self.get_argument('device_group_id')
        device_group = self.session.query(DeviceGroup).filter(DeviceGroup.id == device_group_id).first()
        self.session.delete(device_group)
        self.session.commit()
        self.redirect('/dev/group?device_group_id=') class DeviceGroupUpdateHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        msg = ''
        action = '/dev/group/update'
        device_group_id = self.get_argument('device_group_id')
        device_group = self.session.query(DeviceGroup).filter(DeviceGroup.id == device_group_id).first()
        res_groups = self.session.query(ResGroup).filter(ResGroup.company_id == self.get_secure_cookie('company_id')).all()
        device_time_switches = self.session.query(DeviceTimeSwitch).filter(DeviceTimeSwitch.company_id == self.get_secure_cookie('company_id')).all()
        self.render("dev_group_add.html", auth_user=self.current_user, action=action, device_group=device_group, res_groups=res_groups, device_time_switches=device_time_switches, msg=msg)

    @tornado.web.authenticated
    def post(self):
        device_group_id = self.get_argument('device_group_id')
        res_group_id = self.get_argument('res_group_id')
        device_time_switch_id = self.get_argument('device_time_switch_id')
        name = self.get_argument('name')
        device_group = DeviceGroup(
            id=device_group_id,
            name=name,
            resGroup_id=res_group_id,
            device_time_switch_id=device_time_switch_id,
        )
        self.session.merge(device_group)
        self.session.commit()
        self.redirect('/dev/group?device_group_id='+device_group_id) class DeviceTimeSwitchHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        device_time_switch_id = self.get_argument('device_time_switch_id')
        device_time_switches = self.session.query(DeviceTimeSwitch).filter(DeviceTimeSwitch.company_id == self.get_secure_cookie('company_id')).all()
        if device_time_switch_id == '':
            device_time_switch = self.session.query(DeviceTimeSwitch).filter(DeviceTimeSwitch.company_id == self.get_secure_cookie('company_id')).first()
        else:
            device_time_switch = self.session.query(DeviceTimeSwitch).filter(DeviceTimeSwitch.id == device_time_switch_id).first()
        if device_time_switch:
            device_weeks = device_time_switch.device_week
        else:
            device_weeks = ''
        self.render("dev_timeSwitch.html", auth_user=self.current_user, device_time_switches=device_time_switches, device_weeks=device_weeks) class DeviceTimeSwitchAddHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        action = '/dev/timeSwitch/add'
        device_time_switch = DeviceTimeSwitch()
        self.render("dev_timeSwitch_add.html", auth_user=self.current_user, action=action, device_time_switch=device_time_switch)

    @tornado.web.authenticated
    def post(self):
        name = self.get_argument('name')
        company_id = self.get_secure_cookie('company_id')
        weeks = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
        device_time_switch = DeviceTimeSwitch(
            name=name,
            company_id=company_id,
        )
        self.session.add(device_time_switch)
        self.session.commit()
        for week in weeks:
            device_week = DeviceWeek(
                name=week,
                company_id=company_id,
                device_timeSwitch_id=device_time_switch.id
            )
            self.session.add(device_week)
        self.session.commit()
        self.redirect('/dev/timeSwitch?device_time_switch_id=') class DeviceTimeSwitchUpdateHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        action = '/dev/timeSwitch/update'
        device_time_switch_id = self.get_argument('device_time_switch_id')
        device_time_switch = self.session.query(DeviceTimeSwitch).filter(DeviceTimeSwitch.id == device_time_switch_id).first()
        self.render("dev_timeSwitch_add.html", auth_user=self.current_user, action=action, device_time_switch=device_time_switch)

    @tornado.web.authenticated
    def post(self):
        device_time_switch_id = self.get_argument('device_time_switch_id')
        name = self.get_argument('name')
        device_time_switch = DeviceTimeSwitch(
            id=device_time_switch_id,
            name=name,
        )
        self.session.merge(device_time_switch)
        self.session.commit()
        self.redirect('/dev/timeSwitch?device_time_switch_id='+device_time_switch_id) class DeviceTimeSwitchDeleteHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        device_time_switch_id = self.get_argument('device_time_switch_id')
        device_time_switch = self.session.query(DeviceTimeSwitch).filter(DeviceTimeSwitch.id == device_time_switch_id).first()
        self.session.delete(device_time_switch)
        self.session.commit()
        self.redirect('/dev/timeSwitch?device_time_switch_id=') class DeviceDayAddHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        action = '/dev/day/add'
        device_week_id = self.get_argument('device_week_id')
        device_week = self.session.query(DeviceWeek).filter(DeviceWeek.id == device_week_id).first()
        device_time_switch_id = str(device_week.device_timeSwitch_id)
        device_day = DeviceDay()
        time_list = ['0', '0']
        self.render("dev_day_add.html", auth_user=self.current_user, action=action, device_day=device_day, device_time_switch_id=device_time_switch_id, device_week_id=device_week_id, time_list=time_list)

    @tornado.web.authenticated
    def post(self):
        device_time_switch_id = self.get_argument('device_time_switch_id')
        name = self.get_argument('name')
        hour = self.get_argument('hour')
        screen = self.get_argument('screen')
        second = self.get_argument('second')
        time = hour + ':' + second + ':00'
        company_id = self.get_secure_cookie('company_id')
        device_week_id = self.get_argument('device_week_id')
        device_day = DeviceDay(
            name=name,
            time=time,
            screen=screen,
            device_week_id=device_week_id,
            company_id=company_id,
        )
        self.session.add(device_day)
        self.session.commit()
        self.redirect('/dev/timeSwitch?device_time_switch_id='+device_time_switch_id) class DeviceDayUpdateHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        action = '/dev/day/update'
        device_day_id = self.get_argument('device_day_id')
        device_week_id = self.get_argument('device_week_id')
        device_week = self.session.query(DeviceWeek).filter(DeviceWeek.id == device_week_id).first()
        device_time_switch_id = str(device_week.device_timeSwitch_id)
        device_day = self.session.query(DeviceDay).filter(DeviceDay.id == device_day_id).first()
        time_list = str(device_day.time).split(':')
        self.render("dev_day_add.html", auth_user=self.current_user, action=action, device_day=device_day, device_time_switch_id=device_time_switch_id, device_week_id=device_week_id, time_list=time_list)

    @tornado.web.authenticated
    def post(self):
        device_time_switch_id = self.get_argument('device_time_switch_id')
        id = self.get_argument('id')
        name = self.get_argument('name')
        hour = self.get_argument('hour')
        screen = self.get_argument('screen')
        second = self.get_argument('second')
        time = hour + ':' + second + ':00'
        device_day = DeviceDay(
            id=id,
            name=name,
            time=time,
            screen=screen,
        )
        self.session.merge(device_day)
        self.session.commit()
        self.redirect('/dev/timeSwitch?device_time_switch_id='+device_time_switch_id) class DeviceDayDeleteHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        device_day_id = self.get_argument('device_day_id')
        device_week_id = self.get_argument('device_week_id')
        device_week = self.session.query(DeviceWeek).filter(DeviceWeek.id == device_week_id).first()
        device_time_switch_id = str(device_week.device_timeSwitch_id)
        device_day = self.session.query(DeviceDay).filter(DeviceDay.id == device_day_id).first()
        self.session.delete(device_day)
        self.session.commit()
        self.redirect('/dev/timeSwitch?device_time_switch_id='+device_time_switch_id) class CompanyHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        companys = self.session.query(Company).filter(Company.id == self.get_secure_cookie('company_id')).all()
        self.render("fra_com_list.html", auth_user=self.current_user, companys=companys) class CompanyAddHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        err = ''
        self.render("fra_com_add.html", auth_user=self.current_user, err=err)

    @tornado.web.authenticated
    def post(self):
        name = self.get_argument('name')
        code = self.get_argument('code')
        address = self.get_argument('address')
        parent = self.get_argument('parent')
        company = self.session.query(Company).filter(Company.code == code).first()
        if company:
            err = '公司编码已存在'
            self.render("fra_com_add.html", auth_user=self.current_user, err=err)
        else:
            data = time.strftime("%Y-%m-%d")
            company = Company(
                    name=name,
                    code=code,
                    address=address,
                    parent=parent,
                    data=data,
            )
            self.session.add(company)
            self.session.commit()
            self.redirect('/fra/com') class CompanyDeteleHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        code = self.get_argument('code')
        if code:
            company = self.session.query(Company).filter(Company.code == code).first()
            self.session.delete(company)
            self.session.commit()
            self.redirect('/fra/com')
        else:
            err = '公司编码不存在'
            self.render("fra_com_detail.html", auth_user=self.current_user, err=err) class CompanyUpdateHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        code = self.get_argument('code')
        if code:
            err = ''
            company = self.session.query(Company).filter(Company.code == code).first()
            self.render("fra_com_detail.html", auth_user=self.current_user, company=company, err=err)
        else:
            err = '公司编码不存在'
            self.render("fra_com_detail.html", auth_user=self.current_user, err=err)

    @tornado.web.authenticated
    def post(self):
        name = self.get_argument('name')
        code = self.get_argument('code')
        address = self.get_argument('address')
        parent = self.get_argument('parent')
        company = self.session.query(Company).filter(Company.code == code).first()
        if company:
            data = time.strftime("%Y-%m-%d")
            company = Company(
                    id=company.id,
                    name=name,
                    code=code,
                    address=address,
                    parent=parent,
                    data=data,
            )
            self.session.merge(company)
            self.session.commit()
            self.redirect('/fra/com')
        else:
            err = '公司编码不存在'
            self.render("fra_com_add.html", auth_user=self.current_user, err=err) class UserHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        users = self.session.query(User).filter(User.company_id == self.get_secure_cookie('company_id')).all()
        self.render("fra_user_list.html", auth_user=self.current_user, users=users) class UserAddHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        err = ''
        companys = self.session.query(Company).filter().all()
        self.render("fra_user_add.html", auth_user=self.current_user, companys=companys, err=err)

    @tornado.web.authenticated
    def post(self):
        username = self.get_argument('username')
        # sha256加密
        password = hashlib.sha256(self.get_argument('password')).hexdigest()
        email = self.get_argument('email')
        tell_phone = self.get_argument('tell_phone')
        company_id = self.get_argument('company_id')
        user = self.session.query(User).filter(User.username == username).first()
        if user:
            err = '用户已经存在'
            self.render("fra_user_add.html", auth_user=self.current_user, err=err)
        else:
            data = time.strftime("%Y-%m-%d")
            user = User(
                    username=username,
                    password=password,
                    email=email,
                    data=data,
                    tell_phone=tell_phone,
                    company_id=company_id,
            )
            self.session.add(user)
            self.session.commit()
            self.redirect('/fra/user') class UserUpdateHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        user_id = self.get_argument('id')
        if user_id:
            user = self.session.query(User).filter(User.id == user_id).first()
            if user:
                err = ''
                self.render("fra_user_detail.html", auth_user=self.current_user, user=user, err=err)
            else:
                err = '人员不存在'
                users = self.session.query(User).filter().all()
                self.render("fra_user_list.html", auth_user=self.current_user, users=users, err=err)
        else:
            err = '人员不存在'
            users = self.session.query(User).filter().all()
            self.render("fra_user_list.html", auth_user=self.current_user, users=users, err=err)

    @tornado.web.authenticated
    def post(self):
        id = self.get_argument('id')
        username = self.get_argument('username')
        password = hashlib.sha256(self.get_argument('password')).hexdigest()
        email = self.get_argument('email')
        tell_phone = self.get_argument('tell_phone')
        user = self.session.query(User).filter(User.id == id).first()
        if user:
            if self.get_argument('password') == '':
                user = User(
                    id=id,
                    username=username,
                    email=email,
                    tell_phone=tell_phone,
                )
                self.session.merge(user)
                self.session.commit()
                self.redirect('/fra/user')
            else:
                user = User(
                    id=id,
                    username=username,
                    password=password,
                    email=email,
                    tell_phone=tell_phone,
                )
                self.session.merge(user)
                self.session.commit()
                self.redirect('/fra/user')

        else:
            err = '用户不存在'
            users = self.session.query(User).filter().all()
            self.render("fra_user_list.html", auth_user=self.current_user, users=users, err=err) class UserDeleteHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        user_id = self.get_argument('id')
        if user_id:
            user = self.session.query(User).filter(User.id == user_id).first()
            self.session.delete(user)
            self.session.commit()
            self.redirect('/fra/user')
        else:
            err = '删除的人员不存在'
            self.render("fra_user_list.html", auth_user=self.current_user, err=err) class LoginHandler(BaseHandler):
    def get(self):
        self.render('sys_login.html', login_err='')

    def post(self):
        username = self.get_argument('username')
        password = hashlib.sha256(self.get_argument('password').encode('utf-8')).hexdigest()
        user = self.session.query(User).filter(and_(User.username == username, User.password == password)).first()
        if user:
            self.set_secure_cookie('user_id', str(user.id))
            self.set_secure_cookie('username', username)
            self.set_secure_cookie('company_id', str(user.company_id))
            logging.info(str(username) + ' : login success')
            self.redirect('/')
        else:
            logging.info(str(username) + ' : login fail')
            self.render('sys_login.html', login_err='用户名或密码错误！') class LogoutHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        self.clear_cookie('username', None)
        self.redirect('/login') class MyTaskHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        my_tasks = self.session.query(MyTask).filter(MyTask.company_id == self.get_secure_cookie('company_id')).order_by(MyTask.id.desc()).all()
        self.render("task_list.html", auth_user=self.current_user, my_tasks=my_tasks) class MyTaskDeleteHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        my_task_id = self.get_argument("my_task_id")
        my_task = self.session.query(MyTask).filter(MyTask.id == my_task_id).first()
        self.session.delete(my_task)
        self.session.commit()
        self.redirect('/myTask') class MyTaskDetailHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        my_task_id = self.get_argument("my_task_id")
        my_task = self.session.query(MyTask).filter(MyTask.id == my_task_id).first()
        my_task_contents = my_task.my_task_content
        self.render("task_detail.html", auth_user=self.current_user, my_task_contents=my_task_contents) class SendTimeSwitchHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        device_time_switch_id = self.get_argument("device_time_switch_id")
        device_time_switch, week_list = BaseFunctionHandler.get_device_time_switch(self, device_time_switch_id)
        my_task = MyTask(
            name='定时开关机任务',
            type='time_switch',
            time=time.strftime("%Y-%m-%d %H:%M:%S"),
            user_id=self.get_secure_cookie('user_id'),
            company_id=self.get_secure_cookie('company_id'),
        )
        self.session.add(my_task)
        self.session.commit()
        for device_group in device_time_switch.device_group:
            devices = device_group.device
            for device in devices:
                my_task_content = MyTaskContent(
                    device_id=device.device_id,
                    from_user=self.get_secure_cookie('username'),
                    new_time=time.strftime("%Y-%m-%d %H:%M:%S"),
                    send_time=time.strftime("%Y-%m-%d %H:%M:%S"),
                    send_data=str(week_list),
                    my_task_id=my_task.id
                )
                self.session.add(my_task_content)
        self.session.commit()
        ApiDeviceSocketHandler.send_to_many_device(devices, week_list)
        self.redirect('/myTask') class SendPlaylistHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        res_group_id = self.get_argument('res_group_id')
        res_group, playlist = BaseFunctionHandler.get_res_group_by_res_group_id(res_group_id)
        my_task = MyTask(
            name='播放列表任务',
            type='playlist',
            time=time.strftime("%Y-%m-%d %H:%M:%S"),
            user_id=self.get_secure_cookie('user_id'),
            company_id=self.get_secure_cookie('company_id'),
        )
        self.session.add(my_task)
        self.session.commit()
        device_groups = res_group.deviceGroup
        for device_group in device_groups:
            devices = device_group.device
        for device in devices:
            my_task_content = MyTaskContent(
                    device_id=device.device_id,
                    from_user=self.get_secure_cookie('username'),
                    new_time=time.strftime("%Y-%m-%d %H:%M:%S"),
                    send_time=time.strftime("%Y-%m-%d %H:%M:%S"),
                    send_data=str(playlist),
                    my_task_id=my_task.id
            )
            self.session.add(my_task_content)
        self.session.commit()
        ApiDeviceSocketHandler.send_to_many_device(devices, playlist)
        self.redirect('/myTask') class SendDeviceRestartHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        device_id = self.get_argument('device_id')
        my_task = MyTask(
            name='广告机重启',
            type='deviceRestart',
            time=time.strftime("%Y-%m-%d %H:%M:%S"),
            user_id=self.get_secure_cookie('user_id'),
            company_id=self.get_secure_cookie('company_id'),
        )
        self.session.add(my_task)
        self.session.commit()
        data = [{'cmd': 'deviceRestart'}, {'data': 'restart'}]
        my_task_content = MyTaskContent(
                    device_id=device_id,
                    from_user=self.get_secure_cookie('username'),
                    new_time=time.strftime("%Y-%m-%d %H:%M:%S"),
                    send_time=time.strftime("%Y-%m-%d %H:%M:%S"),
                    send_data=str(data),
                    my_task_id=my_task.id
            )
        self.session.add(my_task_content)
        self.session.commit()
        ApiDeviceSocketHandler.send_to_one_device(device_id, data)
        self.redirect('/myTask') class ResHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        self.redirect('/res/group?res_group_id=') class ResTextHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        # page_now = self.get_argument('page_now')
        # page_size = PAGESIZE
        # text_resources = self.session.query(ResText).filter(ResText.company_id == self.get_secure_cookie('company_id')).all()[1:10]
        text_resources = self.session.query(ResText).filter(ResText.company_id == self.get_secure_cookie('company_id')).order_by(ResText.id.desc()).all()
        self.render("res_text.html", auth_user=self.current_user, text_resources=text_resources) class ResTextDetailHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        action = '/res/text/detail'
        err = ""
        text_id = self.get_argument("id")
        text_resource = self.session.query(ResText).filter(ResText.id == text_id).first()
        self.render("res_text_detail.html", auth_user=self.current_user, action=action, text_resource=text_resource, err=err)

    def post(self):
        id = self.get_argument("id")
        name = self.get_argument("name")
        content = self.get_argument("content")
        memo = self.get_argument("memo")
        text_resource = ResText(
                id=id,
                name=name,
                content=content,
                memo=memo
        )
        try:
            self.session.merge(text_resource)
            self.session.commit()
            self.redirect('/res/text')
        except:
            err = "资源修改失败"
            text_resource = self.session.query(ResText).filter(ResText.id == id).first()
            self.render("res_text_detail.html", auth_user=self.current_user, text_resource=text_resource, err=err) class ResTextAddHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        action = '/res/text/add'
        err = ''
        text_resource = ResText()
        self.render("res_text_detail.html", auth_user=self.current_user, action=action, text_resource=text_resource, err=err)

    @tornado.web.authenticated
    def post(self):
        text_name = self.get_argument("name")
        text_content = self.get_argument("content")
        memo = self.get_argument("memo")
        text_resource = ResText(
                name=text_name,
                content=text_content,
                memo=memo,
                data=time.strftime("%Y-%m-%d"),
                company_id=self.get_secure_cookie('company_id')
        )
        try:
            self.session.add(text_resource)
            self.session.commit()
            self.redirect('/res/text')
        except:
            action = '/res/text/add'
            err = "资源新增失败"
            text_resource = ''
            self.render("res_text_detail.html", auth_user=self.current_user, action=action, text_resource=text_resource, err=err) class ResTextDeleteHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        id = self.get_argument("id")
        text_resource = self.session.query(ResText).filter(ResText.id == id).first()
        self.session.delete(text_resource)
        self.session.commit()
        self.redirect('/res/text') class ResWebHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        # page_now = self.get_argument('page_now')
        # page_size = PAGESIZE
        # text_resources = self.session.query(ResText).filter(ResText.company_id == self.get_secure_cookie('company_id')).all()[1:10]
        web_resources = self.session.query(ResWeb).filter(ResWeb.company_id == self.get_secure_cookie('company_id')).order_by(ResWeb.id.desc()).all()
        self.render("res_web.html", auth_user=self.current_user, web_resources=web_resources) class ResWebDetailHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        action = '/res/web/detail'
        err = ""
        web_id = self.get_argument("id")
        web_resource = self.session.query(ResWeb).filter(ResWeb.id == web_id).first()
        self.render("res_web_detail.html", auth_user=self.current_user, action=action, web_resource=web_resource, err=err)

    def post(self):
        id = self.get_argument("id")
        name = self.get_argument("name")
        content = self.get_argument("content")
        memo = self.get_argument("memo")
        web_resource = ResWeb(
                id=id,
                name=name,
                content=content,
                memo=memo
        )
        try:
            self.session.merge(web_resource)
            self.session.commit()
            self.redirect('/res/web')
        except:
            err = "资源修改失败"
            web_resource = self.session.query(ResWeb).filter(ResWeb.id == id).first()
            self.render("res_web_detail.html", auth_user=self.current_user, web_resource=web_resource, err=err) class ResWebAddHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        action = '/res/web/add'
        err = ''
        web_resource = ResWeb()
        self.render("res_web_detail.html", auth_user=self.current_user, action=action, web_resource=web_resource, err=err)

    @tornado.web.authenticated
    def post(self):
        web_name = self.get_argument("name")
        web_content = self.get_argument("content")
        memo = self.get_argument("memo")
        web_resource = ResWeb(
                name=web_name,
                content=web_content,
                memo=memo,
                data=time.strftime("%Y-%m-%d"),
                company_id=self.get_secure_cookie('company_id')
        )
        try:
            self.session.add(web_resource)
            self.session.commit()
            self.redirect('/res/web')
        except:
            action = '/res/web/add'
            err = "资源新增失败"
            web_resource = ''
            self.render("res_web_detail.html", auth_user=self.current_user, action=action, web_resource=web_resource, err=err) class ResWebDeleteHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        id = self.get_argument("id")
        web_resource = self.session.query(ResWeb).filter(ResWeb.id == id).first()
        self.session.delete(web_resource)
        self.session.commit()
        self.redirect('/res/web') class ResImageHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        image_resources = self.session.query(ResImage).filter(ResImage.company_id == self.get_secure_cookie('company_id')).order_by(ResImage.id.desc()).all()
        self.render("res_image.html", auth_user=self.current_user, image_resources=image_resources) class ResImageDetailHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        action = '/res/image/detail'
        err = ""
        image_id = self.get_argument("id")
        image_resource = self.session.query(ResImage).filter(ResImage.id == image_id).first()
        self.render("res_image_detail.html", auth_user=self.current_user, action=action, image_resource=image_resource, err=err)

    @tornado.web.authenticated
    def post(self):
        image_id = self.get_argument("id")
        name = self.get_argument("name")
        memo = self.get_argument("memo")
        image_resource = ResImage(
                id=image_id,
                name=name,
                memo=memo
        )
        try:
            self.session.merge(image_resource)
            self.session.commit()
            self.redirect('/res/image')
        except:
            err = "图片修改失败"
            image_resource = self.session.query(ResImage).filter(ResImage.id == image_id).first()
            self.render("res_image_detail.html", auth_user=self.current_user, image_resource=image_resource, err=err) class ResImageDeleteHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        image_id = self.get_argument("id")
        image_resource = self.session.query(ResImage).filter(ResImage.id == image_id).first()
        if os.path.exists(image_resource.path):
            os.remove(image_resource.path)
        self.session.delete(image_resource)
        self.session.commit()
        self.redirect('/res/image') class ResImageAddHandler(BaseHandler):

    def check_xsrf_cookie(self):
        pass

    @tornado.web.authenticated
    def get(self):
        self.render("res_image_add.html", auth_user=self.current_user)

    @tornado.web.authenticated
    def post(self):
        username = self.get_secure_cookie("username")
        company_id = self.get_secure_cookie('company_id')
        data = time.strftime("%Y%m%d")
        upload_path = '/media/image/' + username + '/' + data
        if not os.path.isdir(upload_path):
            os.makedirs(upload_path)
        # 提取表单中‘name’为‘file’的文件元数据
        file_metas = self.request.files['file']
        for meta in file_metas:
            filename = meta['filename']
            filepath = os.path.join(upload_path, filename)
            # 有些文件需要已二进制的形式存储，实际中可以更改
            with open(filepath, 'wb') as up:
                up.write(meta['body'])
            img_resources = ResImage()
            img_resources.name = filename
            img_resources.memo = filename
            img_resources.path = filepath
            img_resources.company_id = company_id
            img_resources.data = data
            self.session.add(img_resources)
        self.session.commit()
        json_data = dict()
        json_data['uploaded_file_path'] = filepath
        self.write(json_data) class ResVideoHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        video_resources = self.session.query(ResVideo).filter(ResVideo.company_id == self.get_secure_cookie('company_id')).order_by(ResVideo.id.desc()).all()
        self.render("res_video.html", auth_user=self.current_user, video_resources=video_resources) class ResVideoDetailHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        action = '/res/video/detail'
        err = ""
        video_id = self.get_argument("id")
        video_resource = self.session.query(ResVideo).filter(ResVideo.id == video_id).first()
        self.render("res_video_detail.html", auth_user=self.current_user, action=action, video_resource=video_resource, err=err)

    @tornado.web.authenticated
    def post(self):
        video_id = self.get_argument("id")
        name = self.get_argument("name")
        memo = self.get_argument("memo")
        video_resource = ResVideo(
                id=video_id,
                name=name,
                memo=memo
        )
        try:
            self.session.merge(video_resource)
            self.session.commit()
            self.redirect('/res/video')
        except:
            err = "视频修改失败"
            video_resource = self.session.query(ResVideo).filter(ResVideo.id == video_id).first()
            self.render("res_video_detail.html", auth_user=self.current_user, video_resource=video_resource, err=err) class ResVideoDeleteHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        video_id = self.get_argument("id")
        video_resource = self.session.query(ResVideo).filter(ResVideo.id == video_id).first()
        if os.path.exists(video_resource.path):
            os.remove(video_resource.path)
        self.session.delete(video_resource)
        self.session.commit()
        self.redirect('/res/video') class ResVideoAddHandler(BaseHandler):

    def check_xsrf_cookie(self):
        pass

    @tornado.web.authenticated
    def get(self):
        self.render("res_video_add.html", auth_user=self.current_user)

    @tornado.web.authenticated
    def post(self):
        username = self.get_secure_cookie("username")
        company_id = self.get_secure_cookie('company_id')
        data = time.strftime("%Y%m%d")
        upload_path = '/media/video/' + username + '/' + data
        if not os.path.isdir(upload_path):
            os.makedirs(upload_path)
        # 提取表单中‘name’为‘file’的文件元数据
        file_metas = self.request.files['video_file']
        for meta in file_metas:
            filename = meta['filename']
            filepath = os.path.join(upload_path, filename)
            # 有些文件需要已二进制的形式存储，实际中可以更改
            with open(filepath, 'wb') as up:
                up.write(meta['body'])
            video_resources = ResVideo()
            video_resources.name = filename
            video_resources.memo = filename
            video_resources.path = filepath
            video_resources.company_id = company_id
            video_resources.data = data
            self.session.add(video_resources)
        self.session.commit()
        json_data = dict()
        json_data['uploaded_file_path'] = filepath
        self.write(json_data) class ResGroupHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        res_group_id = self.get_argument('res_group_id')
        res_groups = self.session.query(ResGroup).filter(ResGroup.company_id == self.get_secure_cookie('company_id')).all()
        if res_groups:
            if res_group_id == '':
                res_group = self.session.query(ResGroup).filter().first()
            else:
                res_group = self.session.query(ResGroup).filter(ResGroup.id == res_group_id).first()
            res_texts = res_group.resText
            res_webs = res_group.resWeb
            res_images = res_group.resImage
            res_videos = res_group.resVideo
            self.render("res_group.html", auth_user=self.current_user, hand_res_group=res_group, res_groups=res_groups, res_texts=res_texts, res_webs=res_webs, res_images=res_images, res_videos=res_videos)
        else:
            self.redirect('/res/group/add') class ResGroupAddHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        err = ''
        action = '/res/group/add'
        res_group = ResGroup()
        self.render("res_group_detail.html", auth_user=self.current_user, action=action, res_group=res_group, err=err)

    @tornado.web.authenticated
    def post(self):
        action = '/res/group/add'
        name = self.get_argument('name')
        res_group = self.session.query(ResGroup).filter(ResGroup.name == name).first()
        if res_group:
            err = "资源组名称已经存在"
            res_group = ResGroup()
            self.render("res_group_detail.html", auth_user=self.current_user, action=action, res_group=res_group, err=err)
        else:
            res_group = ResGroup(
                    name=name,
                    data=time.strftime("%Y-%m-%d"),
                    company_id=self.get_secure_cookie('company_id')
            )
            try:
                self.session.add(res_group)
                self.session.commit()
                self.redirect('/res/group?res_group_id=')
            except:
                err = "资源组新增失败"
                res_group = ResGroup()
                self.render("res_group_detail.html", auth_user=self.current_user, action=action, res_group=res_group, err=err) class ResGroupUpdateHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        err = ''
        action = '/res/group/update'
        res_group_id = self.get_argument('res_group_id')
        res_group = self.session.query(ResGroup).filter(ResGroup.id == res_group_id).first()
        self.render("res_group_detail.html", auth_user=self.current_user, action=action, res_group=res_group, err=err)

    @tornado.web.authenticated
    def post(self):
        id = self.get_argument('id')
        name = self.get_argument('name')
        res_group = self.session.query(ResGroup).filter(ResGroup.id == id).first()
        res_group.name = name
        self.session.merge(res_group)
        self.session.commit()
        self.redirect('/res/group?res_group_id=') class ResGroupDeleteHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        res_group_id = self.get_argument('res_group_id')
        res_group = self.session.query(ResGroup).filter(ResGroup.id == res_group_id).first()
        self.session.delete(res_group)
        self.session.commit()
        self.redirect('/res/group?res_group_id=') class ResGroupAddTextHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        err = ''
        res_group_id = self.get_argument('res_group_id')
        res_texts = self.session.query(ResText).filter(ResText.company_id == self.get_secure_cookie('company_id')).all()
        self.render("res_group_add_text.html", auth_user=self.current_user, res_group_id=res_group_id, res_texts=res_texts, err=err)

    @tornado.web.authenticated
    def post(self):
        res_group_id = self.get_argument('res_group_id')
        res_text_ids = self.get_arguments('res_text_ids')
        res_group = self.session.query(ResGroup).filter(ResGroup.id == res_group_id).first()
        for res_text_id in res_text_ids:
            res_text = self.session.query(ResText).filter(ResText.id == res_text_id).first()
            res_group.resText.append(res_text)
        self.session.commit()
        self.redirect('/res/group?res_group_id=' + res_group_id) class ResGroupDeleteTextHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        res_text_id = self.get_argument('res_text_id')
        res_group_id = self.get_argument('res_group_id')
        res_text = self.session.query(ResText).filter(ResText.id == res_text_id).first()
        res_group = self.session.query(ResGroup).filter(ResGroup.id == res_group_id).first()
        res_group.resText.remove(res_text)
        self.session.commit()
        self.redirect('/res/group?res_group_id=' + res_group_id) class ResGroupAddWebHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        err = ''
        res_group_id = self.get_argument('res_group_id')
        res_webs = self.session.query(ResWeb).filter(ResWeb.company_id == self.get_secure_cookie('company_id')).all()
        self.render("res_group_add_web.html", auth_user=self.current_user, res_group_id=res_group_id, res_webs=res_webs, err=err)

    @tornado.web.authenticated
    def post(self):
        res_group_id = self.get_argument('res_group_id')
        res_web_ids = self.get_arguments('res_web_ids')
        res_group = self.session.query(ResGroup).filter(ResGroup.id == res_group_id).first()
        for res_web_id in res_web_ids:
            res_web = self.session.query(ResWeb).filter(ResWeb.id == res_web_id).first()
            res_group.resWeb.append(res_web)
        self.session.commit()
        self.redirect('/res/group?res_group_id=' + res_group_id) class ResGroupDeleteWebHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        res_web_id = self.get_argument('res_web_id')
        res_group_id = self.get_argument('res_group_id')
        res_web = self.session.query(ResWeb).filter(ResWeb.id == res_web_id).first()
        res_group = self.session.query(ResGroup).filter(ResGroup.id == res_group_id).first()
        res_group.resWeb.remove(res_web)
        self.session.commit()
        self.redirect('/res/group?res_group_id=' + res_group_id) class ResGroupAddImageHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        res_group_id = self.get_argument('res_group_id')
        res_images = self.session.query(ResImage).filter(ResImage.company_id == self.get_secure_cookie('company_id')).all()
        self.render("res_group_add_image.html", auth_user=self.current_user, res_group_id=res_group_id, res_images=res_images)

    @tornado.web.authenticated
    def post(self):
        res_group_id = self.get_argument('res_group_id')
        res_image_ids = self.get_arguments('res_image_ids')
        res_group = self.session.query(ResGroup).filter(ResGroup.id == res_group_id).first()
        for res_image_id in res_image_ids:
            res_image = self.session.query(ResImage).filter(ResImage.id == res_image_id).first()
            res_group.resImage.append(res_image)
        self.session.commit()
        self.redirect('/res/group?res_group_id=' + res_group_id) class ResGroupDeleteImageHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        res_image_id = self.get_argument('res_image_id')
        res_group_id = self.get_argument('res_group_id')
        res_image = self.session.query(ResImage).filter(ResImage.id == res_image_id).first()
        res_group = self.session.query(ResGroup).filter(ResGroup.id == res_group_id).first()
        res_group.resImage.remove(res_image)
        self.session.commit()
        self.redirect('/res/group?res_group_id=' + res_group_id) class ResGroupAddVideoHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        res_group_id = self.get_argument('res_group_id')
        res_videos = self.session.query(ResVideo).filter(ResVideo.company_id == self.get_secure_cookie('company_id')).all()
        self.render("res_group_add_video.html", auth_user=self.current_user, res_group_id=res_group_id, res_videos=res_videos)

    @tornado.web.authenticated
    def post(self):
        res_group_id = self.get_argument('res_group_id')
        res_video_ids = self.get_arguments('res_video_ids')
        res_group = self.session.query(ResGroup).filter(ResGroup.id == res_group_id).first()
        for res_video_id in res_video_ids:
            res_video = self.session.query(ResVideo).filter(ResVideo.id == res_video_id).first()
            res_group.resVideo.append(res_video)
        self.session.commit()
        self.redirect('/res/group?res_group_id=' + res_group_id) class ResGroupDeleteVideoHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        res_video_id = self.get_argument('res_video_id')
        res_group_id = self.get_argument('res_group_id')
        res_video = self.session.query(ResVideo).filter(ResVideo.id == res_video_id).first()
        res_group = self.session.query(ResGroup).filter(ResGroup.id == res_group_id).first()
        res_group.resVideo.remove(res_video)
        self.session.commit()
        self.redirect('/res/group?res_group_id=' + res_group_id)
from api.api import ApiUserHandler, ApiScreenNumber, ApiDeviceRegister
from api.apiWebSocket import ApiUserSocketHandler, ApiDeviceSocketHandler
from handlers.dev import DeviceManageHandler, DeviceManageDetailHandler, DeviceGroupHandler, DeviceGroupAddHandler, DeviceGroupDeleteHandler, DeviceGroupUpdateHandler, DeviceTimeSwitchHandler, DeviceTimeSwitchAddHandler, DeviceTimeSwitchUpdateHandler, DeviceTimeSwitchDeleteHandler, \
    DeviceDayAddHandler, DeviceDayUpdateHandler, DeviceDayDeleteHandler
from handlers.fra import CompanyHandler, CompanyAddHandler, CompanyDeteleHandler, CompanyUpdateHandler, UserHandler, UserAddHandler, UserUpdateHandler, UserDeleteHandler
from handlers.login import LoginHandler, LogoutHandler
from handlers.myTask import MyTaskHandler, MyTaskDeleteHandler, MyTaskDetailHandler, SendTimeSwitchHandler, SendPlaylistHandler, SendDeviceRestartHandler
from handlers.res import ResHandler, ResTextHandler, ResTextDetailHandler, ResTextAddHandler, ResTextDeleteHandler, ResWebHandler, ResWebDetailHandler, ResWebAddHandler, ResWebDeleteHandler, ResImageHandler, ResImageDetailHandler, ResImageDeleteHandler, ResImageAddHandler, ResVideoHandler, \
    ResVideoDetailHandler, ResVideoDeleteHandler, ResVideoAddHandler, ResGroupHandler, ResGroupAddHandler, ResGroupUpdateHandler, ResGroupDeleteHandler, ResGroupAddTextHandler, ResGroupDeleteTextHandler, ResGroupAddWebHandler, ResGroupDeleteWebHandler, ResGroupAddImageHandler, \
    ResGroupDeleteImageHandler, ResGroupAddVideoHandler, ResGroupDeleteVideoHandler
#!/usr/bin/python
# _*_coding:utf-8_*_


urls = [
    # (r"/", IndexHandler),
    (r"/", DeviceManageHandler),
    (r"/api/user", ApiUserHandler),
    (r"/api/screen", ApiScreenNumber),
    (r"/api/deviceRegister", ApiDeviceRegister),
    (r"/api/userSocket", ApiUserSocketHandler),
    (r"/api/deviceSocket", ApiDeviceSocketHandler),
    (r"/login", LoginHandler),
    (r"/logout", LogoutHandler),
    (r"/fra", CompanyHandler),
    [r"/fra/com", CompanyHandler],
    (r"/fra/com/add", CompanyAddHandler),
    (r"/fra/com/update", CompanyUpdateHandler),
    (r"/fra/com/delete", CompanyDeteleHandler),
    (r"/fra/user", UserHandler),
    (r"/fra/user/add", UserAddHandler),
    (r"/fra/user/update", UserUpdateHandler),
    (r"/fra/user/delete", UserDeleteHandler),
    (r"/dev", DeviceManageHandler),
    (r"/dev/manage", DeviceManageHandler),
    (r"/dev/manage/detail", DeviceManageDetailHandler),
    (r"/dev/group", DeviceGroupHandler),
    (r"/dev/group/add", DeviceGroupAddHandler),
    (r"/dev/group/delete", DeviceGroupDeleteHandler),
    (r"/dev/group/update", DeviceGroupUpdateHandler),
    (r"/dev/timeSwitch", DeviceTimeSwitchHandler),
    (r"/dev/timeSwitch/add", DeviceTimeSwitchAddHandler),
    (r"/dev/timeSwitch/update", DeviceTimeSwitchUpdateHandler),
    (r"/dev/timeSwitch/delete", DeviceTimeSwitchDeleteHandler),
    (r"/dev/day/add", DeviceDayAddHandler),
    (r"/dev/day/update", DeviceDayUpdateHandler),
    (r"/dev/day/delete", DeviceDayDeleteHandler),
    (r"/res", ResHandler),
    (r"/res/text", ResTextHandler),
    (r"/res/text/detail", ResTextDetailHandler),
    (r"/res/text/add", ResTextAddHandler),
    (r"/res/text/delete", ResTextDeleteHandler),
    (r"/res/web", ResWebHandler),
    (r"/res/web/detail", ResWebDetailHandler),

    (r"/res/web/add", ResWebAddHandler),